@decaf-ts/core 0.7.2 → 0.7.4

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 (246) hide show
  1. package/README.md +6 -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/decorators.d.ts +3 -4
  7. package/lib/esm/identity/decorators.js +5 -11
  8. package/lib/esm/identity/decorators.js.map +1 -1
  9. package/lib/esm/identity/index.d.ts +0 -1
  10. package/lib/esm/identity/index.js +0 -1
  11. package/lib/esm/identity/index.js.map +1 -1
  12. package/lib/esm/index.d.ts +1 -1
  13. package/lib/esm/index.js +1 -1
  14. package/lib/esm/interfaces/ContextuallyLogged.d.ts +8 -0
  15. package/lib/esm/interfaces/ContextuallyLogged.js +2 -0
  16. package/lib/esm/interfaces/ContextuallyLogged.js.map +1 -0
  17. package/lib/esm/interfaces/ErrorParser.d.ts +2 -2
  18. package/lib/esm/interfaces/Executor.d.ts +1 -1
  19. package/lib/esm/interfaces/Observable.d.ts +8 -8
  20. package/lib/esm/interfaces/Observer.d.ts +2 -2
  21. package/lib/esm/interfaces/RawExecutor.d.ts +1 -1
  22. package/lib/esm/model/BaseModel.d.ts +2 -2
  23. package/lib/esm/model/BaseModel.js +2 -2
  24. package/lib/esm/{ram/model/RamSequenceModel.d.ts → model/SequenceModel.d.ts} +3 -3
  25. package/lib/esm/{ram/model/RamSequenceModel.js → model/SequenceModel.js} +12 -11
  26. package/lib/esm/model/SequenceModel.js.map +1 -0
  27. package/lib/esm/model/construction.d.ts +9 -8
  28. package/lib/esm/model/construction.js +2 -2
  29. package/lib/esm/model/construction.js.map +1 -1
  30. package/lib/esm/model/decorators.d.ts +5 -4
  31. package/lib/esm/model/decorators.js +3 -3
  32. package/lib/esm/model/decorators.js.map +1 -1
  33. package/lib/esm/model/index.d.ts +1 -0
  34. package/lib/esm/model/index.js +1 -0
  35. package/lib/esm/model/index.js.map +1 -1
  36. package/lib/esm/overrides/Metadata.d.ts +1 -8
  37. package/lib/esm/overrides/Model.d.ts +75 -0
  38. package/lib/esm/overrides/Model.js +2 -0
  39. package/lib/esm/overrides/Model.js.map +1 -0
  40. package/lib/esm/overrides/index.d.ts +2 -0
  41. package/lib/esm/overrides/index.js +2 -0
  42. package/lib/esm/overrides/index.js.map +1 -1
  43. package/lib/esm/overrides/injectables.d.ts +10 -0
  44. package/lib/esm/overrides/injectables.js +2 -0
  45. package/lib/esm/overrides/injectables.js.map +1 -0
  46. package/lib/esm/overrides/overrides.js +45 -3
  47. package/lib/esm/overrides/overrides.js.map +1 -1
  48. package/lib/esm/persistence/Adapter.d.ts +55 -53
  49. package/lib/esm/persistence/Adapter.js +85 -61
  50. package/lib/esm/persistence/Adapter.js.map +1 -1
  51. package/lib/esm/persistence/Dispatch.d.ts +7 -6
  52. package/lib/esm/persistence/Dispatch.js +25 -18
  53. package/lib/esm/persistence/Dispatch.js.map +1 -1
  54. package/lib/esm/persistence/ObserverHandler.d.ts +7 -6
  55. package/lib/esm/persistence/ObserverHandler.js +5 -4
  56. package/lib/esm/persistence/ObserverHandler.js.map +1 -1
  57. package/lib/esm/persistence/Sequence.d.ts +34 -25
  58. package/lib/esm/persistence/Sequence.js +136 -15
  59. package/lib/esm/persistence/Sequence.js.map +1 -1
  60. package/lib/esm/persistence/constants.d.ts +1 -0
  61. package/lib/esm/persistence/constants.js +1 -0
  62. package/lib/esm/persistence/constants.js.map +1 -1
  63. package/lib/esm/persistence/generators.d.ts +14 -0
  64. package/lib/esm/persistence/generators.js +31 -0
  65. package/lib/esm/persistence/generators.js.map +1 -0
  66. package/lib/esm/persistence/index.d.ts +1 -0
  67. package/lib/esm/persistence/index.js +1 -0
  68. package/lib/esm/persistence/index.js.map +1 -1
  69. package/lib/esm/persistence/migrations.d.ts +8 -8
  70. package/lib/esm/persistence/migrations.js +8 -9
  71. package/lib/esm/persistence/migrations.js.map +1 -1
  72. package/lib/esm/persistence/types.d.ts +38 -20
  73. package/lib/esm/query/Paginator.d.ts +6 -5
  74. package/lib/esm/query/Paginator.js +4 -4
  75. package/lib/esm/query/Paginator.js.map +1 -1
  76. package/lib/esm/query/Statement.d.ts +9 -8
  77. package/lib/esm/query/Statement.js +23 -10
  78. package/lib/esm/query/Statement.js.map +1 -1
  79. package/lib/esm/ram/RamAdapter.d.ts +22 -31
  80. package/lib/esm/ram/RamAdapter.js +36 -34
  81. package/lib/esm/ram/RamAdapter.js.map +1 -1
  82. package/lib/esm/ram/RamPaginator.d.ts +2 -1
  83. package/lib/esm/ram/RamPaginator.js +5 -3
  84. package/lib/esm/ram/RamPaginator.js.map +1 -1
  85. package/lib/esm/ram/RamStatement.d.ts +7 -7
  86. package/lib/esm/ram/RamStatement.js.map +1 -1
  87. package/lib/esm/ram/handlers.d.ts +3 -4
  88. package/lib/esm/ram/handlers.js.map +1 -1
  89. package/lib/esm/ram/index.d.ts +0 -3
  90. package/lib/esm/ram/index.js +0 -3
  91. package/lib/esm/ram/index.js.map +1 -1
  92. package/lib/esm/ram/types.d.ts +4 -12
  93. package/lib/esm/repository/Repository.d.ts +31 -95
  94. package/lib/esm/repository/Repository.js +107 -203
  95. package/lib/esm/repository/Repository.js.map +1 -1
  96. package/lib/esm/repository/decorators.js +4 -3
  97. package/lib/esm/repository/decorators.js.map +1 -1
  98. package/lib/esm/repository/utils.d.ts +1 -1
  99. package/lib/esm/repository/utils.js +2 -3
  100. package/lib/esm/repository/utils.js.map +1 -1
  101. package/lib/esm/utils/ContextualLoggedClass.d.ts +16 -0
  102. package/lib/esm/utils/ContextualLoggedClass.js +29 -0
  103. package/lib/esm/utils/ContextualLoggedClass.js.map +1 -0
  104. package/lib/esm/utils/Services.d.ts +50 -0
  105. package/lib/esm/utils/Services.js +154 -0
  106. package/lib/esm/utils/Services.js.map +1 -0
  107. package/lib/esm/utils/decorators.d.ts +1 -9
  108. package/lib/esm/utils/decorators.js +26 -15
  109. package/lib/esm/utils/decorators.js.map +1 -1
  110. package/lib/esm/utils/index.d.ts +2 -1
  111. package/lib/esm/utils/index.js +2 -1
  112. package/lib/esm/utils/index.js.map +1 -1
  113. package/lib/identity/decorators.cjs +5 -11
  114. package/lib/identity/decorators.d.ts +3 -4
  115. package/lib/identity/decorators.js.map +1 -1
  116. package/lib/identity/index.cjs +0 -1
  117. package/lib/identity/index.d.ts +0 -1
  118. package/lib/identity/index.js.map +1 -1
  119. package/lib/index.cjs +1 -1
  120. package/lib/index.d.ts +1 -1
  121. package/lib/interfaces/ContextuallyLogged.cjs +3 -0
  122. package/lib/interfaces/ContextuallyLogged.d.ts +8 -0
  123. package/lib/interfaces/ContextuallyLogged.js.map +1 -0
  124. package/lib/interfaces/ErrorParser.d.ts +2 -2
  125. package/lib/interfaces/Executor.d.ts +1 -1
  126. package/lib/interfaces/Observable.d.ts +8 -8
  127. package/lib/interfaces/Observer.d.ts +2 -2
  128. package/lib/interfaces/RawExecutor.d.ts +1 -1
  129. package/lib/model/BaseModel.cjs +2 -2
  130. package/lib/model/BaseModel.d.ts +2 -2
  131. package/lib/{ram/model/RamSequenceModel.cjs → model/SequenceModel.cjs} +14 -13
  132. package/lib/{ram/model/RamSequenceModel.d.ts → model/SequenceModel.d.ts} +3 -3
  133. package/lib/model/SequenceModel.js.map +1 -0
  134. package/lib/model/construction.cjs +2 -2
  135. package/lib/model/construction.d.ts +9 -8
  136. package/lib/model/construction.js.map +1 -1
  137. package/lib/model/decorators.cjs +3 -3
  138. package/lib/model/decorators.d.ts +5 -4
  139. package/lib/model/decorators.js.map +1 -1
  140. package/lib/model/index.cjs +1 -0
  141. package/lib/model/index.d.ts +1 -0
  142. package/lib/model/index.js.map +1 -1
  143. package/lib/overrides/Metadata.d.ts +1 -8
  144. package/lib/overrides/Model.cjs +4 -0
  145. package/lib/overrides/Model.d.ts +75 -0
  146. package/lib/overrides/Model.js.map +1 -0
  147. package/lib/overrides/index.cjs +2 -0
  148. package/lib/overrides/index.d.ts +2 -0
  149. package/lib/overrides/index.js.map +1 -1
  150. package/lib/overrides/injectables.cjs +4 -0
  151. package/lib/overrides/injectables.d.ts +10 -0
  152. package/lib/overrides/injectables.js.map +1 -0
  153. package/lib/overrides/overrides.cjs +43 -1
  154. package/lib/overrides/overrides.js.map +1 -1
  155. package/lib/persistence/Adapter.cjs +90 -66
  156. package/lib/persistence/Adapter.d.ts +55 -53
  157. package/lib/persistence/Adapter.js.map +1 -1
  158. package/lib/persistence/Dispatch.cjs +25 -18
  159. package/lib/persistence/Dispatch.d.ts +7 -6
  160. package/lib/persistence/Dispatch.js.map +1 -1
  161. package/lib/persistence/ObserverHandler.cjs +5 -4
  162. package/lib/persistence/ObserverHandler.d.ts +7 -6
  163. package/lib/persistence/ObserverHandler.js.map +1 -1
  164. package/lib/persistence/Sequence.cjs +136 -15
  165. package/lib/persistence/Sequence.d.ts +34 -25
  166. package/lib/persistence/Sequence.js.map +1 -1
  167. package/lib/persistence/constants.cjs +1 -0
  168. package/lib/persistence/constants.d.ts +1 -0
  169. package/lib/persistence/constants.js.map +1 -1
  170. package/lib/persistence/generators.cjs +36 -0
  171. package/lib/persistence/generators.d.ts +14 -0
  172. package/lib/persistence/generators.js.map +1 -0
  173. package/lib/persistence/index.cjs +1 -0
  174. package/lib/persistence/index.d.ts +1 -0
  175. package/lib/persistence/index.js.map +1 -1
  176. package/lib/persistence/migrations.cjs +7 -8
  177. package/lib/persistence/migrations.d.ts +8 -8
  178. package/lib/persistence/migrations.js.map +1 -1
  179. package/lib/persistence/types.d.ts +38 -20
  180. package/lib/query/Paginator.cjs +4 -4
  181. package/lib/query/Paginator.d.ts +6 -5
  182. package/lib/query/Paginator.js.map +1 -1
  183. package/lib/query/Statement.cjs +34 -21
  184. package/lib/query/Statement.d.ts +9 -8
  185. package/lib/query/Statement.js.map +1 -1
  186. package/lib/ram/RamAdapter.cjs +35 -33
  187. package/lib/ram/RamAdapter.d.ts +22 -31
  188. package/lib/ram/RamAdapter.js.map +1 -1
  189. package/lib/ram/RamPaginator.cjs +5 -3
  190. package/lib/ram/RamPaginator.d.ts +2 -1
  191. package/lib/ram/RamPaginator.js.map +1 -1
  192. package/lib/ram/RamStatement.d.ts +7 -7
  193. package/lib/ram/RamStatement.js.map +1 -1
  194. package/lib/ram/handlers.d.ts +3 -4
  195. package/lib/ram/handlers.js.map +1 -1
  196. package/lib/ram/index.cjs +0 -3
  197. package/lib/ram/index.d.ts +0 -3
  198. package/lib/ram/index.js.map +1 -1
  199. package/lib/ram/types.d.ts +4 -12
  200. package/lib/repository/Repository.cjs +108 -204
  201. package/lib/repository/Repository.d.ts +31 -95
  202. package/lib/repository/Repository.js.map +1 -1
  203. package/lib/repository/decorators.cjs +2 -1
  204. package/lib/repository/decorators.js.map +1 -1
  205. package/lib/repository/utils.cjs +2 -3
  206. package/lib/repository/utils.d.ts +1 -1
  207. package/lib/repository/utils.js.map +1 -1
  208. package/lib/utils/ContextualLoggedClass.cjs +33 -0
  209. package/lib/utils/ContextualLoggedClass.d.ts +16 -0
  210. package/lib/utils/ContextualLoggedClass.js.map +1 -0
  211. package/lib/utils/Services.cjs +159 -0
  212. package/lib/utils/Services.d.ts +50 -0
  213. package/lib/utils/Services.js.map +1 -0
  214. package/lib/utils/decorators.cjs +27 -16
  215. package/lib/utils/decorators.d.ts +1 -9
  216. package/lib/utils/decorators.js.map +1 -1
  217. package/lib/utils/index.cjs +2 -1
  218. package/lib/utils/index.d.ts +2 -1
  219. package/lib/utils/index.js.map +1 -1
  220. package/package.json +1 -1
  221. package/lib/esm/identity/utils.d.ts +0 -24
  222. package/lib/esm/identity/utils.js +0 -44
  223. package/lib/esm/identity/utils.js.map +0 -1
  224. package/lib/esm/ram/RamContext.d.ts +0 -28
  225. package/lib/esm/ram/RamContext.js +0 -30
  226. package/lib/esm/ram/RamContext.js.map +0 -1
  227. package/lib/esm/ram/RamSequence.d.ts +0 -75
  228. package/lib/esm/ram/RamSequence.js +0 -145
  229. package/lib/esm/ram/RamSequence.js.map +0 -1
  230. package/lib/esm/ram/model/RamSequenceModel.js.map +0 -1
  231. package/lib/esm/ram/model/index.d.ts +0 -1
  232. package/lib/esm/ram/model/index.js +0 -2
  233. package/lib/esm/ram/model/index.js.map +0 -1
  234. package/lib/identity/utils.cjs +0 -49
  235. package/lib/identity/utils.d.ts +0 -24
  236. package/lib/identity/utils.js.map +0 -1
  237. package/lib/ram/RamContext.cjs +0 -34
  238. package/lib/ram/RamContext.d.ts +0 -28
  239. package/lib/ram/RamContext.js.map +0 -1
  240. package/lib/ram/RamSequence.cjs +0 -149
  241. package/lib/ram/RamSequence.d.ts +0 -75
  242. package/lib/ram/RamSequence.js.map +0 -1
  243. package/lib/ram/model/RamSequenceModel.js.map +0 -1
  244. package/lib/ram/model/index.cjs +0 -18
  245. package/lib/ram/model/index.d.ts +0 -1
  246. package/lib/ram/model/index.js.map +0 -1
package/README.md CHANGED
@@ -4,6 +4,8 @@
4
4
 
5
5
  Decaf Core provides the foundational building blocks for the Decaf TypeScript ecosystem: strongly-typed models, repository pattern, pluggable persistence adapters, a composable query DSL, and pagination/observer utilities. With decorators and an injectable registry, it wires models to repositories and adapters so you can build data access that is framework-agnostic yet fully typed.
6
6
 
