@decaf-ts/core 0.7.59 → 0.7.61
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/core.cjs +1 -1
- package/dist/core.cjs.map +1 -1
- package/dist/core.js +1 -1
- package/dist/core.js.map +1 -1
- package/lib/esm/identity/decorators.js +3 -3
- package/lib/esm/identity/decorators.js.map +1 -1
- package/lib/esm/index.d.ts +2 -2
- package/lib/esm/index.js +6 -3
- package/lib/esm/index.js.map +1 -1
- package/lib/esm/migrations/Migration.d.ts +19 -0
- package/lib/esm/migrations/Migration.js +73 -0
- package/lib/esm/migrations/Migration.js.map +1 -0
- package/lib/esm/migrations/MigrationService.d.ts +25 -0
- package/lib/esm/migrations/MigrationService.js +206 -0
- package/lib/esm/migrations/MigrationService.js.map +1 -0
- package/lib/esm/migrations/constants.d.ts +2 -0
- package/lib/esm/migrations/constants.js +5 -0
- package/lib/esm/migrations/constants.js.map +1 -0
- package/lib/esm/migrations/decorators.d.ts +7 -0
- package/lib/esm/migrations/decorators.js +49 -0
- package/lib/esm/migrations/decorators.js.map +1 -0
- package/lib/esm/migrations/index.d.ts +5 -0
- package/lib/esm/migrations/index.js +6 -0
- package/lib/esm/migrations/index.js.map +1 -0
- package/lib/esm/migrations/types.d.ts +23 -0
- package/lib/esm/migrations/types.js +2 -0
- package/lib/esm/migrations/types.js.map +1 -0
- package/lib/esm/model/SequenceModel.js +1 -1
- package/lib/esm/model/SequenceModel.js.map +1 -1
- package/lib/esm/model/construction.js +4 -3
- package/lib/esm/model/construction.js.map +1 -1
- package/lib/esm/model/decorators.d.ts +0 -1
- package/lib/esm/model/decorators.js +3 -8
- package/lib/esm/model/decorators.js.map +1 -1
- package/lib/esm/overrides/Metadata.d.ts +6 -1
- package/lib/esm/overrides/Model.d.ts +0 -1
- package/lib/esm/overrides/index.d.ts +0 -1
- package/lib/esm/overrides/index.js +0 -1
- package/lib/esm/overrides/index.js.map +1 -1
- package/lib/esm/overrides/injectables.d.ts +1 -1
- package/lib/esm/overrides/overrides.js +17 -9
- package/lib/esm/overrides/overrides.js.map +1 -1
- package/lib/esm/persistence/Adapter.d.ts +11 -18
- package/lib/esm/persistence/Adapter.js +74 -54
- package/lib/esm/persistence/Adapter.js.map +1 -1
- package/lib/esm/persistence/Context.d.ts +3 -3
- package/lib/esm/persistence/Context.js +2 -2
- package/lib/esm/persistence/Context.js.map +1 -1
- package/lib/esm/persistence/Dispatch.d.ts +7 -3
- package/lib/esm/persistence/Dispatch.js +34 -13
- package/lib/esm/persistence/Dispatch.js.map +1 -1
- package/lib/esm/persistence/ObserverHandler.js +1 -1
- package/lib/esm/persistence/ObserverHandler.js.map +1 -1
- package/lib/esm/persistence/Sequence.d.ts +9 -5
- package/lib/esm/persistence/Sequence.js +19 -15
- package/lib/esm/persistence/Sequence.js.map +1 -1
- package/lib/esm/persistence/constants.d.ts +11 -1
- package/lib/esm/persistence/constants.js +26 -3
- package/lib/esm/persistence/constants.js.map +1 -1
- package/lib/esm/persistence/decorators.d.ts +24 -0
- package/lib/esm/persistence/decorators.js +50 -0
- package/lib/esm/persistence/decorators.js.map +1 -0
- package/lib/esm/persistence/errors.d.ts +3 -3
- package/lib/esm/persistence/errors.js.map +1 -1
- package/lib/esm/persistence/event-filters.d.ts +20 -0
- package/lib/esm/persistence/event-filters.js +60 -0
- package/lib/esm/persistence/event-filters.js.map +1 -0
- package/lib/esm/persistence/index.d.ts +1 -1
- package/lib/esm/persistence/index.js +1 -1
- package/lib/esm/persistence/index.js.map +1 -1
- package/lib/esm/persistence/types.d.ts +9 -6
- package/lib/esm/query/Paginator.d.ts +4 -4
- package/lib/esm/query/Paginator.js +17 -8
- package/lib/esm/query/Paginator.js.map +1 -1
- package/lib/esm/query/Statement.d.ts +6 -4
- package/lib/esm/query/Statement.js +24 -18
- package/lib/esm/query/Statement.js.map +1 -1
- package/lib/esm/query/selectors.d.ts +4 -1
- package/lib/esm/ram/RamAdapter.d.ts +6 -5
- package/lib/esm/ram/RamAdapter.js +20 -16
- package/lib/esm/ram/RamAdapter.js.map +1 -1
- package/lib/esm/ram/RamPaginator.d.ts +1 -1
- package/lib/esm/ram/RamPaginator.js +6 -2
- package/lib/esm/ram/RamPaginator.js.map +1 -1
- package/lib/esm/ram/types.d.ts +2 -0
- package/lib/esm/repository/Repository.d.ts +10 -8
- package/lib/esm/repository/Repository.js +107 -76
- package/lib/esm/repository/Repository.js.map +1 -1
- package/lib/esm/repository/decorators.d.ts +1 -1
- package/lib/esm/repository/decorators.js +1 -1
- package/lib/esm/repository/decorators.js.map +1 -1
- package/lib/esm/repository/injectables.d.ts +2 -1
- package/lib/esm/repository/injectables.js.map +1 -1
- package/lib/esm/services/ModelService.d.ts +42 -0
- package/lib/esm/services/ModelService.js +236 -0
- package/lib/esm/services/ModelService.js.map +1 -0
- package/lib/esm/services/PersistenceService.d.ts +16 -0
- package/lib/esm/services/PersistenceService.js +34 -0
- package/lib/esm/services/PersistenceService.js.map +1 -0
- package/lib/esm/services/index.d.ts +3 -0
- package/lib/esm/services/index.js +4 -0
- package/lib/esm/services/index.js.map +1 -0
- package/lib/esm/services/services.d.ts +93 -0
- package/lib/esm/services/services.js +241 -0
- package/lib/esm/services/services.js.map +1 -0
- package/lib/esm/tasks/TaskContext.d.ts +10 -0
- package/lib/esm/tasks/TaskContext.js +22 -0
- package/lib/esm/tasks/TaskContext.js.map +1 -0
- package/lib/esm/tasks/TaskEngine.d.ts +64 -0
- package/lib/esm/tasks/TaskEngine.js +341 -0
- package/lib/esm/tasks/TaskEngine.js.map +1 -0
- package/lib/esm/tasks/TaskEventBus.d.ts +6 -0
- package/lib/esm/tasks/TaskEventBus.js +14 -0
- package/lib/esm/tasks/TaskEventBus.js.map +1 -0
- package/lib/esm/tasks/TaskEventRepository.d.ts +10 -0
- package/lib/esm/tasks/TaskEventRepository.js +35 -0
- package/lib/esm/tasks/TaskEventRepository.js.map +1 -0
- package/lib/esm/tasks/TaskHandler.d.ts +11 -0
- package/lib/esm/tasks/TaskHandler.js +28 -0
- package/lib/esm/tasks/TaskHandler.js.map +1 -0
- package/lib/esm/tasks/TaskHandlerRegistry.d.ts +8 -0
- package/lib/esm/tasks/TaskHandlerRegistry.js +32 -0
- package/lib/esm/tasks/TaskHandlerRegistry.js.map +1 -0
- package/lib/esm/tasks/TaskService.d.ts +11 -0
- package/lib/esm/tasks/TaskService.js +25 -0
- package/lib/esm/tasks/TaskService.js.map +1 -0
- package/lib/esm/tasks/constants.d.ts +26 -0
- package/lib/esm/tasks/constants.js +32 -0
- package/lib/esm/tasks/constants.js.map +1 -0
- package/lib/esm/tasks/decorators.d.ts +4 -0
- package/lib/esm/tasks/decorators.js +20 -0
- package/lib/esm/tasks/decorators.js.map +1 -0
- package/lib/esm/tasks/index.d.ts +3 -0
- package/lib/esm/tasks/index.js +4 -0
- package/lib/esm/tasks/index.js.map +1 -0
- package/lib/esm/tasks/models/TaskBackoffModel.d.ts +10 -0
- package/lib/esm/tasks/models/TaskBackoffModel.js +47 -0
- package/lib/esm/tasks/models/TaskBackoffModel.js.map +1 -0
- package/lib/esm/tasks/models/TaskBaseModel.d.ts +14 -0
- package/lib/esm/tasks/models/TaskBaseModel.js +30 -0
- package/lib/esm/tasks/models/TaskBaseModel.js.map +1 -0
- package/lib/esm/tasks/models/TaskErrorModel.d.ts +9 -0
- package/lib/esm/tasks/models/TaskErrorModel.js +43 -0
- package/lib/esm/tasks/models/TaskErrorModel.js.map +1 -0
- package/lib/esm/tasks/models/TaskEventModel.d.ts +11 -0
- package/lib/esm/tasks/models/TaskEventModel.js +60 -0
- package/lib/esm/tasks/models/TaskEventModel.js.map +1 -0
- package/lib/esm/tasks/models/TaskLogEntryModel.d.ts +9 -0
- package/lib/esm/tasks/models/TaskLogEntryModel.js +41 -0
- package/lib/esm/tasks/models/TaskLogEntryModel.js.map +1 -0
- package/lib/esm/tasks/models/TaskModel.d.ts +28 -0
- package/lib/esm/tasks/models/TaskModel.js +114 -0
- package/lib/esm/tasks/models/TaskModel.js.map +1 -0
- package/lib/esm/tasks/models/TaskStepResultModel.d.ts +10 -0
- package/lib/esm/tasks/models/TaskStepResultModel.js +40 -0
- package/lib/esm/tasks/models/TaskStepResultModel.js.map +1 -0
- package/lib/esm/tasks/models/TaskStepSpecModel.d.ts +7 -0
- package/lib/esm/tasks/models/TaskStepSpecModel.js +32 -0
- package/lib/esm/tasks/models/TaskStepSpecModel.js.map +1 -0
- package/lib/esm/tasks/models/index.d.ts +1 -0
- package/lib/esm/tasks/models/index.js +2 -0
- package/lib/esm/tasks/models/index.js.map +1 -0
- package/lib/esm/tasks/types.d.ts +22 -0
- package/lib/esm/tasks/types.js +2 -0
- package/lib/esm/tasks/types.js.map +1 -0
- package/lib/esm/tasks/utils.d.ts +5 -0
- package/lib/esm/tasks/utils.js +24 -0
- package/lib/esm/tasks/utils.js.map +1 -0
- package/lib/esm/utils/ContextualLoggedClass.d.ts +28 -7
- package/lib/esm/utils/ContextualLoggedClass.js +100 -22
- package/lib/esm/utils/ContextualLoggedClass.js.map +1 -1
- package/lib/esm/utils/decorators.d.ts +4 -4
- package/lib/esm/utils/decorators.js +1 -1
- package/lib/esm/utils/decorators.js.map +1 -1
- package/lib/esm/utils/index.d.ts +0 -1
- package/lib/esm/utils/index.js +0 -1
- package/lib/esm/utils/index.js.map +1 -1
- package/lib/esm/utils/utils.d.ts +1 -0
- package/lib/esm/utils/utils.js +24 -0
- package/lib/esm/utils/utils.js.map +1 -1
- package/lib/identity/decorators.cjs +2 -2
- package/lib/identity/decorators.js.map +1 -1
- package/lib/index.cjs +6 -3
- package/lib/index.d.ts +2 -2
- package/lib/index.js.map +1 -1
- package/lib/migrations/Migration.cjs +77 -0
- package/lib/migrations/Migration.d.ts +19 -0
- package/lib/migrations/Migration.js.map +1 -0
- package/lib/migrations/MigrationService.cjs +210 -0
- package/lib/migrations/MigrationService.d.ts +25 -0
- package/lib/migrations/MigrationService.js.map +1 -0
- package/lib/migrations/constants.cjs +8 -0
- package/lib/migrations/constants.d.ts +2 -0
- package/lib/migrations/constants.js.map +1 -0
- package/lib/migrations/decorators.cjs +52 -0
- package/lib/migrations/decorators.d.ts +7 -0
- package/lib/migrations/decorators.js.map +1 -0
- package/lib/migrations/index.cjs +22 -0
- package/lib/migrations/index.d.ts +5 -0
- package/lib/migrations/index.js.map +1 -0
- package/lib/migrations/types.cjs +3 -0
- package/lib/migrations/types.d.ts +23 -0
- package/lib/migrations/types.js.map +1 -0
- package/lib/model/SequenceModel.cjs +1 -1
- package/lib/model/SequenceModel.js.map +1 -1
- package/lib/model/construction.cjs +4 -3
- package/lib/model/construction.js.map +1 -1
- package/lib/model/decorators.cjs +2 -8
- package/lib/model/decorators.d.ts +0 -1
- package/lib/model/decorators.js.map +1 -1
- package/lib/overrides/Metadata.d.ts +6 -1
- package/lib/overrides/Model.d.ts +0 -1
- package/lib/overrides/index.cjs +0 -1
- package/lib/overrides/index.d.ts +0 -1
- package/lib/overrides/index.js.map +1 -1
- package/lib/overrides/injectables.d.ts +1 -1
- package/lib/overrides/overrides.cjs +17 -9
- package/lib/overrides/overrides.js.map +1 -1
- package/lib/persistence/Adapter.cjs +72 -52
- package/lib/persistence/Adapter.d.ts +11 -18
- package/lib/persistence/Adapter.js.map +1 -1
- package/lib/persistence/Context.cjs +2 -2
- package/lib/persistence/Context.d.ts +3 -3
- package/lib/persistence/Context.js.map +1 -1
- package/lib/persistence/Dispatch.cjs +34 -13
- package/lib/persistence/Dispatch.d.ts +7 -3
- package/lib/persistence/Dispatch.js.map +1 -1
- package/lib/persistence/ObserverHandler.cjs +1 -1
- package/lib/persistence/ObserverHandler.js.map +1 -1
- package/lib/persistence/Sequence.cjs +19 -15
- package/lib/persistence/Sequence.d.ts +9 -5
- package/lib/persistence/Sequence.js.map +1 -1
- package/lib/persistence/constants.cjs +26 -3
- package/lib/persistence/constants.d.ts +11 -1
- package/lib/persistence/constants.js.map +1 -1
- package/lib/persistence/decorators.cjs +54 -0
- package/lib/persistence/decorators.d.ts +24 -0
- package/lib/persistence/decorators.js.map +1 -0
- package/lib/persistence/errors.d.ts +3 -3
- package/lib/persistence/errors.js.map +1 -1
- package/lib/persistence/event-filters.cjs +71 -0
- package/lib/persistence/event-filters.d.ts +20 -0
- package/lib/persistence/event-filters.js.map +1 -0
- package/lib/persistence/index.cjs +1 -1
- package/lib/persistence/index.d.ts +1 -1
- package/lib/persistence/index.js.map +1 -1
- package/lib/persistence/types.d.ts +9 -6
- package/lib/query/Paginator.cjs +20 -11
- package/lib/query/Paginator.d.ts +4 -4
- package/lib/query/Paginator.js.map +1 -1
- package/lib/query/Statement.cjs +48 -42
- package/lib/query/Statement.d.ts +6 -4
- package/lib/query/Statement.js.map +1 -1
- package/lib/query/selectors.d.ts +4 -1
- package/lib/ram/RamAdapter.cjs +20 -16
- package/lib/ram/RamAdapter.d.ts +6 -5
- package/lib/ram/RamAdapter.js.map +1 -1
- package/lib/ram/RamPaginator.cjs +6 -2
- package/lib/ram/RamPaginator.d.ts +1 -1
- package/lib/ram/RamPaginator.js.map +1 -1
- package/lib/ram/types.d.ts +2 -0
- package/lib/repository/Repository.cjs +106 -75
- package/lib/repository/Repository.d.ts +10 -8
- package/lib/repository/Repository.js.map +1 -1
- package/lib/repository/decorators.d.ts +1 -1
- package/lib/repository/decorators.js.map +1 -1
- package/lib/repository/injectables.d.ts +2 -1
- package/lib/repository/injectables.js.map +1 -1
- package/lib/services/ModelService.cjs +240 -0
- package/lib/services/ModelService.d.ts +42 -0
- package/lib/services/ModelService.js.map +1 -0
- package/lib/services/PersistenceService.cjs +38 -0
- package/lib/services/PersistenceService.d.ts +16 -0
- package/lib/services/PersistenceService.js.map +1 -0
- package/lib/services/index.cjs +20 -0
- package/lib/services/index.d.ts +3 -0
- package/lib/services/index.js.map +1 -0
- package/lib/services/services.cjs +246 -0
- package/lib/services/services.d.ts +93 -0
- package/lib/services/services.js.map +1 -0
- package/lib/tasks/TaskContext.cjs +26 -0
- package/lib/tasks/TaskContext.d.ts +10 -0
- package/lib/tasks/TaskContext.js.map +1 -0
- package/lib/tasks/TaskEngine.cjs +345 -0
- package/lib/tasks/TaskEngine.d.ts +64 -0
- package/lib/tasks/TaskEngine.js.map +1 -0
- package/lib/tasks/TaskEventBus.cjs +18 -0
- package/lib/tasks/TaskEventBus.d.ts +6 -0
- package/lib/tasks/TaskEventBus.js.map +1 -0
- package/lib/tasks/TaskEventRepository.cjs +38 -0
- package/lib/tasks/TaskEventRepository.d.ts +10 -0
- package/lib/tasks/TaskEventRepository.js.map +1 -0
- package/lib/tasks/TaskHandler.cjs +32 -0
- package/lib/tasks/TaskHandler.d.ts +11 -0
- package/lib/tasks/TaskHandler.js.map +1 -0
- package/lib/tasks/TaskHandlerRegistry.cjs +36 -0
- package/lib/tasks/TaskHandlerRegistry.d.ts +8 -0
- package/lib/tasks/TaskHandlerRegistry.js.map +1 -0
- package/lib/tasks/TaskService.cjs +29 -0
- package/lib/tasks/TaskService.d.ts +11 -0
- package/lib/tasks/TaskService.js.map +1 -0
- package/lib/tasks/constants.cjs +35 -0
- package/lib/tasks/constants.d.ts +26 -0
- package/lib/tasks/constants.js.map +1 -0
- package/lib/tasks/decorators.cjs +23 -0
- package/lib/tasks/decorators.d.ts +4 -0
- package/lib/tasks/decorators.js.map +1 -0
- package/lib/tasks/index.cjs +20 -0
- package/lib/tasks/index.d.ts +3 -0
- package/lib/tasks/index.js.map +1 -0
- package/lib/tasks/models/TaskBackoffModel.cjs +50 -0
- package/lib/tasks/models/TaskBackoffModel.d.ts +10 -0
- package/lib/tasks/models/TaskBackoffModel.js.map +1 -0
- package/lib/tasks/models/TaskBaseModel.cjs +34 -0
- package/lib/tasks/models/TaskBaseModel.d.ts +14 -0
- package/lib/tasks/models/TaskBaseModel.js.map +1 -0
- package/lib/tasks/models/TaskErrorModel.cjs +46 -0
- package/lib/tasks/models/TaskErrorModel.d.ts +9 -0
- package/lib/tasks/models/TaskErrorModel.js.map +1 -0
- package/lib/tasks/models/TaskEventModel.cjs +63 -0
- package/lib/tasks/models/TaskEventModel.d.ts +11 -0
- package/lib/tasks/models/TaskEventModel.js.map +1 -0
- package/lib/tasks/models/TaskLogEntryModel.cjs +44 -0
- package/lib/tasks/models/TaskLogEntryModel.d.ts +9 -0
- package/lib/tasks/models/TaskLogEntryModel.js.map +1 -0
- package/lib/tasks/models/TaskModel.cjs +117 -0
- package/lib/tasks/models/TaskModel.d.ts +28 -0
- package/lib/tasks/models/TaskModel.js.map +1 -0
- package/lib/tasks/models/TaskStepResultModel.cjs +43 -0
- package/lib/tasks/models/TaskStepResultModel.d.ts +10 -0
- package/lib/tasks/models/TaskStepResultModel.js.map +1 -0
- package/lib/tasks/models/TaskStepSpecModel.cjs +35 -0
- package/lib/tasks/models/TaskStepSpecModel.d.ts +7 -0
- package/lib/tasks/models/TaskStepSpecModel.js.map +1 -0
- package/lib/tasks/models/index.cjs +18 -0
- package/lib/tasks/models/index.d.ts +1 -0
- package/lib/tasks/models/index.js.map +1 -0
- package/lib/tasks/types.cjs +3 -0
- package/lib/tasks/types.d.ts +22 -0
- package/lib/tasks/types.js.map +1 -0
- package/lib/tasks/utils.cjs +29 -0
- package/lib/tasks/utils.d.ts +5 -0
- package/lib/tasks/utils.js.map +1 -0
- package/lib/utils/ContextualLoggedClass.cjs +100 -21
- package/lib/utils/ContextualLoggedClass.d.ts +28 -7
- package/lib/utils/ContextualLoggedClass.js.map +1 -1
- package/lib/utils/decorators.cjs +2 -2
- package/lib/utils/decorators.d.ts +4 -4
- package/lib/utils/decorators.js.map +1 -1
- package/lib/utils/index.cjs +0 -1
- package/lib/utils/index.d.ts +0 -1
- package/lib/utils/index.js.map +1 -1
- package/lib/utils/utils.cjs +25 -0
- package/lib/utils/utils.d.ts +1 -0
- package/lib/utils/utils.js.map +1 -1
- package/package.json +12 -2
- package/lib/esm/overrides/decoration.d.ts +0 -1
- package/lib/esm/overrides/decoration.js +0 -6
- package/lib/esm/overrides/decoration.js.map +0 -1
- package/lib/esm/persistence/migrations.d.ts +0 -21
- package/lib/esm/persistence/migrations.js +0 -103
- package/lib/esm/persistence/migrations.js.map +0 -1
- package/lib/esm/utils/Services.d.ts +0 -83
- package/lib/esm/utils/Services.js +0 -392
- package/lib/esm/utils/Services.js.map +0 -1
- package/lib/overrides/decoration.cjs +0 -8
- package/lib/overrides/decoration.d.ts +0 -1
- package/lib/overrides/decoration.js.map +0 -1
- package/lib/persistence/migrations.cjs +0 -109
- package/lib/persistence/migrations.d.ts +0 -21
- package/lib/persistence/migrations.js.map +0 -1
- package/lib/utils/Services.cjs +0 -398
- package/lib/utils/Services.d.ts +0 -83
- package/lib/utils/Services.js.map +0 -1
package/README.md
CHANGED
|
@@ -29,7 +29,7 @@ Decaf Core provides the foundational building blocks for the Decaf TypeScript ec
|
|
|
29
29
|
|
|
30
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)
|
|
31
31
|
|
|
32
|
-
Minimal size: 20.
|
|
32
|
+
Minimal size: 20.5 KB kb gzipped
|
|
33
33
|
|
|
34
34
|
|
|
35
35
|
# Core Package — Detailed Description
|
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;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",c.STATEMENT="statement",c.QUERY="query",c.GENERATED="generated";const l=Object.assign({},a.DefaultRepositoryFlags,{allowGenerationOverride:!1,enforceUpdateValidation:!0,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,cacheForPopulate:{}});class d{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}=_.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 p extends a.Context{constructor(){super()}}class u extends a.InternalError{constructor(e){super(e,u.name,500)}}class h extends a.InternalError{constructor(e,t=h.name){super(e,t,500)}}class g extends h{constructor(e){super(e,g.name)}}class f extends s.LoggedClass{logFor(e,...t){return e.logger.for(this)}logCtx(e,t){return f.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]}}}function y(e){if(!e)throw new a.InternalError("No name provided");return"string"==typeof e?e.replaceAll(".","-"):o.Metadata.Symbol(o.Metadata.constr(e)).toString().replaceAll(".","-")}function m(e){return e.reduce((e,t)=>e.then(async e=>[...e,await t()]),Promise.resolve([]))}function w(e,t){const{handler:r,args:s}=o.Metadata.get(e,a.OperationKeys.REFLECT+a.OperationKeys.BLOCK)||{};return!!r&&(r(...s,t)??!1)}const b=o.Decoration.flavourResolver.bind(o.Decoration);o.Decoration.flavourResolver=e=>{try{const t=b(e);if(t&&t!==o.DefaultFlavour)return t;const r="function"==typeof e?e:e?.constructor,a=r&&"function"==typeof o.Metadata.registeredFlavour?o.Metadata.registeredFlavour(r):void 0;if(a&&a!==o.DefaultFlavour)return a;const s=_._currentFlavour;if(s){const e=_._cache?.[s];return e?.flavour?e.flavour:s}}catch(e){return o.DefaultFlavour}};class _ extends f{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!_._baseRepository)throw new a.InternalError("This should be overridden when necessary. Otherwise it will be replaced lazily");return _._baseRepository}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=p,this.alias in _._cache)throw new a.InternalError(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);_._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),_._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),_._currentFlavour=this.alias)}Dispatch(){return new _._baseDispatch}ObserverHandler(){return new d}isReserved(e){return!e}async initialize(...e){}async Sequence(e){return new _._baseSequence(e,this)}async flags(e,t,r,...i){let c=r.logger||s.Logging.for(this.toString());return r.correlationId&&(c=c.for({correlationId:r.correlationId})),Object.assign({},l,r,{affectedTables:(Array.isArray(t)?t:[t]).map(n.Model.tableName),writeOperation:e!==a.OperationKeys.READ,timestamp:new Date,operation:e,ignoredValidationProperties:o.Metadata.validationExceptions(Array.isArray(t)&&t[0]?t[0]:t,e),logger:c})}async context(e,t,r,...a){this.log.for(this.context).debug(`Creating new context for ${e} operation on ${r?Array.isArray(r)?r.map(e=>e.name):r.name:"no"} 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:s}=this.logCtx(r,this.prepare),o=t.segregate(),i=Object.entries(o.model).reduce((e,[r,s])=>{if(void 0===s)return e;const o=n.Model.columnName(t.constructor,r);if(this.isReserved(o))throw new a.InternalError(`Property name ${o} is reserved`);return e[o]=s,e},{});return t[e.PersistenceKeys.METADATA]&&(s.silly("Passing along persistence metadata for "+t[e.PersistenceKeys.METADATA]),Object.defineProperty(i,e.PersistenceKeys.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[e.PersistenceKeys.METADATA]})),{record:i,id:t[n.Model.pk(t.constructor)],transient:o.transient}}revert(t,r,s,o,...i){const{log:c,ctx:l}=this.logCtx(i,this.revert),d={};d[n.Model.pk(r)]=s;const p=new r(d);c.silly(`Rebuilding model ${p.constructor.name} id ${s}`);const u=t[e.PersistenceKeys.METADATA],h=Object.keys(p).reduce((e,a)=>(e[a]=t[n.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 h)throw new a.InternalError(`Transient property ${e} already exists on model ${p.constructor.name}. should be impossible`);h[e]=t})),u&&(c.silly(`Passing along ${this.flavour} persistence metadata for ${p.constructor.name} id ${s}: ${u}`),Object.defineProperty(h,e.PersistenceKeys.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:u})),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{log:o,ctxArgs:i}=this.logCtx(s,this.createAll),c=n.Model.tableName(e);return o.debug(`Creating ${t.length} entries ${c} table`),m(t.map((t,a)=>()=>this.create(e,t,r[a],...i)))}async readAll(e,t,...r){const{log:a,ctxArgs:s}=this.logCtx(r,this.readAll),o=n.Model.tableName(e);return a.debug(`Reading ${t.length} entries ${o} table`),m(t.map(t=>()=>this.read(e,t,...s)))}async updateAll(e,t,r,...s){if(t.length!==r.length)throw new a.InternalError("Ids and models must have the same length");const{log:o,ctxArgs:i}=this.logCtx(s,this.updateAll),c=n.Model.tableName(e);return o.debug(`Updating ${t.length} entries ${c} table`),m(t.map((t,a)=>()=>this.update(e,t,r[a],...i)))}async deleteAll(e,t,...r){const{log:a,ctxArgs:s}=_.logCtx(r,this.deleteAll);return a.debug(`Deleting ${t.length} entries from ${e} table`),m(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}=_.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(!_._currentFlavour)throw new a.InternalError("No persistence flavour set. Please initialize your adapter");return _._currentFlavour}static get current(){return _.get(this.currentFlavour)}static get(e){if(!e)return _.get(this._currentFlavour);if(e in this._cache)return this._cache[e];throw new a.InternalError(`No Adapter registered under ${e}.`)}static setCurrent(e){this._currentFlavour=e}static models(e){try{return o.Metadata.flavouredAs(e).filter(n.Model.isModel)}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} - ${n.hashObj(e)}`;if(r in this.proxies)return this.proxies[r];let a;const s=new Proxy(this,{get:(t,r,s)=>{if("_config"===r){const a=Reflect.get(t,r,s);return Object.assign({},a,e)}return"_client"===r?a:Reflect.get(t,r,s)},set:(e,t,r,s)=>"_client"===t?(a=r,!0):Reflect.set(e,t,r,s)});return this.proxies[r]=s,s}migrations(){return o.Metadata.migrationsFor(this)}async getQueryRunner(){return this}async migrate(e=this.migrations(),...t){e instanceof p&&(t=[e],e=this.migrations());const{ctx:r}=_.logCtx(t,this.migrate),a=await this.getQueryRunner();for(const t of e)try{const e=new t;await e.up(a,this,r),await e.down(a,this,r)}catch(e){throw new h(e)}}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String]),r.__metadata("design:returntype",Promise)],_.prototype,"shutdownProxies",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,Object,Object,Object]),r.__metadata("design:returntype",Promise)],_.prototype,"context",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",void 0)],_.prototype,"observe",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],_.prototype,"unObserve",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],_.prototype,"client",null);class O extends a.InternalError{constructor(e){super(e,O.name,500)}}class E extends a.InternalError{constructor(e){super(e,E.name,500)}}var v,x,A,M,C,P;e.QueryClause=void 0,(v=e.QueryClause||(e.QueryClause={})).FIND_BY="findBy",v.SELECT="Select",v.AND="And",v.OR="Or",v.GROUP_BY="GroupBy",v.ORDER_BY="OrderBy",v.THEN="Then",v.THEN_BY="ThenBy",e.Operator=void 0,(x=e.Operator||(e.Operator={})).EQUAL="EQUAL",x.DIFFERENT="DIFFERENT",x.BIGGER="BIGGER",x.BIGGER_EQ="BIGGER_EQ",x.SMALLER="SMALLER",x.SMALLER_EQ="SMALLER_EQ",x.NOT="NOT",x.IN="IN",x.REGEXP="REGEXP",e.GroupOperator=void 0,(A=e.GroupOperator||(e.GroupOperator={})).AND="AND",A.OR="OR",e.PreparedStatementKeys=void 0,(M=e.PreparedStatementKeys||(e.PreparedStatementKeys={})).LIST_BY="listBy",M.FIND_BY="findBy",M.FIND_ONE_BY="findOneBy",M.PAGE_BY="paginateBy";class N extends n.Model{constructor(e,t,r){super(),this.attr1=void 0,this.operator=void 0,this.comparison=void 0,t||r?(this.attr1=e,this.operator=t,this.comparison=r):n.Model.fromModel(this,e)}and(e){return N.and(this,e)}or(e){return N.or(this,e)}not(t){return new N(this,e.Operator.NOT,t)}hasErrors(...t){const r=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof N)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 N){if(!(this.comparison instanceof N)&&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 N.group(t,e.GroupOperator.AND,r)}static or(t,r){return N.group(t,e.GroupOperator.OR,r)}static group(e,t,r){return new N(e,t,r)}static attribute(e){return(new N.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 N(this.attr1,this.operator,this.comparison)}catch(e){throw new O(e)}}}}static builder(){return new N.Builder}static from(e){return new N(e)}}r.__decorate([n.required(),r.__metadata("design:type",Object)],N.prototype,"attr1",void 0),r.__decorate([n.required(),r.__metadata("design:type",String)],N.prototype,"operator",void 0),r.__decorate([n.required(),r.__metadata("design:type",Object)],N.prototype,"comparison",void 0),e.OrderDirection=void 0,(C=e.OrderDirection||(e.OrderDirection={})).ASC="asc",C.DSC="desc",e.Cascade=void 0,(P=e.Cascade||(e.Cascade={})).CASCADE="cascade",P.NONE="none";const D={update:e.Cascade.CASCADE,delete:e.Cascade.NONE},I={Equals:(e,t)=>N.attribute(e).eq(t),Diff:(e,t)=>N.attribute(e).dif(t),LessThan:(e,t)=>N.attribute(e).lt(t),LessThanEqual:(e,t)=>N.attribute(e).lte(t),GreaterThan:(e,t)=>N.attribute(e).gt(t),GreaterThanEqual:(e,t)=>N.attribute(e).gte(t),In:(e,t)=>N.attribute(e).in(t),Matches:(e,t)=>N.attribute(e).regexp(t)},B=e=>e.charAt(0).toLowerCase()+e.slice(1);class T extends s.LoggedClass{static get log(){return this._logger||(this._logger=s.Logging.for(T.name)),this._logger}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(t,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 getFieldsFromMethodName(e){return(this.extractCore(e).split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/).map(e=>{const{operator:t,field:r}=this.parseFieldAndOperator(e);return r+(t??"")})}static extractSelect(t){const r=t.indexOf(e.QueryClause.SELECT);if(-1===r)return;const a=t.substring(r+e.QueryClause.SELECT.length),s=a.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?a.substring(0,s.index):a).split(e.QueryClause.AND).map(B).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(B).filter(Boolean)}static buildWhere(t,r){if(!t&&0===r.length)return;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?I[i]:I.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)}),0!==a.length){if(!n)throw Error("No conditions found in method name");return n}}static parseFieldAndOperator(e){for(const t of Object.keys(I))if(e.endsWith(t)){const r=e.slice(0,-t.length);return{field:B(r),operator:t}}return{field:B(e)}}static extractOrderByField(e){const t=e.match(/OrderBy(.+)$/);if(!t)return;const r=t[1];return r.charAt(0).toLowerCase()+r.slice(1)}static getProperlyOrderByOrThrow(t,r){const a=T.log.for(this.getProperlyOrderByOrThrow);if(r||t){if(r&&!t)throw new O("Expected OrderBy clause, but no sortable field was found in method name.");if(r||!t){if(!Object.values(e.OrderDirection).includes(r))throw new O(`Invalid OrderBy direction ${r}. Expected one of: ${Object.values(e.OrderDirection).join(", ")}.`);return[[t,r]]}a.debug("Ignoring OrderBy clause because direction is undefined.")}}static extractOrderLimitOffset(e,t){const r=this.extractCore(e).split(/And|Or/).length,s=t.slice(r)??[];let n,o,i;if(s.at(-1)instanceof a.Context&&s.pop(),s.length>=1){const t=s[0],r=this.extractOrderByField(e);n=this.getProperlyOrderByOrThrow(r,t)}return 2>s.length||"number"!=typeof s[1]||(o=s[1]),3>s.length||"number"!=typeof s[2]||(i=s[2]),{orderBy:n,limit:o,offset:i}}}function $(){return o.Decoration.for(e.PersistenceKeys.STATEMENT).define({decorator:()=>(t,r,a)=>o.apply(o.methodMetadata(o.Metadata.key(e.PersistenceKeys.STATEMENT,r),!0))(t,r,a),args:[]}).apply()}class R 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.Model.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}constructor(e,t,...r){super(t),this.observers=[],this._overrides={allowGenerationOverride:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,ignoreDevSafeGuards:!1,mergeForUpdate:!0,applyUpdateValidation:!0},e&&(this._adapter=e),t&&(R.register(t,this,this.adapter.alias),e)&&o.Metadata.get(t,o.DecorationKeys.FLAVOUR)===o.DefaultFlavour&&o.uses(e.flavour)(t);const s=this;[this.createAll,this.readAll,this.deleteAll].forEach(e=>{const t=e.name;a.wrapMethodWithContext(s,s[t+"Prefix"],e,s[t+"Suffix"])}),a.wrapMethodWithContextForUpdate(s,s[this.updateAll.name+"Prefix"],this.updateAll,s[this.updateAll.name+"Suffix"])}logCtx(e,t){return _.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 d}async createPrefix(e,...t){const r=await p.args(a.OperationKeys.CREATE,this.class,t,this.adapter,this._overrides||{}),s=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:s}=this.logCtx(t,this.create);a.debug(`Creating new ${this.class.name} in table ${n.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,...s),this.adapter.revert(o,this.class,i,c,r)}async createAll(e,...t){if(!e.length)return e;const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.createAll);a.debug(`Creating ${e.length} new ${this.class.name} in table ${n.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,...s),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 p.args(a.OperationKeys.CREATE,this.class,t,this.adapter,this._overrides||{}),s=r.context.get("ignoreHandlers"),o=r.context.get("ignoreValidation");if(!e.length)return[e,...r.args];const i=n.Model.sequenceFor(e[0]);let c=[];if(n.Model.generatedBySequence(this.class)?(i.name||(i.name=n.Model.sequenceName(e[0],"pk")),c=await(await this.adapter.Sequence(i)).range(e.length,...r.args)):n.Model.generated(this.class,this.pk)||(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]),s||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 p.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:s}=this.logCtx(t,this.read);a.debug(`reading ${this.class.name} from table ${n.Model.tableName(this.class)} with pk ${this.pk}`);const o=await this.adapter.read(this.class,e,...s);return this.adapter.revert(o,this.class,e,void 0,r)}async readAllPrefix(e,...t){const r=await p.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:s}=this.logCtx(t,this.readAll);return a.debug(`reading ${e.length} ${this.class.name} in table ${n.Model.tableName(this.class)}`),(await this.adapter.readAll(this.class,e,...s)).map((t,a)=>this.adapter.revert(t,this.class,e[a],void 0,r))}async update(e,...t){const{ctxArgs:r,log:a,ctx:s}=this.logCtx(t,this.update);let{record:o,id:i,transient:c}=this.adapter.prepare(e,s);return a.debug(`updating ${this.class.name} in table ${n.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,s)}async updatePrefix(e,...t){const r=await p.args(a.OperationKeys.UPDATE,this.class,t,this.adapter,this._overrides||{}),s=r.context,o=s.get("ignoreHandlers"),i=s.get("ignoreValidation"),c=e[this.pk];if(!c)throw new a.InternalError("No value for the Id is defined under the property "+this.pk);let l;if(s.get("applyUpdateValidation")&&(l=await this.read(c,s),s.get("mergeForUpdate")&&(e=n.Model.merge(l,e,this.class))),o||await a.enforceDBDecorators(this,r.context,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,l),!i){const t=await Promise.resolve(e.hasErrors(l,...r.context.get("ignoredValidationProperties")||[]));if(t)throw new a.ValidationError(t.toString())}return[e,...r.args,l]}async updateAll(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.updateAll);a.debug(`Updating ${e.length} new ${this.class.name} in table ${n.Model.tableName(this.class)}`);const o=e.map(e=>this.adapter.prepare(e,r));return(await this.adapter.updateAll(this.class,o.map(e=>e.id),o.map(e=>e.record),...s)).map((e,t)=>this.adapter.revert(e,this.class,o[t].id,r.get("rebuildWithTransient")?o[t].transient:void 0,r))}async updateAllPrefix(e,...t){const r=await p.args(a.OperationKeys.UPDATE,this.class,t,this.adapter,this._overrides||{}),s=r.context,o=s.get("ignoreHandlers"),i=s.get("ignoreValidation"),c=e.map(e=>{const t=e[this.pk];if(!t)throw new a.InternalError("missing id on update operation");return t});let l;if(s.get("applyUpdateValidation")&&(l=await this.readAll(c,s),s.get("mergeForUpdate")&&(e=e.map((e,t)=>n.Model.merge(l[t],e,this.class)))),o||await Promise.all(e.map((e,t)=>a.enforceDBDecorators(this,r.context,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,l?l[t]:void 0))),!i){const t=s.get("ignoredValidationProperties")||[];let r;r=s.get("applyUpdateValidation")?await Promise.all(e.map((e,r)=>Promise.resolve(e.hasErrors(l[r],...t)))):await Promise.resolve(e.map(e=>e.hasErrors(...t)));const n=a.reduceErrorsToPrint(r);if(n)throw new a.ValidationError(n)}return[e,...r.args,l]}async deletePrefix(e,...t){const r=await p.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:s}=this.logCtx(t,this.delete);a.debug(`deleting new ${this.class.name} in table ${n.Model.tableName(this.class)} with pk ${e}`);const o=await this.adapter.delete(this.class,e,...s);return this.adapter.revert(o,this.class,e,void 0,r)}async deleteAllPrefix(e,...t){const r=await p.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:s}=this.logCtx(t,this.create);return a.debug(`deleting ${e.length} ${this.class.name} in table ${n.Model.tableName(this.class)}`),(await this.adapter.deleteAll(this.class,e,...s)).map((t,a)=>this.adapter.revert(t,this.class,e[a],void 0,r))}select(e){return this.adapter.Statement(this._overrides).select(e).from(this.class)}async query(t,r,a=e.OrderDirection.ASC,s,n,...o){const i=await p.args(e.PersistenceKeys.QUERY,this.class,o,this.adapter,this._overrides||{}),{ctx:c}=this.logCtx(i.args,this.query),l=[r,a],d=this.select().where(t).orderBy(l);return s&&d.limit(s),n&&d.offset(n),d.execute(c)}async listBy(t,r,...a){const s=await p.args(e.PreparedStatementKeys.LIST_BY,this.class,a,this.adapter,this._overrides||{}),{log:o,ctxArgs:i}=this.logCtx(s.args,this.listBy);return o.verbose(`listing ${n.Model.tableName(this.class)} by ${t} ${r}`),this.select().orderBy([t,r]).execute(...i)}async paginateBy(t,r,a={offset:1,limit:10},...s){let{offset:o,bookmark:i,limit:c}=a;if(!o&&!i)throw new O("PaginateBy needs a page or a bookmark");const l=await p.args(e.PreparedStatementKeys.PAGE_BY,this.class,s,this.adapter,this._overrides||{}),{log:d,ctxArgs:u}=this.logCtx(l.args,this.paginateBy);let h;if(d.verbose(`paginating ${n.Model.tableName(this.class)} with page size ${c}`),i)h=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where(this.attr(n.Model.pk(this.class)).gt(i)).orderBy([t,r]).paginate(c,...u),o=1;else{if(!o)throw new O("PaginateBy needs a page or a bookmark");h=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([t,r]).paginate(c,...u)}const g=await h.page(o,...u);return h.serialize(g)}async findOneBy(t,r,...s){const o=await p.args(e.PreparedStatementKeys.FIND_ONE_BY,this.class,s,this.adapter,this._overrides||{}),{log:i,ctxArgs:c}=this.logCtx(o.args,this.findOneBy);i.verbose(`finding ${n.Model.tableName(this.class)} with ${t} ${r}`);const l=await this.select().where(this.attr(t).eq(r)).limit(1).execute(...c);if(!l.length)throw new a.NotFoundError("No results found");return l[0]}async findBy(t,r,...a){const s=await p.args(e.PreparedStatementKeys.FIND_BY,this.class,a,this.adapter,this._overrides||{}),{log:o,ctxArgs:i}=this.logCtx(s.args,this.findBy);return o.verbose(`finding ${n.Model.tableName(this.class)} with ${t} ${r}`),this.select().where(this.attr(t).eq(r)).execute(...i)}async statement(t,...r){if(!R.statements(this,t))throw new O("Invalid prepared statement requested "+t);const a=await p.args(e.PersistenceKeys.STATEMENT,this.class,r,this.adapter,this._overrides||{}),{log:s,ctxArgs:n}=this.logCtx(a.args,this.statement);return s.verbose("Executing prepared statement "+t),this[t](...n)}attr(e){return N.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.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,...s){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");const{log:o,ctxArgs:i}=this.logCtx(s,this.updateObservers);o.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(e,t,Array.isArray(r)?r.map(e=>_._baseSequence.parseValue(n.Model.sequenceFor(this.class).type,e)):_._baseSequence.parseValue(n.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)||_.currentFlavour;try{n=this.get(t,i)}catch(e){n=void 0}if(n instanceof R)return n;const c=r||o.Metadata.flavourOf(t)||n&&o.Metadata.get(n,e.PersistenceKeys.ADAPTER)||_.currentFlavour,l=c?_.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=n.Model.tableName(e);let s=r;if(t&&(s=[r,t].join(a.DefaultSeparator)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new a.InternalError("Could not find repository registered under "+r)}static register(e,t,r){let s=n.Model.tableName(e);if(r&&(s=[s,r].join(a.DefaultSeparator)),s in this._cache&&this._cache[s]instanceof R)throw new a.InternalError(s+" already has a registered instance");this._cache[s]=t}static statements(t,r){const a=t instanceof R?t.constructor:t,s=o.Metadata.get(a,r?o.Metadata.key(e.PersistenceKeys.STATEMENT,r):e.PersistenceKeys.STATEMENT);return(r?s:Object.keys(s))||!1}static queries(t,r){const a=t instanceof R?t.constructor:t;return o.Metadata.get(a,r?o.Metadata.key(e.PersistenceKeys.QUERY,r):e.PersistenceKeys.QUERY)}}function K(t,r){if(!(r||(r=o.Decoration.flavourResolver(t instanceof n.Model?t.constructor:t))&&r!==o.DefaultFlavour))throw new a.InternalError("Could not retrieve flavour from model "+(t instanceof n.Model?t.constructor.name:t.name));return n.sf(e.PersistenceKeys.INJECTABLE,r,n.Model.tableName(t))}r.__decorate([$(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String,void 0]),r.__metadata("design:returntype",Promise)],R.prototype,"listBy",null),r.__decorate([$(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String,Object,void 0]),r.__metadata("design:returntype",Promise)],R.prototype,"paginateBy",null),r.__decorate([$(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,void 0]),r.__metadata("design:returntype",Promise)],R.prototype,"findOneBy",null),r.__decorate([$(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,void 0]),r.__metadata("design:returntype",Promise)],R.prototype,"findBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",void 0)],R.prototype,"observe",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],R.prototype,"unObserve",null),_&&(_._baseRepository=R);class k extends t.InjectableRegistryImp{get log(){return this.logger||(this.logger=s.Logging.for(this)),this.logger}constructor(){super()}get(r,a){const s=this.log.for(this.get);let i;try{i=super.get(r)}catch{}if(!i){let c;if("function"==typeof r?c=n.Model.get(r.name)||r:"symbol"!=typeof r&&"string"!=typeof r||(c=n.Model.get(r.toString())),!c)return;const l=e.PersistenceKeys.ADAPTER,d=a||o.Metadata.get(c,l);try{let e=d;try{d&&_.get(d)}catch{const t=_.current;t&&t.flavour===d&&(e=t.alias)}if(i=R.forModel(c,e),i instanceof R)return i;const r=d||o.Metadata.get(i.constructor,l)||o.Metadata.get(c,l);t.Injectables.register(i,K(c,r))}catch(e){s.debug("No registered repository or adapter found. falling back to default adapter. Error: "+(e?.message||JSON.stringify(e)));const t=R.get(c,d);if("function"==typeof t){const e=d?_.get(d):_.current;if(!e)return;return new t(e,c)}}}return i}}async function F(e,t,r,s){const o=t.logger.for(F);if(!s){const t=n.Model.get(e.constructor.name);if(!t)throw new a.InternalError("Could not find model "+e.constructor.name);s=R.forModel(t,r),o.info("Retrieved "+s.toString())}let i;if(void 0===e[n.Model.pk(s.class)])o.info(`No pk found in ${n.Model.tableName(s.class)} - creating`),i=await s.create(e,t);else{o.info(`pk found in ${n.Model.tableName(s.class)} - attempting update`);try{i=await s.update(e,t),o.info("Updated "+n.Model.tableName(s.class))}catch(r){if(!(r instanceof a.NotFoundError))throw r;o.info("update Failed - creating new "+n.Model.tableName(s.class)),i=await s.create(e,t)}o.info("After create update: "+i)}return i}async function j(e,t,r,o){const i=o[r];if(!i)return;if("object"!=typeof i){const t=W(o,r,this.adapter.alias),a=await t.read(i);return await z(e,o,r,i,a),void(o[r]=i)}const c=s.isClass(t.class)?t.class:t.class();if(!c)throw new a.InternalError("Could not find model "+t.class);const l=R.forModel(c,this.adapter.alias),d=await l.create(i,e),p=n.Model.pk(d);await z(e,o,r,d[p],d),o[r]=d[p]}async function L(t,r,a,s){const o=s[a];if(!o)return;if(r.cascade.update!==e.Cascade.CASCADE)return;if("object"!=typeof o){const e=W(s,a,this.adapter.alias),r=await e.read(o,t);return await z(t,s,a,o,r),void(s[a]=o)}const i=await F(s[a],t,this.adapter.alias),c=n.Model.pk(i);await z(t,s,a,i[c],i),s[a]=i[c]}async function q(t,r,a,s){const o=s[a];if(!o)return;if(r.cascade.update!==e.Cascade.CASCADE)return;const i=W(s,a,this.adapter.alias);let c;c=o instanceof n.Model?await i.delete(s[a][i.pk],t):await i.delete(s[a],t),await z(t,s,a,c[i.pk],c)}async function U(e,t,r,s){const o=s[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=e.logger.for(U),l=new Set([...o]);if("object"!==i){const t=W(s,r,this.adapter.alias),a=await t.readAll([...l.values()],e);for(let t=0;t<a.length;t++){const s=a[t];c.info("FOUND ONE TO MANY VALUE: "+JSON.stringify(s)),await z(e,s,r,[...l.values()][t],a)}return s[r]=[...l],void c.info("SET ONE TO MANY IDS: "+s[r])}const d=n.Model.pk(o[0].constructor),p=new Set;for(const t of o){c.info("Creating or updating one-to-many model: "+JSON.stringify(t));const a=await F(t,e,this.adapter.alias);c.info(`caching: ${JSON.stringify(a)} under ${a[d]}`),await z(e,s,r,a[d],a),c.info("Creating or updating one-to-many model: "+JSON.stringify(t)),p.add(a[d])}s[r]=[...p]}async function G(t,r,a,s){const{cascade:n}=r;if(n.update===e.Cascade.CASCADE)return U.call(this,t,r,a,s)}async function Q(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="function"!=typeof r.class||r.class.name?r.class:r.class(),l="object"===i,d=l?R.forModel(c,this.adapter.alias):W(n,s,this.adapter.alias),p=[...new Set([...l?o.map(e=>e[d.pk]):o]).values()];let u,h;try{u=await d.deleteAll(p,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<u.length;e++){h=u[e];try{await z(t,n,s,p[e],h)}catch(r){throw t.logger.error(`Failed to cache record ${p[e]} with key ${s} and model ${JSON.stringify(n,void 0,2)} `,r),r}}n[s]=p}function Y(t,r,a){return[e.PersistenceKeys.POPULATE,t,r,a].join(".")}async function z(e,t,r,a,s){const n=Y(t.constructor.name,r,a),o=e.get("cacheForPopulate")||{};return o[n]=s,e.accumulate({cacheForPopulate:o})}async function V(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(t,r,s,n,o)=>{let i,c;const l=[],d=t.get("cacheForPopulate")||{};for(const t of n){i=Y(r.constructor.name,s,t);try{if(c=d[i],!c)throw Error("Not found in cache")}catch(n){const i=W(r,s,o);if(!i)throw new a.InternalError("Could not find repo");c=await i.read(t,e)}l.push(c)}return l})(e,s,r,o?n:[n],this.adapter.alias);s[r]=o?i:i[0]}const H=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function W(e,t,r){if(!e)throw Error("No model was provided to get repository");let s;if(Array.isArray(e[t])||e[t]instanceof Set){const r=o.Metadata.get(e instanceof n.Model?e.constructor:e,o.Metadata.key(n.ValidationKeys.REFLECT,t,n.ValidationKeys.LIST))?.clazz;if(!r)throw new a.InternalError("Failed to find types decorators for property "+t);s=(Array.isArray(r)?[...r]:[r]).map(e=>"function"!=typeof e||e.name?e:e())}else s=o.Metadata.getPropDesignTypes(e instanceof n.Model?e.constructor:e,t)?.designTypes;const i=s?.find(e=>!H.includes((""+e.name).toLowerCase()));return R.forModel(i,r)}class J extends a.BadRequestError{constructor(e,t=J.name,r=401){super(e,t,r)}}class X extends J{constructor(e,t=X.name){super(e,t,403)}}class Z extends a.InternalError{constructor(e){super(e,Z.name,503)}}function ee(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 te(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 re(e,t,r,s){if(s[r]&&(await this.select().where(N.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 ae(e,t,r,a){throw new J("This adapter does not support user identification")}function se(){return a.timestamp([a.OperationKeys.CREATE])}function ne(){return a.timestamp()}function oe(e){const t="function"==typeof e&&e.name?e:e(),r=n.Model.pk(t);return o.Metadata.allowedTypes(t,r)||[]}function ie(t){return(r,a)=>o.propMetadata(o.Metadata.key(e.PersistenceKeys.GENERATED,a),t||!0)(r,a)}function ce(...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 le(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()}o.Decoration.for(a.DBKeys.TIMESTAMP).extend(ie()).apply(),o.Decoration.for(a.DBKeys.COMPOSED).extend(ie()).apply(),o.Metadata.validationExceptions=((t,r)=>{const s=o.Metadata.get(t,e.PersistenceKeys.NO_VALIDATE)||[],i=Object.entries(s).filter(([,e])=>e.includes(r)).map(([e])=>e);let c=[];return r!==a.OperationKeys.CREATE&&r!==a.OperationKeys.UPDATE||(c=n.Model.nestedRelations(t)),[...new Set([...i,...c])]}).bind(o.Metadata),o.Metadata.migrationsFor=(t=>{if(!(t=t??_.current))throw new a.InternalError("Could not get adapter for migrations");return o.Metadata.innerGet(Symbol.for(e.PersistenceKeys.MIGRATION),t.alias).map(e=>e.class)}).bind(o.Metadata),o.Metadata.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),n.Model.relations=(e,t)=>o.Metadata.relations(e instanceof n.Model?e.constructor:e,t)||[],n.Model.nestedRelations=(t,r=[])=>{let a=[];const s=o.Metadata.get(t,e.PersistenceKeys.RELATIONS);if(!s||!Object.keys(s).length)return[...new Set([...r])];for(const e in s){const t=s[e];if(t?.class&&n.Model.relations(t.class)){const s=n.Model.relations(t.class).map(t=>`${e}.${t}`);r=[...r,...s],a=n.Model.nestedRelations(t.class,r)}}return[...new Set([...r,...a])]},n.Model.generated=((t,r)=>!!o.Metadata.get("function"!=typeof t?t.constructor:t,o.Metadata.key(e.PersistenceKeys.GENERATED,r))).bind(o.Metadata),n.Model.generatedBySequence=((e,t)=>{const r="function"!=typeof e?e.constructor:e;return!!n.Model.sequenceFor(r).generated}).bind(o.Metadata),o.Metadata.createdBy=(t=>{const r=o.Metadata.get("function"!=typeof t?t.constructor:t,e.PersistenceKeys.CREATED_BY);if(!r)throw new a.InternalError("No createdBy metadata found for model. did you use @createdBy()?");return r}).bind(o.Metadata),o.Metadata.updatedBy=(t=>{const r=o.Metadata.get("function"!=typeof t?t.constructor:t,e.PersistenceKeys.UPDATED_BY);if(!r)throw new a.InternalError("No updatedBy metadata found for model. did you use @updatedBy()?");return r}).bind(o.Metadata),n.Model.tableName=t=>{if(!(t instanceof n.Model?n.Model.get(t.constructor.name):t))throw new a.InternalError("Unable to find model "+t);return o.Metadata.get(t instanceof n.Model?t.constructor:t,e.PersistenceKeys.TABLE)||(t instanceof n.Model?t.constructor.name:t.name)},n.Model.columnName=(t,r)=>o.Metadata.get(t instanceof n.Model?t.constructor:t,o.Metadata.key(e.PersistenceKeys.COLUMN,r))||r,n.Model.sequenceName=(e,...t)=>[n.Model.tableName(e),...t].join("_"),n.Model.sequenceFor=(e,t)=>{if(t)throw new u("not currently supported");const r=n.Model.pkProps(e instanceof n.Model?e.constructor:e);if(!r)throw new a.InternalError("No sequence options defined for model. did you use the @pk decorator?");return r},n.Model.indexes=t=>{const r=o.Metadata.get(t instanceof n.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 f{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 _))throw new u("Only Adapters can be observed by dispatch");this.adapter=e,this.models=_.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 u("Only the adapter that was used to observe can be unobserved");this.adapter=void 0}async updateObservers(e,t,r,...s){const o="string"==typeof e?e:n.Model.tableName(e),{log:i,ctxArgs:c}=this.logCtx(s,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}`)}}_&&(_._baseDispatch=de);class pe{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 pe._instance||(pe._instance=new pe),pe._instance}}class ue{constructor(){this.count=14}generate(e){return(""+((e=(e?parseInt(e):0)||0)+1)).padStart(this.count,"0")}static get instance(){return ue._instance||(ue._instance=new ue),ue._instance}}function he(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 g)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 ge extends s.LoggedClass{constructor(){super(),this.transaction=!0,[this.up,this.down].forEach(e=>{const t=e.name;he(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 _.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 _?r=this.getQueryRunner(t.client):(r=t,t=this.adapter);const a=await p.args("migration",n.Model,[e],t);if(!await this.enforceRules(r,t,a.context))throw a.context.logger.verbose(`Skipping migration ${this.constructor.name} due to rules`),new g("Migration skipped for rule enforcement");return[r,t,a.context]}.bind(this)}}class fe extends n.Model{constructor(e){super(e)}}r.__decorate([se(),r.__metadata("design:type",Date)],fe.prototype,"createdAt",void 0),r.__decorate([ne(),r.__metadata("design:type",Date)],fe.prototype,"updatedAt",void 0);const ye={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},me=ye,we={type:"Number",generated:!0,startWith:0,incrementBy:1,cycle:!1},be=Object.assign({},we,{type:"BigInt"});async function _e(e,t,r,s){if(!t.type||!t.generated||s[r])return;let o;t.name||(t.name=n.Model.sequenceName(s,"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=s,c=r,l=await o.next(e),Reflect.set(i,c,l)}function Oe(t,r){return(s,i)=>{if(o.prop()(s,i),!t.type){const e=o.Metadata.type(s.constructor,i);if(![Number.name,String.name,BigInt.name].includes(e?.name||e))throw Error("Incorrrect option type");t.type=e}switch(t.type){case String.name||String.name.toLowerCase():case String:t.generated=void 0!==t.generated&&t.generated,t.type=String;break;case Number.name||String.name.toLowerCase():case Number:t.generated=void 0===t.generated||t.generated,t.type=Number;break;case BigInt.name||BigInt.name.toLowerCase():case BigInt:t.type=BigInt,t.generated=void 0===t.generated||t.generated;break;case"uuid":case"serial":t.generated=!0;break;default:throw Error("Unsupported type")}void 0===t.generated&&(t.generated=!0);const c=[te([e.OrderDirection.ASC,e.OrderDirection.DSC]),n.required(),a.readonly(),o.propMetadata(o.Metadata.key(a.DBKeys.ID,i),t),a.onCreate(_e,t,r)];return t.generated&&c.push(ie()),o.apply(...c)(s,i)}}function Ee(e){const t=Object.assign({},me);return delete t.generated,e=Object.assign({},t,e),o.Decoration.for(a.DBKeys.ID).define({decorator:Oe,args:[e,{priority:60}]}).apply()}e.SequenceModel=class extends fe{constructor(e){super(e)}},r.__decorate([Ee({type:"String",generated:!1}),r.__metadata("design:type",String)],e.SequenceModel.prototype,"id",void 0),r.__decorate([n.required(),te(),r.__metadata("design:type",Object)],e.SequenceModel.prototype,"current",void 0),e.SequenceModel=r.__decorate([ee("??sequence"),n.model(),r.__metadata("design:paramtypes",[Object])],e.SequenceModel);class ve extends f{static{this.lock=new i.MultiLock}constructor(t,r){super(),this.options=t,this.adapter=r,this.repo=R.forModel(e.SequenceModel,r.alias)}async current(...t){const r=(await p.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){const t=r.logger.for(this.current);if(e instanceof a.NotFoundError){if(t.debug(`Sequence.current missing ${s}, returning startWith=${n}`),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){const s=r.logger.for(this.increment),{type:n,incrementBy:o,name:i}=this.options;if(!i)throw new a.InternalError("Sequence name is required");return ve.lock.execute(async()=>{const c=t||o;if(c%o!==0)throw new a.InternalError("Value to increment does not consider the incrementBy setting: "+o);const l="function"==typeof n&&n?.name?n.name:n,d=await this.current(r),p=async t=>{try{return await this.repo.update(new e.SequenceModel({id:i,current:t}),r)}catch(n){if(n instanceof a.NotFoundError)return s.debug(`Sequence create ${i} current=${d} next=${t}`),this.repo.create(new e.SequenceModel({id:i,current:t}),r);throw n}};if("uuid"===l)for(;;){const e=pe.instance.generate(d);try{const t=await p(e);return s.debug(`Sequence uuid increment ${i} current=${d} next=${e}`),t.current}catch(e){if(e instanceof a.ConflictError)continue;throw e}}const u=(e=>{switch(l){case Number.name:return this.parse(e)+c;case BigInt.name:return this.parse(e)+BigInt(c);case String.name:return this.parse(e);case"serial":return ue.instance.generate(e);default:throw new a.InternalError("Should never happen")}})(d),h=await p(u);return s.debug(`Sequence.increment ${i} current=${d} next=${u}`),h.current},i)}async next(...t){const r=await p.args(a.OperationKeys.UPDATE,e.SequenceModel,t,this.adapter),{context:s}=r;return this.increment(void 0,s)}async range(t,...r){const s=await p.args(a.OperationKeys.UPDATE,e.SequenceModel,r,this.adapter),{context:n}=s;if("uuid"===this.options.type||"serial"===this.options.type)throw new u(`type ${this.options.type} is currently not suppported for this adapter`);const o=n.logger.for(this.range),i="function"==typeof this.options.type&&this.options.type?.name?this.options.type.name:this.options.type,c=this.parse(this.options.incrementBy),l=await this.increment(this.parse(t)*c,n);let d=[];for(let e=0;t-1>=e;e++)d.push(l-c*this.parse(e));if(d=d.reverse(),d[d.length-1]!==l&&"String"!==i)throw new a.InternalError("Miscalculation of range");return o.debug("Calculated range: "+d.join(", ")),d}parse(e){return ve.parseValue(this.options.type,e)}static pk(e){return n.Model.sequenceName(e,"pk")}static parseValue(e,t){switch("function"==typeof e&&e?.name?e.name:e){case Number.name||Number.name.toLowerCase():return"string"==typeof t?parseInt(t):"number"==typeof t?t:BigInt(t);case BigInt.name||BigInt.name.toLowerCase():return BigInt(t);case String.name||String.name.toLowerCase():return t.toString();case void 0:case"uuid":case"serial":return t;default:throw new u(`Unsupported sequence type: ${e} for adapter ${this}`)}}}_._baseSequence=ve;class xe extends a.InternalError{constructor(e){super(e,xe.name,500)}}class Ae extends s.LoggedClass{get current(){return this._currentPage}get total(){return this._totalPages}get count(){return this._recordCount}get statement(){return this._statement||(this._statement=this.prepare(this.query)),this._statement}constructor(e,t,r,a){super(),this.adapter=e,this.query=t,this.size=r,this.clazz=a,he(this,this.page,this.pagePrefix,this.page.name)}isPreparedStatement(){const t=this.query;return t.method&&t.method.match(RegExp(`${e.PreparedStatementKeys.FIND_BY}|${e.PreparedStatementKeys.LIST_BY}`,"gi"))}async pagePrefix(t,...r){return[t,...(await p.args(e.PersistenceKeys.QUERY,this.clazz,r,this.adapter)).args]}async pagePrepared(t,...r){const a=R.forModel(this.clazz,this.adapter.alias),s=this.query,{method:n,args:o,params:i}=s,c=RegExp(`^${e.PreparedStatementKeys.FIND_BY}|${e.PreparedStatementKeys.LIST_BY}`,"gi");if(!n.match(c))throw new u(`Method ${n} is not supported for pagination`);c.lastIndex=0;const l=n.replace(c,e.PreparedStatementKeys.PAGE_BY),d=[l,...o];let p={limit:this.size,offset:t,bookmark:this._bookmark};l!==e.PreparedStatementKeys.PAGE_BY||d.length>2?p={direction:i.direction,limit:this.size,offset:t,bookmark:this._bookmark}:d.push(i.direction),d.push(p);const h=await a.statement(...d,...r);return this.apply(h)}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 E("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&e>this._totalPages)throw new E(`Only ${this._totalPages} are available. Cannot go to page ${e}`);return e}async page(e=1,...t){const{ctxArgs:r}=this.adapter.logCtx(t,this.page);if(this.isPreparedStatement())return await this.pagePrepared(e,...r);throw new u("Raw support not available without subclassing this")}serialize(e,t=!1){const r={data:e,current:this.current,total:this.total,count:this.count,bookmark:this._bookmark};try{return t?JSON.stringify(r):r}catch(e){throw new a.SerializationError(e)}}apply(e){const t="string"==typeof e?Ae.deserialize(e):e;return this._currentPage=t.current,this._totalPages=t.total,this._recordCount=t.count,this._bookmark=t.bookmark,t.data}static deserialize(e){try{return JSON.parse(e)}catch(e){throw new a.SerializationError(e)}}static isSerializedPage(e){return e&&"object"==typeof e&&Array.isArray(e.data)&&"number"==typeof e.total&&"number"==typeof e.current&&"number"==typeof e.count}}function Se(e){return function(t,r,a){const s=a.value;return a.value=function(...t){const r=this.class;if(r&&w(r,e))throw Error(`Operation "${e}" is blocked by @BlockOperations for ${r?.name??"Model"}.`);return s.apply(this,t)},a}}const Me=()=>Se(a.OperationKeys.CREATE),Ce=()=>Se(a.OperationKeys.READ),Pe=()=>Se(a.OperationKeys.UPDATE),Ne=()=>Se(a.OperationKeys.DELETE);function De(r){return(a,s,n)=>{n||s?(o.prop()(a,s),r=r||o.Metadata.type(a.constructor,s)):r=r||a,r=y(r);const i=[];if(n&&"number"==typeof n.value)i.push(t.inject(r));else if(n||s){if(n)throw Error("Invalid decorator usage. Should be impossible");i.push(t.inject(r))}else o.Metadata.set(e.PersistenceKeys.SERVICE,r,a),i.push(t.injectable(r,{singleton:!0,callback:e=>Object.defineProperty(e,"name",{enumerable:!0,configurable:!1,writable:!1,value:r})}));return o.apply(...i)(a,s,n)}}class Ie{constructor(e){this.name=e,this.Context=p}async flags(e,t,...r){let a=t.logger||s.Logging.for(this.toString());return t.correlationId&&(a=a.for({correlationId:t.correlationId})),Object.assign({},l,t,{timestamp:new Date,operation:e,logger:a})}async context(e,t,...r){const a=t,s=await this.flags(e,a,...r);return(new this.Context).accumulate(s)}async logCtx(e,t,r=!1){return await Ie.logCtx.bind(this)(e,t,r)}static async logCtx(e,t,r=!1,...s){const n=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 n()]);const o=e.pop();o instanceof p||(e=[...e,await n()]);const i=this?o.logger.for(this).for(t):o.logger.clear().for(this).for(t);return{ctx:o,log:t?i.for(t):i,ctxArgs:[...e,o]}}static get(e){if(!e)throw new a.InternalError("No name provided");const r=y(e),s=t.Injectables.get(r);if(s)return s;throw new a.InternalError("No Service found for "+("string"==typeof e?e:"symbol"==typeof e?e.toString():e.name))}static async boot(...e){const r={context:async e=>(new p).accumulate(Object.assign({},l,{timestamp:new Date,operation:e,logger:s.Logging.get()}))},{log:n,ctxArgs:o}=await this.logCtx.bind(r)(e,this.boot,!0),i=t.Injectables.services();for(const[e,r]of Object.entries(i))try{n.verbose(`Booting ${r.name} service...`);const s=t.Injectables.get(r);if(!s)throw new a.InternalError("Failed to resolve injectable for "+e);s instanceof Be&&(n.verbose(`Initializing ${r.name} service...`),await s.boot(...o))}catch(t){throw new a.InternalError(`Failed to boot ${e} service:${t}`)}}}class Be extends Ie{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...`)}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Promise)],Be.prototype,"boot",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],Be.prototype,"config",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],Be.prototype,"client",null);const Te=e=>"string"==typeof e?e.endsWith("Service")?e:e+"Service":"symbol"==typeof e?e.toString():e.name+"Service";class $e extends Ie{get class(){if(!this.clazz)throw new a.InternalError("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=R.forModel(this.clazz)),this._repository}constructor(e,t){super(t??e.name+"Service"),this.clazz=e}static getService(e){if(!e)throw new a.InternalError("No name provided");const t=Te(e);try{const e=Ie.get(t);if(e)return e}catch(e){}throw new a.InternalError("No ModelService found for alias "+t)}for(e,...t){return new Proxy(this,{get:(r,a,s)=>"repo"===a?r.repo.for(e,...t):Reflect.get(r,a,s)})}async create(e,...t){const{ctxArgs:r}=await this.logCtx(t,this.create,!0);return this.repo.create(e,...r)}async createAll(e,...t){const{ctxArgs:r}=await this.logCtx(t,this.createAll,!0);return this.repo.createAll(e,...r)}async delete(e,...t){const{ctxArgs:r}=await this.logCtx(t,this.delete,!0);return this.repo.delete(e,...r)}async deleteAll(e,...t){const{ctxArgs:r}=await this.logCtx(t,this.deleteAll,!0);return this.repo.deleteAll(e,...r)}async read(e,...t){const{ctxArgs:r}=await this.logCtx(t,this.read,!0);return this.repo.read(e,...r)}async readAll(e,...t){const{ctxArgs:r}=await this.logCtx(t,this.readAll,!0);return this.repo.readAll(e,...r)}async query(e,...t){const r=this.repo?.[e];if("function"!=typeof r)throw Error(`Method "${e}" is not implemented`);return r.apply(this.repo,t)}async update(e,...t){const{ctxArgs:r}=await this.logCtx(t,this.update,!0);return this.repo.update(e,...r)}async updateAll(e,...t){const{ctxArgs:r}=await this.logCtx(t,this.updateAll,!0);return this.repo.updateAll(e,...r)}async listBy(e,t,...r){const{ctxArgs:a}=await this.logCtx(r,this.listBy,!0);return this.repo.listBy(e,t,...a)}async paginateBy(e,t,r,...a){const{ctxArgs:s}=await this.logCtx(a,this.paginateBy,!0);return this.repo.paginateBy(e,t,r,...s)}async findOneBy(e,t,...r){const{ctxArgs:a}=await this.logCtx(r,this.findOneBy,!0);return this.repo.findOneBy(e,t,...a)}async findBy(e,t,...r){const{ctxArgs:a}=await this.logCtx(r,this.findBy,!0);return this.repo.findBy(e,t,...a)}async statement(e,...t){const{ctxArgs:r}=await this.logCtx(t,this.statement,!0);return this.repo.statement(e,...r)}async logCtx(e,t,r=!1){return await $e.logCtx.bind(this.repo.adapter)(e,t,r,this.repo._overrides,this.class)}static forModel(e,t){let a;t=Te(t||e);try{a=$e.get(t)}catch(e){a=void 0}if(a instanceof $e)return a;const s=this;let n=class extends s{constructor(){super(e)}};return n=r.__decorate([De(t),r.__metadata("design:paramtypes",[])],n),new n}static async logCtx(e,t,r=!1,s={},n){const o=async function(){if(!r)throw new a.InternalError("No context provided");return this.context("string"==typeof t?t:t.name,s,n)}.bind(this);1>e.length&&(e=[await o()]);let i=e.pop();i instanceof p||(void 0!==i&&e.push(i),i=await o());const c=this?i.logger.for(this).for(t):i.logger.clear().for(this).for(t);return{ctx:i,log:c,ctxArgs:[...e,i]}}}var Re,Ke,ke,Fe;r.__decorate([Me(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],$e.prototype,"create",null),r.__decorate([Me(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],$e.prototype,"createAll",null),r.__decorate([Ne(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],$e.prototype,"delete",null),r.__decorate([Ne(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],$e.prototype,"deleteAll",null),r.__decorate([Ce(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],$e.prototype,"read",null),r.__decorate([Ce(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],$e.prototype,"readAll",null),r.__decorate([Ce(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,Object]),r.__metadata("design:returntype",Promise)],$e.prototype,"query",null),r.__decorate([Pe(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],$e.prototype,"update",null),r.__decorate([Pe(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,Object]),r.__metadata("design:returntype",Promise)],$e.prototype,"updateAll",null);class je extends f{constructor(t,r){super(),this.adapter=t,this.overrides=r,[this.execute,this.paginate].forEach(t=>{a.prefixMethod(this,t,async(...r)=>{let a=r;if((!a.length||!(a[a.length-1]instanceof p))&&this.fromSelector){const t=await this.adapter.context(e.PersistenceKeys.QUERY,this.overrides||{},this.fromSelector);a=[...a,t]}const{ctx:s,ctxArgs:n}=_.logCtx(a,t.name),o=s.get("forcePrepareSimpleQueries"),i=s.get("forcePrepareComplexQueries");return(o&&this.isSimpleQuery()||i)&&await this.prepare(s),n},t.name)})}get log(){return this.adapter.log.for(je)}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?n.Model.get(e):e,!this.fromSelector)throw new O("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){try{if(this.prepared)return this.executePrepared(...e);const t=this.build();return await this.raw(t,...e)}catch(e){throw new O(e)}}async executePrepared(...e){const t=R.forModel(this.fromSelector,this.adapter.alias),{method:r,args:a,params:s}=this.prepared;return t.statement(r,...a,s,...e)}async raw(e,...t){const{ctx:r,ctxArgs:a}=this.logCtx(t,this.raw);if(!r.get("allowRawStatements"))throw new u("Raw statements are not allowed in the current configuration");const s=await this.adapter.raw(e,!0,...a);if(!this.selectSelector)return s;const o=n.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(s)?s.map(i):i(s)}prepareCondition(t,r){let{attr1:a,operator:s,comparison:n}=t;const o={};switch(s){case e.GroupOperator.AND:case e.GroupOperator.OR:{let e=a,t=n;if("string"!=typeof a){const t=this.prepareCondition(a,r);e=t.method,o.args=[...o.args||[],...t.args||[]]}if(n instanceof N){const e=this.prepareCondition(n,r);t=e.method,o.args=[...o.args||[],...e.args||[]]}o.method=`${e} ${s.toLowerCase()} ${t}`;break}case e.Operator.EQUAL:o.method=a,o.args=[...o.args||[],n];break;case e.Operator.DIFFERENT:o.method=a+" diff",o.args=[...o.args||[],n];break;case e.Operator.REGEXP:o.method=a+" matches",o.args=[...o.args||[],n];break;case e.Operator.BIGGER:o.method=a+" bigger",o.args=[...o.args||[],n];break;case e.Operator.BIGGER_EQ:o.method=a+" bigger than equal";break;case e.Operator.SMALLER:o.method=a+" less",o.args=[...o.args||[],n];break;case e.Operator.SMALLER_EQ:o.method=a+" less than equal",o.args=[...o.args||[],n];break;case e.Operator.IN:o.method=a+" in",o.args=[...o.args||[],n];break;default:throw new O("Unsupported operator "+s)}return o}squash(t){if(this.selectSelector&&this.selectSelector.length)return;if(this.groupBySelector)return;if(this.countSelector)return;if(this.maxSelector)return;if(this.minSelector)return;let r;if(this.whereCondition){if(this.whereCondition.comparison instanceof N)return;r=this.whereCondition.attr1}const a=this.orderBySelector?this.orderBySelector:r?[r,e.OrderDirection.DSC]:[n.Model.pk(this.fromSelector),e.OrderDirection.DSC],[s,o]=a,i={direction:o};this.limitSelector&&(i.limit=this.limitSelector),this.offsetSelector&&(i.offset=this.offsetSelector);const c={class:this.fromSelector,method:e.PreparedStatementKeys.LIST_BY,args:[s],params:i};return r&&(c.method=e.PreparedStatementKeys.FIND_BY,c.args=[r,this.whereCondition.comparison],c.params=i),c}async prepare(t){if(t=t||await this.adapter.context(e.PersistenceKeys.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&t.get("forcePrepareSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const r=[],a={},n={class:this.fromSelector,args:r,params:a},o=[e.QueryClause.FIND_BY];if(this.whereCondition){const e=this.prepareCondition(this.whereCondition,t);o.push(e.method),e.args&&e.args.length&&r.push(...e.args)}return this.selectSelector&&o.push(e.QueryClause.SELECT,this.selectSelector.join(` ${e.QueryClause.AND.toLowerCase()} `)),this.orderBySelector&&(o.push(e.QueryClause.ORDER_BY,this.orderBySelector[0]),a.direction=this.orderBySelector[1]),this.groupBySelector&&o.push(e.QueryClause.GROUP_BY,this.groupBySelector),this.limitSelector&&(a.limit=this.limitSelector),this.offsetSelector&&(a.skip=this.offsetSelector),n.method=s.toCamelCase(o.join(" ")),n.params=a,this.prepared=n,this}isSimpleQuery(){return!(this.selectSelector&&this.selectSelector.length||this.groupBySelector||this.countSelector||this.maxSelector||this.minSelector)}async paginate(e,...t){t.pop();try{return this.adapter.Paginator(this.prepared||this.build(),e,this.fromSelector)}catch(e){throw new O(e)}}toString(){return this.adapter.flavour+" statement"}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array]),r.__metadata("design:returntype",Object)],je.prototype,"select",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(Re="undefined"!=typeof S&&S)?Re:Object]),r.__metadata("design:returntype",Object)],je.prototype,"distinct",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(Ke="undefined"!=typeof S&&S)?Ke:Object]),r.__metadata("design:returntype",Object)],je.prototype,"max",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(ke="undefined"!=typeof S&&S)?ke:Object]),r.__metadata("design:returntype",Object)],je.prototype,"min",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(Fe="undefined"!=typeof S&&S)?Fe:Object]),r.__metadata("design:returntype",Object)],je.prototype,"count",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Object)],je.prototype,"from",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[N]),r.__metadata("design:returntype",Object)],je.prototype,"where",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array]),r.__metadata("design:returntype",Object)],je.prototype,"orderBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Object)],je.prototype,"groupBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Number]),r.__metadata("design:returntype",Object)],je.prototype,"limit",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Number]),r.__metadata("design:returntype",Object)],je.prototype,"offset",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[void 0]),r.__metadata("design:returntype",Promise)],je.prototype,"execute",null);class Le extends je{constructor(e,t){super(e,t)}getSort(){return(t,r)=>{if(!this.orderBySelector)throw new a.InternalError("orderBySelector not set. Should be impossible");const s=this.orderBySelector,[n,i]=s,c=(i+"").toLowerCase()===e.OrderDirection.ASC?1:-1,l=t[n],d=r[n];if(l===d)return 0;if(null==l||null==d)return c*(null==l?1:-1);const{designType:p}=o.Metadata.getPropDesignTypes(t.constructor,n),u=p&&p.name&&p.name.toLowerCase()||typeof l;switch(u){case"string":return c*this.compareStrings(l,d);case"number":return c*this.compareNumbers(l,d);case"bigint":return c*this.compareBigInts(l,d);case"boolean":return c*this.compareBooleans(l,d);case"date":case"object":if(l instanceof Date&&d instanceof Date)return c*this.compareDates(l,d)}throw new O("sorting not supported for type "+u)}}compareBooleans(e,t){return e===t?0:e?1:-1}compareNumbers(e,t){return e-t}compareBigInts(e,t){return e===t?0:e>t?1:-1}compareStrings(e,t){return e.localeCompare(t)}compareDates(e,t){return e.valueOf()-t.valueOf()}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}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 O("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 qe(e,t,r,a){const s=e.get("UUID");if(!s)throw new u("This adapter does not support user identification");a[r]=s}const Ue="ram";class Ge extends Ae{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{ctx:r,ctxArgs:a}=this.adapter.logCtx(t,this.page);if(this.isPreparedStatement())return this.pagePrepared(e,...a);const s=this.prepare(this.statement);let n;if(this._recordCount&&this._totalPages)e=this.validatePage(e),s.skip=(e-1)*this.size,n=await this.adapter.raw(s,!0,...t,r);else if(this._totalPages=this._recordCount=0,n=await this.adapter.raw({...s,limit:void 0},!1,r),this._recordCount=n.count||n.data.length,this._recordCount>0){const t=s?.limit||this.size;return this._totalPages=Math.ceil(this._recordCount/t),await this.page(e,...a)}return this._currentPage=e,n.data||n}}class Qe extends _{constructor(e={},t){super(e,Ue,t),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();return super.prepare(e,...t,r)}revert(e,t,r,a,...s){return super.revert(e,t,r,a,...s)}async create(e,t,r,s){const o=s.logger.for(this.create),i=n.Model.tableName(e);if(o.debug(`creating record in table ${i} with id ${t}`),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 await this.lock.acquire(),this.client.get(i)?.set(t,r),this.lock.release(),r}async read(e,t,r){const s=n.Model.tableName(e);if(!this.client.has(s))throw new a.NotFoundError(`Table ${s} not found`);if(!this.client.get(s)?.has(t))throw new a.NotFoundError(`Record with id ${t} not found in table ${s}`);return this.client.get(s)?.get(t)}async update(e,t,r,s){const o=s.logger.for(this.update),i=n.Model.tableName(e);if(o.debug(`updating record in table ${i} with id ${t}`),!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 await this.lock.acquire(),this.client.get(i)?.set(t,r),this.lock.release(),r}async delete(e,t,r){const s=r.logger.for(this.delete),o=n.Model.tableName(e);if(s.debug(`deleting record from table ${o} with pk ${t}`),!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}`);await this.lock.acquire(),this.client.get(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=n.Model.get(e));const t=n.Model.tableName(e);return this.client.has(t)||this.client.set(t,new Map),this.client.get(t)}async raw(e,t=!0,r){r.logger.for(this.raw).debug("performing raw query: "+JSON.stringify(e));const{where:s,sort:i,limit:c,skip:l,from:d}=e;let{select:p}=e;const u=this.tableFor(d);if(!u)throw new a.InternalError(`Table ${d} not found in RamAdapter`);const h=n.Model.pk(d),g=o.Metadata.get(d,o.Metadata.key(a.DBKeys.ID,h));let f=Array.from(u.entries()).map(([e,t])=>this.revert(t,d,ve.parseValue(g.type,e),void 0,r));f=s?f.filter(s):f;const y=f.length;return i&&(f=f.sort(i)),l&&(f=f.slice(l)),c&&(f=f.slice(0,c)),p&&(p=Array.isArray(p)?p:[p],f=f.map(e=>Object.entries(e).reduce((e,[t,r])=>(p.includes(t)&&(e[t]=r),e),{}))),t?f:{data:f,count:y}}parseError(e){return e instanceof a.BaseError?e:new a.InternalError(e)}Statement(e){return new Le(this,e)}Paginator(e,t,r){return new Ge(this,e,t,r)}for(e,...t){this.proxies||(this.proxies={});const r=`${this.alias} - ${n.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(Ue).for(t).define(a.onCreate(qe),o.propMetadata(t,{})).apply(),o.Decoration.flavouredAs(Ue).for(r).define(a.onCreateUpdate(qe),o.propMetadata(r,{})).apply()}getClient(){return new Map}}Qe.decoration(),t.Injectables.setRegistry(new k);const Ye="##VERSION##",ze="##PACKAGE##";o.Metadata.registerLibrary(ze,Ye),e.AbsMigration=ge,e.Adapter=_,e.AuthorizationError=J,e.BaseModel=fe,e.BigIntSequence=be,e.ClientBasedService=Be,e.Condition=N,e.ConnectionError=Z,e.Context=p,e.ContextualLoggedClass=f,e.DefaultAdapterFlags=l,e.DefaultCascade=D,e.DefaultSequenceOptions=me,e.Dispatch=de,e.ForbiddenError=X,e.InjectablesRegistry=k,e.MethodQueryBuilder=T,e.MigrationError=h,e.MigrationRuleError=g,e.ModelService=$e,e.NoneSequenceOptions=ye,e.NumericSequence=we,e.ObserverError=xe,e.ObserverHandler=d,e.OperatorsMap=I,e.PACKAGE_NAME=ze,e.Paginator=Ae,e.PagingError=E,e.QueryError=O,e.RamAdapter=Qe,e.RamFlavour=Ue,e.RamPaginator=Ge,e.RamStatement=Le,e.Repository=R,e.Sequence=ve,e.Serial=ue,e.Service=Ie,e.Statement=je,e.UUID=pe,e.UnsupportedError=u,e.VERSION=Ye,e.cacheModelForPopulate=z,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.create=Me,e.createOrUpdate=F,e.createdAt=se,e.createdBy=()=>o.Decoration.for(e.PersistenceKeys.CREATED_BY).define({decorator:()=>(t,r)=>o.apply(a.onCreate(ae),o.propMetadata(e.PersistenceKeys.CREATED_BY,r),ie())(t,r),args:[]}).apply(),e.createdByOnCreateUpdate=ae,e.createdByOnRamCreateUpdate=qe,e.del=Ne,e.generateInjectableNameForRepository=K,e.generated=ie,e.getPkTypes=oe,e.getPopulateKey=Y,e.index=te,e.injectableServiceKey=y,e.isOperationBlocked=w,e.manyToMany=(t,r=D,a=!0,s,i)=>{const c=e.PersistenceKeys.MANY_TO_MANY;return o.Decoration.for(c).define({decorator:(e,t,r,a,s)=>{const i={class:e,cascade:t,populate:r};a&&(i.joinTable=a),s&&(i.name=s);const l=oe(e),d=[o.prop(),le(c,i),n.list([e,...l])];return o.apply(...d)},args:[t,r,a,s,i]}).apply()},e.manyToOne=(t,r=D,a=!0,s,i)=>{const c=e.PersistenceKeys.MANY_TO_ONE;return o.Decoration.for(c).define({decorator:(e,t,r,a,s)=>{const i={class:e,cascade:t,populate:r};a&&(i.joinTable=a),s&&(i.name=s);const l=oe(e),d=[o.prop(),le(c,i),n.type([e,...l])];return o.apply(...d)},args:[t,r,a,s,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=ce,e.noValidateOnCreate=()=>ce(a.OperationKeys.CREATE),e.noValidateOnCreateUpdate=()=>ce(a.OperationKeys.UPDATE,a.OperationKeys.CREATE),e.noValidateOnUpdate=()=>ce(a.OperationKeys.UPDATE),e.normalizeImport=async e=>e.then(e=>e.default||e),e.oneToMany=(t,r=D,s=!0,i,c)=>{const l=e.PersistenceKeys.ONE_TO_MANY;return o.Decoration.for(l).define({decorator:(e,t,r,s,i)=>{const c={class:e,cascade:t,populate:r};s&&(c.joinTable=s),i&&(c.name=i);const d=oe(e),p=[o.prop(),le(l,c),n.list([e,...d]),a.onCreate(U,c),a.onUpdate(G,c),a.onDelete(Q,c),a.afterAny(V,c)];return o.apply(...p)},args:[t,r,s,i,c]}).apply()},e.oneToManyOnCreate=U,e.oneToManyOnDelete=Q,e.oneToManyOnUpdate=G,e.oneToOne=(t,r=D,s=!0,i,c)=>{const l=e.PersistenceKeys.ONE_TO_ONE;return o.Decoration.for(l).define({decorator:(e,t,r,s,i)=>{const c={class:e,cascade:t,populate:r};s&&(c.joinTable=s),i&&(c.name=i);const d=oe(e),p=[o.prop(),le(l,c),n.type([e,...d]),a.onCreate(j,c),a.onUpdate(L,c),a.onDelete(q,c),a.afterAny(V,c)];return o.apply(...p)},args:[t,r,s,i,c]}).apply()},e.oneToOneOnCreate=j,e.oneToOneOnDelete=q,e.oneToOneOnUpdate=L,e.pk=Ee,e.pkDec=Oe,e.pkOnCreate=_e,e.populate=V,e.prefixMethod=he,e.prepared=$,e.promiseSequence=m,e.query=(t={})=>o.Decoration.for(e.PersistenceKeys.QUERY).define({decorator:t=>(r,a,s)=>{const n=T.getFieldsFromMethodName(a);return o.apply(o.methodMetadata(o.Metadata.key(e.PersistenceKeys.QUERY,a),{...t,fields:n}),$(),(e=>(t,r,a)=>{a.value=new Proxy(a.value,{apply(t,r,a){const{select:s,where:n,groupBy:o,orderBy:i,limit:c,offset:l}=T.build(t.name,...a);let d=r.select(s);n&&(d=d.where(n));const{allowLimit:p,allowOffset:u,allowOrderBy:h,throws:g}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...e},f=[{key:"orderBy",value:(i||[])[0],allowed:h},{key:"limit",value:c,allowed:p},{key:"offset",value:l,allowed:u}];for(const e of f)if(void 0!==e.value){if(!e.allowed&&g)throw new O(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()}})})(t))(r,a,s)},args:[t]}).apply(),e.read=Ce,e.relation=le,e.repository=(r,s)=>(i,c)=>c?t.inject(o.Metadata.constr(r))(i,c):(o.Metadata.set(a.DBKeys.REPOSITORY,o.Metadata.key(s||_.currentFlavour,n.Model.tableName(r)),i),o.metadata(a.DBKeys.REPOSITORY,i.name)(r),s=s||o.Metadata.get(i.constructor,e.PersistenceKeys.ADAPTER),R.register(r,i,s),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=W,e.service=De,e.table=ee,e.unique=()=>{const t=e.PersistenceKeys.UNIQUE;return o.Decoration.for(t).define(n.async(),a.onCreateUpdate(re),o.propMetadata(t,{})).apply()},e.uniqueOnCreateUpdate=re,e.update=Pe,e.updatedAt=ne,e.updatedBy=()=>o.Decoration.for(e.PersistenceKeys.UPDATED_BY).define({decorator:()=>(t,r)=>o.apply(a.onUpdate(ae),o.propMetadata(e.PersistenceKeys.UPDATED_BY,r),ie())(t,r),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/logging"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/decoration"),require("@decaf-ts/transactional-decorators")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/injectable-decorators","tslib","@decaf-ts/db-decorators","@decaf-ts/logging","@decaf-ts/decorator-validation","@decaf-ts/decoration","@decaf-ts/transactional-decorators"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).core={},e.decafTsInjectableDecorators,e.tslib,e.decafTsDbDecorators,e.decafTsLogging,e.decafTsDecoratorValidation,e.decafTsDecoration,e.decafTsTransactionalDecorators);
|
|
1
|
+
var e,t;e=this,t=function(e,t,r,a,s,n,o,i){"use strict";var c,l,d,p,u;e.QueryClause=void 0,(c=e.QueryClause||(e.QueryClause={})).FIND_BY="findBy",c.SELECT="Select",c.AND="And",c.OR="Or",c.GROUP_BY="GroupBy",c.ORDER_BY="OrderBy",c.THEN="Then",c.THEN_BY="ThenBy",e.Operator=void 0,(l=e.Operator||(e.Operator={})).EQUAL="EQUAL",l.DIFFERENT="DIFFERENT",l.BIGGER="BIGGER",l.BIGGER_EQ="BIGGER_EQ",l.SMALLER="SMALLER",l.SMALLER_EQ="SMALLER_EQ",l.NOT="NOT",l.IN="IN",l.REGEXP="REGEXP",e.GroupOperator=void 0,(d=e.GroupOperator||(e.GroupOperator={})).AND="AND",d.OR="OR",e.PreparedStatementKeys=void 0,(p=e.PreparedStatementKeys||(e.PreparedStatementKeys={})).LIST_BY="listBy",p.FIND_BY="findBy",p.FIND_ONE_BY="findOneBy",p.PAGE_BY="paginateBy",e.PersistenceKeys=void 0,(u=e.PersistenceKeys||(e.PersistenceKeys={})).PERSISTENCE="persistence",u.INDEX="index",u.UNIQUE="unique",u.ADAPTER="adapter",u.INJECTABLE="decaf_{0}_adapter_for_{1}",u.SERVICE="service",u.TABLE="table",u.COLUMN="column",u.METADATA="__metadata",u.OWNERSHIP="ownership",u.CREATED_BY="ownership.created-by",u.UPDATED_BY="ownership.updated-by",u.RELATIONS="__relations",u.RELATION="relation",u.ONE_TO_ONE="relation.one-to-one",u.ONE_TO_MANY="relation.one-to-many",u.MANY_TO_ONE="relation.many-to-one",u.MANY_TO_MANY="relation.many-to-many",u.POPULATE="populate",u.NO_VALIDATE="no-validate",u.MIGRATION="migration",u.STATEMENT="statement",u.QUERY="query",u.UUID="uuid",u.INITIALIZATION="initialization",u.BY_KEY="by-key";const h=Object.assign({},a.DefaultRepositoryFlags,{enforceUpdateValidation:!0,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,cacheForPopulate:{},observeFullResult:!0,paginateByBookmark:!1,dryRun:!1}),g=[a.OperationKeys.CREATE,a.OperationKeys.UPDATE,a.OperationKeys.DELETE,a.BulkCrudOperationKeys.CREATE_ALL,a.BulkCrudOperationKeys.UPDATE_ALL,a.BulkCrudOperationKeys.DELETE_ALL],y=[a.OperationKeys.READ,a.BulkCrudOperationKeys.READ_ALL],f=[e.PersistenceKeys.STATEMENT,e.PreparedStatementKeys.FIND_ONE_BY],m=[e.PersistenceKeys.QUERY,e.PreparedStatementKeys.PAGE_BY,e.PreparedStatementKeys.LIST_BY,e.PreparedStatementKeys.FIND_BY],b=[e.PreparedStatementKeys.PAGE_BY];class _{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}=B.logCtx(this.updateObservers,void 0,!1,...a);(await Promise.allSettled(this.observers.filter(a=>{const{filter:o}=a;if(!o)return!0;try{return o(e,t,r,...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 w extends a.Context{constructor(e){super(e)}}class O extends s.LoggedClass{logCtx(e,t,r=!1,a){return O.logCtx.call(this,t,a||{},r,...e.filter(e=>void 0!==e))}static logFrom(e,t,r,a){const s=e.context?t.clear().for(e):t.for(e);return a?s.for(a):s}static logCtx(e,t,r=!1,...n){const o=(e,t,r)=>{const a=t.log||s.Logging.get();return t.log=e.context?a.clear().for(e):a.for(e),"string"==typeof r?t.for=e=>Object.assign(t,{log:t.log.for(e)}):t.log=t.log.for(r),t};let i=n.pop();const c=i instanceof w;if(i&&!c&&(n.push(i),i=void 0),!r&&!c)throw new a.InternalError("No context provided");if(c&&!r){if(!i)throw new a.InternalError("Missing context. should be impossible");return o(this,{log:i.logger,ctx:i,ctxArgs:[...n,i]},e)}return async function(...r){if(!this)throw new a.InternalError("No contextual provided");if(!this.context)throw new a.InternalError("Invalid contextual provided");return this.context("string"==typeof e?e:e.name,t||{},...r)}.call(this,...[...n,i].filter(Boolean)).then(t=>o(this,{log:t.logger,ctx:t,ctxArgs:[...n,t]},e))}}class v extends O{constructor(){super(),this._Context=w}get Context(){return this._Context}async context(e,t,...r){this.log.for(this.context).debug(`Creating new context for ${"string"==typeof e?e:e.name} operation with flag overrides: ${Object.keys(t)}`);let a=r.pop();return a instanceof w||(r.push(a),a=void 0),this.flags,!a||a instanceof this.Context?(new this.Context).accumulate(t):new this.Context(a).accumulate(t)}}class E extends a.InternalError{constructor(e){super(e,E.name,500)}}class A extends a.InternalError{constructor(e,t=A.name){super(e,t,500)}}class x extends A{constructor(e){super(e,x.name)}}function C(e){if(!e)throw new a.InternalError("No name provided");return"string"==typeof e?e.replaceAll(".","-"):o.Metadata.Symbol(o.Metadata.constr(e)).toString().replaceAll(".","-")}function P(e){return e.reduce((e,t)=>e.then(async e=>[...e,await t()]),Promise.resolve([]))}function M(e,t){const{handler:r,args:s}=o.Metadata.get(e,a.OperationKeys.REFLECT+a.OperationKeys.BLOCK)||{};return!!r&&(r(...s,t)??!1)}function N(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 x)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 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 T{constructor(){this.count=14}generate(e){return(""+((e=(e?parseInt(e):0)||0)+1)).padStart(this.count,"0")}static get instance(){return T._instance||(T._instance=new T),T._instance}}const I=o.Decoration.flavourResolver.bind(o.Decoration);o.Decoration.flavourResolver=e=>{try{const t=I(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=B._currentFlavour;if(s){const e=B._cache?.[s];return e?.flavour?e.flavour:s}}catch(e){return o.DefaultFlavour}};class B extends v{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!B._baseRepository)throw new a.InternalError("This should be overridden when necessary. Otherwise it will be replaced lazily");return B._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.alias in B._cache)throw new a.InternalError(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);B._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),B._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),B._currentFlavour=this.alias)}Dispatch(){return new B._baseDispatch}ObserverHandler(){return new _}isReserved(e){return!e}async initialize(...e){}async Sequence(e,t){return new B._baseSequence(e,this,t)}async flags(e,t,r,...i){if("string"==typeof t)throw new a.InternalError("Model must be a constructor or array of constructors or undefined. this should be impossible");const c=Array.isArray(t)?t.length?t[0]:void 0:t,l=c?n.Model.tableName(c)+" - ":"";r.correlationId=r.correlationId||`${l}${e}-${D.instance.generate()}`;const d=r.logger||s.Logging.for(this);return d.setConfig({correlationId:r.correlationId}),Object.assign({},h,r,{affectedTables:t?[...new Set([...(Array.isArray(t)?t:[t]).filter(Boolean),...r.affectedTables?Array.isArray(r.affectedTables)?r.affectedTables:[r.affectedTables]:[]])]:r.affectedTables,args:i,writeOperation:e!==a.OperationKeys.READ,timestamp:new Date,operation:e,ignoredValidationProperties:t?o.Metadata.validationExceptions(Array.isArray(t)&&t[0]?t[0]:t,e):[],logger:d})}get Context(){return w}async context(e,t,r,...a){this.log.for(this.context).silly(`creating new context for ${e} operation on ${r?Array.isArray(r)?r.map(e=>n.Model.tableName(e)):n.Model.tableName(r):"no"} table with flag overrides: ${JSON.stringify(t)}`);let s=a.pop();void 0===s||s instanceof w||(a.push(s),s=void 0);const o=await this.flags("string"==typeof e?e:e.name,r,t,...a);return s?new this.Context(s).accumulate({...o,parentContext:s}):(new this.Context).accumulate(o)}prepare(t,...r){const{log:s}=this.logCtx(r,this.prepare),o=t.segregate(),i=Object.entries(o.model).reduce((e,[r,s])=>{if(void 0===s)return e;const o=n.Model.columnName(t.constructor,r);if(this.isReserved(o))throw new a.InternalError(`Property name ${o} is reserved`);return e[o]=s,e},{});return t[e.PersistenceKeys.METADATA]&&(s.silly("Passing along persistence metadata for "+t[e.PersistenceKeys.METADATA]),Object.defineProperty(i,e.PersistenceKeys.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[e.PersistenceKeys.METADATA]})),{record:i,id:t[n.Model.pk(t.constructor)],transient:o.transient}}revert(t,r,s,o,...i){const{log:c,ctx:l}=this.logCtx(i,this.revert),d={};d[n.Model.pk(r)]=s;const p=new r(d);c.silly(`Rebuilding model ${p.constructor.name} id ${s}`);const u=t[e.PersistenceKeys.METADATA],h=Object.keys(p).reduce((e,a)=>(e[a]=t[n.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 h)throw new a.InternalError(`Transient property ${e} already exists on model ${p.constructor.name}. should be impossible`);h[e]=t})),u&&(c.silly(`Passing along ${this.flavour} persistence metadata for ${p.constructor.name} id ${s}: ${u}`),Object.defineProperty(h,e.PersistenceKeys.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:u})),h}async createAll(e,t,r,...s){const{log:o,ctxArgs:i}=this.logCtx(s,this.createAll);if(!t||!r)throw new a.ValidationError("Ids and models cannot be null or undefined");if(t.length!==r.length)throw new a.ValidationError("Ids and models must have the same length");const c=n.Model.tableName(e);return o.debug(`Creating ${t.length} entries ${c} table`),P(t.map((t,a)=>()=>this.create(e,t,r[a],...i)))}async readAll(e,t,...r){const{log:a,ctxArgs:s}=this.logCtx(r,this.readAll),o=n.Model.tableName(e);return a.debug(`Reading ${t.length} entries ${o} table`),P(t.map(t=>()=>this.read(e,t,...s)))}async updateAll(e,t,r,...s){const{log:o,ctxArgs:i}=this.logCtx(s,this.updateAll);if(t.length!==r.length)throw new a.InternalError("Ids and models must have the same length");const c=n.Model.tableName(e);return o.debug(`Updating ${t.length} entries ${c} table`),P(t.map((t,a)=>()=>this.update(e,t,r[a],...i)))}async deleteAll(e,t,...r){const{log:a,ctxArgs:s}=this.logCtx(r,this.deleteAll);return a.debug(`Deleting ${t.length} entries from ${e} table`),P(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.silly("Registering new observer "+e.toString()),this.dispatch||(r.verbose("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).debug(`Observer ${e.toString()} removed`)}async updateObservers(e,t,r,...s){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");await this.observerHandler.updateObservers(e,t,r,...s)}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(!B._currentFlavour)throw new a.InternalError("No persistence flavour set. Please initialize your adapter");return B._currentFlavour}static get current(){return B.get(this.currentFlavour)}static get(e){if(!e)return B.get(this._currentFlavour);if(e in this._cache)return this._cache[e];throw new a.InternalError(`No Adapter registered under ${e}.`)}static setCurrent(e){this._currentFlavour=e}static models(e){try{return o.Metadata.flavouredAs(e).filter(n.Model.isModel)}catch(e){throw new a.InternalError(e)}}static decoration(){}get client(){return this._client||(this._client=this.getClient()),this._client}for(e,...t){this.proxies||(this.proxies={});const r=`${this.alias} - ${n.hashObj(e)}`;if(r in this.proxies)return this.proxies[r];let a;const s=new Proxy(this,{get:(t,r,s)=>{if("_config"===r){const a=Reflect.get(t,r,s);return Object.assign({},a,e)}return"_client"===r?a:Reflect.get(t,r,s)},set:(e,t,r,s)=>"_client"===t?(a=r,!0):Reflect.set(e,t,r,s)});return this.proxies[r]=s,s}migrations(){return o.Metadata.migrationsFor(this)}async getQueryRunner(){return this}logCtx(e,t,r=!1,a){return super.logCtx(e,t,r,a)}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String]),r.__metadata("design:returntype",Promise)],B.prototype,"shutdownProxies",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,Object,w]),r.__metadata("design:returntype",Promise)],B.prototype,"context",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",void 0)],B.prototype,"observe",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],B.prototype,"unObserve",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],B.prototype,"client",null);class K extends a.InternalError{constructor(e){super(e,K.name,500)}}class $ extends a.InternalError{constructor(e){super(e,$.name,500)}}class R extends n.Model{constructor(e,t,r){super(),this.attr1=void 0,this.operator=void 0,this.comparison=void 0,t||r?(this.attr1=e,this.operator=t,this.comparison=r):n.Model.fromModel(this,e)}and(e){return R.and(this,e)}or(e){return R.or(this,e)}not(t){return new R(this,e.Operator.NOT,t)}hasErrors(...t){const r=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof R)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 R){if(!(this.comparison instanceof R)&&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 R.group(t,e.GroupOperator.AND,r)}static or(t,r){return R.group(t,e.GroupOperator.OR,r)}static group(e,t,r){return new R(e,t,r)}static attribute(e){return(new R.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 R(this.attr1,this.operator,this.comparison)}catch(e){throw new K(e)}}}}static builder(){return new R.Builder}static from(e){return new R(e)}}var L,k;r.__decorate([n.required(),r.__metadata("design:type",Object)],R.prototype,"attr1",void 0),r.__decorate([n.required(),r.__metadata("design:type",String)],R.prototype,"operator",void 0),r.__decorate([n.required(),r.__metadata("design:type",Object)],R.prototype,"comparison",void 0),e.OrderDirection=void 0,(L=e.OrderDirection||(e.OrderDirection={})).ASC="asc",L.DSC="desc",e.Cascade=void 0,(k=e.Cascade||(e.Cascade={})).CASCADE="cascade",k.NONE="none";const F={update:e.Cascade.CASCADE,delete:e.Cascade.NONE},j={Equals:(e,t)=>R.attribute(e).eq(t),Diff:(e,t)=>R.attribute(e).dif(t),LessThan:(e,t)=>R.attribute(e).lt(t),LessThanEqual:(e,t)=>R.attribute(e).lte(t),GreaterThan:(e,t)=>R.attribute(e).gt(t),GreaterThanEqual:(e,t)=>R.attribute(e).gte(t),In:(e,t)=>R.attribute(e).in(t),Matches:(e,t)=>R.attribute(e).regexp(t)},U=e=>e.charAt(0).toLowerCase()+e.slice(1);class q extends s.LoggedClass{static get log(){return this._logger||(this._logger=s.Logging.for(q.name)),this._logger}static 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(t,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 getFieldsFromMethodName(e){return(this.extractCore(e).split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/).map(e=>{const{operator:t,field:r}=this.parseFieldAndOperator(e);return r+(t??"")})}static extractSelect(t){const r=t.indexOf(e.QueryClause.SELECT);if(-1===r)return;const a=t.substring(r+e.QueryClause.SELECT.length),s=a.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?a.substring(0,s.index):a).split(e.QueryClause.AND).map(U).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(U).filter(Boolean)}static buildWhere(t,r){if(!t&&0===r.length)return;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?j[i]:j.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)}),0!==a.length){if(!n)throw Error("No conditions found in method name");return n}}static parseFieldAndOperator(e){for(const t of Object.keys(j))if(e.endsWith(t)){const r=e.slice(0,-t.length);return{field:U(r),operator:t}}return{field:U(e)}}static extractOrderByField(e){const t=e.match(/OrderBy(.+)$/);if(!t)return;const r=t[1];return r.charAt(0).toLowerCase()+r.slice(1)}static getProperlyOrderByOrThrow(t,r){const a=q.log.for(this.getProperlyOrderByOrThrow);if(r||t){if(r&&!t)throw new K("Expected OrderBy clause, but no sortable field was found in method name.");if(r||!t){if(!Object.values(e.OrderDirection).includes(r))throw new K(`Invalid OrderBy direction ${r}. Expected one of: ${Object.values(e.OrderDirection).join(", ")}.`);return[[t,r]]}a.debug("Ignoring OrderBy clause because direction is undefined.")}}static extractOrderLimitOffset(e,t){const r=this.extractCore(e).split(/And|Or/).length,s=t.slice(r)??[];let n,o,i;if(s.at(-1)instanceof a.Context&&s.pop(),s.length>=1){const t=s[0],r=this.extractOrderByField(e);n=this.getProperlyOrderByOrThrow(r,t)}return 2>s.length||"number"!=typeof s[1]||(o=s[1]),3>s.length||"number"!=typeof s[2]||(i=s[2]),{orderBy:n,limit:o,offset:i}}}function Y(){return o.Decoration.for(e.PersistenceKeys.STATEMENT).define({decorator:()=>(t,r,a)=>o.apply(o.methodMetadata(o.Metadata.key(e.PersistenceKeys.STATEMENT,r),!0))(t,r,a),args:[]}).apply()}function G(e){return J(e,[a.OperationKeys.CREATE,a.BulkCrudOperationKeys.CREATE_ALL])}function z(e){return J(e,[a.OperationKeys.UPDATE,a.BulkCrudOperationKeys.UPDATE_ALL])}function Q(e){return J(e,[a.OperationKeys.DELETE,a.BulkCrudOperationKeys.DELETE_ALL])}function H(e){return J(e,g)}function V(e){return J(e,Object.values(a.OperationKeys))}function W(e){return J(e,Object.values(a.BulkCrudOperationKeys))}function J(e,t){return(r,s,i,...c)=>{if("string"==typeof e)throw new a.InternalError("clazz cannot be string. This should be impossible");const{log:l}=O.prototype.logCtx(c,J);return l.silly(`filtering ${s} event for${r?" "+(n.Model.tableName(r)||r):""} ${i}`),("string"==typeof r?r===n.Model.tableName(e)||r===e.constructor.name:o.Metadata.constr(e)===o.Metadata.constr(r))&&t.includes(s)}}const X={onlyOnCreate:G,onlyOnUpdate:z,onlyOnDelete:Q,onlyOnTransactional:H,onlyOnSingle:V,onlyOnBulk:W};function Z(e){const t=Object.assign({},X);return Object.entries(t).forEach(([r,a])=>{t[r]=a(e.class)}),t}class ee 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.Model.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}get filters(){return Z(this)}constructor(e,t,...r){super(t),this.observers=[],this._overrides={allowGenerationOverride:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,ignoreDevSafeGuards:!1,mergeForUpdate:!0,applyUpdateValidation:!0},e&&(this._adapter=e),t&&(ee.register(t,this,this.adapter.alias),e)&&o.Metadata.get(t,o.DecorationKeys.FLAVOUR)===o.DefaultFlavour&&o.uses(e.flavour)(t);const s=this;[this.createAll,this.readAll,this.deleteAll].forEach(e=>{const t=e.name;a.wrapMethodWithContext(s,s[t+"Prefix"],e,s[t+"Suffix"])}),a.wrapMethodWithContextForUpdate(s,s[this.updateAll.name+"Prefix"],this.updateAll,s[this.updateAll.name+"Suffix"])}logCtx(e,t,r=!1){const a=this.adapter.logCtx([this.class,...e],t,r,this._overrides||{});function s(e){return e.ctxArgs.shift(),e}return a instanceof Promise?a.then(s):s(a)}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 _}async createPrefix(e,...t){const{ctx:r,ctxArgs:s,log:n}=(await this.logCtx(t,a.OperationKeys.CREATE,!0)).for(this.createPrefix),o=r.get("ignoreHandlers"),i=r.get("ignoreValidation");if(n.silly(`handlerSetting: ${o}, validationSetting: ${i}`),e=new this.class(e),o||await a.enforceDBDecorators(this,r,e,a.OperationKeys.CREATE,a.OperationKeys.ON),!i){const t=r.get("ignoredValidationProperties")||[];n.silly("ignored validation properties: "+t);const s=await Promise.resolve(e.hasErrors(...t));if(s)throw new a.ValidationError(s.toString())}return[e,...s]}async create(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.create);a.debug(`Creating new ${this.class.name} in table ${n.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,...s),this.adapter.revert(o,this.class,i,c,r)}async createAll(e,...t){if(!e.length)return e;const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.createAll);a.debug(`Creating ${e.length} new ${this.class.name} in table ${n.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,...s),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{ctx:r,ctxArgs:s,log:o}=(await this.logCtx(t,a.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAllPrefix),i=r.get("ignoreHandlers"),c=r.get("ignoreValidation");if(o.silly(`handlerSetting: ${i}, validationSetting: ${c}`),!e.length)return[e,...s];const l=n.Model.sequenceFor(e[0]);let d=[];if(n.Model.generatedBySequence(this.class)?(l.name||(l.name=n.Model.sequenceName(e[0],"pk")),d=await(await this.adapter.Sequence(l)).range(e.length,...s)):n.Model.generated(this.class,this.pk)||(d=e.map((e,t)=>{if(void 0===e[this.pk])throw new a.InternalError("Primary key is not defined for model in position "+t);return e[this.pk]})),e=await Promise.all(e.map(async(e,t)=>(e=new this.class(e),l.type&&(e[this.pk]="String"!==l.type||l.generated?d[t]:""+e[this.pk]),i||await a.enforceDBDecorators(this,r,e,a.OperationKeys.CREATE,a.OperationKeys.ON),e))),!c){const t=r.get("ignoredValidationProperties")||[];o.silly("ignored validation properties: "+t);const s=await Promise.all(e.map(e=>Promise.resolve(e.hasErrors(...t)))),n=a.reduceErrorsToPrint(s);if(n)throw new a.ValidationError(n)}return[e,...s]}async readPrefix(e,...t){const{ctx:r,ctxArgs:s,log:n}=(await this.logCtx(t,a.OperationKeys.READ,!0)).for(this.readPrefix),o=r.get("ignoreHandlers");n.silly("handlerSetting: "+o);const i=new this.class;return i[this.pk]=e,o||await a.enforceDBDecorators(this,r,i,a.OperationKeys.READ,a.OperationKeys.ON),[e,...s]}async read(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.read);a.debug(`reading ${this.class.name} from table ${n.Model.tableName(this.class)} with pk ${this.pk}`);const o=await this.adapter.read(this.class,e,...s);return this.adapter.revert(o,this.class,e,void 0,r)}async readAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:n}=(await this.logCtx(t,a.BulkCrudOperationKeys.READ_ALL,!0)).for(this.readAllPrefix),o=r.get("ignoreHandlers");return n.silly("handlerSetting: "+o),o||await Promise.all(e.map(async e=>{const t=new this.class;return t[this.pk]=e,a.enforceDBDecorators(this,r,t,a.OperationKeys.READ,a.OperationKeys.ON)})),[e,...s]}async readAll(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.readAll);return a.debug(`reading ${e.length} ${this.class.name} in table ${n.Model.tableName(this.class)}`),(await this.adapter.readAll(this.class,e,...s)).map((t,a)=>this.adapter.revert(t,this.class,e[a],void 0,r))}async update(e,...t){const{ctxArgs:r,log:a,ctx:s}=this.logCtx(t,this.update);let{record:o,id:i,transient:c}=this.adapter.prepare(e,s);return a.debug(`updating ${this.class.name} in table ${n.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,s)}async updatePrefix(e,...t){const{ctx:r,ctxArgs:s,log:o}=(await this.logCtx(t,a.OperationKeys.UPDATE,!0)).for(this.updatePrefix),i=r.get("ignoreHandlers"),c=r.get("ignoreValidation");o.silly(`handlerSetting: ${i}, validationSetting: ${c}`);const l=e[this.pk];if(!l)throw new a.InternalError("No value for the Id is defined under the property "+this.pk);let d;if(r.get("applyUpdateValidation")&&(d=await this.read(l,r),r.get("mergeForUpdate")&&(e=n.Model.merge(d,e,this.class))),i||await a.enforceDBDecorators(this,r,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,d),!c){const t=r.get("ignoredValidationProperties")||[];o.silly("ignored validation properties: "+t);const s=await Promise.resolve(e.hasErrors(d,...t));if(s)throw new a.ValidationError(s.toString())}return[e,...s,d]}async updateAll(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.updateAll);a.verbose(`Updating ${e.length} new ${this.class.name} in table ${n.Model.tableName(this.class)}`);const o=e.map(e=>this.adapter.prepare(e,r));return(await this.adapter.updateAll(this.class,o.map(e=>e.id),o.map(e=>e.record),...s)).map((e,t)=>this.adapter.revert(e,this.class,o[t].id,r.get("rebuildWithTransient")?o[t].transient:void 0,r))}async updateAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:o}=(await this.logCtx(t,a.BulkCrudOperationKeys.UPDATE_ALL,!0)).for(this.updateAllPrefix),i=r.get("ignoreHandlers"),c=r.get("ignoreValidation");o.silly(`handlerSetting: ${i}, ignoredValidation: ${c}`);const l=e.map(e=>{const t=e[this.pk];if(!t)throw new a.InternalError("missing id on update operation");return t});let d;if(r.get("applyUpdateValidation")&&(d=await this.readAll(l,r),r.get("mergeForUpdate")&&(e=e.map((e,t)=>n.Model.merge(d[t],e,this.class)))),i||await Promise.all(e.map((e,t)=>a.enforceDBDecorators(this,r,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,d?d[t]:void 0))),!c){const t=r.get("ignoredValidationProperties")||[];let s;o.silly("ignored validation properties: "+t),s=r.get("applyUpdateValidation")?await Promise.all(e.map((e,r)=>Promise.resolve(e.hasErrors(d[r],...t)))):await Promise.resolve(e.map(e=>e.hasErrors(...t)));const n=a.reduceErrorsToPrint(s);if(n)throw new a.ValidationError(n)}return[e,...s,d]}async deletePrefix(e,...t){const{ctx:r,ctxArgs:s,log:n}=(await this.logCtx(t,a.OperationKeys.DELETE,!0)).for(this.deletePrefix),o=r.get("ignoreHandlers");if(n.silly("handlerSetting: "+o),!o){const t=await this.read(e,...s);await a.enforceDBDecorators(this,r,t,a.OperationKeys.DELETE,a.OperationKeys.ON)}return[e,...s]}async delete(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.delete);a.debug(`deleting new ${this.class.name} in table ${n.Model.tableName(this.class)} with pk ${e}`);const o=await this.adapter.delete(this.class,e,...s);return this.adapter.revert(o,this.class,e,void 0,r)}async deleteAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:n}=(await this.logCtx(t,a.BulkCrudOperationKeys.DELETE_ALL,!0)).for(this.deleteAllPrefix),o=r.get("ignoreHandlers");if(n.silly("handlerSetting: "+o),!o){const t=await this.readAll(e,...s);await Promise.all(t.map(async e=>a.enforceDBDecorators(this,r,e,a.OperationKeys.DELETE,a.OperationKeys.ON)))}return[e,...s]}async deleteAll(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.create);return a.debug(`deleting ${e.length} ${this.class.name} in table ${n.Model.tableName(this.class)}`),(await this.adapter.deleteAll(this.class,e,...s)).map((t,a)=>this.adapter.revert(t,this.class,e[a],void 0,r))}select(e){return this.adapter.Statement(this._overrides).select(e).from(this.class)}async query(t,r,a=e.OrderDirection.ASC,s,n,...o){const{ctxArgs:i}=(await this.logCtx(o,e.PersistenceKeys.QUERY,!0)).for(this.query),c=[r,a],l=this.select().where(t).orderBy(c);return s&&l.limit(s),n&&l.offset(n),l.execute(...i)}async listBy(t,r,...a){const{log:s,ctxArgs:o}=(await this.logCtx(a,e.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return s.verbose(`listing ${n.Model.tableName(this.class)} by ${t} ${r}`),this.select().orderBy([t,r]).execute(...o)}async paginateBy(t,r,a={offset:1,limit:10},...s){const o=a.offset||1,{offset:i,bookmark:c,limit:l}=a;if(!i&&!c)throw new K("PaginateBy needs a page or a bookmark");const{log:d,ctx:p,ctxArgs:u}=(await this.logCtx(s,e.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);let h;if(d.verbose(`paginating ${n.Model.tableName(this.class)} with page size ${l}`),c&&p.get("paginateByBookmark"))h=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where((()=>r===e.OrderDirection.ASC?this.attr(n.Model.pk(this.class)).gt(c):this.attr(n.Model.pk(this.class)).lt(c))()).orderBy([t,r]).paginate(l,...u);else{if(!i)throw new K("PaginateBy needs a page or a bookmark");h=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([t,r]).paginate(l,...u)}const g=await h.page(o,c,...u);return h.serialize(g)}async findOneBy(t,r,...s){const{log:o,ctxArgs:i}=(await this.logCtx(s,e.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);o.verbose(`finding ${n.Model.tableName(this.class)} with ${t} ${r}`);const c=await this.select().where(this.attr(t).eq(r)).limit(1).execute(...i);if(!c.length)throw new a.NotFoundError("No results found");return c[0]}async findBy(t,r,...a){const{log:s,ctxArgs:o}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return s.verbose(`finding ${n.Model.tableName(this.class)} with ${t} ${r}`),this.select().where(this.attr(t).eq(r)).execute(...o)}async statement(t,...r){if(!ee.statements(this,t))throw new K("Invalid prepared statement requested "+t);const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PersistenceKeys.STATEMENT,!0)).for(this.statement);return a.verbose("Executing prepared statement "+t),this[t](...s)}attr(e){return R.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.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,...s){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");const{log:o,ctxArgs:i}=this.logCtx(s,this.updateObservers);o.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(e,t,Array.isArray(r)?r.map(e=>B._baseSequence.parseValue(n.Model.sequenceFor(this.class).type,e)):B._baseSequence.parseValue(n.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)||B.currentFlavour;try{n=this.get(t,i)}catch(e){n=void 0}if(n instanceof ee)return n;const c=r||o.Metadata.flavourOf(t)||n&&o.Metadata.get(n,e.PersistenceKeys.ADAPTER)||B.currentFlavour,l=c?B.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=n.Model.tableName(e);let s=r;if(t&&(s=[r,t].join(a.DefaultSeparator)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new a.InternalError("Could not find repository registered under "+r)}static register(e,t,r){let s=n.Model.tableName(e);if(r&&(s=[s,r].join(a.DefaultSeparator)),s in this._cache&&this._cache[s]instanceof ee)throw new a.InternalError(s+" already has a registered instance");this._cache[s]=t}static statements(t,r){const a=t instanceof ee?t.constructor:t,s=o.Metadata.get(a,r?o.Metadata.key(e.PersistenceKeys.STATEMENT,r):e.PersistenceKeys.STATEMENT);return(r?s:Object.keys(s))||!1}static queries(t,r){const a=t instanceof ee?t.constructor:t;return o.Metadata.get(a,r?o.Metadata.key(e.PersistenceKeys.QUERY,r):e.PersistenceKeys.QUERY)}}function te(t,r){if(!(r||(r=o.Decoration.flavourResolver(t instanceof n.Model?t.constructor:t))&&r!==o.DefaultFlavour))throw new a.InternalError("Could not retrieve flavour from model "+(t instanceof n.Model?t.constructor.name:t.name));return n.sf(e.PersistenceKeys.INJECTABLE,r,n.Model.tableName(t))}r.__decorate([Y(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String,void 0]),r.__metadata("design:returntype",Promise)],ee.prototype,"listBy",null),r.__decorate([Y(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String,Object,void 0]),r.__metadata("design:returntype",Promise)],ee.prototype,"paginateBy",null),r.__decorate([Y(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,void 0]),r.__metadata("design:returntype",Promise)],ee.prototype,"findOneBy",null),r.__decorate([Y(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,void 0]),r.__metadata("design:returntype",Promise)],ee.prototype,"findBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",void 0)],ee.prototype,"observe",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],ee.prototype,"unObserve",null),B&&(B._baseRepository=ee);class re extends t.InjectableRegistryImp{get log(){return this.logger||(this.logger=s.Logging.for(this)),this.logger}constructor(){super()}get(r,a){const s=this.log.for(this.get);let i;try{i=super.get(r)}catch{}if(!i){let c;if("function"==typeof r?c=n.Model.get(r.name)||r:"symbol"!=typeof r&&"string"!=typeof r||(c=n.Model.get(r.toString())),!c)return;const l=e.PersistenceKeys.ADAPTER,d=a||o.Metadata.get(c,l);try{let e=d;try{d&&B.get(d)}catch{const t=B.current;t&&t.flavour===d&&(e=t.alias)}if(i=ee.forModel(c,e),i instanceof ee)return i;const r=d||o.Metadata.get(i.constructor,l)||o.Metadata.get(c,l);t.Injectables.register(i,te(c,r))}catch(e){s.debug("No registered repository or adapter found. falling back to default adapter. Error: "+(e?.message||JSON.stringify(e)));const t=ee.get(c,d);if("function"==typeof t){const e=d?B.get(d):B.current;if(!e)return;return new t(e,c)}}}return i}}var ae,se,ne,oe,ie;async function ce(e,t,r,s){const o=t.logger.for(ce);if(!s){const t=n.Model.get(e.constructor.name);if(!t)throw new a.InternalError("Could not find model "+e.constructor.name);s=ee.forModel(t,r),o.info("Retrieved "+s.toString())}let i;if(void 0===e[n.Model.pk(s.class)])o.info(`No pk found in ${n.Model.tableName(s.class)} - creating`),i=await s.create(e,t);else{o.info(`pk found in ${n.Model.tableName(s.class)} - attempting update`);try{i=await s.update(e,t),o.info("Updated "+n.Model.tableName(s.class))}catch(r){if(!(r instanceof a.NotFoundError))throw r;o.info("update Failed - creating new "+n.Model.tableName(s.class)),i=await s.create(e,t)}o.info("After create update: "+i)}return i}async function le(e,t,r,s){const o=s[r];if(!o)return;if("object"!=typeof o){const t=_e(s,r,this.adapter.alias),a=await t.read(o,e);return await fe(e,s,r,o,a),void(s[r]=o)}const i="function"!=typeof t.class||t.class.name?t.class:t.class();if(!i)throw new a.InternalError("Could not find model "+t.class);const c=ee.forModel(i,this.adapter.alias),l=await c.create(o,e),d=n.Model.pk(l);await fe(e,s,r,l[d],l),s[r]=l[d]}async function de(t,r,a,s){const o=s[a];if(!o)return;if(r.cascade.update!==e.Cascade.CASCADE)return;if("object"!=typeof o){const e=_e(s,a,this.adapter.alias),r=await e.read(o,t);return await fe(t,s,a,o,r),void(s[a]=o)}const i=await ce(s[a],t,this.adapter.alias),c=n.Model.pk(i);await fe(t,s,a,i[c],i),s[a]=i[c]}async function pe(t,r,a,s){const o=s[a];if(!o)return;if(r.cascade.update!==e.Cascade.CASCADE)return;const i=_e(s,a,this.adapter.alias);let c;c=o instanceof n.Model?await i.delete(s[a][i.pk],t):await i.delete(s[a],t),await fe(t,s,a,c[i.pk],c)}async function ue(e,t,r,s){const o=s[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=e.logger.for(ue),l=new Set([...o]);if("object"!==i){const t=_e(s,r,this.adapter.alias),a=await t.readAll([...l.values()],e);for(let t=0;t<a.length;t++){const s=a[t];c.info("FOUND ONE TO MANY VALUE: "+JSON.stringify(s)),await fe(e,s,r,[...l.values()][t],a)}return s[r]=[...l],void c.info("SET ONE TO MANY IDS: "+s[r])}const d=n.Model.pk(o[0].constructor),p=new Set;for(const t of o){c.info("Creating or updating one-to-many model: "+JSON.stringify(t));const a=await ce(t,e,this.adapter.alias);c.info(`caching: ${JSON.stringify(a)} under ${a[d]}`),await fe(e,s,r,a[d],a),c.info("Creating or updating one-to-many model: "+JSON.stringify(t)),p.add(a[d])}s[r]=[...p]}async function he(t,r,a,s){const{cascade:n}=r;if(n.update===e.Cascade.CASCADE)return ue.call(this,t,r,a,s)}async function ge(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="function"!=typeof r.class||r.class.name?r.class:r.class(),l="object"===i,d=l?ee.forModel(c,this.adapter.alias):_e(n,s,this.adapter.alias),p=[...new Set([...l?o.map(e=>e[d.pk]):o]).values()];let u,h;try{u=await d.deleteAll(p,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<u.length;e++){h=u[e];try{await fe(t,n,s,p[e],h)}catch(r){throw t.logger.error(`Failed to cache record ${p[e]} with key ${s} and model ${JSON.stringify(n,void 0,2)} `,r),r}}n[s]=p}function ye(t,r,a){return[e.PersistenceKeys.POPULATE,t,r,a].join(".")}async function fe(e,t,r,a,s){const n=ye(t.constructor.name,r,a),o=e.get("cacheForPopulate")||{};return o[n]=s,e.accumulate({cacheForPopulate:o})}async function me(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(t,r,s,n,o)=>{let i,c;const l=[],d=t.get("cacheForPopulate")||{};for(const t of n){i=ye(r.constructor.name,s,t);try{if(c=d[i],!c)throw Error("Not found in cache")}catch(n){const i=_e(r,s,o);if(!i)throw new a.InternalError("Could not find repo");c=await i.read(t,e)}l.push(c)}return l})(e,s,r,o?n:[n],this.adapter.alias);s[r]=o?i:i[0]}(e=>{e.PENDING="pending",e.RUNNING="running",e.FAILED="failed",e.SUCCEEDED="succeeded",e.CANCELED="canceled",e.WAITING_RETRY="waiting_retry"})(ae||(ae={})),(e=>{e.EXPONENTIAL="exponential",e.FIXED="fixed"})(se||(se={})),(e=>{e.NONE="none",e.FULL="full"})(ne||(ne={})),(e=>{e.STATUS="status",e.LOG="log",e.PROGRESS="progress"})(oe||(oe={})),(e=>{e.ATOMIC="atomic",e.COMPOSITE="composite"})(ie||(ie={}));const be=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function _e(e,t,r){if(!e)throw Error("No model was provided to get repository");let s;if(Array.isArray(e[t])||e[t]instanceof Set){const r=o.Metadata.get(e instanceof n.Model?e.constructor:e,o.Metadata.key(n.ValidationKeys.REFLECT,t,n.ValidationKeys.LIST))?.clazz;if(!r)throw new a.InternalError("Failed to find types decorators for property "+t);s=(Array.isArray(r)?[...r]:[r]).map(e=>"function"!=typeof e||e.name?e:e())}else s=o.Metadata.getPropDesignTypes(e instanceof n.Model?e.constructor:e,t)?.designTypes;const i=s?.find(e=>!be.includes((""+e.name).toLowerCase()));return ee.forModel(i,r)}class we extends a.BadRequestError{constructor(e,t=we.name,r=401){super(e,t,r)}}class Oe extends we{constructor(e,t=Oe.name){super(e,t,403)}}class ve extends a.InternalError{constructor(e){super(e,ve.name,503)}}function Ee(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 Ae(t){return o.Decoration.for(e.PersistenceKeys.COLUMN).define({decorator:t=>(r,a)=>o.propMetadata(o.Metadata.key(e.PersistenceKeys.COLUMN,a),t||a)(r,a),args:[t]}).apply()}function xe(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 Se(e,t,r,s){if(s[r]&&(await this.select().where(R.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 Ce(e,t,r,a){throw new we("This adapter does not support user identification")}function Pe(){return a.timestamp([a.OperationKeys.CREATE])}function Me(){return a.timestamp()}function Ne(e){const t="function"==typeof e&&e.name?e:e(),r=n.Model.pk(t);return o.Metadata.allowedTypes(t,r)||[]}function De(...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 Ie extends n.Model{constructor(e){super(e)}}r.__decorate([Ae(),Pe(),o.description("timestamp of creation"),r.__metadata("design:type",Date)],Ie.prototype,"createdAt",void 0),r.__decorate([Ae(),Me(),o.description("timestamp of last update"),r.__metadata("design:type",Date)],Ie.prototype,"updatedAt",void 0);let Be=class extends Ie{constructor(e){super(e)}};r.__decorate([n.required(),n.type(String),n.option(se),o.description("the backoff strategy"),r.__metadata("design:type",String)],Be.prototype,"strategy",void 0),r.__decorate([n.required(),o.description("timestamp of creation"),r.__metadata("design:type",Number)],Be.prototype,"baseMs",void 0),r.__decorate([n.required(),o.description("timestamp of creation"),r.__metadata("design:type",Number)],Be.prototype,"maxMs",void 0),r.__decorate([n.type(String),n.option(ne),o.description("optional jitter strategy"),r.__metadata("design:type",String)],Be.prototype,"jitter",void 0),Be=r.__decorate([n.model(),r.__metadata("design:paramtypes",[Object])],Be),o.Metadata.tasks=(()=>o.Metadata.innerGet(Symbol.for("tasks"))).bind(o.Metadata),o.Metadata.taskFor=(e=>{const t=o.Metadata.tasks();return t?t[e]:void 0}).bind(o.Metadata),o.Metadata.validationExceptions=((t,r)=>{const s=o.Metadata.get(t,e.PersistenceKeys.NO_VALIDATE)||[],i=Object.entries(s).filter(([,e])=>e.includes(r)).map(([e])=>e);let c=[];return r!==a.OperationKeys.CREATE&&r!==a.OperationKeys.UPDATE||(c=n.Model.nestedRelations(t)),[...new Set([...i,...c])]}).bind(o.Metadata),o.Metadata.migrationsFor=(t=>{if(!(t=t??B.current))throw new a.InternalError("Could not get adapter for migrations");return o.Metadata.innerGet(Symbol.for(e.PersistenceKeys.MIGRATION),t.alias).map(e=>e.class)}).bind(o.Metadata),o.Metadata.migrations=(()=>{const t=o.Metadata.innerGet(Symbol.for([e.PersistenceKeys.MIGRATION,e.PersistenceKeys.BY_KEY].join("-")));return Object.values(t).flat().map(e=>[e.class.name,e.class])}).bind(o.Metadata),o.Metadata.relations=((t,r)=>{const s=o.Metadata.get(t,e.PersistenceKeys.RELATIONS);if(s){if(!r)return Object.keys(s);if(!s[r])throw new a.InternalError("No relations metadata found for property "+r);return s[r]}}).bind(o.Metadata),n.Model.relations=(e,t)=>o.Metadata.relations(e instanceof n.Model?e.constructor:e,t)||[],n.Model.nestedRelations=((t,r=[])=>{let a=[];const s=o.Metadata.get(t,e.PersistenceKeys.RELATIONS);if(!s||!Object.keys(s).length)return[...new Set([...r])];for(const e in s){const t=s[e];if(t?.class&&n.Model.relations(t.class)){const s=n.Model.relations(t.class).map(t=>`${e}.${t}`);r=[...r,...s],a=n.Model.nestedRelations(t.class,r)}}return[...new Set([...r,...a])]}).bind(n.Model),n.Model.generatedBySequence=((e,t)=>{const r="function"!=typeof e?e.constructor:e;return!!n.Model.sequenceFor(r).generated}).bind(n.Model),o.Metadata.createdBy=(t=>{const r=o.Metadata.get("function"!=typeof t?t.constructor:t,e.PersistenceKeys.CREATED_BY);if(!r)throw new a.InternalError("No createdBy metadata found for model. did you use @createdBy()?");return r}).bind(o.Metadata),o.Metadata.updatedBy=(t=>{const r=o.Metadata.get("function"!=typeof t?t.constructor:t,e.PersistenceKeys.UPDATED_BY);if(!r)throw new a.InternalError("No updatedBy metadata found for model. did you use @updatedBy()?");return r}).bind(o.Metadata),n.Model.tableName=t=>{if(!(t instanceof n.Model?n.Model.get(t.constructor.name):t))throw new a.InternalError("Unable to find model "+t);return o.Metadata.get(t instanceof n.Model?t.constructor:t,e.PersistenceKeys.TABLE)||(t instanceof n.Model?t.constructor.name:t.name)},n.Model.columnName=(t,r)=>o.Metadata.get(t instanceof n.Model?t.constructor:t,o.Metadata.key(e.PersistenceKeys.COLUMN,r))||r,n.Model.sequenceName=(e,...t)=>[n.Model.tableName(e),...t].join("_"),n.Model.sequenceFor=(e,t)=>{if(t)throw new E("not currently supported");const r=n.Model.pkProps(e instanceof n.Model?e.constructor:e);if(!r)throw new a.InternalError("No sequence options defined for model. did you use the @pk decorator?");return r},n.Model.indexes=t=>{const r=o.Metadata.get(t instanceof n.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 Ke extends O{constructor(){super()}logCtx(e,t,r=!1){if(!this.adapter)throw new a.InternalError("Adapter not set yet");return this.adapter.logCtx(e,t,r)}async initialize(...t){if(!this.adapter)return void this.log.for(this.initialize).verbose("No adapter observed for dispatch; skipping initialization");const{log:r}=(await this.logCtx(t,e.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize);r.verbose(`Initializing ${this.adapter}'s event Dispatch`);const s=this.adapter;[a.OperationKeys.CREATE,a.OperationKeys.UPDATE,a.OperationKeys.DELETE,a.BulkCrudOperationKeys.CREATE_ALL,a.BulkCrudOperationKeys.UPDATE_ALL,a.BulkCrudOperationKeys.DELETE_ALL].forEach(e=>{if(!s[e])throw new a.InternalError(`Method ${e} not found in ${s.alias} adapter to bind Observables Dispatch`);let t=Object.getOwnPropertyDescriptor(s,e),r=s;for(;!t&&r!==Object.prototype;)r=Object.getPrototypeOf(r),t=Object.getOwnPropertyDescriptor(r,e);function 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&&t.writable?s[e]=new Proxy(s[e],{apply:async(t,r,a)=>{const{log:s,ctxArgs:o,ctx:i}=r.logCtx(a.slice(3-(4-a.length),a.length),t),[c,l,d]=a,p=await t.call(r,c,l,d,...o),u=[c,n(e),l];return i.get("observeFullResult")&&u.push(p),this.updateObservers(...u,...o).catch(t=>s.error(`Failed to dispatch observer refresh for ${e} on ${c.name||c} for ${l}: ${t}`)),p}}):this.log.error(`Could not find method ${e} to bind Observables Dispatch`)})}async close(){}observe(e){if(!(e instanceof B))throw new E("Only Adapters can be observed by dispatch");this.adapter=e,this.models=B.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 E("Only the adapter that was used to observe can be unobserved");this.adapter=void 0}async updateObservers(e,t,r,...s){if(!e)throw new a.InternalError("Model must be provided for observer update");const o=e&&"string"==typeof e?e:n.Model.tableName(e),{log:i,ctxArgs:c,ctx:l}=this.logCtx(s,this.updateObservers);if(this.adapter)try{i.debug(`dispatching observer refresh for ${t}:${o}: ${r}${l.get("observeFullResult")?" - including result":""}`),await this.adapter.refresh(e,t,r,...c)}catch(e){throw new a.InternalError("Failed to refresh dispatch: "+e)}else i.verbose(`No adapter observed for dispatch; skipping observer update for ${o}:${t}`)}toString(){return(this.adapter?this.adapter.toString():"uninitialized")+" event dispatch"}}B&&(B._baseDispatch=Ke);class $e extends n.Model{constructor(e){super(e)}}r.__decorate([Pe(),r.__metadata("design:type",Date)],$e.prototype,"createdAt",void 0),r.__decorate([Me(),r.__metadata("design:type",Date)],$e.prototype,"updatedAt",void 0);const Re={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},Le=Re,ke={type:"Number",generated:!0,startWith:0,incrementBy:1,cycle:!1},Fe=Object.assign({},ke,{type:"BigInt"});async function je(e,t,r,s){if(!t.type||!t.generated||s[r])return;let o;t.name||(t.name=n.Model.sequenceName(s,"pk"));try{o=await this.adapter.Sequence(t,this._overrides)}catch(e){throw new a.InternalError(`Failed to instantiate Sequence ${t.name}: ${e}`)}var i,c,l;i=s,c=r,l=await o.next(e),Reflect.set(i,c,l)}function Ue(t,r){return(s,i)=>{if(o.prop()(s,i),!t.type){const e=o.Metadata.type(s.constructor,i);if(![Number.name,String.name,BigInt.name].includes(e?.name||e))throw Error("Incorrrect option type");t.type=e}switch(t.type){case String.name||String.name.toLowerCase():case String:t.generated=void 0!==t.generated&&t.generated,t.type=String;break;case Number.name||String.name.toLowerCase():case Number:t.generated=void 0===t.generated||t.generated,t.type=Number;break;case BigInt.name||BigInt.name.toLowerCase():case BigInt:t.type=BigInt,t.generated=void 0===t.generated||t.generated;break;case"uuid":case"serial":t.generated=!0;break;default:throw Error("Unsupported type")}void 0===t.generated&&(t.generated=!0);const c=[xe([e.OrderDirection.ASC,e.OrderDirection.DSC]),n.required(),a.readonly(),o.propMetadata(o.Metadata.key(a.DBKeys.ID,i),t),a.onCreate(je,t,r)];return t.generated&&c.push(a.generated()),o.apply(...c)(s,i)}}function qe(e){const t=Object.assign({},Le);return delete t.generated,e=Object.assign({},t,e),o.Decoration.for(a.DBKeys.ID).define({decorator:Ue,args:[e,{priority:60}]}).apply()}e.SequenceModel=class extends $e{constructor(e){super(e)}},r.__decorate([qe({type:String,generated:!1}),r.__metadata("design:type",String)],e.SequenceModel.prototype,"id",void 0),r.__decorate([n.required(),xe(),r.__metadata("design:type",Object)],e.SequenceModel.prototype,"current",void 0),e.SequenceModel=r.__decorate([Ee("??sequence"),n.model(),r.__metadata("design:paramtypes",[Object])],e.SequenceModel);class Ye extends O{static{this.lock=new i.MultiLock}constructor(t,r,a={}){super(),this.options=t,this.adapter=r,this.repo=ee.forModel(e.SequenceModel,r.alias).override(a)}async current(...e){const{log:t,ctx:r}=await this.logCtx(e,a.OperationKeys.READ,!0),{name:s,startWith: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(t.debug(`Sequence.current missing ${s}, returning startWith=${n}`),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){const{log:s,ctx:n}=this.adapter.logCtx([r],this.increment),{type:o,incrementBy:i,name:c}=this.options;if(!c)throw new a.InternalError("Sequence name is required");return Ye.lock.execute(async()=>{const r=t||i;if(r%i!==0)throw new a.InternalError("Value to increment does not consider the incrementBy setting: "+i);const l="function"==typeof o&&o?.name?o.name:o,d=await this.current(n),p=async t=>{try{return await this.repo.update(new e.SequenceModel({id:c,current:t}),n)}catch(r){if(r instanceof a.NotFoundError)return s.debug(`Sequence create ${c} current=${d} next=${t}`),this.repo.create(new e.SequenceModel({id:c,current:t}),n);throw r}};if("uuid"===l)for(;;){const e=D.instance.generate(d);try{const t=await p(e);return s.debug(`Sequence uuid increment ${c} current=${d} next=${e}`),t.current}catch(e){if(e instanceof a.ConflictError)continue;throw e}}const u=(e=>{switch(l){case Number.name:return this.parse(e)+r;case BigInt.name:return this.parse(e)+BigInt(r);case String.name:return this.parse(e);case"serial":return T.instance.generate(e);default:throw new a.InternalError("Should never happen")}})(d),h=await p(u);return s.debug(`Sequence.increment ${c} current=${d} next=${u}`),h.current},c)}async next(...e){const{ctx:t}=(await this.logCtx(e,a.OperationKeys.UPDATE,!0)).for(this.next);return this.increment(void 0,t)}async range(e,...t){const{ctx:r,log:s}=(await this.logCtx(t,a.OperationKeys.UPDATE,!0)).for(this.range);if("uuid"===this.options.type||"serial"===this.options.type)throw new E(`type ${this.options.type} is currently not suppported for this adapter`);const n="function"==typeof this.options.type&&this.options.type?.name?this.options.type.name:this.options.type,o=this.parse(this.options.incrementBy),i=await this.increment(this.parse(e)*o,r);let c=[];for(let t=0;e-1>=t;t++)c.push(i-o*this.parse(t));if(c=c.reverse(),c[c.length-1]!==i&&"String"!==n)throw new a.InternalError("Miscalculation of range");return s.debug("Calculated range: "+c.join(", ")),c}parse(e){return Ye.parseValue(this.options.type,e)}logCtx(t,r,a=!1){const s=this.adapter.logCtx([e.SequenceModel,...t],r,a);function n(e){return e.ctxArgs.shift(),e}return s instanceof Promise?s.then(n):n(s)}static pk(e){return n.Model.sequenceName(e,"pk")}static parseValue(e,t){switch("function"==typeof e&&e?.name?e.name:e){case Number.name||Number.name.toLowerCase():return"string"==typeof t?parseInt(t):"number"==typeof t?t:BigInt(t);case BigInt.name||BigInt.name.toLowerCase():return BigInt(t);case String.name||String.name.toLowerCase():return t.toString();case void 0:case"uuid":case"serial":return t;default:throw new E(`Unsupported sequence type: ${e} for adapter ${this}`)}}}B._baseSequence=Ye;class Ge extends a.InternalError{constructor(e){super(e,Ge.name,500)}}class ze extends s.LoggedClass{get current(){return this._currentPage}get total(){return this._totalPages}get count(){return this._recordCount}get statement(){return this._statement||(this._statement=this.prepare(this.query)),this._statement}constructor(e,t,r,a){super(),this.adapter=e,this.query=t,this.size=r,this.clazz=a,N(this,this.page,this.pagePrefix,this.page.name)}isPreparedStatement(){const t=this.query;return t.method&&t.method.match(RegExp(`${e.PreparedStatementKeys.FIND_BY}|${e.PreparedStatementKeys.LIST_BY}`,"gi"))}async pagePrefix(t,...r){const{ctxArgs:a}=(await this.adapter.logCtx([this.clazz,...r],e.PreparedStatementKeys.PAGE_BY,!0)).for(this.pagePrefix);return a.shift(),[t,...a]}async pagePrepared(t,r,...a){const{log:s,ctxArgs:n}=this.adapter.logCtx(!r||r instanceof w?[r,...a]:[...a],this.pagePrepared);s.debug(`Running paged prepared statement ${t} page${r?" - bookmark "+r:""}`),!r||r instanceof w||(this._bookmark=r);const o=ee.forModel(this.clazz,this.adapter.alias),i=this.query,{method:c,args:l,params:d}=i,p=RegExp(`^${e.PreparedStatementKeys.FIND_BY}|${e.PreparedStatementKeys.LIST_BY}`,"gi");if(!c.match(p))throw new E(`Method ${c} is not supported for pagination`);p.lastIndex=0;const u=c.replace(p,e.PreparedStatementKeys.PAGE_BY),h=[u,...l];let g={limit:this.size,offset:t,bookmark:this._bookmark};u!==e.PreparedStatementKeys.PAGE_BY||h.length>2?g={direction:d.direction,limit:this.size,offset:t,bookmark:this._bookmark}:h.push(d.direction),h.push(g);const y=await o.statement(...h,...n);return this.apply(y)}async next(...e){return this.page(this.current+1,...e)}async previous(...e){return this.page(this.current-1,...e)}validatePage(e){if(1>e||!Number.isInteger(e))throw new $("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&e>this._totalPages)throw new $(`Only ${this._totalPages} are available. Cannot go to page ${e}`);return e}async page(e=1,t,...r){const{ctxArgs:a}=this.adapter.logCtx([t,...r],this.page);if(this.isPreparedStatement())return await this.pagePrepared(e,...a);throw new E("Raw support not available without subclassing this")}serialize(e,t=!1){const r={data:e,current:this.current,total:this.total,count:this.count,bookmark:this._bookmark};try{return t?JSON.stringify(r):r}catch(e){throw new a.SerializationError(e)}}apply(e){const t="string"==typeof e?ze.deserialize(e):e;return this._currentPage=t.current,this._totalPages=t.total,this._recordCount=t.count,this._bookmark=t.bookmark,t.data}static deserialize(e){try{return JSON.parse(e)}catch(e){throw new a.SerializationError(e)}}static isSerializedPage(e){return e&&"object"==typeof e&&Array.isArray(e.data)&&"number"==typeof e.total&&"number"==typeof e.current&&"number"==typeof e.count}}var Qe,He,Ve,We;class Je extends O{constructor(e,t){super(),this.adapter=e,this.overrides=t,[this.execute,this.paginate].forEach(e=>{a.prefixMethod(this,e,(...t)=>this.executionPrefix(e,...t),e.name)})}async executionPrefix(t,...r){const{ctx:a,ctxArgs:s,log:n}=(await this.adapter.logCtx([this.fromSelector,...r],t.name===this.paginate.name?e.PreparedStatementKeys.PAGE_BY:e.PersistenceKeys.QUERY,!0,this.overrides||{})).for(t);s.shift();const o=a.get("forcePrepareSimpleQueries"),i=a.get("forcePrepareComplexQueries");return n.silly(`statement force simple ${o}, forceComplex: ${i}`),(o&&this.isSimpleQuery()||i)&&(n.silly(`squashing ${i?"complex":"simple"} query to prepared statement`),await this.prepare(a),n.silly(`squashed ${i?"complex":"simple"} query to ${JSON.stringify(this.prepared,null,2)}`)),s}get log(){return this.adapter.log.for(Je)}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?n.Model.get(e):e,!this.fromSelector)throw new K("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){const{log:t,ctxArgs:r}=this.logCtx(e,this.execute);try{if(this.prepared)return this.executePrepared(...e);t.silly("Building raw statement...");const a=this.build();return t.silly("executing raw statement"),await this.raw(a,...r)}catch(e){throw new K(e)}}async executePrepared(...e){const t=ee.forModel(this.fromSelector,this.adapter.alias),{method:r,args:a,params:s}=this.prepared;return t.statement(r,...a,s,...e)}async raw(e,...t){const{ctx:r,ctxArgs:a}=this.logCtx(t,this.raw);if(!r.get("allowRawStatements"))throw new E("Raw statements are not allowed in the current configuration");const s=await this.adapter.raw(e,!0,...a);if(!this.selectSelector)return s;const o=n.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(s)?s.map(i):i(s)}prepareCondition(t,r){let{attr1:a,operator:s,comparison:n}=t;const o={};switch(s){case e.GroupOperator.AND:case e.GroupOperator.OR:{let e=a,t=n;if("string"!=typeof a){const t=this.prepareCondition(a,r);e=t.method,o.args=[...o.args||[],...t.args||[]]}if(n instanceof R){const e=this.prepareCondition(n,r);t=e.method,o.args=[...o.args||[],...e.args||[]]}o.method=`${e} ${s.toLowerCase()} ${t}`;break}case e.Operator.EQUAL:o.method=a,o.args=[...o.args||[],n];break;case e.Operator.DIFFERENT:o.method=a+" diff",o.args=[...o.args||[],n];break;case e.Operator.REGEXP:o.method=a+" matches",o.args=[...o.args||[],n];break;case e.Operator.BIGGER:o.method=a+" bigger",o.args=[...o.args||[],n];break;case e.Operator.BIGGER_EQ:o.method=a+" bigger than equal";break;case e.Operator.SMALLER:o.method=a+" less",o.args=[...o.args||[],n];break;case e.Operator.SMALLER_EQ:o.method=a+" less than equal",o.args=[...o.args||[],n];break;case e.Operator.IN:o.method=a+" in",o.args=[...o.args||[],n];break;default:throw new K("Unsupported operator "+s)}return o}squash(t){if(this.selectSelector&&this.selectSelector.length)return;if(this.groupBySelector)return;if(this.countSelector)return;if(this.maxSelector)return;if(this.minSelector)return;let r;if(this.whereCondition){if(this.whereCondition.comparison instanceof R)return;r=this.whereCondition.attr1}const a=this.orderBySelector?this.orderBySelector:r?[r,e.OrderDirection.DSC]:[n.Model.pk(this.fromSelector),e.OrderDirection.DSC],[s,o]=a,i={direction:o};this.limitSelector&&(i.limit=this.limitSelector),this.offsetSelector&&(i.offset=this.offsetSelector);const c={class:this.fromSelector,method:e.PreparedStatementKeys.LIST_BY,args:[s],params:i};return r&&(c.method=e.PreparedStatementKeys.FIND_BY,c.args=[r,this.whereCondition.comparison],c.params=i),c}async prepare(t){if(t=t||await this.adapter.context(e.PersistenceKeys.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&t.get("forcePrepareSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const r=[],a={},n={class:this.fromSelector,args:r,params:a},o=[e.QueryClause.FIND_BY];if(this.whereCondition){const e=this.prepareCondition(this.whereCondition,t);o.push(e.method),e.args&&e.args.length&&r.push(...e.args)}return this.selectSelector&&o.push(e.QueryClause.SELECT,this.selectSelector.join(` ${e.QueryClause.AND.toLowerCase()} `)),this.orderBySelector&&(o.push(e.QueryClause.ORDER_BY,this.orderBySelector[0]),a.direction=this.orderBySelector[1]),this.groupBySelector&&o.push(e.QueryClause.GROUP_BY,this.groupBySelector),this.limitSelector&&(a.limit=this.limitSelector),this.offsetSelector&&(a.skip=this.offsetSelector),n.method=s.toCamelCase(o.join(" ")),n.params=a,this.prepared=n,this}isSimpleQuery(){return!(this.selectSelector&&this.selectSelector.length||this.groupBySelector||this.countSelector||this.maxSelector||this.minSelector)}async paginate(e,...t){t.pop();try{return this.adapter.Paginator(this.prepared||this.build(),e,this.fromSelector)}catch(e){throw new K(e)}}toString(){return this.adapter.flavour+" statement"}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array]),r.__metadata("design:returntype",Object)],Je.prototype,"select",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(Qe="undefined"!=typeof S&&S)?Qe:Object]),r.__metadata("design:returntype",Object)],Je.prototype,"distinct",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(He="undefined"!=typeof S&&S)?He:Object]),r.__metadata("design:returntype",Object)],Je.prototype,"max",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(Ve="undefined"!=typeof S&&S)?Ve:Object]),r.__metadata("design:returntype",Object)],Je.prototype,"min",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(We="undefined"!=typeof S&&S)?We:Object]),r.__metadata("design:returntype",Object)],Je.prototype,"count",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Object)],Je.prototype,"from",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[R]),r.__metadata("design:returntype",Object)],Je.prototype,"where",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array]),r.__metadata("design:returntype",Object)],Je.prototype,"orderBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Object)],Je.prototype,"groupBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Number]),r.__metadata("design:returntype",Object)],Je.prototype,"limit",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Number]),r.__metadata("design:returntype",Object)],Je.prototype,"offset",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[void 0]),r.__metadata("design:returntype",Promise)],Je.prototype,"execute",null);class Xe extends O{constructor(e){super(),this.name=e,this.observers=[],this.Context=w}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:new _,writable:!1});const r=this.log.for(this.observe);this.observerHandler.observe(e,t),r.verbose("Registered new observer "+(e.constructor.name||e.toString()))}unObserve(e){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables? or are you unregistering whe you shouldn't");this.observerHandler.unObserve(e);const t=this.log.for(this.unObserve);t.verbose(`Observer ${e.toString()} removed`),this.observerHandler.count()||(delete this.observerHandler,t.verbose("No longer being observed"))}async updateObservers(e,t,r,...s){if(!this.observerHandler)throw new a.InternalError("ObserverHandler not initialized. Did you register any observables?");const{log:n,ctxArgs:o}=this.logCtx(s,this.updateObservers);n.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(e,t,r,...o)}async flags(e,t,...r){t.correlationId=t.correlationId||`${e}-${D.instance.generate()}`;const a=t.logger||s.Logging.for(this);return a.setConfig({correlationId:t.correlationId}),Object.assign({},h,t,{args:r,timestamp:new Date,operation:e,logger:a})}async refresh(e,t,r,...a){return this.updateObservers(e,t,r,...a)}async context(e,t,...r){this.log.for(this.context).silly(`creating new context for ${e} operation with flag overrides: ${JSON.stringify(t)}`);let a=r.pop();void 0===a||a instanceof w||(r.push(a),a=void 0);const s=await this.flags("string"==typeof e?e:e.name,t,...r);return a?new this.Context(a).accumulate({...s,parentContext:a}):(new this.Context).accumulate(s)}logCtx(e,t,r=!1,a){return O.logCtx.call(this,t,a||{},r,...e.filter(e=>void 0!==e))}static get(e){if(!e)throw new a.InternalError("No name provided");const r=C(e),s=t.Injectables.get(r);if(s)return s;throw new a.InternalError("No Service found for "+("string"==typeof e?e:"symbol"==typeof e?e.toString():e.name))}static async boot(...r){let s=r.pop();void 0===s||s instanceof w||(r.push(s),s=void 0);const n=await Xe.prototype.flags(e.PersistenceKeys.INITIALIZATION,{},...r);s=s?new w(s).accumulate({...n,parentContext:s}):(new w).accumulate(n),r=[...r,s];const{log:o,ctxArgs:i}=Xe.prototype.logCtx(r,this.boot),c=t.Injectables.services();for(const[e,r]of Object.entries(c))try{o.verbose(`Booting ${r.name} service...`);const s=t.Injectables.get(r);if(!s)throw new a.InternalError("Failed to resolve injectable for "+e);s instanceof Ze&&(o.verbose(`Initializing ${r.name} service...`),await s.boot(...i))}catch(t){throw new a.InternalError(`Failed to boot ${e} service:${t}`)}}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",void 0)],Xe.prototype,"observe",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],Xe.prototype,"unObserve",null);class Ze extends Xe{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...`)}}function et(e){return function(t,r,a){const s=a.value;return a.value=function(...t){const r=this.class;if(r&&M(r,e))throw Error(`Operation "${e}" is blocked by @BlockOperations for ${r?.name??"Model"}.`);return s.apply(this,t)},a}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Promise)],Ze.prototype,"boot",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],Ze.prototype,"config",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],Ze.prototype,"client",null);const tt=()=>et(a.OperationKeys.CREATE),rt=()=>et(a.OperationKeys.READ),at=()=>et(a.OperationKeys.UPDATE),st=()=>et(a.OperationKeys.DELETE);function nt(r){return(a,s,n)=>{n||s?(o.prop()(a,s),r=r||o.Metadata.type(a.constructor,s)):r=r||a,r=C(r);const i=[];if(n&&"number"==typeof n.value)i.push(t.inject(r));else if(n||s){if(n)throw Error("Invalid decorator usage. Should be impossible");i.push(t.inject(r))}else o.Metadata.set(e.PersistenceKeys.SERVICE,r,a),i.push(t.injectable(r,{singleton:!0,callback:e=>Object.defineProperty(e,"name",{enumerable:!0,configurable:!1,writable:!1,value:r})}));return o.apply(...i)(a,s,n)}}const ot=e=>"string"==typeof e?e.endsWith("Service")?e:e+"Service":"symbol"==typeof e?e.toString():e.name+"Service";class it extends Xe{get class(){if(!this.clazz)throw new a.InternalError("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=ee.forModel(this.clazz)),this._repository}constructor(e,t){super(t??e.name+"Service"),this.clazz=e}static getService(e){if(!e)throw new a.InternalError("No name provided");const t=ot(e);try{const e=Xe.get(t);if(e)return e}catch(e){}throw new a.InternalError("No ModelService found for alias "+t)}for(e,...t){return new Proxy(this,{get:(r,a,s)=>"repo"===a?r.repo.for(e,...t):Reflect.get(r,a,s)})}async create(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.CREATE,!0)).for(this.create);return this.repo.create(e,...r)}async createAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAll);return this.repo.createAll(e,...r)}async delete(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.DELETE,!0)).for(this.delete);return this.repo.delete(e,...r)}async deleteAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.DELETE_ALL,!0)).for(this.deleteAll);return this.repo.deleteAll(e,...r)}async read(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.READ,!0)).for(this.read);return this.repo.read(e,...r)}async readAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.READ_ALL,!0)).for(this.readAll);return this.repo.readAll(e,...r)}async query(t,...r){const{ctxArgs:s}=(await this.logCtx(r,e.PersistenceKeys.QUERY,!0)).for(this.query),n=this.repo?.[t];if("function"!=typeof n)throw new a.InternalError(`Method "${t}" is not implemented`);return n.apply(this.repo,s)}async update(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.UPDATE,!0)).for(this.update);return this.repo.update(e,...r)}async updateAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.UPDATE_ALL,!0)).for(this.updateAll);return this.repo.updateAll(e,...r)}async listBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return this.repo.listBy(t,r,...s)}async paginateBy(t,r,a,...s){const{ctxArgs:n}=(await this.logCtx(s,e.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);return this.repo.paginateBy(t,r,a,...n)}async findOneBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);return this.repo.findOneBy(t,r,...s)}async findBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(t,r,...s)}async statement(t,...r){const{ctxArgs:a}=(await this.logCtx(r,e.PersistenceKeys.STATEMENT,!0)).for(this.statement);return this.repo.statement(t,...a)}static forModel(e,t){let a;t=ot(t||e);try{a=it.get(t)}catch(e){a=void 0}if(a instanceof it)return a;const s=this;let n=class extends s{constructor(){super(e)}};return n=r.__decorate([nt(t),r.__metadata("design:paramtypes",[])],n),new n}refresh(e,t,r,...a){return this.repo.refresh(e,t,r,...a)}observe(e,t){return this.repo.observe(e,t)}unObserve(e){return this.repo.unObserve(e)}updateObservers(e,t,r,...a){return this.repo.updateObservers(e,t,r,...a)}logCtx(e,t,r=!1){const a=this.repo.adapter.logCtx([this.repo.class,...e],t,r,this.repo._overrides||{});function s(e){return e.ctxArgs.shift(),e}return a instanceof Promise?a.then(s):s(a)}}r.__decorate([tt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],it.prototype,"create",null),r.__decorate([tt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],it.prototype,"createAll",null),r.__decorate([st(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],it.prototype,"delete",null),r.__decorate([st(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],it.prototype,"deleteAll",null),r.__decorate([rt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],it.prototype,"read",null),r.__decorate([rt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],it.prototype,"readAll",null),r.__decorate([rt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,Object]),r.__metadata("design:returntype",Promise)],it.prototype,"query",null),r.__decorate([at(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],it.prototype,"update",null),r.__decorate([at(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,Object]),r.__metadata("design:returntype",Promise)],it.prototype,"updateAll",null),t.Injectables.setRegistry(new re);const ct="##VERSION##",lt="##PACKAGE##";o.Metadata.registerLibrary(lt,ct),e.AbsContextual=v,e.Adapter=B,e.AuthorizationError=we,e.BaseModel=$e,e.BigIntSequence=Fe,e.ClientBasedService=Ze,e.Condition=R,e.ConnectionError=ve,e.Context=w,e.ContextualLoggedClass=O,e.DefaultAdapterFlags=h,e.DefaultCascade=F,e.DefaultRepositoryFilters=X,e.DefaultSequenceOptions=Le,e.Dispatch=Ke,e.ForbiddenError=Oe,e.InjectablesRegistry=re,e.MethodQueryBuilder=q,e.MigrationError=A,e.MigrationRuleError=x,e.ModelService=it,e.MultipleSelectOperationKeys=m,e.NonTransactionOperationKeys=y,e.NoneSequenceOptions=Re,e.NumericSequence=ke,e.ObserverError=Ge,e.ObserverHandler=_,e.OperatorsMap=j,e.PACKAGE_NAME=lt,e.PaginationOperationKeys=b,e.Paginator=ze,e.PagingError=$,e.PersistenceService=class extends Ze{constructor(){super()}async initialize(...t){const r=t.shift();if(!r||!Array.isArray(r)||r instanceof w||!r.every(e=>Array.isArray(e)))throw new a.InternalError("Missing/invalid configuration");const{log:s}=(await this.logCtx(t,e.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize),n=r.map(([e,t,...r])=>{try{s.silly(`Initializing ${e.name} with config: ${JSON.stringify(t)}`);const a=new e(t,...r);return s.debug(`Initialized ${a.toString()}...`),a}catch(t){throw new a.InternalError(`Failed to initialize ${e.name}: ${t}`)}});return{client:n,config:r}}},e.QueryError=K,e.Repository=ee,e.SelectOperationKeys=f,e.Sequence=Ye,e.Serial=T,e.Service=Xe,e.Statement=Je,e.TransactionOperationKeys=g,e.UUID=D,e.UnsupportedError=E,e.VERSION=ct,e.cacheModelForPopulate=fe,e.column=Ae,e.create=tt,e.createOrUpdate=ce,e.createdAt=Pe,e.createdBy=()=>o.Decoration.for(e.PersistenceKeys.CREATED_BY).define({decorator:()=>(t,r)=>o.apply(a.onCreate(Ce),o.propMetadata(e.PersistenceKeys.CREATED_BY,r),a.generated(e.PersistenceKeys.CREATED_BY))(t,r),args:[]}).apply(),e.createdByOnCreateUpdate=Ce,e.del=st,e.generateInjectableNameForRepository=te,e.getFilters=Z,e.getPkTypes=Ne,e.getPopulateKey=ye,e.index=xe,e.injectableServiceKey=C,e.isOperationBlocked=M,e.manyToMany=(t,r=F,a=!0,s,i)=>{const c=e.PersistenceKeys.MANY_TO_MANY;return o.Decoration.for(c).define({decorator:(e,t,r,a,s)=>{const i={class:e,cascade:t,populate:r};a&&(i.joinTable=a),s&&(i.name=s);const l=Ne(e),d=[o.prop(),Te(c,i),n.list([e,...l])];return o.apply(...d)},args:[t,r,a,s,i]}).apply()},e.manyToOne=(t,r=F,a=!0,s,i)=>{const c=e.PersistenceKeys.MANY_TO_ONE;return o.Decoration.for(c).define({decorator:(e,t,r,a,s)=>{const i={class:e,cascade:t,populate:r};a&&(i.joinTable=a),s&&(i.name=s);const l=Ne(e),d=[o.prop(),Te(c,i),n.type([e,...l])];return o.apply(...d)},args:[t,r,a,s,i]}).apply()},e.noValidateOn=De,e.noValidateOnCreate=()=>De(a.OperationKeys.CREATE),e.noValidateOnCreateUpdate=()=>De(a.OperationKeys.UPDATE,a.OperationKeys.CREATE),e.noValidateOnUpdate=()=>De(a.OperationKeys.UPDATE),e.normalizeImport=async e=>e.then(e=>e.default||e),e.oneToMany=(t,r=F,s=!0,i,c)=>{const l=e.PersistenceKeys.ONE_TO_MANY;return o.Decoration.for(l).define({decorator:(e,t,r,s,i)=>{const c={class:e,cascade:t,populate:r};s&&(c.joinTable=s),i&&(c.name=i);const d=Ne(e),p=[o.prop(),Te(l,c),n.list([e,...d]),a.onCreate(ue,c),a.onUpdate(he,c),a.onDelete(ge,c),a.afterAny(me,c)];return o.apply(...p)},args:[t,r,s,i,c]}).apply()},e.oneToManyOnCreate=ue,e.oneToManyOnDelete=ge,e.oneToManyOnUpdate=he,e.oneToOne=(t,r=F,s=!0,i,c)=>{const l=e.PersistenceKeys.ONE_TO_ONE;return o.Decoration.for(l).define({decorator:(e,t,r,s,i)=>{const c={class:e,cascade:t,populate:r};s&&(c.joinTable=s),i&&(c.name=i);const d=Ne(e),p=[o.prop(),Te(l,c),n.type([e,...d]),a.onCreate(le,c),a.onUpdate(de,c),a.onDelete(pe,c),a.afterAny(me,c)];return o.apply(...p)},args:[t,r,s,i,c]}).apply()},e.oneToOneOnCreate=le,e.oneToOneOnDelete=pe,e.oneToOneOnUpdate=de,e.onlyOnBulk=W,e.onlyOnCreate=G,e.onlyOnDelete=Q,e.onlyOnFilter=J,e.onlyOnSingle=V,e.onlyOnTransactional=H,e.onlyOnUpdate=z,e.pk=qe,e.pkDec=Ue,e.pkOnCreate=je,e.populate=me,e.prefixMethod=N,e.prepared=Y,e.promiseSequence=P,e.query=(t={})=>o.Decoration.for(e.PersistenceKeys.QUERY).define({decorator:t=>(r,a,s)=>{const n=q.getFieldsFromMethodName(a);return o.apply(o.methodMetadata(o.Metadata.key(e.PersistenceKeys.QUERY,a),{...t,fields:n}),Y(),(e=>(t,r,a)=>{a.value=new Proxy(a.value,{apply(t,r,a){const{select:s,where:n,groupBy:o,orderBy:i,limit:c,offset:l}=q.build(t.name,...a);let d=r.select(s);n&&(d=d.where(n));const{allowLimit:p,allowOffset:u,allowOrderBy:h,throws:g}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...e},y=[{key:"orderBy",value:(i||[])[0],allowed:h},{key:"limit",value:c,allowed:p},{key:"offset",value:l,allowed:u}];for(const e of y)if(void 0!==e.value){if(!e.allowed&&g)throw new K(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()}})})(t))(r,a,s)},args:[t]}).apply(),e.read=rt,e.relation=Te,e.repository=(r,s)=>(i,c)=>c?t.inject(o.Metadata.constr(r))(i,c):(o.Metadata.set(a.DBKeys.REPOSITORY,o.Metadata.key(s||B.currentFlavour,n.Model.tableName(r)),i),o.metadata(a.DBKeys.REPOSITORY,i.name)(r),s=s||o.Metadata.get(i.constructor,e.PersistenceKeys.ADAPTER),ee.register(r,i,s),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=_e,e.service=nt,e.table=Ee,e.unique=()=>{const t=e.PersistenceKeys.UNIQUE;return o.Decoration.for(t).define(n.async(),a.onCreateUpdate(Se),o.propMetadata(t,{})).apply()},e.uniqueOnCreateUpdate=Se,e.update=at,e.updatedAt=Me,e.updatedBy=()=>o.Decoration.for(e.PersistenceKeys.UPDATED_BY).define({decorator:()=>(t,r)=>o.apply(a.onUpdate(Ce),o.propMetadata(e.PersistenceKeys.UPDATED_BY,r),a.generated(e.PersistenceKeys.UPDATED_BY))(t,r),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/logging"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/decoration"),require("@decaf-ts/transactional-decorators")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/injectable-decorators","tslib","@decaf-ts/db-decorators","@decaf-ts/logging","@decaf-ts/decorator-validation","@decaf-ts/decoration","@decaf-ts/transactional-decorators"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).core={},e.decafTsInjectableDecorators,e.tslib,e.decafTsDbDecorators,e.decafTsLogging,e.decafTsDecoratorValidation,e.decafTsDecoration,e.decafTsTransactionalDecorators);
|
|
2
2
|
//# sourceMappingURL=core.cjs.map
|