7
+ > Release docs refreshed on 2025-11-26. See [workdocs/reports/RELEASE_NOTES.md](./workdocs/reports/RELEASE_NOTES.md) for ticket summaries.
8
+
7
9
  ![Licence](https://img.shields.io/github/license/decaf-ts/core.svg?style=plastic)
8
10
  ![GitHub language count](https://img.shields.io/github/languages/count/decaf-ts/core?style=plastic)
9
11
  ![GitHub top language](https://img.shields.io/github/languages/top/decaf-ts/core?style=plastic)
@@ -27,7 +29,7 @@ Decaf Core provides the foundational building blocks for the Decaf TypeScript ec
27
29
 
28
30
  Documentation [here](https://decaf-ts.github.io/injectable-decorators/), Test results [here](https://decaf-ts.github.io/injectable-decorators/workdocs/reports/html/test-report.html) and Coverage [here](https://decaf-ts.github.io/injectable-decorators/workdocs/reports/coverage/lcov-report/index.html)
29
31
 
30
- Minimal size: 13.8 KB kb gzipped
32
+ Minimal size: 15.4 KB kb gzipped
31
33
 
32
34
 
33
35
  # Core Package — Detailed Description
@@ -358,6 +360,9 @@ async function injectablesExample() {
358
360
  - builder;
359
361
  - etc;
360
362
 
363
+ ## Release Documentation Hooks
364
+ Stay aligned with the automated release pipeline by reviewing [Release Notes](./workdocs/reports/RELEASE_NOTES.md) and [Dependencies](./workdocs/reports/DEPENDENCIES.md) after trying these recipes (updated on 2025-11-26).
365
+
361
366
 
362
367
  ### Related
363
368
 
package/dist/core.cjs CHANGED
@@ -1,2 +1,2 @@
1
- var e,t;e=this,t=function(e,t,r,a,s,n,o,i){"use strict";var c;function d(){return(e,t,r)=>{if(!r)throw Error("final decorator can only be used on methods");return r?.configurable&&(r.configurable=!1),r}}e.PersistenceKeys=void 0,(c=e.PersistenceKeys||(e.PersistenceKeys={})).INDEX="index",c.UNIQUE="unique",c.ADAPTER="adapter",c.INJECTABLE="decaf_{0}_adapter_for_{1}",c.TABLE="table",c.COLUMN="column",c.METADATA="__metadata",c.OWNERSHIP="ownership",c.CREATED_BY="ownership.created-by",c.UPDATED_BY="ownership.updated-by",c.RELATIONS="__relations",c.RELATION="relation",c.ONE_TO_ONE="relation.one-to-one",c.ONE_TO_MANY="relation.one-to-many",c.MANY_TO_ONE="relation.many-to-one",c.MANY_TO_MANY="relation.many-to-many",c.POPULATE="populate",c.NO_VALIDATE="no-validate",c.MIGRATION="migration";class l extends a.BadRequestError{constructor(e,t=l.name,r=401){super(e,t,r)}}class u extends l{constructor(e,t=u.name){super(e,t,403)}}class p extends a.InternalError{constructor(e){super(e,p.name,503)}}class h{constructor(){this.observers=[]}count(){return this.observers.length}observe(e,t){if(-1!==this.observers.map(e=>e.observer).indexOf(e))throw new a.InternalError("Observer already registered");this.observers.push({observer:e,filter:t})}unObserve(e){const t=this.observers.map(e=>e.observer).indexOf(e);if(-1===t)throw new a.InternalError("Failed to find Observer");this.observers.splice(t,1)}async updateObservers(e,t,r,a,...s){(await Promise.allSettled(this.observers.filter(s=>{const{filter:n}=s;if(!n)return!0;try{return n(t,r,a)}catch(t){return e.error(`Failed to filter observer ${s.observer.toString()}: ${t}`),!1}}).map(e=>{e.observer.refresh(t,r,a,...s)}))).forEach((t,r)=>{"rejected"===t.status&&e.error(`Failed to update observable ${this.observers[r].toString()}: ${t.reason}`)})}}function f(t){if(!(t instanceof s.Model?s.Model.get(t.constructor.name):t))throw new a.InternalError("Unable to find model "+t);return o.Metadata.get(t instanceof s.Model?t.constructor:t,e.PersistenceKeys.TABLE)||(t instanceof s.Model?t.constructor.name:t.name)}function y(t,r){return o.Metadata.get(t instanceof s.Model?t.constructor:t,o.Metadata.key(e.PersistenceKeys.COLUMN,r))||r}function g(e,...t){return[f(e),...t].join("_")}class m extends a.InternalError{constructor(e){super(e,m.name,500)}}class b extends a.InternalError{constructor(e,t=b.name){super(e,t,500)}}class w extends b{constructor(e){super(e,w.name)}}const O=o.Decoration.flavourResolver.bind(o.Decoration);o.Decoration.flavourResolver=e=>{try{const t=O(e);if(t&&t!==o.DefaultFlavour)return t;const r="function"==typeof e?e:e?.constructor,a=r&&"function"==typeof o.Metadata.registeredFlavour?o.Metadata.registeredFlavour(r):void 0;if(a&&a!==o.DefaultFlavour)return a;const s=v._currentFlavour;if(s){const e=v._cache?.[s];return e?.flavour?e.flavour:s}}catch(e){return o.DefaultFlavour}};class v extends n.LoggedClass{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!v._baseRepository)throw new a.InternalError("This should be overridden when necessary. Otherwise it will be replaced lazily");return v._baseRepository}async shutdownProxies(e){if(this.proxies){if(e&&!(e in this.proxies))throw new a.InternalError("No proxy found for "+e);if(e)try{await this.proxies[e].shutdown(),delete this.proxies[e]}catch(t){this.log.error(`Failed to shutdown proxied adapter ${e}: ${t}`)}else for(const e in this.proxies){try{await this.proxies[e].shutdown()}catch(t){this.log.error(`Failed to shutdown proxied adapter ${e}: ${t}`);continue}delete this.proxies[e]}}}async shutdown(){await this.shutdownProxies(),this.dispatch&&await this.dispatch.close()}constructor(e,t,r){if(super(),this._config=e,this.flavour=t,this._alias=r,this.Context=a.Context,this.alias in v._cache)throw new a.InternalError(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);v._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),v._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),v._currentFlavour=this.alias)}Dispatch(){return new v._baseDispatch}ObserverHandler(){return new h}isReserved(e){return!e}async initialize(...e){}async flags(e,t,r,...s){return Object.assign({},a.DefaultRepositoryFlags,r,{affectedTables:f(t),writeOperation:e!==a.OperationKeys.READ,timestamp:new Date,operation:e,ignoredValidationProperties:o.Metadata.validationExceptions(t,e)})}async context(e,t,r,...a){this.log.for(this.context).debug(`Creating new context for ${e} operation on ${r.name} model with flag overrides: ${JSON.stringify(t)}`);const s=await this.flags(e,r,t,...a);return(new this.Context).accumulate(s)}prepare(t,r,...s){const n=this.log.for(this.prepare),o=t.segregate(),i=Object.entries(o.model).reduce((e,[r,s])=>{if(void 0===s)return e;const n=y(t,r);if(this.isReserved(n))throw new a.InternalError(`Property name ${n} is reserved`);return e[n]=s,e},{});return t[e.PersistenceKeys.METADATA]&&(n.silly("Passing along persistence metadata for "+t[e.PersistenceKeys.METADATA]),Object.defineProperty(i,e.PersistenceKeys.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:t[e.PersistenceKeys.METADATA]})),{record:i,id:t[r],transient:o.transient}}revert(t,r,n,o,i,...c){const d=this.log.for(this.revert),l={};l[n]=o;const u="string"==typeof r?s.Model.build(l,r):new r(l);d.silly(`Rebuilding model ${u.constructor.name} id ${o}`);const p=t[e.PersistenceKeys.METADATA],h=Object.keys(u).reduce((e,r)=>(r===n||(e[r]=t[y(e,r)]),e),u);return i&&(d.verbose("re-adding transient properties: "+Object.keys(i).join(", ")),Object.entries(i).forEach(([e,t])=>{if(e in h)throw new a.InternalError(`Transient property ${e} already exists on model ${u.constructor.name}. should be impossible`);h[e]=t})),p&&(d.silly(`Passing along ${this.flavour} persistence metadata for ${u.constructor.name} id ${o}: ${p}`),Object.defineProperty(h,e.PersistenceKeys.METADATA,{enumerable:!1,configurable:!1,writable:!1,value:p})),h}async createAll(e,t,r,...s){if(t.length!==r.length)throw new a.InternalError("Ids and models must have the same length");const n=this.log.for(this.createAll);return n.verbose(`Creating ${t.length} entries ${e} table`),n.debug("pks: "+t),Promise.all(t.map((t,a)=>this.create(e,t,r[a],...s)))}async readAll(e,t,...r){const a=this.log.for(this.readAll);return a.verbose(`Reading ${t.length} entries ${e} table`),a.debug("pks: "+t),Promise.all(t.map(t=>this.read(e,t,...r)))}async updateAll(e,t,r,...s){if(t.length!==r.length)throw new a.InternalError("Ids and models must have the same length");const n=this.log.for(this.updateAll);return n.verbose(`Updating ${t.length} entries ${e} table`),n.debug("pks: "+t),Promise.all(t.map((t,a)=>this.update(e,t,r[a],...s)))}async deleteAll(e,t,...r){const a=this.log.for(this.createAll);return a.verbose(`Deleting ${t.length} entries ${e} table`),a.debug("pks: "+t),Promise.all(t.map(t=>this.delete(e,t,...r)))}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1}),this.observerHandler.observe(e,t),this.log.for(this.observe).verbose("Registering new observer "+e.toString()),this.dispatch||(this.log.for(this.observe).info("Creating dispatch for "+this.alias),this.dispatch=this.Dispatch(),this.dispatch.observe(this))}unObserve(e){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(e),this.log.for(this.unObserve).verbose(`Observer ${e.toString()} removed`)}async updateObservers(e,t,r,...s){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");this.log.for(this.updateObservers).verbose(`Updating ${this.observerHandler.count()} observers for adapter ${this.alias}`),await this.observerHandler.updateObservers(this.log,e,t,r,...s)}async refresh(e,t,r,...a){return this.updateObservers(e,t,r,...a)}toString(){return this.flavour+" persistence Adapter"}static flavourOf(e){return o.Metadata.flavourOf(e)}static get currentFlavour(){if(!v._currentFlavour)throw new a.InternalError("No persistence flavour set. Please initialize your adapter");return v._currentFlavour}static get current(){return v.get(this.currentFlavour)}static get(e){if(!e)return v.get(this._currentFlavour);if(e in this._cache)return this._cache[e];throw new a.InternalError(`No Adapter registered under ${e}.`)}static setCurrent(e){this._currentFlavour=e}static models(e){try{return o.Metadata.flavouredAs(e)}catch(e){throw new a.InternalError(e)}}static decoration(){}get client(){return this._client||(this._client=this.getClient()),this._client}for(e,...t){this.proxies||(this.proxies={});const r=`${this.alias} - ${s.hashObj(e)}`;if(r in this.proxies)return this.proxies[r];let a;const n=new Proxy(this,{get:(t,r,s)=>{if("_config"===r){const a=Reflect.get(t,r,s);return Object.assign({},a,e)}return"_client"===r?a:Reflect.get(t,r,s)},set:(e,t,r,s)=>"_client"===t?(a=r,!0):Reflect.set(e,t,r,s)});return this.proxies[r]=n,n}migrations(){return o.Metadata.migrationsFor(this)}async migrate(e=this.migrations()){for(const t of e)try{const e=new t;await e.up(this,this,this.log),await e.down(this,this,this.log)}catch(e){throw new b(e)}}}var _,E;r.__decorate([d(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String]),r.__metadata("design:returntype",Promise)],v.prototype,"shutdownProxies",null),r.__decorate([d(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,Object,Object,Object]),r.__metadata("design:returntype",Promise)],v.prototype,"context",null),r.__decorate([d(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",void 0)],v.prototype,"observe",null),r.__decorate([d(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],v.prototype,"unObserve",null),r.__decorate([d(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],v.prototype,"client",null),e.OrderDirection=void 0,(_=e.OrderDirection||(e.OrderDirection={})).ASC="asc",_.DSC="desc",e.Cascade=void 0,(E=e.Cascade||(e.Cascade={})).CASCADE="cascade",E.NONE="none";const A={update:e.Cascade.CASCADE,delete:e.Cascade.NONE};class D{get log(){return this.logger||(this.logger=n.Logging.for(this)),this.logger}constructor(e){this.options=e}static pk(e){return g(e,"pk")}static parseValue(e,t){switch(e){case"Number":return"string"==typeof t?parseInt(t):"number"==typeof t?t:BigInt(t);case"BigInt":return BigInt(t);case void 0:case"String":return t;default:throw new m(`Unsupported sequence type: ${e} for adapter ${this}`)}}}var M,P;e.Operator=void 0,(M=e.Operator||(e.Operator={})).EQUAL="EQUAL",M.DIFFERENT="DIFFERENT",M.BIGGER="BIGGER",M.BIGGER_EQ="BIGGER_EQ",M.SMALLER="SMALLER",M.SMALLER_EQ="SMALLER_EQ",M.NOT="NOT",M.IN="IN",M.REGEXP="REGEXP",e.GroupOperator=void 0,(P=e.GroupOperator||(e.GroupOperator={})).AND="AND",P.OR="OR";class T extends a.InternalError{constructor(e){super(e,T.name,500)}}class I extends a.InternalError{constructor(e){super(e,I.name,500)}}class C extends s.Model{constructor(e,t,r){super(),this.attr1=void 0,this.operator=void 0,this.comparison=void 0,this.attr1=e,this.operator=t,this.comparison=r}and(e){return C.and(this,e)}or(e){return C.or(this,e)}not(t){return new C(this,e.Operator.NOT,t)}hasErrors(...t){const r=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof C)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(e.Operator).indexOf(this.operator))return{operator:{condition:t}}}if(this.attr1 instanceof C){if(!(this.comparison instanceof C)&&this.operator!==e.Operator.NOT)return{comparison:{condition:t}};if(-1===Object.values(e.GroupOperator).indexOf(this.operator)&&this.operator!==e.Operator.NOT)return{operator:{condition:t}}}},a=super.hasErrors(...t);return this.isAsync()?(async()=>await Promise.resolve(a)??r())():a??r()}static and(t,r){return C.group(t,e.GroupOperator.AND,r)}static or(t,r){return C.group(t,e.GroupOperator.OR,r)}static group(e,t,r){return new C(e,t,r)}static attribute(e){return(new C.Builder).attribute(e)}static attr(e){return this.attribute(e)}static{this.Builder=class{constructor(){this.attr1=void 0,this.operator=void 0,this.comparison=void 0}attribute(e){return this.attr1=e,this}attr(e){return this.attribute(e)}eq(t){return this.setOp(e.Operator.EQUAL,t)}dif(t){return this.setOp(e.Operator.DIFFERENT,t)}gt(t){return this.setOp(e.Operator.BIGGER,t)}lt(t){return this.setOp(e.Operator.SMALLER,t)}gte(t){return this.setOp(e.Operator.BIGGER_EQ,t)}lte(t){return this.setOp(e.Operator.SMALLER_EQ,t)}in(t){return this.setOp(e.Operator.IN,t)}regexp(t){return this.setOp(e.Operator.REGEXP,RegExp(t).source)}setOp(e,t){return this.operator=e,this.comparison=t,this.build()}build(){try{return new C(this.attr1,this.operator,this.comparison)}catch(e){throw new T(e)}}}}static builder(){return new C.Builder}}r.__decorate([s.required(),r.__metadata("design:type",Object)],C.prototype,"attr1",void 0),r.__decorate([s.required(),r.__metadata("design:type",String)],C.prototype,"operator",void 0),r.__decorate([s.required(),r.__metadata("design:type",Object)],C.prototype,"comparison",void 0);class N extends a.Repository{static{this._cache={}}get log(){return this.logger||(this.logger=this.adapter.log.for(this.toString())),this.logger}get adapter(){if(!this._adapter)throw new a.InternalError("No adapter found for this repository. did you use the @uses decorator or pass it in the constructor?");return this._adapter}get tableName(){return this._tableName||(this._tableName=N.table(this.class)),this._tableName}get pkProps(){return super.pkProps}constructor(e,t,...r){super(t),this.observers=[],e&&(this._adapter=e),t&&(N.register(t,this,this.adapter.alias),e)&&o.Metadata.get(t,o.DecorationKeys.FLAVOUR)===o.DefaultFlavour&&o.uses(e.flavour)(t),[this.createAll,this.readAll,this.updateAll,this.deleteAll].forEach(e=>{const t=e.name;a.wrapMethodWithContext(this,this[t+"Prefix"],e,this[t+"Suffix"])})}override(e){return this.log.for(this.override).debug("Overriding repository flags with "+JSON.stringify(e)),new Proxy(this,{get:(t,r,a)=>{const s=Reflect.get(t,r,a);return"_overrides"!==r?s:Object.assign({},s,e)}})}for(e,...t){return new Proxy(this,{get:(r,a,s)=>"adapter"===a?this.adapter.for(e,...t):Reflect.get(r,a,s)})}ObserverHandler(){return new h}async createPrefix(e,...t){const r=await a.Context.args(a.OperationKeys.CREATE,this.class,t,this.adapter,this._overrides||{});e=new this.class(e),await a.enforceDBDecorators(this,r.context,e,a.OperationKeys.CREATE,a.OperationKeys.ON);const s=await Promise.resolve(e.hasErrors(...r.context.get("ignoredValidationProperties")||[]));if(s)throw new a.ValidationError(s.toString());return[e,...r.args]}async create(e,...t){let r,{record:a,id:s,transient:n}=this.adapter.prepare(e,this.pk);return a=await this.adapter.create(this.tableName,s,a,...t),t.length&&(r=t[t.length-1]),this.adapter.revert(a,this.class,this.pk,s,r&&r.get("rebuildWithTransient")?n:void 0)}async createSuffix(e,t){return super.createSuffix(e,t)}async createAll(e,...t){if(!e.length)return e;const r=e.map(e=>this.adapter.prepare(e,this.pk)),a=r.map(e=>e.id);let s=r.map(e=>e.record);return s=await this.adapter.createAll(this.tableName,a,s,...t),s.map((e,t)=>this.adapter.revert(e,this.class,this.pk,a[t]))}async createAllPrefix(e,...t){const r=await a.Context.args(a.OperationKeys.CREATE,this.class,t,this.adapter,this._overrides||{});if(!e.length)return[e,...r.args];const s=N.getSequenceOptions(e[0]);let n=[];s.type?(s.name||(s.name=D.pk(e[0])),n=await(await this.adapter.Sequence(s)).range(e.length)):n=e.map((e,t)=>{if(void 0===e[this.pk])throw new a.InternalError("Primary key is not defined for model in position "+t);return e[this.pk]}),e=await Promise.all(e.map(async(e,t)=>(e=new this.class(e),s.type&&(e[this.pk]="String"!==s.type||s.generated?n[t]:""+e[this.pk]),await a.enforceDBDecorators(this,r.context,e,a.OperationKeys.CREATE,a.OperationKeys.ON),e)));const o=r.context.get("ignoredValidationProperties")||[],i=(await Promise.all(e.map(e=>Promise.resolve(e.hasErrors(...o))))).reduce((e,t,r)=>(t&&(e="string"==typeof e?e+`\n - ${r}: ${t.toString()}`:` - ${r}: ${t.toString()}`),e),void 0);if(i)throw new a.ValidationError(i);return[e,...r.args]}async readPrefix(e,...t){const r=await a.Context.args(a.OperationKeys.READ,this.class,t,this.adapter,this._overrides||{}),s=new this.class;return s[this.pk]=e,await a.enforceDBDecorators(this,r.context,s,a.OperationKeys.READ,a.OperationKeys.ON),[e,...r.args]}async read(e,...t){const r=await this.adapter.read(this.tableName,e,...t);return this.adapter.revert(r,this.class,this.pk,e)}async readAllPrefix(e,...t){const r=await a.Context.args(a.OperationKeys.READ,this.class,t,this.adapter,this._overrides||{});return await Promise.all(e.map(async e=>{const t=new this.class;return t[this.pk]=e,a.enforceDBDecorators(this,r.context,t,a.OperationKeys.READ,a.OperationKeys.ON)})),[e,...r.args]}async readAll(e,...t){return(await this.adapter.readAll(this.tableName,e,...t)).map((t,r)=>this.adapter.revert(t,this.class,this.pk,e[r]))}async update(e,...t){let{record:r,id:a,transient:s}=this.adapter.prepare(e,this.pk);return r=await this.adapter.update(this.tableName,a,r,...t),this.adapter.revert(r,this.class,this.pk,a,s)}async updatePrefix(e,...t){const r=await a.Context.args(a.OperationKeys.UPDATE,this.class,t,this.adapter,this._overrides||{}),s=e[this.pk];if(!s)throw new a.InternalError("No value for the Id is defined under the property "+this.pk);const n=await this.read(s,...r.args);e=this.merge(n,e),await a.enforceDBDecorators(this,r.context,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,n);const o=await Promise.resolve(e.hasErrors(n,...N.relations(this.class),...r.context.get("ignoredValidationProperties")||[]));if(o)throw new a.ValidationError(o.toString());return N.getMetadata(n)&&(N.getMetadata(e)||N.setMetadata(e,N.getMetadata(n))),[e,...r.args]}async updateAll(e,...t){const r=e.map(e=>this.adapter.prepare(e,this.pk));return(await this.adapter.updateAll(this.tableName,r.map(e=>e.id),r.map(e=>e.record),...t)).map((e,t)=>this.adapter.revert(e,this.class,this.pk,r[t].id))}async updateAllPrefix(e,...t){const r=await a.Context.args(a.OperationKeys.UPDATE,this.class,t,this.adapter,this._overrides||{}),s=e.map(e=>{const t=e[this.pk];if(!t)throw new a.InternalError("missing id on update operation");return t}),n=await this.readAll(s,...r.args);e=e.map((e,t)=>(e=this.merge(n[t],e),N.getMetadata(n[t])&&(N.getMetadata(e)||N.setMetadata(e,N.getMetadata(n[t]))),e)),await Promise.all(e.map((e,t)=>a.enforceDBDecorators(this,r.context,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,n[t])));const o=r.context.get("ignoredValidationProperties")||[],i=(await Promise.all(e.map((e,t)=>Promise.resolve(e.hasErrors(n[t],e,...o))))).reduce((e,t,r)=>(t&&(e="string"==typeof e?e+`\n - ${r}: ${t.toString()}`:` - ${r}: ${t.toString()}`),e),void 0);if(i)throw new a.ValidationError(i);return e.forEach((e,t)=>{N.getMetadata(n[t])&&(N.getMetadata(e)||N.setMetadata(e,N.getMetadata(n[t])))}),[e,...r.args]}async deletePrefix(e,...t){const r=await a.Context.args(a.OperationKeys.DELETE,this.class,t,this.adapter,this._overrides||{}),s=await this.read(e,...r.args);return await a.enforceDBDecorators(this,r.context,s,a.OperationKeys.DELETE,a.OperationKeys.ON),[e,...r.args]}async delete(e,...t){const r=await this.adapter.delete(this.tableName,e,...t);return this.adapter.revert(r,this.class,this.pk,e)}async deleteAllPrefix(e,...t){const r=await a.Context.args(a.OperationKeys.DELETE,this.class,t,this.adapter,this._overrides||{}),s=await this.readAll(e,...r.args);return await Promise.all(s.map(async e=>a.enforceDBDecorators(this,r.context,e,a.OperationKeys.DELETE,a.OperationKeys.ON))),[e,...r.args]}async deleteAll(e,...t){return(await this.adapter.deleteAll(this.tableName,e,...t)).map((t,r)=>this.adapter.revert(t,this.class,this.pk,e[r]))}select(e){return this.adapter.Statement().select(e).from(this.class)}async query(t,r,a=e.OrderDirection.ASC,s,n){const o=[r,a],i=this.select().where(t).orderBy(o);return s&&i.limit(s),n&&i.offset(n),i.execute()}attr(e){return C.attr(e)}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const r=this.log.for(this.observe),a=N.table(this.class);this.adapter.observe(this,e=>a===e),r.verbose(`now observing ${this.adapter} filtering on table === ${a}`),this.observerHandler.observe(e,t),r.verbose("Registered new observer "+e.toString())}unObserve(e){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(e),this.log.for(this.unObserve).verbose(`Observer ${e.toString()} removed`),this.observerHandler.count()||(this.log.verbose(`No more observers registered for ${this.adapter}, unsubscribing`),this.adapter.unObserve(this),this.log.verbose("No longer observing adapter "+this.adapter.flavour))}async updateObservers(e,t,r,...s){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");this.log.for(this.updateObservers).verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(this.log,e,t,Array.isArray(r)?r.map(e=>D.parseValue(this.pkProps?.type,e)):D.parseValue(this.pkProps?.type,r),...s)}async refresh(e,t,r,...a){return this.updateObservers(e,t,r,...a)}static forModel(t,r,...s){let n;const i=r||o.Metadata.flavourOf(t)||v.currentFlavour;try{n=this.get(t,i)}catch(e){n=void 0}if(n instanceof N)return n;const c=r||o.Metadata.flavourOf(t)||n&&o.Metadata.get(n,e.PersistenceKeys.ADAPTER)||v.currentFlavour,d=c?v.get(c):void 0;if(!d)throw new a.InternalError("No registered persistence adapter found flavour "+c);return n=n||d.repository(),new n(d,t,...s)}static get(e,t){const r=N.table(e);let s=r;if(t&&(s=[r,t].join(a.DefaultSeparator)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new a.InternalError("Could not find repository registered under "+r)}static register(e,t,r){let s=N.table(e);if(r&&(s=[s,r].join(a.DefaultSeparator)),s in this._cache&&this._cache[s]instanceof N)throw new a.InternalError(s+" already has a registered instance");this._cache[s]=t}static setMetadata(t,r){Object.defineProperty(t,e.PersistenceKeys.METADATA,{enumerable:!1,configurable:!0,writable:!1,value:r})}static getMetadata(t){const r=Object.getOwnPropertyDescriptor(t,e.PersistenceKeys.METADATA);return r?r.value:void 0}static removeMetadata(t){Object.getOwnPropertyDescriptor(t,e.PersistenceKeys.METADATA)&&delete t[e.PersistenceKeys.METADATA]}static getSequenceOptions(e){const t=s.Model.pk(e.constructor),r=o.Metadata.key(a.DBKeys.ID,t),n=o.Metadata.get(e.constructor,r);if(!n)throw new a.InternalError("No sequence options defined for model. did you use the @pk decorator?");return n}static indexes(t){const r=o.Metadata.get(t instanceof s.Model?t.constructor:t,e.PersistenceKeys.INDEX);return Object.keys(r||{}).reduce((t,a)=>(t[a]={[e.PersistenceKeys.INDEX]:r[a]},t),{})}static relations(e){return o.Metadata.relations(e instanceof s.Model?e.constructor:e)||[]}static table(e){return f(e)}static column(e,t){return y(e,t)}}function x(t,r){if(!(r||(r=o.Decoration.flavourResolver(t instanceof s.Model?t.constructor:t))&&r!==o.DefaultFlavour))throw new a.InternalError("Could not retrieve flavour from model "+(t instanceof s.Model?t.constructor.name:t.name));return s.sf(e.PersistenceKeys.INJECTABLE,r,f(t))}r.__decorate([d(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",void 0)],N.prototype,"observe",null),r.__decorate([d(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],N.prototype,"unObserve",null),v&&(v._baseRepository=N);class R extends t.InjectableRegistryImp{get log(){return this.logger||(this.logger=n.Logging.for(this)),this.logger}constructor(){super()}get(r,a){const n=this.log.for(this.get);let i;try{i=super.get(r)}catch{}if(!i){let c;if("function"==typeof r?c=r:"symbol"!=typeof r&&"string"!=typeof r||(c=s.Model.get(r.toString())),!c)return;const d=e.PersistenceKeys.ADAPTER,l=a||o.Metadata.get(c,d);try{let e=l;try{l&&v.get(l)}catch{const t=v.current;t&&t.flavour===l&&(e=t.alias)}if(i=N.forModel(c,e),i instanceof N)return i;const r=l||o.Metadata.get(i.constructor,d)||o.Metadata.get(c,d);t.Injectables.register(i,x(c,r))}catch(e){n.debug("No registered repository or adapter found. falling back to default adapter. Error: "+(e?.message||JSON.stringify(e)));const t=N.get(c,l);if("function"==typeof t){const e=l?v.get(l):v.current;if(!e)return;return new t(e,c)}}}return i}}class B extends n.LoggedClass{constructor(){super()}async initialize(){if(!this.adapter)return void this.log.verbose("No adapter observed for dispatch; skipping initialization");const e=this.adapter;[a.OperationKeys.CREATE,a.OperationKeys.UPDATE,a.OperationKeys.DELETE,a.BulkCrudOperationKeys.CREATE_ALL,a.BulkCrudOperationKeys.UPDATE_ALL,a.BulkCrudOperationKeys.DELETE_ALL].forEach(t=>{if(!e[t])throw new a.InternalError(`Method ${t} not found in ${e.alias} adapter to bind Observables Dispatch`);let r=Object.getOwnPropertyDescriptor(e,t),s=e;for(;!r&&s!==Object.prototype;)s=Object.getPrototypeOf(s),r=Object.getOwnPropertyDescriptor(s,t);r&&r.writable?e[t]=new Proxy(e[t],{apply:async(e,r,s)=>{const[n,o]=s,i=await e.apply(r,s);return this.updateObservers(n,(e=>{switch(e){case a.BulkCrudOperationKeys.CREATE_ALL:return a.OperationKeys.CREATE;case a.BulkCrudOperationKeys.UPDATE_ALL:return a.OperationKeys.UPDATE;case a.BulkCrudOperationKeys.DELETE_ALL:return a.OperationKeys.DELETE;default:return e}})(t),o).then(()=>{this.log.verbose(`Observer refresh dispatched by ${t} for ${n}`),this.log.debug("pks: "+o)}).catch(e=>this.log.error(`Failed to dispatch observer refresh for ${t} on ${n}: ${e}`)),i}}):this.log.error(`Could not find method ${t} to bind Observables Dispatch`)})}async close(){}observe(e){if(!(e instanceof v))throw new m("Only Adapters can be observed by dispatch");this.adapter=e,this.models=v.models(this.adapter.alias),this.initialize().then(()=>this.log.verbose(`Dispatch initialized for ${this.adapter.alias} adapter`))}unObserve(e){if(this.adapter!==e)throw new m("Only the adapter that was used to observe can be unobserved");this.adapter=void 0}async updateObservers(e,t,r){if(this.adapter)try{await this.adapter.refresh(e,t,r)}catch(e){throw new a.InternalError("Failed to refresh dispatch: "+e)}else this.log.verbose(`No adapter observed for dispatch; skipping observer update for ${e}:${t}`)}}function K(e,t,r,a){const s=async function(...e){let a;try{a=await Promise.resolve(r.call(this,...e))}catch(e){if(e instanceof w)return;throw e}return Promise.resolve(t.apply(this,a))}.bind(e),n=a||t.name;Object.defineProperty(s,"name",{enumerable:!0,configurable:!0,writable:!1,value:n}),e[n]=s}v&&(v._baseDispatch=B);class $ extends n.LoggedClass{constructor(){super(),this.transaction=!0,[this.up,this.down].forEach(e=>{const t=e.name;K(this,e,this.prefix(t))})}get adapter(){const t=o.Metadata.get(this.constructor,e.PersistenceKeys.MIGRATION);if(!t)throw new a.InternalError("No migration metadata for "+this.constructor.name);const r=t.flavour;return v.get(r)}async enforceRules(t,r,a){const s=o.Metadata.get(this.constructor,e.PersistenceKeys.MIGRATION)?.rules;if(!s||!s.length)return!0;let n;for(const e of s)if(n=a.for(e),!await e(t,r,n))return!1;return!0}prefix(e){return async function(t){let r;t instanceof v?r=this.getQueryRunner(t.client):(r=t,t=this.adapter);const a=this.log.for(e);if(!await this.enforceRules(r,t,a))throw a.verbose(`Skipping migration ${this.constructor.name} due to rules`),new w("Migration skipped for rule enforcement");return[r,t,a]}.bind(this)}}o.Metadata.validationExceptions=((t,r)=>{const a=o.Metadata.get(t,e.PersistenceKeys.NO_VALIDATE);return a?Object.entries(a).filter(([,e])=>e.includes(r)).map(([e])=>e):[]}).bind(o.Metadata),s.Model.shouldValidateNestedHandler=((t,r)=>{const a=o.Metadata.get(t.constructor);if(!a)return!1;const n=a[e.PersistenceKeys.RELATIONS],i=a[e.PersistenceKeys.RELATION];if(Array.isArray(n)&&n?.includes(r)){const e=Object.keys(i)[0],a=s.Model.isPropertyModel(t,r);return i[e]?.class!==a}return!0}).bind(s.Model),o.Metadata.migrationsFor=(t=>{if(!(t=t??v.current))throw new a.InternalError("Could not get adapter for migrations");return o.Metadata.innerGet(Symbol.for(e.PersistenceKeys.MIGRATION),t.alias).map(e=>e.class)}).bind(o.Metadata),o.Metadata.relations=((t,r)=>{const s=o.Metadata.get(t,e.PersistenceKeys.RELATIONS);if(s){if(!r)return Object.keys(s);if(!s[r])throw new a.InternalError("No relations metadata found for property "+r);return s[r]}}).bind(o.Metadata),s.Model.relations=(e,t)=>o.Metadata.relations(e,t)||[];class k extends a.InternalError{constructor(e){super(e,k.name,500)}}const j={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},L=j,F={type:"Number",generated:!0,startWith:0,incrementBy:1,cycle:!1},q=Object.assign({},F,{type:"BigInt"});async function U(e,t,r,n){if(!n){const t=s.Model.get(e.constructor.name);if(!t)throw new a.InternalError("Could not find model "+e.constructor.name);n=N.forModel(t,r)}if(void 0===e[n.pk])return n.create(e,t);try{return n.update(e,t)}catch(r){if(!(r instanceof a.NotFoundError))throw r;return n.create(e,t)}}async function G(e,t,r,o){const i=o[r];if(!i)return;if("object"!=typeof i){const t=ee(o,r,this.adapter.alias),a=await t.read(i);return await X(e,o,r,i,a),void(o[r]=i)}const c=n.isClass(t.class)?t.class:t.class();if(!c)throw new a.InternalError("Could not find model "+t.class);const d=N.forModel(c,this.adapter.alias),l=await d.create(i),u=s.Model.pk(l);await X(e,o,r,l[u],l),o[r]=l[u]}async function H(t,r,a,n){const o=n[a];if(!o)return;if(r.cascade.update!==e.Cascade.CASCADE)return;if("object"!=typeof o){const e=ee(n,a,this.adapter.alias),r=await e.read(o);return await X(t,n,a,o,r),void(n[a]=o)}const i=await U(n[a],t,this.adapter.alias),c=s.Model.pk(i);await X(t,n,a,i[c],i),n[a]=i[c]}async function V(t,r,a,n){const o=n[a];if(!o)return;if(r.cascade.update!==e.Cascade.CASCADE)return;const i=ee(n,a,this.adapter.alias);let c;c=o instanceof s.Model?await i.delete(n[a][i.pk]):await i.delete(n[a]),await X(t,n,a,c[i.pk],c)}async function Q(e,t,r,n){const o=n[r];if(!o||!o.length)return;const i=typeof o[0];if(!o.every(e=>typeof e===i))throw new a.InternalError(`Invalid operation. All elements of property ${r} must match the same type.`);const c=new Set([...o]);if("object"!==i){const t=ee(n,r,this.adapter.alias);for(const a of c){const s=await t.read(a);await X(e,n,r,a,s)}return void(n[r]=[...c])}const d=s.Model.pk(o[0]),l=new Set;for(const t of o){const a=await U(t,e,this.adapter.alias);await X(e,n,r,a[d],a),l.add(a[d])}n[r]=[...l]}async function Y(t,r,a,s){const{cascade:n}=r;if(n.update===e.Cascade.CASCADE)return Q.call(this,t,r,a,s)}async function z(t,r,s,n){if(r.cascade.delete!==e.Cascade.CASCADE)return;const o=n[s];if(!o||!o.length)return;const i=typeof o[0];if(!o.every(e=>typeof e===i))throw new a.InternalError(`Invalid operation. All elements of property ${s} must match the same type.`);const c="object"===i,d=c?N.forModel(o[0],this.adapter.alias):ee(n,s,this.adapter.alias),l=new Set([...c?o.map(e=>e[d.pk]):o]);for(const e of l.values()){const r=await d.delete(e);await X(t,n,s,e,r)}n[s]=[...l]}function W(t,r,a){return[e.PersistenceKeys.POPULATE,t,r,a].join(".")}async function X(e,t,r,a,s){const n=W(t.constructor.name,r,a);return e.accumulate({[n]:s})}async function J(e,t,r,s){if(!t.populate)return;const n=s[r],o=Array.isArray(n);if(void 0===n||o&&0===n.length)return;const i=await(async(e,t,r,s,n)=>{let o,i;const c=[];for(const d of s){o=W(t.constructor.name,r,d);try{i=await e.get(o)}catch(e){const s=ee(t,r,n);if(!s)throw new a.InternalError("Could not find repo");i=await s.read(d)}c.push(i)}return c})(e,s,r,o?n:[n],this.adapter.alias);s[r]=o?i:i[0]}const Z=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function ee(e,t,r){if(!e)throw Error("No model was provided to get repository");let n;if(Array.isArray(e[t])||e[t]instanceof Set){const r=o.Metadata.get(e instanceof s.Model?e.constructor:e,o.Metadata.key(s.ValidationKeys.REFLECT,t,s.ValidationKeys.LIST))?.clazz;if(!r)throw new a.InternalError("Failed to find types decorators for property "+t);n=(Array.isArray(r)?[...r]:[r]).map(e=>"function"!=typeof e||e.name?e:e())}else n=o.Metadata.getPropDesignTypes(e instanceof s.Model?e.constructor:e,t)?.designTypes;const i=n?.find(e=>!Z.includes((""+e.name).toLowerCase()));return N.forModel(i,r)}function te(t){return o.Decoration.for(e.PersistenceKeys.TABLE).define({decorator:t=>r=>o.metadata(e.PersistenceKeys.TABLE,t||r.name.toLowerCase())(r),args:[t]}).apply()}function re(t,r,a){return o.Decoration.for(e.PersistenceKeys.INDEX).define({decorator:(t,r,a)=>(s,n)=>("string"==typeof t&&(a=t,t=void 0,r=void 0),"string"==typeof r&&(a=r,r=void 0),!r&&t&&t.find(t=>![e.OrderDirection.ASC,e.OrderDirection.DSC].includes(t))&&(r=t,t=void 0),o.propMetadata(o.Metadata.key(`${e.PersistenceKeys.INDEX}${r&&r?.length?"."+r.join("."):""}`,n),{directions:t,compositions:r,name:a})(s,n)),args:[t,r,a]}).apply()}async function ae(e,t,r,s){if(s[r]&&(await this.select().where(C.attribute(r).eq(s[r])).execute()).length)throw new a.ConflictError(`model already exists with property ${r} equal to ${JSON.stringify(s[r],void 0,2)}`)}async function se(e,t,r,a){throw new l("This adapter does not support user identification")}function ne(){return a.timestamp([a.OperationKeys.CREATE])}function oe(){return a.timestamp()}function ie(...t){return(r,a)=>{const s=o.Metadata.get(r,o.Metadata.key(e.PersistenceKeys.NO_VALIDATE,a))||[],n=[...new Set([...s,...t])];return o.apply(o.metadata(o.Metadata.key(e.PersistenceKeys.NO_VALIDATE,a),n))(r,a)}}function ce(t,r){return o.Decoration.for(e.PersistenceKeys.RELATIONS).define({decorator:(t,r)=>(a,s)=>(o.propMetadata(t,r)(a,s),o.propMetadata(o.Metadata.key(e.PersistenceKeys.RELATIONS,s),Object.assign({},r,{key:t}))(a,s)),args:[t,r]}).apply()}async function de(e,t,r,s){if(!t.type||!t.generated||s[r])return;let n;t.name||(t.name=g(s,"pk"));try{n=await this.adapter.Sequence(t)}catch(e){throw new a.InternalError(`Failed to instantiate Sequence ${t.name}: ${e}`)}const o=await n.next();Object.defineProperty(s,r,{enumerable:!0,writable:!1,configurable:!0,value:o})}function le(t=L){t=Object.assign({},L,t,{generated:!(!t.type||void 0!==t.generated)||t.generated||L.generated});const r=a.DBKeys.ID;return o.Decoration.for(r).define({decorator:(t,r)=>(n,i)=>o.apply(re([e.OrderDirection.ASC,e.OrderDirection.DSC]),s.required(),a.readonly(),o.propMetadata(o.Metadata.key(a.DBKeys.ID,i),t),a.onCreate(de,t,r))(n,i),args:[t,{priority:60}]}).apply()}class ue extends s.Model{constructor(e){super(e)}}r.__decorate([ne(),r.__metadata("design:type",Date)],ue.prototype,"createdOn",void 0),r.__decorate([oe(),r.__metadata("design:type",Date)],ue.prototype,"updatedOn",void 0);class pe extends n.LoggedClass{get current(){return this._currentPage}get total(){return this._totalPages}get count(){return this._recordCount}get statement(){return this._statement||(this._statement=this.prepare(this.query)),this._statement}constructor(e,t,r,a){super(),this.adapter=e,this.query=t,this.size=r,this.clazz=a}async next(){return this.page(this.current+1)}async previous(){return this.page(this.current-1)}validatePage(e){if(1>e||!Number.isInteger(e))throw new I("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&e>this._totalPages)throw new I(`Only ${this._totalPages} are available. Cannot go to page ${e}`);return e}}var he,fe,ye,ge,me;class be extends n.LoggedClass{constructor(e){super(),this.adapter=e}get log(){return this.adapter.log.for(be)}select(e){return Object.defineProperty(this,"selectSelector",{value:e,writable:!1}),this}distinct(e){return this.distinctSelector=e,this}max(e){return this.maxSelector=e,this}min(e){return this.minSelector=e,this}count(e){return this.countSelector=e,this}from(e){if(this.fromSelector="string"==typeof e?s.Model.get(e):e,!this.fromSelector)throw new T("Could not find selector model: "+e);return this}where(e){return this.whereCondition=e,this}orderBy(e){return this.orderBySelector=e,this}groupBy(e){return this.groupBySelector=e,this}limit(e){return this.limitSelector=e,this}offset(e){return this.offsetSelector=e,this}async execute(){try{const e=this.build();return await this.raw(e)}catch(e){throw new a.InternalError(e)}}async raw(e){const t=await this.adapter.raw(e);if(!this.selectSelector)return t;const r=s.Model.pk(this.fromSelector),a=function(e){const t=e[r];return this.adapter.revert(e,this.fromSelector,r,t)}.bind(this);return Array.isArray(t)?t.map(a):a(t)}}r.__decorate([d(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array]),r.__metadata("design:returntype",Object)],be.prototype,"select",null),r.__decorate([d(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(he="undefined"!=typeof S&&S)?he:Object]),r.__metadata("design:returntype",Object)],be.prototype,"distinct",null),r.__decorate([d(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(fe="undefined"!=typeof S&&S)?fe:Object]),r.__metadata("design:returntype",Object)],be.prototype,"max",null),r.__decorate([d(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(ye="undefined"!=typeof S&&S)?ye:Object]),r.__metadata("design:returntype",Object)],be.prototype,"min",null),r.__decorate([d(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(ge="undefined"!=typeof S&&S)?ge:Object]),r.__metadata("design:returntype",Object)],be.prototype,"count",null),r.__decorate([d(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Object)],be.prototype,"from",null),r.__decorate([d(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[C]),r.__metadata("design:returntype",Object)],be.prototype,"where",null),r.__decorate([d(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array]),r.__metadata("design:returntype",Object)],be.prototype,"orderBy",null),r.__decorate([d(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Object)],be.prototype,"groupBy",null),r.__decorate([d(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Number]),r.__metadata("design:returntype",Object)],be.prototype,"limit",null),r.__decorate([d(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Number]),r.__metadata("design:returntype",Object)],be.prototype,"offset",null),r.__decorate([d(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[]),r.__metadata("design:returntype",Promise)],be.prototype,"execute",null),e.QueryClause=void 0,(me=e.QueryClause||(e.QueryClause={})).FIND_BY="findBy",me.SELECT="Select",me.AND="And",me.OR="Or",me.GROUP_BY="GroupBy",me.ORDER_BY="OrderBy",me.THEN="Then",me.THEN_BY="ThenBy";const we={Equals:(e,t)=>C.attribute(e).eq(t),Diff:(e,t)=>C.attribute(e).dif(t),LessThan:(e,t)=>C.attribute(e).lt(t),LessThanEqual:(e,t)=>C.attribute(e).lte(t),GreaterThan:(e,t)=>C.attribute(e).gt(t),GreaterThanEqual:(e,t)=>C.attribute(e).gte(t),Between:(e,t,r)=>C.attribute(e).gte(t).and(C.attribute(e).lte(r)),In:(e,t)=>C.attribute(e).in(t),Matches:(e,t)=>C.attribute(e).regexp(t)},Oe=e=>e.charAt(0).toLowerCase()+e.slice(1);class ve{static build(t,...r){if(!t.startsWith(e.QueryClause.FIND_BY))throw Error("Unsupported method "+t);const a=this.extractCore(t),s=this.extractSelect(t),n=this.extractGroupBy(t),o=this.buildWhere(a,r),{orderBy:i,limit:c,offset:d}=this.extractOrderLimitOffset(a,r);return{action:"find",select:s,where:o,groupBy:n,orderBy:i,limit:c,offset:d}}static extractCore(t){const r=t.substring(e.QueryClause.FIND_BY.length),a=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return a?r.substring(0,a.index):r}static extractSelect(t){const r=t.indexOf(e.QueryClause.SELECT);if(-1===r)return;const a=t.substring(r+e.QueryClause.SELECT.length),s=a.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?a.substring(0,s.index):a).split(e.QueryClause.AND).map(Oe).filter(Boolean)}static extractGroupBy(t){const r=t.indexOf(e.QueryClause.GROUP_BY);if(-1!==r)return t.substring(r+e.QueryClause.GROUP_BY.length).split(e.QueryClause.ORDER_BY)[0].split(e.QueryClause.THEN_BY).map(Oe).filter(Boolean)}static buildWhere(t,r){const a=(t.split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/),s=t.match(/And|Or/g)||[];let n;if(a.forEach((t,a)=>{const{field:o,operator:i}=this.parseFieldAndOperator(t),c=i?we[i]:we.Equals;if(!c)throw Error("Unsupported operator "+i);const d=r[a];if(void 0===d)throw Error("Invalid value for field "+o);const l=c(o,d);n=0===a?l:s[a-1]===e.QueryClause.AND?n.and(l):n.or(l)}),!n)throw Error("No conditions found in method name");return n}static parseFieldAndOperator(e){for(const t of Object.keys(we))if(e.endsWith(t)){const r=e.slice(0,-t.length);return{field:Oe(r),operator:t}}return{field:Oe(e)}}static extractOrderLimitOffset(e,t){const r=e.split(/And|Or/).length,a=t.slice(r);let s,n,o;return a.length>=1&&Array.isArray(a[0])&&(s=a[0]),2>a.length||"number"!=typeof a[1]||(n=a[1]),3>a.length||"number"!=typeof a[2]||(o=a[2]),{orderBy:s,limit:n,offset:o}}}class _e extends pe{constructor(e,t,r,a){super(e,t,r,a)}prepare(e){const t=Object.assign({},e);return t.limit=this.size,t}async page(e=1){const t=this.prepare(this.statement);if(!this._recordCount||!this._totalPages){this._totalPages=this._recordCount=0;const e=await this.adapter.raw({...t,limit:void 0})||[];if(this._recordCount=e.length,this._recordCount>0){const e=t?.limit||this.size;this._totalPages=Math.ceil(this._recordCount/e)}}e=this.validatePage(e),t.skip=(e-1)*this.size;const r=await this.adapter.raw(t);return this._currentPage=e,r}}class Ee extends be{constructor(e){super(e)}getSort(){return(e,t)=>{if(!this.orderBySelector)throw new a.InternalError("orderBySelector not set. Should be impossible");const r=this.orderBySelector,[s,n]=r,{designType:i}=o.Metadata.getPropDesignTypes(e.constructor,s);if(!i)throw new T("type not compatible with sorting: "+i);switch(i.name){case"string":case"String":return("asc"===n?1:-1)*e[s].localeCompare(t[s]);case"number":case"Number":return("asc"===n?1:-1)*(e[s]-t[s]);case"object":case"Object":if(e[s]instanceof Date&&t[s]instanceof Date)return("asc"===n?1:-1)*(e[s].valueOf()-t[s].valueOf());throw new T("Sorting not supported for not date classes");default:throw new T("sorting not supported for type "+i)}}}build(){const e={select:this.selectSelector,from:this.fromSelector,where:this.whereCondition?this.parseCondition(this.whereCondition).where:e=>!0,limit:this.limitSelector,skip:this.offsetSelector};return this.orderBySelector&&(e.sort=this.getSort()),e}async paginate(e){try{const t=this.build();return new _e(this.adapter,t,e,this.fromSelector)}catch(e){throw new a.InternalError(e)}}parseCondition(t){return{where:r=>{const{attr1:s,operator:n,comparison:o}=t;if(-1===[e.GroupOperator.AND,e.GroupOperator.OR,e.Operator.NOT].indexOf(n))switch(n){case e.Operator.BIGGER:return r[s]>o;case e.Operator.BIGGER_EQ:return r[s]>=o;case e.Operator.DIFFERENT:return r[s]!==o;case e.Operator.EQUAL:return r[s]===o;case e.Operator.REGEXP:if("string"!=typeof r[s])throw new T("Invalid regexp comparison on a non string attribute: "+r[s]);return!!r[s].match(RegExp(o,"g"));case e.Operator.SMALLER:return r[s]<o;case e.Operator.SMALLER_EQ:return r[s]<=o;default:throw new a.InternalError("Invalid operator for standard comparisons: "+n)}else{if(n===e.Operator.NOT)throw new a.InternalError("Not implemented");{const t=this.parseCondition(s),i=this.parseCondition(o);switch(n){case e.GroupOperator.AND:return t.where(r)&&i.where(r);case e.GroupOperator.OR:return t.where(r)||i.where(r);default:throw new a.InternalError("Invalid operator for And/Or comparisons: "+n)}}}}}}}class Ae extends a.Context{constructor(){super()}}e.RamSequenceModel=class extends ue{constructor(e){super(e)}},r.__decorate([le(),r.__metadata("design:type",String)],e.RamSequenceModel.prototype,"id",void 0),r.__decorate([s.required(),re(),r.__metadata("design:type",Object)],e.RamSequenceModel.prototype,"current",void 0),e.RamSequenceModel=r.__decorate([te("__RamSequence"),s.model(),r.__metadata("design:paramtypes",[Object])],e.RamSequenceModel);class De extends D{constructor(t,r){super(t),this.repo=N.forModel(e.RamSequenceModel,r.alias)}async current(){const{name:e,startWith:t}=this.options;try{const t=await this.repo.read(e);return this.parse(t.current)}catch(r){if(r instanceof a.NotFoundError){if(void 0===t)throw new a.InternalError("Starting value is not defined for a non existing sequence");try{return this.parse(t)}catch(e){throw new a.InternalError(`Failed to parse initial value for sequence ${t}: ${e}`)}}throw new a.InternalError(`Failed to retrieve current value for sequence ${e}: ${r}`)}}parse(e){return D.parseValue(this.options.type,e)}async increment(t,r){const{type:s,incrementBy:n,name:o}=this.options;let i;const c=r||n;if(c%n!==0)throw new a.InternalError("Value to increment does not consider the incrementBy setting: "+n);switch(s){case"Number":i=this.parse(t)+c;break;case"BigInt":i=this.parse(t)+BigInt(c);break;case"String":i=this.parse(t);break;default:throw new a.InternalError("Should never happen")}let d;const l=this.repo.override({ignoredValidationProperties:["updatedOn"]});try{d=await l.update(new e.RamSequenceModel({id:o,current:i}))}catch(t){if(!(t instanceof a.NotFoundError))throw t;d=await l.create(new e.RamSequenceModel({id:o,current:i}))}return d.current}async next(){const e=await this.current();return this.increment(e)}async range(e){const t=await this.current(),r=this.parse(this.options.incrementBy),s=await this.increment(t,this.parse(e)*r),n=[];for(let a=1;e>=a;a++)n.push(t+r*this.parse(a));if(n[n.length-1]!==s&&"String"!==this.options.type)throw new a.InternalError("Miscalculation of range");return n}}async function Me(e,t,r,a){const s=e.get("UUID");if(!s)throw new m("This adapter does not support user identification");a[r]=s}const Pe="ram";class Te extends v{constructor(e={},t){super(e,Pe,t),this.Context=Ae,this.indexes={},this.lock=new i.Lock}repository(){return super.repository()}async flags(e,t,r){return Object.assign(await super.flags(e,t,r),{UUID:this.config.user||""+Date.now()})}Dispatch(){return super.Dispatch()}async index(...e){return Promise.resolve(void 0)}prepare(e,t){const r=super.prepare(e,t);return delete r.record[t],r}revert(e,t,r,a){return super.revert(e,t,r,a)}async create(e,t,r){if(await this.lock.acquire(),this.client.has(e)||this.client.set(e,new Map),this.client.get(e)&&this.client.get(e)?.has(t))throw new a.ConflictError(`Record with id ${t} already exists in table ${e}`);return this.client.get(e)?.set(t,r),this.lock.release(),r}async read(e,t){if(!this.client.has(e))throw new a.NotFoundError(`Table ${e} not found`);if(!this.client.get(e)?.has(t))throw new a.NotFoundError(`Record with id ${t} not found in table ${e}`);return this.client.get(e)?.get(t)}async update(e,t,r){if(await this.lock.acquire(),!this.client.has(e))throw new a.NotFoundError(`Table ${e} not found`);if(!this.client.get(e)?.has(t))throw new a.NotFoundError(`Record with id ${t} not found in table ${e}`);return this.client.get(e)?.set(t,r),this.lock.release(),r}async delete(e,t){if(await this.lock.acquire(),!this.client.has(e))throw new a.NotFoundError(`Table ${e} not found`);if(!this.client.get(e)?.has(t))throw new a.NotFoundError(`Record with id ${t} not found in table ${e}`);const r=this.client.get(e)?.get(t);return this.client.get(e)?.delete(t),this.lock.release(),r}tableFor(e){"string"==typeof e&&(e=s.Model.get(e));const t=N.table(e);return this.client.has(t)||this.client.set(t,new Map),this.client.get(t)}async raw(e){const{where:t,sort:r,limit:n,skip:i,from:c}=e;let{select:d}=e;const l=this.tableFor(c);if(!l)throw new a.InternalError(`Table ${c} not found in RamAdapter`);const u=s.Model.pk(c),p=o.Metadata.get(c,o.Metadata.key(a.DBKeys.ID,u));let h=Array.from(l.entries()).map(([e,t])=>this.revert(t,c,u,D.parseValue(p.type,e)));return h=t?h.filter(t):h,r&&(h=h.sort(r)),i&&(h=h.slice(i)),n&&(h=h.slice(0,n)),d&&(d=Array.isArray(d)?d:[d],h=h.map(e=>Object.entries(e).reduce((e,[t,r])=>(d.includes(t)&&(e[t]=r),e),{}))),h}parseError(e){return e instanceof a.BaseError?e:new a.InternalError(e)}Statement(){return new Ee(this)}async Sequence(e){return new De(e,this)}for(e,...t){this.proxies||(this.proxies={});const r=`${this.alias} - ${s.hashObj(e)}`;if(r in this.proxies)return this.proxies[r];const a=new Proxy(this,{get:(t,r,a)=>{if("_config"===r){const s=Reflect.get(t,r,a);return Object.assign({},s,e)}return Reflect.get(t,r,a)}});return this.proxies[r]=a,a}static decoration(){super.decoration();const t=e.PersistenceKeys.CREATED_BY,r=e.PersistenceKeys.UPDATED_BY;o.Decoration.flavouredAs(Pe).for(t).define(a.onCreate(Me),o.propMetadata(t,{})).apply(),o.Decoration.flavouredAs(Pe).for(r).define(a.onCreateUpdate(Me),o.propMetadata(r,{})).apply()}getClient(){return new Map}}Te.decoration(),t.Injectables.setRegistry(new R);const Ie="##VERSION##",Ce="##PACKAGE##";o.Metadata.registerLibrary(Ce,Ie),e.AbsMigration=$,e.Adapter=v,e.AuthorizationError=l,e.BaseModel=ue,e.BigIntSequence=q,e.Condition=C,e.ConnectionError=p,e.DefaultCascade=A,e.DefaultSequenceOptions=L,e.Dispatch=B,e.ForbiddenError=u,e.InjectablesRegistry=R,e.MethodQueryBuilder=ve,e.MigrationError=b,e.MigrationRuleError=w,e.NoneSequenceOptions=j,e.NumericSequence=F,e.ObserverError=k,e.ObserverHandler=h,e.OperatorsMap=we,e.PACKAGE_NAME=Ce,e.Paginator=pe,e.PagingError=I,e.QueryError=T,e.RamAdapter=Te,e.RamContext=Ae,e.RamFlavour=Pe,e.RamPaginator=_e,e.RamSequence=De,e.RamStatement=Ee,e.Repository=N,e.Sequence=D,e.Statement=be,e.UnsupportedError=m,e.VERSION=Ie,e.cacheModelForPopulate=X,e.column=t=>o.Decoration.for(e.PersistenceKeys.COLUMN).define({decorator:t=>(r,a)=>o.propMetadata(o.Metadata.key(e.PersistenceKeys.COLUMN,a),t||a)(r,a),args:[t]}).apply(),e.createOrUpdate=U,e.createdAt=ne,e.createdBy=()=>{const t=e.PersistenceKeys.CREATED_BY;return o.Decoration.for(t).define({decorator:()=>o.apply(a.onCreate(se),o.propMetadata(t,{})),args:[]}).apply()},e.createdByOnCreateUpdate=se,e.createdByOnRamCreateUpdate=Me,e.final=d,e.generateInjectableNameForRepository=x,e.getColumnName=y,e.getPopulateKey=W,e.getTableName=f,e.index=re,e.manyToMany=(t,r=A,a=!0,n,i)=>{const c=e.PersistenceKeys.MANY_TO_MANY;return o.Decoration.for(c).define({decorator:(e,t,r,a,n)=>{const i={class:e,cascade:t,populate:r};return a&&(i.joinTable=a),n&&(i.name=n),o.apply(o.prop(),ce(c,i),s.list([e,String,Number,BigInt]))},args:[t,r,a,n,i]}).apply()},e.manyToOne=(t,r=A,a=!0,n,i)=>{const c=e.PersistenceKeys.MANY_TO_ONE;return o.Decoration.for(c).define({decorator:(e,t,r,a,n)=>{const i={class:e,cascade:t,populate:r};return a&&(i.joinTable=a),n&&(i.name=n),o.apply(o.prop(),ce(c,i),s.type([e,String,Number,BigInt]))},args:[t,r,a,n,i]}).apply()},e.migration=(t,r)=>o.Decoration.for(e.PersistenceKeys.MIGRATION).define({decorator:(t,r)=>a=>{const s=o.Metadata.innerGet(Symbol.for(e.PersistenceKeys.MIGRATION),t)||[];return o.Metadata.set(e.PersistenceKeys.MIGRATION,t,[...s,{class:a}]),o.metadata(e.PersistenceKeys.MIGRATION,{flavour:t,rules:r})(a)},args:[t,r]}).apply(),e.noValidateOn=ie,e.noValidateOnCreate=()=>ie(a.OperationKeys.CREATE),e.noValidateOnCreateUpdate=()=>ie(a.OperationKeys.UPDATE,a.OperationKeys.CREATE),e.noValidateOnUpdate=()=>ie(a.OperationKeys.UPDATE),e.oneToMany=(t,r=A,n=!0,i,c)=>{const d=e.PersistenceKeys.ONE_TO_MANY;return o.Decoration.for(d).define({decorator:(e,t,r,n,i)=>{const c={class:e,cascade:t,populate:r};return n&&(c.joinTable=n),i&&(c.name=i),o.apply(o.prop(),ce(d,c),s.list([e,String,Number,BigInt]),a.onCreate(Q,c),a.onUpdate(Y,c),a.onDelete(z,c),a.afterAny(J,c))},args:[t,r,n,i,c]}).apply()},e.oneToManyOnCreate=Q,e.oneToManyOnDelete=z,e.oneToManyOnUpdate=Y,e.oneToOne=(t,r=A,n=!0,i,c)=>{const d=e.PersistenceKeys.ONE_TO_ONE;return o.Decoration.for(d).define({decorator:(e,t,r,n,i)=>{const c={class:e,cascade:t,populate:r};return n&&(c.joinTable=n),i&&(c.name=i),o.apply(o.prop(),ce(d,c),s.type([e,String,Number,BigInt]),a.onCreate(G,c),a.onUpdate(H,c),a.onDelete(V,c),a.afterAny(J,c))},args:[t,r,n,i,c]}).apply()},e.oneToOneOnCreate=G,e.oneToOneOnDelete=V,e.oneToOneOnUpdate=H,e.pk=le,e.pkOnCreate=de,e.populate=J,e.prefixMethod=K,e.query=function(e={}){return(t,r,a)=>{const s=r.toString();a.value=function(...t){const{select:r,where:a,groupBy:n,orderBy:o,limit:i,offset:c}=ve.build(s,...t);let d=this.select(r);a&&(d=d.where(a));const{allowLimit:l,allowOffset:u,allowOrderBy:p,throws:h}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...e},f=[{key:"orderBy",value:(o||[])[0],allowed:p},{key:"limit",value:i,allowed:l},{key:"offset",value:c,allowed:u}];for(const e of f)if(void 0!==e.value){if(!e.allowed&&h)throw new T(e.key[0].toUpperCase()+e.key.slice(1)+" is not allowed for this query");e.allowed&&(d=d[e.key](e.value))}return d.execute()}}},e.relation=ce,e.repository=(r,n)=>(i,c)=>c?t.inject(r[s.ModelKeys.ANCHOR]||r)(i,c):(o.metadata(a.DBKeys.REPOSITORY,i.name)(r),n=n||o.Metadata.get(i.constructor,e.PersistenceKeys.ADAPTER),N.register(o.Metadata.constr(r),i,n),t.injectable(o.Metadata.constr(r),{callback:e=>(Object.defineProperty(e,a.DBKeys.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:r}),e)})(i)),e.repositoryFromTypeMetadata=ee,e.sequenceNameForModel=g,e.table=te,e.unique=()=>{const t=e.PersistenceKeys.UNIQUE;return o.Decoration.for(t).define(a.onCreateUpdate(ae),o.propMetadata(t,{})).apply()},e.uniqueOnCreateUpdate=ae,e.updatedAt=oe,e.updatedBy=()=>{const t=e.PersistenceKeys.UPDATED_BY;return o.Decoration.for(t).define({decorator:()=>o.apply(a.onUpdate(se),o.propMetadata(t,{})),args:[]}).apply()}},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/injectable-decorators"),require("tslib"),require("@decaf-ts/db-decorators"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/logging"),require("@decaf-ts/decoration"),require("@decaf-ts/transactional-decorators")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/injectable-decorators","tslib","@decaf-ts/db-decorators","@decaf-ts/decorator-validation","@decaf-ts/logging","@decaf-ts/decoration","@decaf-ts/transactional-decorators"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).core={},e.decafTsInjectableDecorators,e.tslib,e.decafTsDbDecorators,e.decafTsDecoratorValidation,e.decafTsLogging,e.decafTsDecoration,e.decafTsTransactionalDecorators);
1
+ var e,t;e=this,t=function(e,t,r,a,s,n,o,i){"use strict";var c;e.PersistenceKeys=void 0,(c=e.PersistenceKeys||(e.PersistenceKeys={})).INDEX="index",c.UNIQUE="unique",c.ADAPTER="adapter",c.INJECTABLE="decaf_{0}_adapter_for_{1}",c.SERVICE="service",c.TABLE="table",c.COLUMN="column",c.METADATA="__metadata",c.OWNERSHIP="ownership",c.CREATED_BY="ownership.created-by",c.UPDATED_BY="ownership.updated-by",c.RELATIONS="__relations",c.RELATION="relation",c.ONE_TO_ONE="relation.one-to-one",c.ONE_TO_MANY="relation.one-to-many",c.MANY_TO_ONE="relation.many-to-one",c.MANY_TO_MANY="relation.many-to-many",c.POPULATE="populate",c.NO_VALIDATE="no-validate",c.MIGRATION="migration";class l{constructor(){this.observers=[]}count(){return this.observers.length}observe(e,t){if(-1!==this.observers.map((e=>e.observer)).indexOf(e))throw new a.InternalError("Observer already registered");this.observers.push({observer:e,filter:t})}unObserve(e){const t=this.observers.map((e=>e.observer)).indexOf(e);if(-1===t)throw new a.InternalError("Failed to find Observer");this.observers.splice(t,1)}async updateObservers(e,t,r,...a){const{log:s,ctxArgs:n}=f.logCtx(a,this.updateObservers);(await Promise.allSettled(this.observers.filter((a=>{const{filter:o}=a;if(!o)return!0;try{return o(e,t,r,...n)}catch(e){return s.error(`Failed to filter observer ${a.observer.toString()}: ${e}`),!1}})).map((a=>{a.observer.refresh(e,t,r,...n)})))).forEach(((e,t)=>{"rejected"===e.status&&s.error(`Failed to update observable ${this.observers[t].toString()}: ${e.reason}`)}))}}class d extends a.InternalError{constructor(e){super(e,d.name,500)}}class u extends a.InternalError{constructor(e,t=u.name){super(e,t,500)}}class p extends u{constructor(e){super(e,p.name)}}class h extends n.LoggedClass{logFor(e,...t){return e.logger.for(this)}logCtx(e,t){return h.logCtx.call(this,e,t)}static logCtx(e,t){if(1>e.length)throw new a.InternalError("No context provided");const r=e.pop();if(!(r instanceof a.Context))throw new a.InternalError("No context provided");if(e.filter((e=>e instanceof a.Context)).length>1)throw Error("here");const s=this?r.logger.for(this).for(t):r.logger.clear().for(this).for(t);return{ctx:r,log:t?s.for(t):s,ctxArgs:[...e,r]}}}const g=o.Decoration.flavourResolver.bind(o.Decoration);o.Decoration.flavourResolver=e=>{try{const t=g(e);if(t&&t!==o.DefaultFlavour)return t;const r="function"==typeof e?e:e?.constructor,a=r&&"function"==typeof o.Metadata.registeredFlavour?o.Metadata.registeredFlavour(r):void 0;if(a&&a!==o.DefaultFlavour)return a;const s=f._currentFlavour;if(s){const e=f._cache?.[s];return e?.flavour?e.flavour:s}}catch(e){return o.DefaultFlavour}};class f extends h{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!f._baseRepository)throw new a.InternalError("This should be overridden when necessary. Otherwise it will be replaced lazily");return f._baseRepository}async shutdownProxies(e){if(this.proxies){if(e&&!(e in this.proxies))throw new a.InternalError("No proxy found for "+e);if(e)try{await this.proxies[e].shutdown(),delete this.proxies[e]}catch(t){this.log.error(`Failed to shutdown proxied adapter ${e}: ${t}`)}else for(const e in this.proxies){try{await this.proxies[e].shutdown()}catch(t){this.log.error(`Failed to shutdown proxied adapter ${e}: ${t}`);continue}delete this.proxies[e]}}}async shutdown(){await this.shutdownProxies(),this.dispatch&&await this.dispatch.close()}constructor(e,t,r){if(super(),this._config=e,this.flavour=t,this._alias=r,this.Context=a.Context,this.alias in f._cache)throw new a.InternalError(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);f._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),f._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),f._currentFlavour=this.alias)}Dispatch(){return new f._baseDispatch}ObserverHandler(){return new l}isReserved(e){return!e}async initialize(...e){}async Sequence(e){return new f._baseSequence(e,this)}async flags(e,t,r,...i){let c=r.logger||n.Logging.for(this.toString());return r.correlationId&&(c=c.for({correlationId:r.correlationId})),Object.assign({},a.DefaultRepositoryFlags,r,{affectedTables:(Array.isArray(t)?t:[t]).map(s.Model.tableName),writeOperation:e!==a.OperationKeys.READ,timestamp:new Date,operation:e,ignoredValidationProperties:Array.isArray(t)?[]:o.Metadata.validationExceptions(t,e),logger:c})}async context(e,t,r,...a){this.log.for(this.context).debug(`Creating new context for ${e} operation on ${Array.isArray(r)?r.map((e=>e.name)):r.name} model with flag overrides: ${JSON.stringify(t)}`);const s=await this.flags(e,r,t,...a);return(new this.Context).accumulate(s)}prepare(t,...r){const{log:n}=this.logCtx(r,this.prepare),o=t.segregate(),i=Object.entries(o.model).reduce(((e,[r,n])=>{if(void 0===n)return e;const o=s.Model.columnName(t.constructor,r);if(this.isReserved(o))throw new a.InternalError(`Property name ${o} is reserved`);return e[o]=n,e}),{});return t[e.PersistenceKeys.METADATA]&&(n.silly("Passing along persistence metadata for "+t[e.PersistenceKeys.METADATA]),Object.defineProperty(i,e.PersistenceKeys.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[e.PersistenceKeys.METADATA]})),{record:i,id:t[s.Model.pk(t.constructor)],transient:o.transient}}revert(t,r,n,o,...i){const{log:c,ctx:l}=this.logCtx(i,this.revert),d={},u=s.Model.pk(r);d[u]=n;const p=new r(d);c.silly(`Rebuilding model ${p.constructor.name} id ${n}`);const h=t[e.PersistenceKeys.METADATA],g=Object.keys(p).reduce(((e,a)=>(a===u||(e[a]=t[s.Model.columnName(r,a)]),e)),p);return l.get("rebuildWithTransient")&&o&&(c.verbose("re-adding transient properties: "+Object.keys(o).join(", ")),Object.entries(o).forEach((([e,t])=>{if(e in g)throw new a.InternalError(`Transient property ${e} already exists on model ${p.constructor.name}. should be impossible`);g[e]=t}))),h&&(c.silly(`Passing along ${this.flavour} persistence metadata for ${p.constructor.name} id ${n}: ${h}`),Object.defineProperty(g,e.PersistenceKeys.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:h})),g}async createAll(e,t,r,...n){if(t.length!==r.length)throw new a.InternalError("Ids and models must have the same length");const{log:o,ctxArgs:i}=this.logCtx(n,this.createAll),c=s.Model.tableName(e);return o.debug(`Creating ${t.length} entries ${c} table`),Promise.all(t.map(((t,a)=>this.create(e,t,r[a],...i))))}async readAll(e,t,...r){const{log:a,ctxArgs:n}=this.logCtx(r,this.readAll),o=s.Model.tableName(e);return a.debug(`Reading ${t.length} entries ${o} table`),Promise.all(t.map((t=>this.read(e,t,...n))))}async updateAll(e,t,r,...n){if(t.length!==r.length)throw new a.InternalError("Ids and models must have the same length");const{log:o,ctxArgs:i}=this.logCtx(n,this.updateAll),c=s.Model.tableName(e);return o.debug(`Updating ${t.length} entries ${c} table`),Promise.all(t.map(((t,a)=>this.update(e,t,r[a],...i))))}async deleteAll(e,t,...r){const{log:a,ctxArgs:s}=f.logCtx(r,this.deleteAll);return a.verbose(`Deleting ${t.length} entries from ${e} table`),Promise.all(t.map((t=>this.delete(e,t,...s))))}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1}),this.observerHandler.observe(e,t);const r=this.log.for(this.observe);r.verbose("Registering new observer "+e.toString()),this.dispatch||(r.info("Creating dispatch for "+this.alias),this.dispatch=this.Dispatch(),this.dispatch.observe(this))}unObserve(e){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(e),this.log.for(this.unObserve).verbose(`Observer ${e.toString()} removed`)}async updateObservers(e,t,r,...s){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");const{log:n,ctxArgs:o}=f.logCtx(s,this.updateObservers);n.verbose(`Updating ${this.observerHandler.count()} observers for adapter ${this.alias}: Event: `),await this.observerHandler.updateObservers(e,t,r,...o)}async refresh(e,t,r,...a){return this.updateObservers(e,t,r,...a)}toString(){return this.flavour+" adapter"}static flavourOf(e){return o.Metadata.flavourOf(e)}static get currentFlavour(){if(!f._currentFlavour)throw new a.InternalError("No persistence flavour set. Please initialize your adapter");return f._currentFlavour}static get current(){return f.get(this.currentFlavour)}static get(e){if(!e)return f.get(this._currentFlavour);if(e in this._cache)return this._cache[e];throw new a.InternalError(`No Adapter registered under ${e}.`)}static setCurrent(e){this._currentFlavour=e}static models(e){try{return o.Metadata.flavouredAs(e)}catch(e){throw new a.InternalError(e)}}static decoration(){}static logCtx(e,t){return super.logCtx(e,t)}get client(){return this._client||(this._client=this.getClient()),this._client}for(e,...t){this.proxies||(this.proxies={});const r=`${this.alias} - ${s.hashObj(e)}`;if(r in this.proxies)return this.proxies[r];let a;const n=new Proxy(this,{get:(t,r,s)=>{if("_config"===r){const a=Reflect.get(t,r,s);return Object.assign({},a,e)}return"_client"===r?a:Reflect.get(t,r,s)},set:(e,t,r,s)=>"_client"===t?(a=r,!0):Reflect.set(e,t,r,s)});return this.proxies[r]=n,n}migrations(){return o.Metadata.migrationsFor(this)}async getQueryRunner(){return this}async migrate(e=this.migrations(),...t){e instanceof a.Context&&(t=[e],e=this.migrations());const{ctx:r}=f.logCtx(t,this.migrate),s=await this.getQueryRunner();for(const t of e)try{const e=new t;await e.up(s,this,r),await e.down(s,this,r)}catch(e){throw new u(e)}}}var y,m;r.__decorate([n.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String]),r.__metadata("design:returntype",Promise)],f.prototype,"shutdownProxies",null),r.__decorate([n.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,Object,Object,Object]),r.__metadata("design:returntype",Promise)],f.prototype,"context",null),r.__decorate([n.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",void 0)],f.prototype,"observe",null),r.__decorate([n.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],f.prototype,"unObserve",null),r.__decorate([n.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],f.prototype,"client",null),e.OrderDirection=void 0,(y=e.OrderDirection||(e.OrderDirection={})).ASC="asc",y.DSC="desc",e.Cascade=void 0,(m=e.Cascade||(e.Cascade={})).CASCADE="cascade",m.NONE="none";const b={update:e.Cascade.CASCADE,delete:e.Cascade.NONE};var w,O;e.Operator=void 0,(w=e.Operator||(e.Operator={})).EQUAL="EQUAL",w.DIFFERENT="DIFFERENT",w.BIGGER="BIGGER",w.BIGGER_EQ="BIGGER_EQ",w.SMALLER="SMALLER",w.SMALLER_EQ="SMALLER_EQ",w.NOT="NOT",w.IN="IN",w.REGEXP="REGEXP",e.GroupOperator=void 0,(O=e.GroupOperator||(e.GroupOperator={})).AND="AND",O.OR="OR";class _ extends a.InternalError{constructor(e){super(e,_.name,500)}}class v extends a.InternalError{constructor(e){super(e,v.name,500)}}class E extends s.Model{constructor(e,t,r){super(),this.attr1=void 0,this.operator=void 0,this.comparison=void 0,this.attr1=e,this.operator=t,this.comparison=r}and(e){return E.and(this,e)}or(e){return E.or(this,e)}not(t){return new E(this,e.Operator.NOT,t)}hasErrors(...t){const r=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof E)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(e.Operator).indexOf(this.operator))return{operator:{condition:t}}}if(this.attr1 instanceof E){if(!(this.comparison instanceof E)&&this.operator!==e.Operator.NOT)return{comparison:{condition:t}};if(-1===Object.values(e.GroupOperator).indexOf(this.operator)&&this.operator!==e.Operator.NOT)return{operator:{condition:t}}}},a=super.hasErrors(...t);return this.isAsync()?(async()=>await Promise.resolve(a)??r())():a??r()}static and(t,r){return E.group(t,e.GroupOperator.AND,r)}static or(t,r){return E.group(t,e.GroupOperator.OR,r)}static group(e,t,r){return new E(e,t,r)}static attribute(e){return(new E.Builder).attribute(e)}static attr(e){return this.attribute(e)}static{this.Builder=class{constructor(){this.attr1=void 0,this.operator=void 0,this.comparison=void 0}attribute(e){return this.attr1=e,this}attr(e){return this.attribute(e)}eq(t){return this.setOp(e.Operator.EQUAL,t)}dif(t){return this.setOp(e.Operator.DIFFERENT,t)}gt(t){return this.setOp(e.Operator.BIGGER,t)}lt(t){return this.setOp(e.Operator.SMALLER,t)}gte(t){return this.setOp(e.Operator.BIGGER_EQ,t)}lte(t){return this.setOp(e.Operator.SMALLER_EQ,t)}in(t){return this.setOp(e.Operator.IN,t)}regexp(t){return this.setOp(e.Operator.REGEXP,RegExp(t).source)}setOp(e,t){return this.operator=e,this.comparison=t,this.build()}build(){try{return new E(this.attr1,this.operator,this.comparison)}catch(e){throw new _(e)}}}}static builder(){return new E.Builder}}r.__decorate([s.required(),r.__metadata("design:type",Object)],E.prototype,"attr1",void 0),r.__decorate([s.required(),r.__metadata("design:type",String)],E.prototype,"operator",void 0),r.__decorate([s.required(),r.__metadata("design:type",Object)],E.prototype,"comparison",void 0);class x extends a.Repository{static{this._cache={}}get log(){return this.logger||(this.logger=this.adapter.log.for(this.toString())),this.logger}get adapter(){if(!this._adapter)throw new a.InternalError("No adapter found for this repository. did you use the @uses decorator or pass it in the constructor?");return this._adapter}get tableName(){return this._tableName||(this._tableName=s.Model.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}constructor(e,t,...r){super(t),this.observers=[],e&&(this._adapter=e),t&&(x.register(t,this,this.adapter.alias),e)&&o.Metadata.get(t,o.DecorationKeys.FLAVOUR)===o.DefaultFlavour&&o.uses(e.flavour)(t),[this.createAll,this.readAll,this.updateAll,this.deleteAll].forEach((e=>{const t=e.name;a.wrapMethodWithContext(this,this[t+"Prefix"],e,this[t+"Suffix"])}))}logCtx(e,t){return f.logCtx(e,t)}override(e){return new Proxy(this,{get:(t,r,a)=>{const s=Reflect.get(t,r,a);return"_overrides"!==r?s:Object.assign({},s,e)}})}for(e,...t){return new Proxy(this,{get:(r,a,s)=>"adapter"===a?this.adapter.for(e,...t):Reflect.get(r,a,s)})}ObserverHandler(){return new l}async createPrefix(e,...t){const r=await a.Context.args(a.OperationKeys.CREATE,this.class,t,this.adapter,this._overrides||{}),s=!1!==r.context.get("ignoreHandlers"),n=!r.context.get("ignoreValidation");if(e=new this.class(e),s&&await a.enforceDBDecorators(this,r.context,e,a.OperationKeys.CREATE,a.OperationKeys.ON),n){const t=await Promise.resolve(e.hasErrors(...r.context.get("ignoredValidationProperties")||[]));if(t)throw new a.ValidationError(t.toString())}return[e,...r.args]}async create(e,...t){const{ctx:r,log:a,ctxArgs:n}=this.logCtx(t,this.create);a.debug(`Creating new ${this.class.name} in table ${s.Model.tableName(this.class)}`);let{record:o,id:i,transient:c}=this.adapter.prepare(e,r);return o=await this.adapter.create(this.class,i,o,...n),this.adapter.revert(o,this.class,i,c,r)}async createSuffix(e,t){return super.createSuffix(e,t)}async createAll(e,...t){if(!e.length)return e;const{ctx:r,log:a,ctxArgs:n}=this.logCtx(t,this.createAll);a.debug(`Creating ${e.length} new ${this.class.name} in table ${s.Model.tableName(this.class)}`);const o=e.map((e=>this.adapter.prepare(e,r))),i=o.map((e=>e.id));let c=o.map((e=>e.record));return c=await this.adapter.createAll(this.class,i,c,...n),c.map(((e,t)=>this.adapter.revert(e,this.class,i[t],r.get("rebuildWithTransient")?o[t].transient:void 0,r)))}async createAllPrefix(e,...t){const r=await a.Context.args(a.OperationKeys.CREATE,this.class,t,this.adapter,this._overrides||{}),n=!1!==r.context.get("ignoreHandlers"),o=!r.context.get("ignoreValidation");if(!e.length)return[e,...r.args];const i=s.Model.sequenceFor(e[0]);let c=[];if(i.type?(i.name||(i.name=s.Model.sequenceName(e[0],"pk")),c=await(await this.adapter.Sequence(i)).range(e.length,...r.args)):c=e.map(((e,t)=>{if(void 0===e[this.pk])throw new a.InternalError("Primary key is not defined for model in position "+t);return e[this.pk]})),e=await Promise.all(e.map((async(e,t)=>(e=new this.class(e),i.type&&(e[this.pk]="String"!==i.type||i.generated?c[t]:""+e[this.pk]),n&&await a.enforceDBDecorators(this,r.context,e,a.OperationKeys.CREATE,a.OperationKeys.ON),e)))),o){const t=r.context.get("ignoredValidationProperties")||[],s=await Promise.all(e.map((e=>Promise.resolve(e.hasErrors(...t))))),n=a.reduceErrorsToPrint(s);if(n)throw new a.ValidationError(n)}return[e,...r.args]}async readPrefix(e,...t){const r=await a.Context.args(a.OperationKeys.READ,this.class,t,this.adapter,this._overrides||{}),s=new this.class;return s[this.pk]=e,await a.enforceDBDecorators(this,r.context,s,a.OperationKeys.READ,a.OperationKeys.ON),[e,...r.args]}async read(e,...t){const{ctx:r,log:a,ctxArgs:n}=this.logCtx(t,this.read);a.debug(`reading ${this.class.name} from table ${s.Model.tableName(this.class)} with pk ${this.pk}`);const o=await this.adapter.read(this.class,e,...n);return this.adapter.revert(o,this.class,e,void 0,r)}async readAllPrefix(e,...t){const r=await a.Context.args(a.OperationKeys.READ,this.class,t,this.adapter,this._overrides||{});return await Promise.all(e.map((async e=>{const t=new this.class;return t[this.pk]=e,a.enforceDBDecorators(this,r.context,t,a.OperationKeys.READ,a.OperationKeys.ON)}))),[e,...r.args]}async readAll(e,...t){const{ctx:r,log:a,ctxArgs:n}=this.logCtx(t,this.readAll);return a.debug(`reading ${e.length} ${this.class.name} in table ${s.Model.tableName(this.class)}`),(await this.adapter.readAll(this.class,e,...n)).map(((t,a)=>this.adapter.revert(t,this.class,e[a],void 0,r)))}async update(e,...t){const{ctxArgs:r,log:a,ctx:n}=this.logCtx(t,this.update);let{record:o,id:i,transient:c}=this.adapter.prepare(e,n);return a.debug(`updating ${this.class.name} in table ${s.Model.tableName(this.class)} with id ${i}`),o=await this.adapter.update(this.class,i,o,...r),this.adapter.revert(o,this.class,i,c,n)}async updatePrefix(e,...t){const r=await a.Context.args(a.OperationKeys.UPDATE,this.class,t,this.adapter,this._overrides||{}),n=!1!==r.context.get("ignoreHandlers"),o=!r.context.get("ignoreValidation"),i=e[this.pk];if(!i)throw new a.InternalError("No value for the Id is defined under the property "+this.pk);const c=await this.read(i,...r.args);if(e=s.Model.merge(c,e,this.class),n&&await a.enforceDBDecorators(this,r.context,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,c),o){const t=await Promise.resolve(e.hasErrors(c,...s.Model.relations(this.class),...r.context.get("ignoredValidationProperties")||[]));if(t)throw new a.ValidationError(t.toString())}return[e,...r.args]}async updateAll(e,...t){const{ctx:r,log:a,ctxArgs:n}=this.logCtx(t,this.updateAll);a.debug(`Updating ${e.length} new ${this.class.name} in table ${s.Model.tableName(this.class)}`);const o=e.map((e=>this.adapter.prepare(e,r)));return(await this.adapter.updateAll(this.class,o.map((e=>e.id)),o.map((e=>e.record)),...n)).map(((e,t)=>this.adapter.revert(e,this.class,o[t].id,r.get("rebuildWithTransient")?o[t].transient:void 0,r)))}async updateAllPrefix(e,...t){const r=await a.Context.args(a.OperationKeys.UPDATE,this.class,t,this.adapter,this._overrides||{}),n=!1!==r.context.get("ignoreHandlers"),o=!r.context.get("ignoreValidation"),i=e.map((e=>{const t=e[this.pk];if(!t)throw new a.InternalError("missing id on update operation");return t})),c=await this.readAll(i,...r.args);if(e=e.map(((e,t)=>s.Model.merge(c[t],e,this.class))),n&&await Promise.all(e.map(((e,t)=>a.enforceDBDecorators(this,r.context,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,c[t])))),o){const t=r.context.get("ignoredValidationProperties")||[],s=await Promise.all(e.map(((e,r)=>Promise.resolve(e.hasErrors(c[r],e,...t))))),n=a.reduceErrorsToPrint(s);if(n)throw new a.ValidationError(n)}return[e,...r.args]}async deletePrefix(e,...t){const r=await a.Context.args(a.OperationKeys.DELETE,this.class,t,this.adapter,this._overrides||{}),s=await this.read(e,...r.args);return await a.enforceDBDecorators(this,r.context,s,a.OperationKeys.DELETE,a.OperationKeys.ON),[e,...r.args]}async delete(e,...t){const{ctx:r,log:a,ctxArgs:n}=this.logCtx(t,this.delete);a.debug(`deleting new ${this.class.name} in table ${s.Model.tableName(this.class)} with pk ${e}`);const o=await this.adapter.delete(this.class,e,...n);return this.adapter.revert(o,this.class,e,void 0,r)}async deleteAllPrefix(e,...t){const r=await a.Context.args(a.OperationKeys.DELETE,this.class,t,this.adapter,this._overrides||{}),s=await this.readAll(e,...r.args);return await Promise.all(s.map((async e=>a.enforceDBDecorators(this,r.context,e,a.OperationKeys.DELETE,a.OperationKeys.ON)))),[e,...r.args]}async deleteAll(e,...t){const{ctx:r,log:a,ctxArgs:n}=this.logCtx(t,this.create);return a.debug(`deleting ${e.length} ${this.class.name} in table ${s.Model.tableName(this.class)}`),(await this.adapter.deleteAll(this.class,e,...n)).map(((t,a)=>this.adapter.revert(t,this.class,e[a],void 0,r)))}select(e){return this.adapter.Statement().select(e).from(this.class)}async query(t,r,a=e.OrderDirection.ASC,s,n){const o=[r,a],i=this.select().where(t).orderBy(o);return s&&i.limit(s),n&&i.offset(n),i.execute()}attr(e){return E.attr(e)}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const r=this.log.for(this.observe),a=s.Model.tableName(this.class);this.adapter.observe(this,((e,t,r,...s)=>"string"==typeof e?e===a:o.Metadata.constr(e)===o.Metadata.constr(this.class))),r.verbose(`now observing ${this.adapter} filtering on table === ${a}`),this.observerHandler.observe(e,t),r.verbose("Registered new observer "+e.toString())}unObserve(e){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(e),this.log.for(this.unObserve).verbose(`Observer ${e.toString()} removed`),this.observerHandler.count()||(this.log.verbose(`No more observers registered for ${this.adapter}, unsubscribing`),this.adapter.unObserve(this),this.log.verbose("No longer observing adapter "+this.adapter.flavour))}async updateObservers(e,t,r,...n){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");const{log:o,ctxArgs:i}=this.logCtx(n,this.updateObservers);o.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(e,t,Array.isArray(r)?r.map((e=>f._baseSequence.parseValue(s.Model.sequenceFor(this.class).type,e))):f._baseSequence.parseValue(s.Model.sequenceFor(this.class).type,r),...i)}async refresh(e,t,r,...a){return this.updateObservers(e,t,r,...a)}static forModel(t,r,...s){let n;const i=r||o.Metadata.flavourOf(t)||f.currentFlavour;try{n=this.get(t,i)}catch(e){n=void 0}if(n instanceof x)return n;const c=r||o.Metadata.flavourOf(t)||n&&o.Metadata.get(n,e.PersistenceKeys.ADAPTER)||f.currentFlavour,l=c?f.get(c):void 0;if(!l)throw new a.InternalError("No registered persistence adapter found flavour "+c);return n=n||l.repository(),new n(l,t,...s)}static get(e,t){const r=s.Model.tableName(e);let n=r;if(t&&(n=[r,t].join(a.DefaultSeparator)),n in this._cache)return this._cache[n];if(r in this._cache)return this._cache[r];throw new a.InternalError("Could not find repository registered under "+r)}static register(e,t,r){let n=s.Model.tableName(e);if(r&&(n=[n,r].join(a.DefaultSeparator)),n in this._cache&&this._cache[n]instanceof x)throw new a.InternalError(n+" already has a registered instance");this._cache[n]=t}}function A(t,r){if(!(r||(r=o.Decoration.flavourResolver(t instanceof s.Model?t.constructor:t))&&r!==o.DefaultFlavour))throw new a.InternalError("Could not retrieve flavour from model "+(t instanceof s.Model?t.constructor.name:t.name));return s.sf(e.PersistenceKeys.INJECTABLE,r,s.Model.tableName(t))}r.__decorate([n.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",void 0)],x.prototype,"observe",null),r.__decorate([n.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],x.prototype,"unObserve",null),f&&(f._baseRepository=x);class M extends t.InjectableRegistryImp{get log(){return this.logger||(this.logger=n.Logging.for(this)),this.logger}constructor(){super()}get(r,a){const n=this.log.for(this.get);let i;try{i=super.get(r)}catch{}if(!i){let c;if("function"==typeof r?c=r:"symbol"!=typeof r&&"string"!=typeof r||(c=s.Model.get(r.toString())),!c)return;const l=e.PersistenceKeys.ADAPTER,d=a||o.Metadata.get(c,l);try{let e=d;try{d&&f.get(d)}catch{const t=f.current;t&&t.flavour===d&&(e=t.alias)}if(i=x.forModel(c,e),i instanceof x)return i;const r=d||o.Metadata.get(i.constructor,l)||o.Metadata.get(c,l);t.Injectables.register(i,A(c,r))}catch(e){n.debug("No registered repository or adapter found. falling back to default adapter. Error: "+(e?.message||JSON.stringify(e)));const t=x.get(c,d);if("function"==typeof t){const e=d?f.get(d):f.current;if(!e)return;return new t(e,c)}}}return i}}class C extends h{constructor(){super()}async initialize(){if(!this.adapter)return void this.log.for(this.initialize).verbose("No adapter observed for dispatch; skipping initialization");const e=this.adapter;[a.OperationKeys.CREATE,a.OperationKeys.UPDATE,a.OperationKeys.DELETE,a.BulkCrudOperationKeys.CREATE_ALL,a.BulkCrudOperationKeys.UPDATE_ALL,a.BulkCrudOperationKeys.DELETE_ALL].forEach((t=>{if(!e[t])throw new a.InternalError(`Method ${t} not found in ${e.alias} adapter to bind Observables Dispatch`);let r=Object.getOwnPropertyDescriptor(e,t),s=e;for(;!r&&s!==Object.prototype;)s=Object.getPrototypeOf(s),r=Object.getOwnPropertyDescriptor(s,t);r&&r.writable?e[t]=new Proxy(e[t],{apply:async(e,r,s)=>{const{log:n,ctxArgs:o}=r.logCtx(s,e),[i,c]=s,l=await e.apply(r,o);return this.updateObservers(i,(e=>{switch(e){case a.BulkCrudOperationKeys.CREATE_ALL:return a.OperationKeys.CREATE;case a.BulkCrudOperationKeys.UPDATE_ALL:return a.OperationKeys.UPDATE;case a.BulkCrudOperationKeys.DELETE_ALL:return a.OperationKeys.DELETE;default:return e}})(t),c,l,...o.slice(s.length)).then((()=>{n.verbose(`Observer refresh dispatched by ${t} for ${i}`),n.debug("pks: "+c)})).catch((e=>n.error(`Failed to dispatch observer refresh for ${t} on ${i}: ${e}`))),l}}):this.log.error(`Could not find method ${t} to bind Observables Dispatch`)}))}async close(){}observe(e){if(!(e instanceof f))throw new d("Only Adapters can be observed by dispatch");this.adapter=e,this.models=f.models(this.adapter.alias),this.initialize().then((()=>this.log.verbose(`Dispatch initialized for ${this.adapter.alias} adapter`)))}unObserve(e){if(this.adapter!==e)throw new d("Only the adapter that was used to observe can be unobserved");this.adapter=void 0}async updateObservers(e,t,r,...n){const o="string"==typeof e?e:s.Model.tableName(e),{log:i,ctxArgs:c}=this.logCtx(n,this.updateObservers);if(this.adapter)try{i.debug(`Dispatching ${t} from table ${o} for ${t} with id: ${JSON.stringify(r)}`),await this.adapter.refresh(e,t,r,...c)}catch(e){throw new a.InternalError("Failed to refresh dispatch: "+e)}else i.verbose(`No adapter observed for dispatch; skipping observer update for ${o}:${t}`)}}f&&(f._baseDispatch=C);class D{generate(e){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))}static get instance(){return D._instance||(D._instance=new D),D._instance}}class N{constructor(){this.count=14}generate(e){return(""+((e=(e?parseInt(e):0)||0)+1)).padStart(this.count,"0")}static get instance(){return N._instance||(N._instance=new N),N._instance}}function I(e,t,r,a){const s=async function(...e){let a;try{a=await Promise.resolve(r.call(this,...e))}catch(e){if(e instanceof p)return;throw e}return Promise.resolve(t.apply(this,a))}.bind(e),n=a||t.name;Object.defineProperty(s,"name",{enumerable:!0,configurable:!0,writable:!1,value:n}),e[n]=s}class P extends n.LoggedClass{constructor(){super(),this.transaction=!0,[this.up,this.down].forEach((e=>{const t=e.name;I(this,e,this.prefix(t))}))}get adapter(){const t=o.Metadata.get(this.constructor,e.PersistenceKeys.MIGRATION);if(!t)throw new a.InternalError("No migration metadata for "+this.constructor.name);const r=t.flavour;return f.get(r)}async enforceRules(t,r,a){const s=o.Metadata.get(this.constructor,e.PersistenceKeys.MIGRATION)?.rules;if(!s||!s.length)return!0;for(const e of s)if(!await e(t,r,a))return!1;return!0}prefix(e){return async function(t){let r;t instanceof f?r=this.getQueryRunner(t.client):(r=t,t=this.adapter);const n=await a.Context.args("migration",s.Model,[e],t);if(!await this.enforceRules(r,t,n.context))throw n.context.logger.verbose(`Skipping migration ${this.constructor.name} due to rules`),new p("Migration skipped for rule enforcement");return[r,t,n.context]}.bind(this)}}async function T(e,t,r,n){if(!n){const t=s.Model.get(e.constructor.name);if(!t)throw new a.InternalError("Could not find model "+e.constructor.name);n=x.forModel(t,r)}if(void 0===e[s.Model.pk(n.class)])return n.create(e,t);try{return n.update(e,t)}catch(r){if(!(r instanceof a.NotFoundError))throw r;return n.create(e,t)}}async function R(e,t,r,o){const i=o[r];if(!i)return;if("object"!=typeof i){const t=G(o,r,this.adapter.alias),a=await t.read(i);return await k(e,o,r,i,a),void(o[r]=i)}const c=n.isClass(t.class)?t.class:t.class();if(!c)throw new a.InternalError("Could not find model "+t.class);const l=x.forModel(c,this.adapter.alias),d=await l.create(i),u=s.Model.pk(d);await k(e,o,r,d[u],d),o[r]=d[u]}async function $(t,r,a,n){const o=n[a];if(!o)return;if(r.cascade.update!==e.Cascade.CASCADE)return;if("object"!=typeof o){const e=G(n,a,this.adapter.alias),r=await e.read(o);return await k(t,n,a,o,r),void(n[a]=o)}const i=await T(n[a],t,this.adapter.alias),c=s.Model.pk(i);await k(t,n,a,i[c],i),n[a]=i[c]}async function B(t,r,a,n){const o=n[a];if(!o)return;if(r.cascade.update!==e.Cascade.CASCADE)return;const i=G(n,a,this.adapter.alias);let c;c=o instanceof s.Model?await i.delete(n[a][i.pk]):await i.delete(n[a]),await k(t,n,a,c[i.pk],c)}async function K(e,t,r,n){const o=n[r];if(!o||!o.length)return;const i=typeof o[0];if(!o.every((e=>typeof e===i)))throw new a.InternalError(`Invalid operation. All elements of property ${r} must match the same type.`);const c=new Set([...o]);if("object"!==i){const t=G(n,r,this.adapter.alias);for(const a of c){const s=await t.read(a);await k(e,n,r,a,s)}return void(n[r]=[...c])}const l=s.Model.pk(o[0]),d=new Set;for(const t of o){const a=await T(t,e,this.adapter.alias);await k(e,n,r,a[l],a),d.add(a[l])}n[r]=[...d]}async function j(t,r,a,s){const{cascade:n}=r;if(n.update===e.Cascade.CASCADE)return K.call(this,t,r,a,s)}async function F(t,r,s,n){if(r.cascade.delete!==e.Cascade.CASCADE)return;const o=n[s];if(!o||!o.length)return;const i=typeof o[0];if(!o.every((e=>typeof e===i)))throw new a.InternalError(`Invalid operation. All elements of property ${s} must match the same type.`);const c="object"===i,l=c?x.forModel(o[0],this.adapter.alias):G(n,s,this.adapter.alias),d=new Set([...c?o.map((e=>e[l.pk])):o]);for(const e of d.values()){const r=await l.delete(e);await k(t,n,s,e,r)}n[s]=[...d]}function L(t,r,a){return[e.PersistenceKeys.POPULATE,t,r,a].join(".")}async function k(e,t,r,a,s){const n=L(t.constructor.name,r,a);return e.accumulate({[n]:s})}async function q(e,t,r,s){if(!t.populate)return;const n=s[r],o=Array.isArray(n);if(void 0===n||o&&0===n.length)return;const i=await(async(e,t,r,s,n)=>{let o,i;const c=[];for(const l of s){o=L(t.constructor.name,r,l);try{i=await e.get(o)}catch(e){const s=G(t,r,n);if(!s)throw new a.InternalError("Could not find repo");i=await s.read(l)}c.push(i)}return c})(e,s,r,o?n:[n],this.adapter.alias);s[r]=o?i:i[0]}const U=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function G(e,t,r){if(!e)throw Error("No model was provided to get repository");let n;if(Array.isArray(e[t])||e[t]instanceof Set){const r=o.Metadata.get(e instanceof s.Model?e.constructor:e,o.Metadata.key(s.ValidationKeys.REFLECT,t,s.ValidationKeys.LIST))?.clazz;if(!r)throw new a.InternalError("Failed to find types decorators for property "+t);n=(Array.isArray(r)?[...r]:[r]).map((e=>"function"!=typeof e||e.name?e:e()))}else n=o.Metadata.getPropDesignTypes(e instanceof s.Model?e.constructor:e,t)?.designTypes;const i=n?.find((e=>!U.includes((""+e.name).toLowerCase())));return x.forModel(i,r)}class V extends a.BadRequestError{constructor(e,t=V.name,r=401){super(e,t,r)}}class H extends V{constructor(e,t=H.name){super(e,t,403)}}class Q extends a.InternalError{constructor(e){super(e,Q.name,503)}}function z(t){return o.Decoration.for(e.PersistenceKeys.TABLE).define({decorator:t=>r=>o.metadata(e.PersistenceKeys.TABLE,t||r.name.toLowerCase())(r),args:[t]}).apply()}function Y(t,r,a){return o.Decoration.for(e.PersistenceKeys.INDEX).define({decorator:(t,r,a)=>(s,n)=>("string"==typeof t&&(a=t,t=void 0,r=void 0),"string"==typeof r&&(a=r,r=void 0),!r&&t&&t.find((t=>![e.OrderDirection.ASC,e.OrderDirection.DSC].includes(t)))&&(r=t,t=void 0),o.propMetadata(o.Metadata.key(`${e.PersistenceKeys.INDEX}${r&&r?.length?"."+r.join("."):""}`,n),{directions:t,compositions:r,name:a})(s,n)),args:[t,r,a]}).apply()}async function W(e,t,r,s){if(s[r]&&(await this.select().where(E.attribute(r).eq(s[r])).execute()).length)throw new a.ConflictError(`model already exists with property ${r} equal to ${JSON.stringify(s[r],void 0,2)}`)}async function X(e,t,r,a){throw new V("This adapter does not support user identification")}function J(){return a.timestamp([a.OperationKeys.CREATE])}function Z(){return a.timestamp()}function ee(...t){return(r,a)=>{const s=o.Metadata.get(r,o.Metadata.key(e.PersistenceKeys.NO_VALIDATE,a))||[],n=[...new Set([...s,...t])];return o.apply(o.metadata(o.Metadata.key(e.PersistenceKeys.NO_VALIDATE,a),n))(r,a)}}function te(t,r){return o.Decoration.for(e.PersistenceKeys.RELATIONS).define({decorator:(t,r)=>(a,s)=>(o.propMetadata(t,r)(a,s),o.propMetadata(o.Metadata.key(e.PersistenceKeys.RELATIONS,s),Object.assign({},r,{key:t}))(a,s)),args:[t,r]}).apply()}class re extends s.Model{constructor(e){super(e)}}r.__decorate([J(),r.__metadata("design:type",Date)],re.prototype,"createdAt",void 0),r.__decorate([Z(),r.__metadata("design:type",Date)],re.prototype,"updatedAt",void 0);const ae={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},se=ae,ne={type:"Number",generated:!0,startWith:0,incrementBy:1,cycle:!1},oe=Object.assign({},ne,{type:"BigInt"});async function ie(e,t,r,n){if(!t.type||!t.generated||n[r])return;let o;t.name||(t.name=s.Model.sequenceName(n,"pk"));try{o=await this.adapter.Sequence(t)}catch(e){throw new a.InternalError(`Failed to instantiate Sequence ${t.name}: ${e}`)}var i,c,l;i=n,c=r,l=await o.next(e),Reflect.set(i,c,l)}function ce(t=se){t=Object.assign({},se,t,{generated:!(!t.type||void 0!==t.generated)||t.generated||se.generated});const r=a.DBKeys.ID;return o.Decoration.for(r).define({decorator:(t,r)=>(n,i)=>o.apply(Y([e.OrderDirection.ASC,e.OrderDirection.DSC]),s.required(),a.readonly(),o.propMetadata(o.Metadata.key(a.DBKeys.ID,i),t),a.onCreate(ie,t,r))(n,i),args:[t,{priority:60}]}).apply()}e.SequenceModel=class extends re{constructor(e){super(e)}},r.__decorate([ce({type:"String",generated:!1}),r.__metadata("design:type",String)],e.SequenceModel.prototype,"id",void 0),r.__decorate([s.required(),Y(),r.__metadata("design:type",Object)],e.SequenceModel.prototype,"current",void 0),e.SequenceModel=r.__decorate([z("??sequence"),s.model(),r.__metadata("design:paramtypes",[Object])],e.SequenceModel);class le extends h{constructor(t,r){super(),this.options=t,this.adapter=r,this.repo=x.forModel(e.SequenceModel,r.alias)}async current(...t){const r=(await a.Context.args(a.OperationKeys.READ,e.SequenceModel,t,this.adapter)).context,{name:s,startWith:n}=this.options;try{const e=await this.repo.read(s,r);return this.parse(e.current)}catch(e){if(e instanceof a.NotFoundError){if(void 0===n)throw new a.InternalError("Starting value is not defined for a non existing sequence");try{return this.parse(n)}catch(e){throw new a.InternalError(`Failed to parse initial value for sequence ${n}: ${e}`)}}throw new a.InternalError(`Failed to retrieve current value for sequence ${s}: ${e}`)}}async increment(t,r,s){const{type:n,incrementBy:o,name:i}=this.options;let c;const l=r||o;if(l%o!=0)throw new a.InternalError("Value to increment does not consider the incrementBy setting: "+o);switch(n){case"Number":c=this.parse(t)+l;break;case"BigInt":c=this.parse(t)+BigInt(l);break;case"String":c=this.parse(t);break;case"serial":c=N.instance.generate(t);break;case"uuid":c=D.instance.generate(t);break;default:throw new a.InternalError("Should never happen")}let d;try{d=await this.repo.update(new e.SequenceModel({id:i,current:c}),s)}catch(o){if(!(o instanceof a.NotFoundError))throw o;try{d=await this.repo.create(new e.SequenceModel({id:i,current:c}),s)}catch(e){if(!(e instanceof a.ConflictError)||"uuid"!==n)throw e;return this.increment(t,r,s)}}return d.current}async next(...t){const r=await a.Context.args(a.OperationKeys.UPDATE,e.SequenceModel,t,this.adapter),{context:s,args:n}=r,o=await this.current(...n);return this.increment(o,void 0,s)}async range(t,...r){const s=await a.Context.args(a.OperationKeys.UPDATE,e.SequenceModel,r,this.adapter),{context:n,args:o}=s,i=await this.current(...o),c=this.parse(this.options.incrementBy),l=await this.increment(i,this.parse(t)*c,n),d=[];for(let e=1;t>=e;e++)d.push(i+c*this.parse(e));if(d[d.length-1]!==l&&"String"!==this.options.type)throw new a.InternalError("Miscalculation of range");return d}parse(e){return le.parseValue(this.options.type,e)}static pk(e){return s.Model.sequenceName(e,"pk")}static parseValue(e,t){switch(e){case"Number":return"string"==typeof t?parseInt(t):"number"==typeof t?t:BigInt(t);case"BigInt":return BigInt(t);case void 0:case"String":case"uuid":case"serial":return t;default:throw new d(`Unsupported sequence type: ${e} for adapter ${this}`)}}}f._baseSequence=le,o.Metadata.validationExceptions=((t,r)=>{const a=o.Metadata.get(t,e.PersistenceKeys.NO_VALIDATE);return a?Object.entries(a).filter((([,e])=>e.includes(r))).map((([e])=>e)):[]}).bind(o.Metadata),s.Model.shouldValidateNestedHandler=((t,r)=>{const a=o.Metadata.get(t.constructor);if(!a)return!1;const n=a[e.PersistenceKeys.RELATIONS],i=a[e.PersistenceKeys.RELATION];if(Array.isArray(n)&&n?.includes(r)){const e=Object.keys(i)[0],a=s.Model.isPropertyModel(t,r);return i[e]?.class!==a}return!0}).bind(s.Model),o.Metadata.migrationsFor=(t=>{if(!(t=t??f.current))throw new a.InternalError("Could not get adapter for migrations");return o.Metadata.innerGet(Symbol.for(e.PersistenceKeys.MIGRATION),t.alias).map((e=>e.class))}).bind(o.Metadata),o.Metadata.relations=((t,r)=>{const s=o.Metadata.get(t,e.PersistenceKeys.RELATIONS);if(s){if(!r)return Object.keys(s);if(!s[r])throw new a.InternalError("No relations metadata found for property "+r);return s[r]}}).bind(o.Metadata),s.Model.relations=(e,t)=>o.Metadata.relations(e instanceof s.Model?e.constructor:e,t)||[],s.Model.tableName=t=>{if(!(t instanceof s.Model?s.Model.get(t.constructor.name):t))throw new a.InternalError("Unable to find model "+t);return o.Metadata.get(t instanceof s.Model?t.constructor:t,e.PersistenceKeys.TABLE)||(t instanceof s.Model?t.constructor.name:t.name)},s.Model.columnName=(t,r)=>o.Metadata.get(t instanceof s.Model?t.constructor:t,o.Metadata.key(e.PersistenceKeys.COLUMN,r))||r,s.Model.sequenceName=(e,...t)=>[s.Model.tableName(e),...t].join("_"),s.Model.sequenceFor=(e,t)=>{if(t)throw new d("not currently supported");const r=s.Model.pkProps(e instanceof s.Model?e.constructor:e);if(!r)throw new a.InternalError("No sequence options defined for model. did you use the @pk decorator?");return r},s.Model.indexes=t=>{const r=o.Metadata.get(t instanceof s.Model?t.constructor:t,e.PersistenceKeys.INDEX);return Object.keys(r||{}).reduce(((t,a)=>(t[a]={[e.PersistenceKeys.INDEX]:r[a]},t)),{})},t.Injectables.services=()=>o.Metadata.innerGet(Symbol.for(e.PersistenceKeys.SERVICE)),t.Injectables.repositories=()=>o.Metadata.innerGet(Symbol.for(a.DBKeys.REPOSITORY));class de extends a.InternalError{constructor(e){super(e,de.name,500)}}class ue extends n.LoggedClass{get current(){return this._currentPage}get total(){return this._totalPages}get count(){return this._recordCount}get statement(){return this._statement||(this._statement=this.prepare(this.query)),this._statement}constructor(e,t,r,a){super(),this.adapter=e,this.query=t,this.size=r,this.clazz=a}async next(...e){return this.page(this.current+1,...e)}async previous(...e){return this.page(this.current-1,...e)}validatePage(e){if(1>e||!Number.isInteger(e))throw new v("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&e>this._totalPages)throw new v(`Only ${this._totalPages} are available. Cannot go to page ${e}`);return e}}class pe{constructor(e){this.name=e,this.Context=a.Context}async flags(e,t,...r){let s=t.logger||n.Logging.for(this.toString());return t.correlationId&&(s=s.for({correlationId:t.correlationId})),Object.assign({},a.DefaultRepositoryFlags,t,{timestamp:new Date,operation:e,logger:s})}async context(e,t,...r){const a=await this.flags(e,t,...r);return(new this.Context).accumulate(a)}async logCtx(e,t,r=!1){return await pe.logCtx.bind(this)(e,t,r)}static async logCtx(e,t,r=!1){const s=async function(){if(!r)throw new a.InternalError("No context provided");return this.context("string"==typeof t?t:t.name,{})}.bind(this);1>e.length&&(e=[await s()]);const n=e.pop();n instanceof a.Context||(e=[...e,await s()]);const o=this?n.logger.for(this).for(t):n.logger.clear().for(this).for(t);return{ctx:n,log:t?o.for(t):o,ctxArgs:[...e,n]}}static get(e){if(!e)throw new a.InternalError("No name provided");const r=t.Injectables.get(e);if(r)return r;throw new a.InternalError("No Service found for "+("string"==typeof e?e:"symbol"==typeof e?e.toString():e.name))}static async boot(...e){const r={context:async e=>(new a.Context).accumulate(Object.assign({},a.DefaultRepositoryFlags,{timestamp:new Date,operation:e,logger:n.Logging.get()}))},{log:s,ctxArgs:o}=await this.logCtx.bind(r)(e,this.boot,!0),i=t.Injectables.services();for(const[e,t]of Object.entries(i))try{const e=new t;e instanceof he&&await e.boot(...o)}catch(t){s.error(`Failed to boot ${e} service`,t)}}}class he extends pe{constructor(){super()}async boot(...e){const{log:t,ctxArgs:r}=await this.logCtx(e,this.boot,!0);t.verbose(`Initializing ${this.toString()}...`);const{config:a,client:s}=await this.initialize(...r);this._config=a,this._client=s}get config(){if(!this._config)throw new a.InternalError("Config not initialized");return this._config}get client(){if(!this._client)throw new a.InternalError("Client not initialized");return this._client}async shutdown(...e){const{log:t}=await this.logCtx(e,this.shutdown,!0);t.info(`Shutting down ${this.name} service...`)}}var ge,fe,ye,me,be;r.__decorate([n.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Promise)],he.prototype,"boot",null),r.__decorate([n.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],he.prototype,"config",null),r.__decorate([n.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],he.prototype,"client",null);class we extends h{constructor(e){super(),this.adapter=e}get log(){return this.adapter.log.for(we)}select(e){return Object.defineProperty(this,"selectSelector",{value:e,writable:!1}),this}distinct(e){return this.distinctSelector=e,this}max(e){return this.maxSelector=e,this}min(e){return this.minSelector=e,this}count(e){return this.countSelector=e,this}from(e){if(this.fromSelector="string"==typeof e?s.Model.get(e):e,!this.fromSelector)throw new _("Could not find selector model: "+e);return this}where(e){return this.whereCondition=e,this}orderBy(e){return this.orderBySelector=e,this}groupBy(e){return this.groupBySelector=e,this}limit(e){return this.limitSelector=e,this}offset(e){return this.offsetSelector=e,this}async execute(...e){let t=e;if((!t.length||!(t[t.length-1]instanceof a.Context))&&this.fromSelector){const e=await this.adapter.context(a.OperationKeys.READ,{},this.fromSelector);t=[...t,e]}const{ctx:r}=f.logCtx(t,this.toString());try{const e=this.build();return await this.raw(e,r)}catch(e){throw new a.InternalError(e)}}async raw(e,...t){const{ctx:r,ctxArgs:a}=this.logCtx(t,this.raw),n=await this.adapter.raw(e,...a);if(!this.selectSelector)return n;const o=s.Model.pk(this.fromSelector),i=function(e){const t=e[o];return this.adapter.revert(e,this.fromSelector,t,void 0,r)}.bind(this);return Array.isArray(n)?n.map(i):i(n)}toString(){return this.adapter.flavour+" statement"}}r.__decorate([n.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array]),r.__metadata("design:returntype",Object)],we.prototype,"select",null),r.__decorate([n.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(ge="undefined"!=typeof S&&S)?ge:Object]),r.__metadata("design:returntype",Object)],we.prototype,"distinct",null),r.__decorate([n.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(fe="undefined"!=typeof S&&S)?fe:Object]),r.__metadata("design:returntype",Object)],we.prototype,"max",null),r.__decorate([n.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(ye="undefined"!=typeof S&&S)?ye:Object]),r.__metadata("design:returntype",Object)],we.prototype,"min",null),r.__decorate([n.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(me="undefined"!=typeof S&&S)?me:Object]),r.__metadata("design:returntype",Object)],we.prototype,"count",null),r.__decorate([n.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Object)],we.prototype,"from",null),r.__decorate([n.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[E]),r.__metadata("design:returntype",Object)],we.prototype,"where",null),r.__decorate([n.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array]),r.__metadata("design:returntype",Object)],we.prototype,"orderBy",null),r.__decorate([n.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Object)],we.prototype,"groupBy",null),r.__decorate([n.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Number]),r.__metadata("design:returntype",Object)],we.prototype,"limit",null),r.__decorate([n.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Number]),r.__metadata("design:returntype",Object)],we.prototype,"offset",null),r.__decorate([n.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[void 0]),r.__metadata("design:returntype",Promise)],we.prototype,"execute",null),e.QueryClause=void 0,(be=e.QueryClause||(e.QueryClause={})).FIND_BY="findBy",be.SELECT="Select",be.AND="And",be.OR="Or",be.GROUP_BY="GroupBy",be.ORDER_BY="OrderBy",be.THEN="Then",be.THEN_BY="ThenBy";const Oe={Equals:(e,t)=>E.attribute(e).eq(t),Diff:(e,t)=>E.attribute(e).dif(t),LessThan:(e,t)=>E.attribute(e).lt(t),LessThanEqual:(e,t)=>E.attribute(e).lte(t),GreaterThan:(e,t)=>E.attribute(e).gt(t),GreaterThanEqual:(e,t)=>E.attribute(e).gte(t),Between:(e,t,r)=>E.attribute(e).gte(t).and(E.attribute(e).lte(r)),In:(e,t)=>E.attribute(e).in(t),Matches:(e,t)=>E.attribute(e).regexp(t)},_e=e=>e.charAt(0).toLowerCase()+e.slice(1);class ve{static build(t,...r){if(!t.startsWith(e.QueryClause.FIND_BY))throw Error("Unsupported method "+t);const a=this.extractCore(t),s=this.extractSelect(t),n=this.extractGroupBy(t),o=this.buildWhere(a,r),{orderBy:i,limit:c,offset:l}=this.extractOrderLimitOffset(a,r);return{action:"find",select:s,where:o,groupBy:n,orderBy:i,limit:c,offset:l}}static extractCore(t){const r=t.substring(e.QueryClause.FIND_BY.length),a=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return a?r.substring(0,a.index):r}static extractSelect(t){const r=t.indexOf(e.QueryClause.SELECT);if(-1===r)return;const a=t.substring(r+e.QueryClause.SELECT.length),s=a.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?a.substring(0,s.index):a).split(e.QueryClause.AND).map(_e).filter(Boolean)}static extractGroupBy(t){const r=t.indexOf(e.QueryClause.GROUP_BY);if(-1!==r)return t.substring(r+e.QueryClause.GROUP_BY.length).split(e.QueryClause.ORDER_BY)[0].split(e.QueryClause.THEN_BY).map(_e).filter(Boolean)}static buildWhere(t,r){const a=(t.split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/),s=t.match(/And|Or/g)||[];let n;if(a.forEach(((t,a)=>{const{field:o,operator:i}=this.parseFieldAndOperator(t),c=i?Oe[i]:Oe.Equals;if(!c)throw Error("Unsupported operator "+i);const l=r[a];if(void 0===l)throw Error("Invalid value for field "+o);const d=c(o,l);n=0===a?d:s[a-1]===e.QueryClause.AND?n.and(d):n.or(d)})),!n)throw Error("No conditions found in method name");return n}static parseFieldAndOperator(e){for(const t of Object.keys(Oe))if(e.endsWith(t)){const r=e.slice(0,-t.length);return{field:_e(r),operator:t}}return{field:_e(e)}}static extractOrderLimitOffset(e,t){const r=e.split(/And|Or/).length,a=t.slice(r);let s,n,o;return a.length>=1&&Array.isArray(a[0])&&(s=a[0]),2>a.length||"number"!=typeof a[1]||(n=a[1]),3>a.length||"number"!=typeof a[2]||(o=a[2]),{orderBy:s,limit:n,offset:o}}}class Ee extends ue{constructor(e,t,r,a){super(e,t,r,a)}prepare(e){const t=Object.assign({},e);return t.limit=this.size,t}async page(e=1,...t){const r=await a.Context.args(a.OperationKeys.READ,this.clazz,t,this.adapter),s=this.prepare(this.statement);if(!this._recordCount||!this._totalPages){this._totalPages=this._recordCount=0;const e=await this.adapter.raw({...s,limit:void 0},r.context)||[];if(this._recordCount=e.length,this._recordCount>0){const e=s?.limit||this.size;this._totalPages=Math.ceil(this._recordCount/e)}}e=this.validatePage(e),s.skip=(e-1)*this.size;const n=await this.adapter.raw(s,await this.adapter.context(a.OperationKeys.READ,{},this.clazz));return this._currentPage=e,n}}class xe extends we{constructor(e){super(e)}getSort(){return(e,t)=>{if(!this.orderBySelector)throw new a.InternalError("orderBySelector not set. Should be impossible");const r=this.orderBySelector,[s,n]=r,{designType:i}=o.Metadata.getPropDesignTypes(e.constructor,s);if(!i)throw new _("type not compatible with sorting: "+i);switch(i.name){case"string":case"String":return("asc"===n?1:-1)*e[s].localeCompare(t[s]);case"number":case"Number":return("asc"===n?1:-1)*(e[s]-t[s]);case"object":case"Object":if(e[s]instanceof Date&&t[s]instanceof Date)return("asc"===n?1:-1)*(e[s].valueOf()-t[s].valueOf());throw new _("Sorting not supported for not date classes");default:throw new _("sorting not supported for type "+i)}}}build(){const e={select:this.selectSelector,from:this.fromSelector,where:this.whereCondition?this.parseCondition(this.whereCondition).where:e=>!0,limit:this.limitSelector,skip:this.offsetSelector};return this.orderBySelector&&(e.sort=this.getSort()),e}async paginate(e){try{const t=this.build();return new Ee(this.adapter,t,e,this.fromSelector)}catch(e){throw new a.InternalError(e)}}parseCondition(t){return{where:r=>{const{attr1:s,operator:n,comparison:o}=t;if(-1===[e.GroupOperator.AND,e.GroupOperator.OR,e.Operator.NOT].indexOf(n))switch(n){case e.Operator.BIGGER:return r[s]>o;case e.Operator.BIGGER_EQ:return r[s]>=o;case e.Operator.DIFFERENT:return r[s]!==o;case e.Operator.EQUAL:return r[s]===o;case e.Operator.REGEXP:if("string"!=typeof r[s])throw new _("Invalid regexp comparison on a non string attribute: "+r[s]);return!!r[s].match(RegExp(o,"g"));case e.Operator.SMALLER:return r[s]<o;case e.Operator.SMALLER_EQ:return r[s]<=o;default:throw new a.InternalError("Invalid operator for standard comparisons: "+n)}else{if(n===e.Operator.NOT)throw new a.InternalError("Not implemented");{const t=this.parseCondition(s),i=this.parseCondition(o);switch(n){case e.GroupOperator.AND:return t.where(r)&&i.where(r);case e.GroupOperator.OR:return t.where(r)||i.where(r);default:throw new a.InternalError("Invalid operator for And/Or comparisons: "+n)}}}}}}}async function Ae(e,t,r,a){const s=e.get("UUID");if(!s)throw new d("This adapter does not support user identification");a[r]=s}const Me="ram";class Ce extends f{constructor(e={},t){super(e,Me,t),this.Context=a.Context,this.indexes={},this.lock=new i.Lock}repository(){return super.repository()}async flags(e,t,r){return Object.assign(await super.flags(e,t,r),{UUID:this.config.user||""+Date.now()})}Dispatch(){return super.Dispatch()}async index(...e){return Promise.resolve(void 0)}prepare(e,...t){const r=t.pop(),a=super.prepare(e,...t,r);return delete a.record[s.Model.pk(e.constructor)],a}revert(e,t,r,a,...s){return super.revert(e,t,r,a,...s)}async create(e,t,r,n){const o=n.logger.for(this.create),i=s.Model.tableName(e);if(o.debug(`creating record in table ${i} with id ${t}`),await this.lock.acquire(),this.client.has(i)||this.client.set(i,new Map),this.client.get(i)&&this.client.get(i)?.has(t))throw new a.ConflictError(`Record with id ${t} already exists in table ${i}`);return this.client.get(i)?.set(t,r),this.lock.release(),r}async read(e,t,r){const n=s.Model.tableName(e);if(!this.client.has(n))throw new a.NotFoundError(`Table ${n} not found`);if(!this.client.get(n)?.has(t))throw new a.NotFoundError(`Record with id ${t} not found in table ${n}`);return this.client.get(n)?.get(t)}async update(e,t,r,n){const o=n.logger.for(this.update),i=s.Model.tableName(e);if(o.debug(`updating record in table ${i} with id ${t}`),await this.lock.acquire(),!this.client.has(i))throw new a.NotFoundError(`Table ${i} not found`);if(!this.client.get(i)?.has(t))throw new a.NotFoundError(`Record with id ${t} not found in table ${i}`);return this.client.get(i)?.set(t,r),this.lock.release(),r}async delete(e,t,r){const n=r.logger.for(this.delete),o=s.Model.tableName(e);if(n.debug(`deleting record from table ${o} with pk ${t}`),await this.lock.acquire(),!this.client.has(o))throw new a.NotFoundError(`Table ${o} not found`);if(!this.client.get(o)?.has(t))throw new a.NotFoundError(`Record with id ${t} not found in table ${o}`);const i=this.client.get(o)?.get(t);return this.client.get(o)?.delete(t),this.lock.release(),i}tableFor(e){"string"==typeof e&&(e=s.Model.get(e));const t=s.Model.tableName(e);return this.client.has(t)||this.client.set(t,new Map),this.client.get(t)}async raw(e,t){t.logger.for(this.raw).debug("performing raw query: "+JSON.stringify(e));const{where:r,sort:n,limit:i,skip:c,from:l}=e;let{select:d}=e;const u=this.tableFor(l);if(!u)throw new a.InternalError(`Table ${l} not found in RamAdapter`);const p=s.Model.pk(l),h=o.Metadata.get(l,o.Metadata.key(a.DBKeys.ID,p));let g=Array.from(u.entries()).map((([e,r])=>this.revert(r,l,le.parseValue(h.type,e),void 0,t)));return g=r?g.filter(r):g,n&&(g=g.sort(n)),c&&(g=g.slice(c)),i&&(g=g.slice(0,i)),d&&(d=Array.isArray(d)?d:[d],g=g.map((e=>Object.entries(e).reduce(((e,[t,r])=>(d.includes(t)&&(e[t]=r),e)),{})))),g}parseError(e){return e instanceof a.BaseError?e:new a.InternalError(e)}Statement(){return new xe(this)}for(e,...t){this.proxies||(this.proxies={});const r=`${this.alias} - ${s.hashObj(e)}`;if(r in this.proxies)return this.proxies[r];const a=new Proxy(this,{get:(t,r,a)=>{if("_config"===r){const s=Reflect.get(t,r,a);return Object.assign({},s,e)}return Reflect.get(t,r,a)}});return this.proxies[r]=a,a}static decoration(){super.decoration();const t=e.PersistenceKeys.CREATED_BY,r=e.PersistenceKeys.UPDATED_BY;o.Decoration.flavouredAs(Me).for(t).define(a.onCreate(Ae),o.propMetadata(t,{})).apply(),o.Decoration.flavouredAs(Me).for(r).define(a.onCreateUpdate(Ae),o.propMetadata(r,{})).apply()}getClient(){return new Map}}Ce.decoration(),t.Injectables.setRegistry(new M);const De="##VERSION##",Ne="##PACKAGE##";o.Metadata.registerLibrary(Ne,De),e.AbsMigration=P,e.Adapter=f,e.AuthorizationError=V,e.BaseModel=re,e.BigIntSequence=oe,e.ClientBasedService=he,e.Condition=E,e.ConnectionError=Q,e.ContextualLoggedClass=h,e.DefaultCascade=b,e.DefaultSequenceOptions=se,e.Dispatch=C,e.ForbiddenError=H,e.InjectablesRegistry=M,e.MethodQueryBuilder=ve,e.MigrationError=u,e.MigrationRuleError=p,e.NoneSequenceOptions=ae,e.NumericSequence=ne,e.ObserverError=de,e.ObserverHandler=l,e.OperatorsMap=Oe,e.PACKAGE_NAME=Ne,e.Paginator=ue,e.PagingError=v,e.QueryError=_,e.RamAdapter=Ce,e.RamFlavour=Me,e.RamPaginator=Ee,e.RamStatement=xe,e.Repository=x,e.Sequence=le,e.Serial=N,e.Service=pe,e.Statement=we,e.UUID=D,e.UnsupportedError=d,e.VERSION=De,e.cacheModelForPopulate=k,e.column=t=>o.Decoration.for(e.PersistenceKeys.COLUMN).define({decorator:t=>(r,a)=>o.propMetadata(o.Metadata.key(e.PersistenceKeys.COLUMN,a),t||a)(r,a),args:[t]}).apply(),e.createOrUpdate=T,e.createdAt=J,e.createdBy=()=>{const t=e.PersistenceKeys.CREATED_BY;return o.Decoration.for(t).define({decorator:()=>o.apply(a.onCreate(X),o.propMetadata(t,{})),args:[]}).apply()},e.createdByOnCreateUpdate=X,e.createdByOnRamCreateUpdate=Ae,e.generateInjectableNameForRepository=A,e.getPopulateKey=L,e.index=Y,e.manyToMany=(t,r=b,a=!0,n,i)=>{const c=e.PersistenceKeys.MANY_TO_MANY;return o.Decoration.for(c).define({decorator:(e,t,r,a,n)=>{const i={class:e,cascade:t,populate:r};return a&&(i.joinTable=a),n&&(i.name=n),o.apply(o.prop(),te(c,i),s.list([e,String,Number,BigInt]))},args:[t,r,a,n,i]}).apply()},e.manyToOne=(t,r=b,a=!0,n,i)=>{const c=e.PersistenceKeys.MANY_TO_ONE;return o.Decoration.for(c).define({decorator:(e,t,r,a,n)=>{const i={class:e,cascade:t,populate:r};return a&&(i.joinTable=a),n&&(i.name=n),o.apply(o.prop(),te(c,i),s.type([e,String,Number,BigInt]))},args:[t,r,a,n,i]}).apply()},e.migration=(t,r)=>o.Decoration.for(e.PersistenceKeys.MIGRATION).define({decorator:(t,r)=>a=>{const s=o.Metadata.innerGet(Symbol.for(e.PersistenceKeys.MIGRATION),t)||[];return o.Metadata.set(e.PersistenceKeys.MIGRATION,t,[...s,{class:a}]),o.metadata(e.PersistenceKeys.MIGRATION,{flavour:t,rules:r})(a)},args:[t,r]}).apply(),e.noValidateOn=ee,e.noValidateOnCreate=()=>ee(a.OperationKeys.CREATE),e.noValidateOnCreateUpdate=()=>ee(a.OperationKeys.UPDATE,a.OperationKeys.CREATE),e.noValidateOnUpdate=()=>ee(a.OperationKeys.UPDATE),e.oneToMany=(t,r=b,n=!0,i,c)=>{const l=e.PersistenceKeys.ONE_TO_MANY;return o.Decoration.for(l).define({decorator:(e,t,r,n,i)=>{const c={class:e,cascade:t,populate:r};return n&&(c.joinTable=n),i&&(c.name=i),o.apply(o.prop(),te(l,c),s.list([e,String,Number,BigInt]),a.onCreate(K,c),a.onUpdate(j,c),a.onDelete(F,c),a.afterAny(q,c))},args:[t,r,n,i,c]}).apply()},e.oneToManyOnCreate=K,e.oneToManyOnDelete=F,e.oneToManyOnUpdate=j,e.oneToOne=(t,r=b,n=!0,i,c)=>{const l=e.PersistenceKeys.ONE_TO_ONE;return o.Decoration.for(l).define({decorator:(e,t,r,n,i)=>{const c={class:e,cascade:t,populate:r};return n&&(c.joinTable=n),i&&(c.name=i),o.apply(o.prop(),te(l,c),s.type([e,String,Number,BigInt]),a.onCreate(R,c),a.onUpdate($,c),a.onDelete(B,c),a.afterAny(q,c))},args:[t,r,n,i,c]}).apply()},e.oneToOneOnCreate=R,e.oneToOneOnDelete=B,e.oneToOneOnUpdate=$,e.pk=ce,e.pkOnCreate=ie,e.populate=q,e.prefixMethod=I,e.query=function(e={}){return(t,r,a)=>{const s=r.toString();a.value=function(...t){const{select:r,where:a,groupBy:n,orderBy:o,limit:i,offset:c}=ve.build(s,...t);let l=this.select(r);a&&(l=l.where(a));const{allowLimit:d,allowOffset:u,allowOrderBy:p,throws:h}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...e},g=[{key:"orderBy",value:(o||[])[0],allowed:p},{key:"limit",value:i,allowed:d},{key:"offset",value:c,allowed:u}];for(const e of g)if(void 0!==e.value){if(!e.allowed&&h)throw new _(e.key[0].toUpperCase()+e.key.slice(1)+" is not allowed for this query");e.allowed&&(l=l[e.key](e.value))}return l.execute()}}},e.relation=te,e.repository=(r,n)=>(i,c)=>c?t.inject(o.Metadata.constr(r))(i,c):(o.Metadata.set(a.DBKeys.REPOSITORY,o.Metadata.key(n||f.currentFlavour,s.Model.tableName(r)),i),o.metadata(a.DBKeys.REPOSITORY,i.name)(r),n=n||o.Metadata.get(i.constructor,e.PersistenceKeys.ADAPTER),x.register(o.Metadata.constr(r),i,n),t.injectable(o.Metadata.constr(r),{callback:e=>(Object.defineProperty(e,a.DBKeys.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:r}),e)})(i)),e.repositoryFromTypeMetadata=G,e.table=z,e.unique=()=>{const t=e.PersistenceKeys.UNIQUE;return o.Decoration.for(t).define(s.async(),a.onCreateUpdate(W),o.propMetadata(t,{})).apply()},e.uniqueOnCreateUpdate=W,e.updatedAt=Z,e.updatedBy=()=>{const t=e.PersistenceKeys.UPDATED_BY;return o.Decoration.for(t).define({decorator:()=>o.apply(a.onUpdate(X),o.propMetadata(t,{})),args:[]}).apply()}},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/injectable-decorators"),require("tslib"),require("@decaf-ts/db-decorators"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/logging"),require("@decaf-ts/decoration"),require("@decaf-ts/transactional-decorators")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/injectable-decorators","tslib","@decaf-ts/db-decorators","@decaf-ts/decorator-validation","@decaf-ts/logging","@decaf-ts/decoration","@decaf-ts/transactional-decorators"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).core={},e.decafTsInjectableDecorators,e.tslib,e.decafTsDbDecorators,e.decafTsDecoratorValidation,e.decafTsLogging,e.decafTsDecoration,e.decafTsTransactionalDecorators);
2
2
  //# sourceMappingURL=core.cjs.map