@decaf-ts/for-nest 0.11.2 → 0.12.1
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 +274 -2
- package/dist/for-nest.cjs +1 -1
- package/dist/for-nest.cjs.map +1 -1
- package/dist/for-nest.js +1 -1
- package/dist/for-nest.js.map +1 -1
- package/lib/cjs/auth/AuthInterceptor.cjs +93 -0
- package/lib/cjs/auth/AuthInterceptor.cjs.map +1 -0
- package/lib/cjs/auth/DecafAuthHandler.cjs +37 -0
- package/lib/cjs/auth/DecafAuthHandler.cjs.map +1 -0
- package/lib/cjs/auth/DecafAuthModule.cjs +50 -0
- package/lib/cjs/auth/DecafAuthModule.cjs.map +1 -0
- package/lib/cjs/auth/constants.cjs +10 -0
- package/lib/cjs/auth/constants.cjs.map +1 -0
- package/lib/cjs/auth/decorators.cjs +28 -0
- package/lib/cjs/auth/decorators.cjs.map +1 -0
- package/lib/cjs/{ram → auth}/index.cjs +6 -2
- package/lib/cjs/auth/index.cjs.map +1 -0
- package/lib/cjs/bin/cli.cjs +1 -1
- package/lib/cjs/bin/cli.cjs.map +1 -1
- package/lib/cjs/cli-module.cjs +63 -6
- package/lib/cjs/cli-module.cjs.map +1 -1
- package/lib/cjs/constants.cjs +4 -5
- package/lib/cjs/constants.cjs.map +1 -1
- package/lib/cjs/controllers.cjs +15 -112
- package/lib/cjs/controllers.cjs.map +1 -1
- package/lib/cjs/core-module.cjs +7 -7
- package/lib/cjs/core-module.cjs.map +1 -1
- package/lib/cjs/decaf-model/DecafModelModule.cjs +27 -3
- package/lib/cjs/decaf-model/DecafModelModule.cjs.map +1 -1
- package/lib/cjs/decaf-model/FromModelController.cjs +618 -792
- package/lib/cjs/decaf-model/FromModelController.cjs.map +1 -1
- package/lib/cjs/decaf-model/decorators/ApiOperationFromModel.cjs +52 -15
- package/lib/cjs/decaf-model/decorators/ApiOperationFromModel.cjs.map +1 -1
- package/lib/cjs/decaf-model/decorators/ApiParamsFromModel.cjs +1 -1
- package/lib/cjs/decaf-model/decorators/ApiParamsFromModel.cjs.map +1 -1
- package/lib/cjs/decaf-model/decorators/DecafBody.cjs +1 -1
- package/lib/cjs/decaf-model/decorators/DecafBody.cjs.map +1 -1
- package/lib/cjs/decaf-model/decorators/DecafParams.cjs +1 -1
- package/lib/cjs/decaf-model/decorators/DecafParams.cjs.map +1 -1
- package/lib/cjs/decaf-model/decorators/controller-config.cjs +29 -0
- package/lib/cjs/decaf-model/decorators/controller-config.cjs.map +1 -0
- package/lib/cjs/decaf-model/decorators/decorators.cjs +4 -44
- package/lib/cjs/decaf-model/decorators/decorators.cjs.map +1 -1
- package/lib/cjs/decaf-model/decorators/expose.cjs +13 -0
- package/lib/cjs/decaf-model/decorators/expose.cjs.map +1 -0
- package/lib/cjs/decaf-model/decorators/index.cjs +2 -1
- package/lib/cjs/decaf-model/decorators/index.cjs.map +1 -1
- package/lib/cjs/decaf-model/decorators/types.cjs +1 -1
- package/lib/cjs/decaf-model/decorators/types.cjs.map +1 -1
- package/lib/cjs/decaf-model/decorators/utils.cjs +3 -2
- package/lib/cjs/decaf-model/decorators/utils.cjs.map +1 -1
- package/lib/cjs/decaf-model/index.cjs +27 -18
- package/lib/cjs/decaf-model/index.cjs.map +1 -1
- package/lib/cjs/decaf-model/types.cjs +1 -1
- package/lib/cjs/decaf-model/types.cjs.map +1 -1
- package/lib/cjs/decaf-model/utils.cjs +10 -4
- package/lib/cjs/decaf-model/utils.cjs.map +1 -1
- package/lib/cjs/decoration.cjs +1 -1
- package/lib/cjs/decoration.cjs.map +1 -1
- package/lib/cjs/decorators.cjs +93 -0
- package/lib/cjs/decorators.cjs.map +1 -0
- package/lib/cjs/events-module/DecafStreamModule.cjs +1 -1
- package/lib/cjs/events-module/DecafStreamModule.cjs.map +1 -1
- package/lib/cjs/events-module/EventsController.cjs +1 -1
- package/lib/cjs/events-module/EventsController.cjs.map +1 -1
- package/lib/cjs/events-module/constant.cjs +1 -1
- package/lib/cjs/events-module/constant.cjs.map +1 -1
- package/lib/cjs/events-module/index.cjs +1 -1
- package/lib/cjs/events-module/index.cjs.map +1 -1
- package/lib/cjs/events-module/utils.cjs +1 -1
- package/lib/cjs/events-module/utils.cjs.map +1 -1
- package/lib/cjs/factory/NestBootstraper.cjs +11 -4
- package/lib/cjs/factory/NestBootstraper.cjs.map +1 -1
- package/lib/cjs/factory/errors/cors.cjs +1 -1
- package/lib/cjs/factory/errors/cors.cjs.map +1 -1
- package/lib/cjs/factory/errors/index.cjs +1 -1
- package/lib/cjs/factory/errors/index.cjs.map +1 -1
- package/lib/cjs/factory/errors/throttling.cjs +1 -1
- package/lib/cjs/factory/errors/throttling.cjs.map +1 -1
- package/lib/cjs/factory/exceptions/DecafErrorFilter.cjs +105 -6
- package/lib/cjs/factory/exceptions/DecafErrorFilter.cjs.map +1 -1
- package/lib/cjs/factory/exceptions/decorators.cjs +4 -1
- package/lib/cjs/factory/exceptions/decorators.cjs.map +1 -1
- package/lib/cjs/factory/exceptions/index.cjs +1 -1
- package/lib/cjs/factory/exceptions/index.cjs.map +1 -1
- package/lib/cjs/factory/index.cjs +1 -1
- package/lib/cjs/factory/index.cjs.map +1 -1
- package/lib/cjs/factory/openapi/DtoBuilder.cjs +36 -5
- package/lib/cjs/factory/openapi/DtoBuilder.cjs.map +1 -1
- package/lib/cjs/factory/openapi/SwaggerBuilder.cjs +1 -1
- package/lib/cjs/factory/openapi/SwaggerBuilder.cjs.map +1 -1
- package/lib/cjs/factory/openapi/SwaggerCustomUI.cjs +1 -1
- package/lib/cjs/factory/openapi/SwaggerCustomUI.cjs.map +1 -1
- package/lib/cjs/factory/openapi/constants.cjs +1 -1
- package/lib/cjs/factory/openapi/constants.cjs.map +1 -1
- package/lib/cjs/factory/openapi/index.cjs +1 -1
- package/lib/cjs/factory/openapi/index.cjs.map +1 -1
- package/lib/cjs/index.cjs +6 -5
- package/lib/cjs/index.cjs.map +1 -1
- package/lib/cjs/interceptors/DecafRequestHandlerInterceptor.cjs +24 -20
- package/lib/cjs/interceptors/DecafRequestHandlerInterceptor.cjs.map +1 -1
- package/lib/cjs/interceptors/index.cjs +2 -3
- package/lib/cjs/interceptors/index.cjs.map +1 -1
- package/lib/cjs/module.cjs +4 -1
- package/lib/cjs/module.cjs.map +1 -1
- package/lib/cjs/overrides/Adapter.cjs +1 -1
- package/lib/cjs/overrides/Adapter.cjs.map +1 -1
- package/lib/cjs/overrides/ModelBuilderExtensions.cjs +1 -1
- package/lib/cjs/overrides/ModelBuilderExtensions.cjs.map +1 -1
- package/lib/cjs/overrides/constants.cjs +1 -1
- package/lib/cjs/overrides/constants.cjs.map +1 -1
- package/lib/cjs/overrides/decoration.cjs +1 -1
- package/lib/cjs/overrides/decoration.cjs.map +1 -1
- package/lib/cjs/overrides/helpers.cjs +1 -1
- package/lib/cjs/overrides/helpers.cjs.map +1 -1
- package/lib/cjs/overrides/index.cjs +2 -1
- package/lib/cjs/overrides/index.cjs.map +1 -1
- package/lib/cjs/overrides/logging.cjs +5 -0
- package/lib/cjs/overrides/logging.cjs.map +1 -0
- package/lib/cjs/overrides/overrides.cjs +1 -1
- package/lib/cjs/overrides/overrides.cjs.map +1 -1
- package/lib/cjs/request/DecafAuthHandler.cjs +4 -38
- package/lib/cjs/request/DecafAuthHandler.cjs.map +1 -1
- package/lib/cjs/request/DecafHandlerExecutor.cjs +1 -1
- package/lib/cjs/request/DecafHandlerExecutor.cjs.map +1 -1
- package/lib/cjs/request/DecafRequestContext.cjs +12 -19
- package/lib/cjs/request/DecafRequestContext.cjs.map +1 -1
- package/lib/cjs/request/DecafResponseInterceptor.cjs +5 -3
- package/lib/cjs/request/DecafResponseInterceptor.cjs.map +1 -1
- package/lib/cjs/request/index.cjs +1 -1
- package/lib/cjs/request/index.cjs.map +1 -1
- package/lib/cjs/swagger-types.cjs +1 -1
- package/lib/cjs/swagger-types.cjs.map +1 -1
- package/lib/cjs/types.cjs +1 -1
- package/lib/cjs/types.cjs.map +1 -1
- package/lib/cjs/utils.cjs +1 -1
- package/lib/cjs/utils.cjs.map +1 -1
- package/lib/cjs/webhooks/DecafWebhookModule.cjs +4 -3
- package/lib/cjs/webhooks/DecafWebhookModule.cjs.map +1 -1
- package/lib/cjs/webhooks/controllers.cjs +49 -54
- package/lib/cjs/webhooks/controllers.cjs.map +1 -1
- package/lib/cjs/webhooks/index.cjs +1 -1
- package/lib/cjs/webhooks/index.cjs.map +1 -1
- package/lib/cjs/webhooks/types.cjs +1 -1
- package/lib/cjs/webhooks/types.cjs.map +1 -1
- package/lib/esm/auth/AuthInterceptor.js +84 -0
- package/lib/esm/auth/AuthInterceptor.js.map +1 -0
- package/lib/esm/auth/DecafAuthHandler.js +31 -0
- package/lib/esm/auth/DecafAuthHandler.js.map +1 -0
- package/lib/esm/auth/DecafAuthModule.js +42 -0
- package/lib/esm/auth/DecafAuthModule.js.map +1 -0
- package/lib/esm/auth/constants.js +6 -0
- package/lib/esm/auth/constants.js.map +1 -0
- package/lib/esm/auth/decorators.js +22 -0
- package/lib/esm/auth/decorators.js.map +1 -0
- package/lib/esm/auth/index.js +6 -0
- package/lib/esm/auth/index.js.map +1 -0
- package/lib/esm/cli-module.js +62 -5
- package/lib/esm/cli-module.js.map +1 -1
- package/lib/esm/constants.js +2 -3
- package/lib/esm/constants.js.map +1 -1
- package/lib/esm/controllers.js +15 -112
- package/lib/esm/controllers.js.map +1 -1
- package/lib/esm/core-module.js +6 -6
- package/lib/esm/core-module.js.map +1 -1
- package/lib/esm/decaf-model/DecafModelModule.js +26 -2
- package/lib/esm/decaf-model/DecafModelModule.js.map +1 -1
- package/lib/esm/decaf-model/FromModelController.js +622 -796
- package/lib/esm/decaf-model/FromModelController.js.map +1 -1
- package/lib/esm/decaf-model/decorators/ApiOperationFromModel.js +52 -14
- package/lib/esm/decaf-model/decorators/ApiOperationFromModel.js.map +1 -1
- package/lib/esm/decaf-model/decorators/controller-config.js +25 -0
- package/lib/esm/decaf-model/decorators/controller-config.js.map +1 -0
- package/lib/esm/decaf-model/decorators/decorators.js +1 -42
- package/lib/esm/decaf-model/decorators/decorators.js.map +1 -1
- package/lib/esm/decaf-model/decorators/expose.js +9 -0
- package/lib/esm/decaf-model/decorators/expose.js.map +1 -0
- package/lib/esm/decaf-model/decorators/index.js +1 -0
- package/lib/esm/decaf-model/decorators/index.js.map +1 -1
- package/lib/esm/decaf-model/decorators/utils.js +2 -1
- package/lib/esm/decaf-model/decorators/utils.js.map +1 -1
- package/lib/esm/decaf-model/index.js +10 -3
- package/lib/esm/decaf-model/index.js.map +1 -1
- package/lib/esm/decaf-model/utils.js +9 -3
- package/lib/esm/decaf-model/utils.js.map +1 -1
- package/lib/esm/decorators.js +87 -0
- package/lib/esm/decorators.js.map +1 -0
- package/lib/esm/events-module/utils.js.map +1 -1
- package/lib/esm/factory/NestBootstraper.js +10 -3
- package/lib/esm/factory/NestBootstraper.js.map +1 -1
- package/lib/esm/factory/exceptions/DecafErrorFilter.js +105 -7
- package/lib/esm/factory/exceptions/DecafErrorFilter.js.map +1 -1
- package/lib/esm/factory/exceptions/decorators.js +3 -0
- package/lib/esm/factory/exceptions/decorators.js.map +1 -1
- package/lib/esm/factory/openapi/DtoBuilder.js +35 -4
- package/lib/esm/factory/openapi/DtoBuilder.js.map +1 -1
- package/lib/esm/index.js +5 -4
- package/lib/esm/index.js.map +1 -1
- package/lib/esm/interceptors/DecafRequestHandlerInterceptor.js +24 -20
- package/lib/esm/interceptors/DecafRequestHandlerInterceptor.js.map +1 -1
- package/lib/esm/interceptors/index.js +1 -2
- package/lib/esm/interceptors/index.js.map +1 -1
- package/lib/esm/module.js +3 -0
- package/lib/esm/module.js.map +1 -1
- package/lib/esm/overrides/index.js +1 -0
- package/lib/esm/overrides/index.js.map +1 -1
- package/lib/esm/overrides/logging.js +2 -0
- package/lib/esm/overrides/logging.js.map +1 -0
- package/lib/esm/request/DecafAuthHandler.js +1 -35
- package/lib/esm/request/DecafAuthHandler.js.map +1 -1
- package/lib/esm/request/DecafRequestContext.js +11 -18
- package/lib/esm/request/DecafRequestContext.js.map +1 -1
- package/lib/esm/request/DecafResponseInterceptor.js +4 -2
- package/lib/esm/request/DecafResponseInterceptor.js.map +1 -1
- package/lib/esm/webhooks/DecafWebhookModule.js +2 -1
- package/lib/esm/webhooks/DecafWebhookModule.js.map +1 -1
- package/lib/esm/webhooks/controllers.js +48 -53
- package/lib/esm/webhooks/controllers.js.map +1 -1
- package/lib/types/{interceptors → auth}/AuthInterceptor.d.cts +4 -1
- package/lib/types/{interceptors → auth}/AuthInterceptor.d.mts +4 -1
- package/lib/types/auth/DecafAuthHandler.d.cts +22 -0
- package/lib/types/auth/DecafAuthHandler.d.mts +22 -0
- package/lib/types/auth/DecafAuthModule.d.cts +9 -0
- package/lib/types/auth/DecafAuthModule.d.mts +9 -0
- package/lib/types/auth/constants.d.cts +5 -0
- package/lib/types/auth/constants.d.mts +5 -0
- package/lib/types/auth/decorators.d.cts +4 -0
- package/lib/types/auth/decorators.d.mts +4 -0
- package/lib/types/auth/index.d.cts +6 -0
- package/lib/types/auth/index.d.mts +6 -0
- package/lib/types/cli-module.d.cts +1 -4
- package/lib/types/cli-module.d.mts +1 -4
- package/lib/types/constants.d.cts +2 -3
- package/lib/types/constants.d.mts +2 -3
- package/lib/types/controllers.d.cts +7 -12
- package/lib/types/controllers.d.mts +7 -12
- package/lib/types/decaf-model/DecafModelModule.d.cts +1 -0
- package/lib/types/decaf-model/DecafModelModule.d.mts +1 -0
- package/lib/types/decaf-model/FromModelController.d.cts +32 -52
- package/lib/types/decaf-model/FromModelController.d.mts +32 -52
- package/lib/types/decaf-model/decorators/ApiOperationFromModel.d.cts +0 -2
- package/lib/types/decaf-model/decorators/ApiOperationFromModel.d.mts +0 -2
- package/lib/types/decaf-model/decorators/controller-config.d.cts +18 -0
- package/lib/types/decaf-model/decorators/controller-config.d.mts +18 -0
- package/lib/types/decaf-model/decorators/decorators.d.cts +1 -29
- package/lib/types/decaf-model/decorators/decorators.d.mts +1 -29
- package/lib/types/decaf-model/decorators/expose.d.cts +1 -0
- package/lib/types/decaf-model/decorators/expose.d.mts +1 -0
- package/lib/types/decaf-model/decorators/index.d.cts +1 -0
- package/lib/types/decaf-model/decorators/index.d.mts +1 -0
- package/lib/types/decaf-model/decorators/types.d.cts +8 -21
- package/lib/types/decaf-model/decorators/types.d.mts +8 -21
- package/lib/types/decaf-model/index.d.cts +11 -3
- package/lib/types/decaf-model/index.d.mts +11 -3
- package/lib/types/decaf-model/utils.d.cts +2 -1
- package/lib/types/decaf-model/utils.d.mts +2 -1
- package/lib/types/decorators.d.cts +35 -0
- package/lib/types/decorators.d.mts +35 -0
- package/lib/types/factory/NestBootstraper.d.cts +5 -0
- package/lib/types/factory/NestBootstraper.d.mts +5 -0
- package/lib/types/factory/exceptions/DecafErrorFilter.d.cts +33 -1
- package/lib/types/factory/exceptions/DecafErrorFilter.d.mts +33 -1
- package/lib/types/factory/openapi/DtoBuilder.d.cts +7 -3
- package/lib/types/factory/openapi/DtoBuilder.d.mts +7 -3
- package/lib/types/index.d.cts +5 -4
- package/lib/types/index.d.mts +5 -4
- package/lib/types/interceptors/DecafRequestHandlerInterceptor.d.cts +1 -2
- package/lib/types/interceptors/DecafRequestHandlerInterceptor.d.mts +1 -2
- package/lib/types/interceptors/index.d.cts +1 -2
- package/lib/types/interceptors/index.d.mts +1 -2
- package/lib/types/overrides/Adapter.d.cts +1 -1
- package/lib/types/overrides/Adapter.d.mts +1 -1
- package/lib/types/overrides/index.d.cts +1 -0
- package/lib/types/overrides/index.d.mts +1 -0
- package/lib/types/overrides/logging.d.cts +1 -0
- package/lib/types/overrides/logging.d.mts +1 -0
- package/lib/types/request/DecafAuthHandler.d.cts +1 -10
- package/lib/types/request/DecafAuthHandler.d.mts +1 -10
- package/lib/types/request/DecafRequestContext.d.cts +5 -5
- package/lib/types/request/DecafRequestContext.d.mts +5 -5
- package/lib/types/types.d.cts +12 -24
- package/lib/types/types.d.mts +12 -24
- package/package.json +12 -13
- package/lib/cjs/interceptors/AuthInterceptor.cjs +0 -52
- package/lib/cjs/interceptors/AuthInterceptor.cjs.map +0 -1
- package/lib/cjs/interceptors/context.cjs +0 -18
- package/lib/cjs/interceptors/context.cjs.map +0 -1
- package/lib/cjs/migrations/index.cjs +0 -35
- package/lib/cjs/migrations/index.cjs.map +0 -1
- package/lib/cjs/migrations/migration-module.cjs +0 -60
- package/lib/cjs/migrations/migration-module.cjs.map +0 -1
- package/lib/cjs/migrations/migration-options.cjs +0 -4
- package/lib/cjs/migrations/migration-options.cjs.map +0 -1
- package/lib/cjs/ram/RamRequestTransformer.cjs +0 -26
- package/lib/cjs/ram/RamRequestTransformer.cjs.map +0 -1
- package/lib/cjs/ram/index.cjs.map +0 -1
- package/lib/esm/interceptors/AuthInterceptor.js +0 -43
- package/lib/esm/interceptors/AuthInterceptor.js.map +0 -1
- package/lib/esm/interceptors/context.js +0 -12
- package/lib/esm/interceptors/context.js.map +0 -1
- package/lib/esm/migrations/index.js +0 -18
- package/lib/esm/migrations/index.js.map +0 -1
- package/lib/esm/migrations/migration-module.js +0 -52
- package/lib/esm/migrations/migration-module.js.map +0 -1
- package/lib/esm/migrations/migration-options.js +0 -7
- package/lib/esm/migrations/migration-options.js.map +0 -1
- package/lib/esm/ram/RamRequestTransformer.js +0 -21
- package/lib/esm/ram/RamRequestTransformer.js.map +0 -1
- package/lib/esm/ram/index.js +0 -2
- package/lib/esm/ram/index.js.map +0 -1
- package/lib/types/interceptors/context.d.cts +0 -6
- package/lib/types/interceptors/context.d.mts +0 -6
- package/lib/types/migrations/index.d.cts +0 -17
- package/lib/types/migrations/index.d.mts +0 -17
- package/lib/types/migrations/migration-module.d.cts +0 -15
- package/lib/types/migrations/migration-module.d.mts +0 -15
- package/lib/types/migrations/migration-options.d.cts +0 -11
- package/lib/types/migrations/migration-options.d.mts +0 -11
- package/lib/types/ram/RamRequestTransformer.d.cts +0 -5
- package/lib/types/ram/RamRequestTransformer.d.mts +0 -5
- package/lib/types/ram/index.d.cts +0 -1
- package/lib/types/ram/index.d.mts +0 -1
package/README.md
CHANGED
|
@@ -28,7 +28,7 @@ This repository is meant to provide an enterprise template for any standard Type
|
|
|
28
28
|
|
|
29
29
|
Documentation available [here](https://decaf-ts.github.io/for-nest/)
|
|
30
30
|
|
|
31
|
-
Minimal size:
|
|
31
|
+
Minimal size: 14 KB kb gzipped
|
|
32
32
|
|
|
33
33
|
|
|
34
34
|
### Description
|
|
@@ -53,8 +53,280 @@ Now you can create new repositories from this template and enjoy having everythi
|
|
|
53
53
|
- [WebStorm](./workdocs/tutorials/For%20Developers.md#webstorm)
|
|
54
54
|
- [Considerations](./workdocs/tutorials/For%20Developers.md#considerations)
|
|
55
55
|
|
|
56
|
+
---
|
|
56
57
|
|
|
57
|
-
|
|
58
|
+
## Module Configuration
|
|
59
|
+
|
|
60
|
+
### `DecafModule.forRootAsync(options)`
|
|
61
|
+
|
|
62
|
+
The main entry point. Boots persistence, registers controllers, and wires the request pipeline.
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
import { DecafModule } from "@decaf-ts/for-nest";
|
|
66
|
+
|
|
67
|
+
@Module({
|
|
68
|
+
imports: [
|
|
69
|
+
DecafModule.forRootAsync({
|
|
70
|
+
conf: [
|
|
71
|
+
[FabricClientAdapter, fabricConfig, new FabricTransformer()],
|
|
72
|
+
[TypeORMAdapter, pgConfig, new TypeORMTransformer()],
|
|
73
|
+
[NanoAdapter, couchConfig, new NanoTransformer()],
|
|
74
|
+
],
|
|
75
|
+
autoControllers: true,
|
|
76
|
+
aggregations: false,
|
|
77
|
+
handlers: [ImpersonateHandler],
|
|
78
|
+
controllerExposure: { Product: true, Batch: ["hlf-fabric"] },
|
|
79
|
+
controllerConfig: { Product: { auth: { public: true } } },
|
|
80
|
+
observerOptions: { enableObserverEvents: true },
|
|
81
|
+
initialization: async () => { await Service.boot(); },
|
|
82
|
+
}),
|
|
83
|
+
],
|
|
84
|
+
})
|
|
85
|
+
export class AppModule {}
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
#### `DecafModuleOptions`
|
|
89
|
+
|
|
90
|
+
| Option | Type | Required | Default | Description |
|
|
91
|
+
|---|---|---|---|---|
|
|
92
|
+
| `conf` | `[Constructor<Adapter>, ConfigOf<Adapter>, ...any[], Transformer?][]` | Yes | — | Array of adapter tuples: `[AdapterClass, adapterConfig, ...args, transformer?]`. The trailing transformer (instance or constructor) maps request context fields to adapter-specific keys. If omitted, the adapter's registered `@requestToContextTransformer` is used. |
|
|
93
|
+
| `autoControllers` | `boolean` | Yes | — | When `true`, auto-generates CRUD controllers for all models registered to each adapter flavour. |
|
|
94
|
+
| `autoServices` | `boolean` | No | `false` | When `true`, generates a `ModelService` provider for every tracked model (injectable as `${ModelName}Service`). |
|
|
95
|
+
| `aggregations` | `boolean` | No | `true` | When `false`, disables grouping/aggregation routes globally by setting `allowGroupingQueries: false` as a `globalDefaults` override. |
|
|
96
|
+
| `controllerExposure` | `Record<string, boolean \| string[]>` | No | — | Per-model exposure overrides. `true` exposes on all flavours; an array of flavour strings restricts exposure; `false` hides the model. When omitted, the `@expose` decorator metadata is used. |
|
|
97
|
+
| `controllerConfig` | `Record<string, ModelControllerFactoryConfig>` | No | — | Per-model controller factory config. Merged on top of decorator-level `@controllerConfig` and `globalDefaults`. See [ModelControllerFactoryConfig](#modelcontrollerfactoryconfig) below. |
|
|
98
|
+
| `observerOptions` | `ObserverEventsOptions` | No | — | SSE observer event configuration. See [ObserverEventsOptions](#observereventsoptions) below. |
|
|
99
|
+
| `handlers` | `Type<DecafRequestHandler>[]` | No | `[]` | Request handlers executed by `DecafHandlerExecutor` before the controller method. Each handler receives `(context, req, res)`. |
|
|
100
|
+
| `initialization` | `() => Promise<void>` | No | — | Called once after persistence boots but before the Nest module finishes initializing. Use for `Service.boot()` or similar setup. |
|
|
101
|
+
| `alias` | `string` | No | — | Optional adapter alias for multi-instance scenarios. |
|
|
102
|
+
|
|
103
|
+
#### `ModelControllerFactoryConfig`
|
|
104
|
+
|
|
105
|
+
Per-controller knobs merged in this priority order (later wins):
|
|
106
|
+
|
|
107
|
+
1. `globalDefaults` (from `aggregations: false`)
|
|
108
|
+
2. `@controllerConfig()` decorator on the model class
|
|
109
|
+
3. `controllerConfig[modelName]` in `DecafModuleOptions`
|
|
110
|
+
|
|
111
|
+
| Option | Type | Default | Description |
|
|
112
|
+
|---|---|---|---|
|
|
113
|
+
| `allowStatementlessQuery` | `boolean` | `false` | Allows `@query()` methods without a matching `@statement()` to be exposed as GET routes. |
|
|
114
|
+
| `allowGroupingQueries` | `boolean \| GroupingQueryFlags` | `true` | Enables or fine-tunes aggregation endpoints (`count`, `avg`, `max`, `min`, `sum`, `distinct`, `group`). Set to `false` to hide all aggregation routes. |
|
|
115
|
+
| `allowBulkStatement` | `boolean \| BulkStatementFlags` | `false` | Enables or fine-tunes bulk CRUD routes (`bulk` path: GET=readAll, PUT=updateAll, DELETE=deleteAll). |
|
|
116
|
+
| `auth` | `AuthConfig` | — | Per-controller auth configuration. See [AuthConfig](#authconfig) below. |
|
|
117
|
+
|
|
118
|
+
**`GroupingQueryFlags`**: `{ count?: boolean; avg?: boolean; max?: boolean; min?: boolean; sum?: boolean; distinct?: boolean; group?: boolean }`
|
|
119
|
+
|
|
120
|
+
**`BulkStatementFlags`**: `{ create?: boolean; read?: boolean; update?: boolean; delete?: boolean }`
|
|
121
|
+
|
|
122
|
+
#### `AuthConfig`
|
|
123
|
+
|
|
124
|
+
Applied at the **class level** to every auto-generated controller for that model:
|
|
125
|
+
|
|
126
|
+
| Option | Type | Default | Description |
|
|
127
|
+
|---|---|---|---|
|
|
128
|
+
| `public` | `boolean` | `false` | When `true`, applies `@Public()` — the `AuthInterceptor` skips authorization entirely. |
|
|
129
|
+
| `roles` | `string[]` | — | When provided, applies `@RequireRoles(...roles)` — the auth handler validates the user has all listed roles. |
|
|
130
|
+
| `skipModelRoles` | `boolean` | `false` | When `true`, sets `SKIP_MODEL_ROLES_KEY` metadata — the `AuthInterceptor` passes `undefined` as the model to `authHandler.authorize()`, so model-level `@roles()` checks are skipped. Route-level roles (if set) still apply. |
|
|
131
|
+
|
|
132
|
+
If `auth` is omitted, `@Auth(Model)` is applied by default (requires authentication + model-level role checks).
|
|
133
|
+
|
|
134
|
+
#### `ObserverEventsOptions`
|
|
135
|
+
|
|
136
|
+
| Option | Type | Default | Description |
|
|
137
|
+
|---|---|---|---|
|
|
138
|
+
| `enableObserverEvents` | `boolean` | `false` | Enables SSE stream events globally. |
|
|
139
|
+
| `observerFlavours` | `any[]` | all registered | List of adapter flavours that will emit stream events. |
|
|
140
|
+
| `observerApiPath` | `string` | `"/events"` | SSE endpoint path. |
|
|
141
|
+
|
|
142
|
+
---
|
|
143
|
+
|
|
144
|
+
## Auth Configuration
|
|
145
|
+
|
|
146
|
+
### `DecafAuthModule.forRoot(options)`
|
|
147
|
+
|
|
148
|
+
Optional standalone module for registering auth wiring independently of `DecafCoreModule`.
|
|
149
|
+
|
|
150
|
+
```ts
|
|
151
|
+
import { DecafAuthModule } from "@decaf-ts/for-nest";
|
|
152
|
+
|
|
153
|
+
@Module({
|
|
154
|
+
imports: [
|
|
155
|
+
DecafAuthModule.forRoot({
|
|
156
|
+
global: true,
|
|
157
|
+
handler: MyAuthHandler,
|
|
158
|
+
}),
|
|
159
|
+
],
|
|
160
|
+
})
|
|
161
|
+
export class AppModule {}
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
> **Note:** `DecafCoreModule` (booted via `DecafModule.forRootAsync`) already registers `DecafRequestHandlerInterceptor` as a global `APP_INTERCEPTOR`. `DecafAuthModule` does **not** duplicate this registration.
|
|
165
|
+
|
|
166
|
+
#### `DecafAuthModuleOptions`
|
|
167
|
+
|
|
168
|
+
| Option | Type | Default | Description |
|
|
169
|
+
|---|---|---|---|
|
|
170
|
+
| `global` | `boolean` | `false` | When `true`, registers `AuthInterceptor` as a global `APP_INTERCEPTOR` (via `useExisting`) and marks the module as `@Global()`. When `false`, `AuthInterceptor` is provided but only activated on routes decorated with `@Auth()` or `@RequireRoles()`. |
|
|
171
|
+
| `handler` | `Type<AuthHandler>` | — | Concrete auth handler class. Registered both as itself and under the `AUTH_HANDLER` token. |
|
|
172
|
+
|
|
173
|
+
### Manual Auth Wiring (without `DecafAuthModule`)
|
|
174
|
+
|
|
175
|
+
For full control, wire auth directly in your module:
|
|
176
|
+
|
|
177
|
+
```ts
|
|
178
|
+
import { AUTH_HANDLER, AuthInterceptor } from "@decaf-ts/for-nest";
|
|
179
|
+
import { APP_INTERCEPTOR } from "@nestjs/core";
|
|
180
|
+
|
|
181
|
+
@Global()
|
|
182
|
+
@Module({
|
|
183
|
+
providers: [
|
|
184
|
+
AuthInterceptor,
|
|
185
|
+
AuthService,
|
|
186
|
+
FabricKeycloakAuthHandler,
|
|
187
|
+
{ provide: AUTH_HANDLER, useClass: FabricKeycloakAuthHandler },
|
|
188
|
+
{ provide: APP_INTERCEPTOR, useExisting: AuthInterceptor },
|
|
189
|
+
],
|
|
190
|
+
exports: [AUTH_HANDLER, AuthInterceptor, AuthService],
|
|
191
|
+
})
|
|
192
|
+
export class AuthModule {}
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
---
|
|
196
|
+
|
|
197
|
+
## Auth Decorators
|
|
198
|
+
|
|
199
|
+
### `@Auth(model?)`
|
|
200
|
+
|
|
201
|
+
Applies `ApiBearerAuth()`, `UseInterceptors(AuthInterceptor)`, and (when a model is given) sets `AUTH_META_KEY` metadata so the handler knows which model is being accessed.
|
|
202
|
+
|
|
203
|
+
```ts
|
|
204
|
+
@Auth(Product)
|
|
205
|
+
@Controller("product")
|
|
206
|
+
export class ProductController {}
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
### `@Public()`
|
|
210
|
+
|
|
211
|
+
Marks a route or controller as public — `AuthInterceptor` skips authorization.
|
|
212
|
+
|
|
213
|
+
```ts
|
|
214
|
+
@Public()
|
|
215
|
+
@Get("health")
|
|
216
|
+
health() { return { status: "ok" }; }
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
### `@RequireRoles(...roles)`
|
|
220
|
+
|
|
221
|
+
Requires the user to have all listed roles. Applies `ApiSecurity("bearer")`, `SetMetadata(REQUIRED_ROLES_KEY, roles)`, and `UseInterceptors(AuthInterceptor)`.
|
|
222
|
+
|
|
223
|
+
```ts
|
|
224
|
+
@RequireRoles("admin", "writer")
|
|
225
|
+
@Put("product/:id")
|
|
226
|
+
update() {}
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
### `@SkipFabricIdentity()` *(application-specific)*
|
|
230
|
+
|
|
231
|
+
Application-level decorator (e.g. in ew-backend) that sets metadata to skip Fabric identity re-enrollment for specific routes. Not part of `for-nest`.
|
|
232
|
+
|
|
233
|
+
---
|
|
234
|
+
|
|
235
|
+
## Auth Handler
|
|
236
|
+
|
|
237
|
+
### `AuthHandler<EC, C, D>`
|
|
238
|
+
|
|
239
|
+
Abstract base class from `@decaf-ts/for-http/server`. Concrete handlers extend it and override:
|
|
240
|
+
|
|
241
|
+
| Method | Required | Description |
|
|
242
|
+
|---|---|---|
|
|
243
|
+
| `extractFromAuth(ctx: EC): D \| Promise<D>` | Yes | Pulls auth data (user, roles, organization) from the platform execution context. MUST throw `AuthorizationError` when unauthenticated. |
|
|
244
|
+
| `bindToContext(ctx: C, data: D)` | Yes* | Binds auth data to the request context. Default implementation calls `ctx.accumulate(data)`. Override to add adapter-specific keys (e.g. `UUID`, `organization`). |
|
|
245
|
+
| `validate(data, routeRoles, model, ...args)` | No | Default validates route roles then model-level roles (from `@roles()`). Override for custom logic. |
|
|
246
|
+
|
|
247
|
+
\* The default `bindToContext` exists but every concrete handler typically overrides it.
|
|
248
|
+
|
|
249
|
+
```ts
|
|
250
|
+
import { AuthHandler } from "@decaf-ts/for-nest";
|
|
251
|
+
import { AuthorizationError } from "@decaf-ts/core";
|
|
252
|
+
|
|
253
|
+
class CustomAuthHandler extends AuthHandler {
|
|
254
|
+
protected extractFromAuth(ctx: ExecutionContext) {
|
|
255
|
+
const req = ctx.switchToHttp().getRequest();
|
|
256
|
+
const token = req.headers.authorization?.split(" ")[1];
|
|
257
|
+
if (!token) throw new AuthorizationError("Unauthenticated");
|
|
258
|
+
return { user: "alice", roles: ["admin"] };
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
protected bindToContext(ctx: DecafRequestContext, data: AuthData) {
|
|
262
|
+
ctx.accumulate({ UUID: data.user, user: data.user });
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
### `AuthData` / `UserData`
|
|
268
|
+
|
|
269
|
+
| Field | Type | Description |
|
|
270
|
+
|---|---|---|
|
|
271
|
+
| `user` | `string` | Authenticated user identifier. |
|
|
272
|
+
| `roles` | `string[]` | Roles granted to the user. |
|
|
273
|
+
| `organization` | `string` | Organization / tenant / MSP. |
|
|
274
|
+
|
|
275
|
+
---
|
|
276
|
+
|
|
277
|
+
## Auth Interceptor Flow
|
|
278
|
+
|
|
279
|
+
```
|
|
280
|
+
Request → AuthInterceptor → DecafRequestHandlerInterceptor → Controller
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
1. **`AuthInterceptor`** (request-scoped):
|
|
284
|
+
- Reads `IS_PUBLIC_KEY` — if `true`, skips auth.
|
|
285
|
+
- Reads `AUTH_META_KEY` (model name) and `REQUIRED_ROLES_KEY` (route roles).
|
|
286
|
+
- Reads `SKIP_MODEL_ROLES_KEY` — if `true`, passes `undefined` as model (skips model-level role checks).
|
|
287
|
+
- Calls `authHandler.authorize(ctx, effectiveModel, requiredRoles, requestContext)`.
|
|
288
|
+
- Runs `applyTransformers()` — iterates `Adapter.flavoursToTransform()`, instantiates each `RequestToContextTransformer` if needed, calls `transformer.from(requestContext)`, and accumulates the result.
|
|
289
|
+
- Enriches the logger with `user` / `organization` if present.
|
|
290
|
+
|
|
291
|
+
2. **`DecafRequestHandlerInterceptor`** (request-scoped, registered by `DecafCoreModule`):
|
|
292
|
+
- Calls `contextualize(req)` — accumulates `headers`, `logger`, `timestamp`, `operation` into the request context.
|
|
293
|
+
- Calls `executor.exec(req, res)` — runs all registered `DecafRequestHandler` instances in sequence.
|
|
294
|
+
|
|
295
|
+
---
|
|
296
|
+
|
|
297
|
+
## Webhook Module
|
|
298
|
+
|
|
299
|
+
### `DecafWebhookModule.forRootAsync(options)`
|
|
300
|
+
|
|
301
|
+
Standalone module for webhook delivery. Boots its own persistence layer (separate from `DecafModule`).
|
|
302
|
+
|
|
303
|
+
```ts
|
|
304
|
+
import { DecafWebhookModule } from "@decaf-ts/for-nest";
|
|
305
|
+
|
|
306
|
+
@Module({
|
|
307
|
+
imports: [
|
|
308
|
+
DecafWebhookModule.forRootAsync({
|
|
309
|
+
conf: [[NanoAdapter, couchConfig, new NanoTransformer()]],
|
|
310
|
+
webhookApiPath: "/webhooks",
|
|
311
|
+
handlers: [WebhookAuthHandler],
|
|
312
|
+
}),
|
|
313
|
+
],
|
|
314
|
+
})
|
|
315
|
+
export class AppModule {}
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
#### `DecafWebhookModuleOptions`
|
|
319
|
+
|
|
320
|
+
| Option | Type | Required | Default | Description |
|
|
321
|
+
|---|---|---|---|---|
|
|
322
|
+
| `conf` | same as `DecafModuleOptions.conf` | Yes | — | Adapter tuples for webhook persistence. |
|
|
323
|
+
| `handlers` | `Type<DecafRequestHandler>[]` | No | `[]` | Request handlers for the webhook pipeline. |
|
|
324
|
+
| `initialization` | `() => Promise<void>` | No | — | Called after webhook persistence boots. |
|
|
325
|
+
| `webhookApiPath` | `string` | No | `"/webhooks"` | Router prefix for webhook controllers. |
|
|
326
|
+
|
|
327
|
+
---
|
|
328
|
+
|
|
329
|
+
## Migration execution
|
|
58
330
|
|
|
59
331
|
`DecafCoreModule.migrate` wraps `MigrationService.migrateAdapters` once the persistence layer is ready. Use it to orchestrate upgrades across the adapters you boot in `DecafCoreModule.bootPersistence`.
|
|
60
332
|
|
package/dist/for-nest.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e,t;e=this,t=function(e,t,r,o,a,s,i,n,c,p,d,l,u,h,m,f,y,g){"use strict";function _(e){var t=Object.create(null);return e&&Object.keys(e).forEach(r=>{if("default"!==r){var o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,o.get?o:{enumerable:!0,get:()=>e[r]})}}),t.default=e,Object.freeze(t)}var A=_(m);const b="swagger",E={API_OPERATION:b+"/apiOperation",API_RESPONSE:b+"/apiResponse",API_PRODUCES:b+"/apiProduces",API_CONSUMES:b+"/apiConsumes",API_TAGS:b+"/apiUseTags",API_CALLBACKS:b+"/apiCallbacks",API_PARAMETERS:b+"/apiParameters",API_HEADERS:b+"/apiHeaders",API_MODEL_PROPERTIES:b+"/apiModelProperties",API_MODEL_PROPERTIES_ARRAY:b+"/apiModelPropertiesArray",API_SECURITY:b+"/apiSecurity",API_EXCLUDE_ENDPOINT:b+"/apiExcludeEndpoint",API_EXCLUDE_CONTROLLER:b+"/apiExcludeController",API_EXTRA_MODELS:b+"/apiExtraModels",API_EXTENSION:b+"/apiExtension",API_SCHEMA:b+"/apiSchema",API_DEFAULT_GETTER:b+"/apiDefaultGetter",API_LINK:b+"/apiLink"},P=e=>void 0===e;function O(e){if("function"==typeof e)return O(e());if(Array.isArray(e))return e;if("object"!=typeof e)return[];const t=Object.values(e).filter(e=>"number"==typeof e).map(e=>e.toString());return Object.keys(e).filter(e=>!t.includes(e)).map(t=>e[t])}function R(e){return e.filter(i.isString).length>0?"string":"number"}function v(e,t,r=!0){return(o,a)=>{const s=Reflect.getMetadata(E.API_MODEL_PROPERTIES_ARRAY,o)||[],n=":"+a;s.includes(n)||Reflect.defineMetadata(E.API_MODEL_PROPERTIES_ARRAY,[...s,":"+a],o);const c=Reflect.getMetadata(e,o,a);if(c){const s=i.pickBy(t,i.negate(P)),n=r?{...c,...s}:{...s,...c};Reflect.defineMetadata(e,n,o,a)}else{const r=o?.constructor?._OPENAPI_METADATA_FACTORY?.()[a]?.type??Reflect.getMetadata("design:type",o,a);Reflect.defineMetadata(e,{type:r,required:!1,...i.pickBy(t,i.negate(P))},o,a)}}}function w(e={}){return D(e)}function D(e={},t=!0){const[r,o]=((e,t)=>{if(!e)return[e,t];if(t)return[e,t];const r=i.isArray(e);return[r?e[0]:e,r]})(e.type,e.isArray);if((a=e={...e,type:r,isArray:o}).isArray&&"enum"in a&&void 0!==a.enum){e.type="array";const t=O(e.enum);e.items={type:R(t),enum:t},delete e.enum}else if("enum"in e&&void 0!==e.enum){const t=O(e.enum);e.enum=t,e.type=R(t)}var a;return Array.isArray(e.type)&&(e.type="array",e.items={type:"array",items:{type:e.type[0]}}),v(E.API_MODEL_PROPERTIES,e,t)}function S(e,r){const{handler:o,args:a}=t.Metadata.get(e,c.OperationKeys.REFLECT+c.OperationKeys.BLOCK)||{};return!!o&&(o(...a,r)??!1)}function T(e,r,a){const s={GET:[c.OperationKeys.READ,o.Get],POST:[c.OperationKeys.CREATE,o.Post],PUT:[c.OperationKeys.UPDATE,o.Put],PATCH:[c.OperationKeys.UPDATE,o.Patch],DELETE:[c.OperationKeys.DELETE,o.Delete]},[i,p]=s[r];return S(e,i)?t.apply(n.ApiExcludeEndpoint()):t.apply(p(a))}function C(e=[]){const t=e.map(e=>n.ApiParam({name:e.name,description:e.description??"Path parameter: "+e.name,required:e.required??!0,type:e.type??String}));return o.applyDecorators(...t)}const x=o.createParamDecorator((e,t)=>{const r=t.switchToHttp().getRequest().body,a=t.getClass(),s=a.class;if(!s)throw new o.InternalServerErrorException(`ModelConstructor not found on controller ${a.name}. Ensure the controller was created via FromModelController.`);return r?Array.isArray(r)?r.map(e=>new s(e)):new s(r):r}),M=o.createParamDecorator((e,t)=>{const r=t.switchToHttp().getRequest(),o=r?.params??{},a=e??Object.keys(o),s=a.map(e=>o[e]);return{raw:o,valuesInOrder:s,keysInOrder:a}});function I(e=[]){const t=e.map(e=>e.name);return M(t)}const $=o.createParamDecorator((e,t)=>{const r={...t.switchToHttp().getRequest().query??{}};if(void 0!==r.limit){const e=Number(r.limit);Number.isNaN(e)||(r.limit=e)}if(void 0!==r.offset){const e=Number(r.offset);Number.isNaN(e)||(r.offset=e)}if(void 0!==r.bookmark){const e=Number(r.bookmark);r.bookmark=Number.isNaN(e)?r.bookmark:e}return r});function q(e){const t={GET:o.Get,POST:o.Post,PUT:o.Put,PATCH:o.Patch,DELETE:o.Delete}[e];if(!t)throw Error(`Unsupported HTTP verb "${e}". No NestJS decorator mapping was found.`);return t}const F="DecafModuleOptions",k="DecafAdapter",N="DecafRoute",j=Symbol("DecafHandlers"),L=Symbol("DecafAdapterForOptions"),K=Symbol("AUTH_HANDLER"),B="auth:meta",U=Symbol("decaf:context");function H(t){const r=t?"string"==typeof t?t:t.name:void 0,a=[n.ApiBearerAuth(),o.UseInterceptors(e.AuthInterceptor)];return r&&a.push(o.SetMetadata(B,r)),o.applyDecorators(...a)}e.AuthInterceptor=class{constructor(e,t){this.reflector=e,this.authHandler=t}async intercept(e,t){const r=l.Logging.for(this).for(this.intercept),o=this.reflector.get(B,e.getHandler())??this.reflector.get(B,e.getClass());return r.verbose("Intercepted request"+(o?" for "+o:"")),this.authHandler?await this.authHandler.authorize(e,o):r.debug("No auth handler/model"),t.handle()}},e.AuthInterceptor=p.__decorate([o.Injectable(),p.__param(1,o.Optional()),p.__param(1,o.Inject(K)),p.__metadata("design:paramtypes",[d.Reflector,Object])],e.AuthInterceptor);class G{parseRequest(e){const t=e.headers.authorization?.split(" ")[1];return t}async authorize(e,r){const o=e.switchToHttp().getRequest(),i=this.parseRequest(o);if(!i)throw new s.AuthorizationError("Unauthenticated");if(!t.Metadata.get(a.Model.get(r),s.PersistenceKeys.AUTH_ROLE).includes(i))throw new s.AuthorizationError("Missing role: "+i)}}var z;e.DecafRequestContext=class{constructor(e){this.req=e,this.uuid=s.UUID.instance.generate()}get request(){return this.req}put(e){let t;try{t=this.ctx.get("overrides")}catch(e){t={}}this._ctx=this.ctx.accumulate({overrides:Object.assign(t,e)})}applyCtx(e){if(this._ctx)throw new c.InternalError("Trying to overwrite context");this._ctx=e}get ctx(){if(!this._ctx)throw new c.InternalError("Context not initialized for request");return this._ctx}},e.DecafRequestContext=p.__decorate([o.Injectable({scope:o.Scope.REQUEST}),p.__param(0,o.Inject(d.REQUEST)),p.__metadata("design:paramtypes",[Request])],e.DecafRequestContext),e.DecafHandlerExecutor=z=class{constructor(e,t){this.handlers=e,this.context=t}async exec(e,t){l.Logging.for(z.name).for(this.exec).debug(`CONTEXT ${this.context.uuid} running ${this.handlers.length} handlers for request ${e.method} ${e.url}`);for(const r of this.handlers)await r.handle(this.context,e,t)}},e.DecafHandlerExecutor=z=p.__decorate([o.Injectable({scope:o.Scope.REQUEST}),p.__param(0,o.Inject(j)),p.__metadata("design:paramtypes",[Array,e.DecafRequestContext])],e.DecafHandlerExecutor),e.DecafResponseInterceptor=class{constructor(e){this.ctx=e}intercept(e,t){let r=e.switchToHttp().getResponse();return t.handle().pipe(u.tap(e=>{r=this.ctx.ctx.toResponse(r)}))}},e.DecafResponseInterceptor=p.__decorate([o.Injectable(),p.__metadata("design:paramtypes",[e.DecafRequestContext])],e.DecafResponseInterceptor);const Q=e=>({name:e,description:e+" parameter for the query",required:!0,type:String});function V(e,t,r,a=!1){const i=q(r),c=(e=>e.split("/").filter(e=>e.startsWith(":")).map(e=>e.slice(1)))(t).map(Q),p=[];return"GET"===r&&a&&p.push(n.ApiQuery({name:"direction",required:!1,enum:s.OrderDirection,description:"the sort order when applicable"}),n.ApiQuery({name:"limit",required:!1,description:"limit or page size when applicable"}),n.ApiQuery({name:"offset",required:!1,description:"offset or bookmark when applicable"})),{method:[i(t),...c.map(n.ApiParam),...p,n.ApiOperation({summary:`Retrieve records using according to "${e}".`}),n.ApiOkResponse({description:"Result successfully retrieved."}),n.ApiNoContentResponse({description:"No content returned by the method."})],params:[I(c),o.Query()]}}function Y(e,t,r,o){const a=e?.prototype??e;o.method.forEach(e=>e(a,t,r)),o.params?.forEach((e,r)=>e(a,t,r))}function J(e,t,...r){if(e instanceof s.ModelService)return"function"==typeof e[t]?e[t](...r):e.statement(t,...r);if("function"==typeof e[t])return e[t](...r);throw Error(`Persistence method "${t}" not found on ${e?.constructor?.name}`)}function X(e){return async function(t,r){const o=this.log.for(e);try{o.debug(`Invoking persistence method "${e}" given parameters: ${JSON.stringify(t.valuesInOrder)}`);const{direction:a,limit:s,offset:i}=r;return await J(this.persistence(),e,...t.valuesInOrder,a,s,i)}catch(t){throw o.error(`Custom query "${e}" failed`,t),t}}}function W(e,t,r){return Object.defineProperty(e.prototype||e,t,{value:r,writable:!1}),Object.getOwnPropertyDescriptor(e.prototype||e,t)}class Z extends s.Service{constructor(e,t){super(),this.clientContext=e}logCtx(e,t,r=!1,o){const a=this.clientContext.ctx;let i;e=e.filter(e=>void 0!==e),o&&(o.headers||o.ip)&&(i=o,o={});const n=s.ContextualLoggedClass.logCtx.call(this,t,o||{},r,...e,a);return this.bindLoggerToRequest(n,i)}bindLoggerToRequest(e,t){const r=this;function o(e,t){return e.log=((e,t)=>{const o=(e=>{if(!e)return;const t=e.headers,r=te(t?.["x-forwarded-for"])??te(t?.["x-real-ip"])??te(t?.["X-Forwarded-For"])??te(t?.["X-Real-IP"]);if(r)return r;if("string"==typeof e.ip&&e.ip.length)return e.ip;const o=e.socket||e.connection;return o&&"string"==typeof o.remoteAddress&&o.remoteAddress.length?o.remoteAddress:void 0})(t??r.clientContext.request);if(!o)return e;const a={ip:o};return e.for(a)})(e.log,t),e}return(e=>"object"==typeof e&&null!==e&&"function"==typeof e.then)(e)?e.then(e=>o(e,t)):o(e,t)}}class ee extends Z{persistence(e){if(!this._persistence)try{this._persistence=s.Service.get(this.class)}catch(e){try{this._persistence=s.ModelService.getService(this.class)}catch(e){this._persistence=s.Repository.forModel(this.class)}}const t=this.clientContext.request[L]||{};return e&&this.clientContext.put(t),e?this._persistence instanceof s.Repository?this._persistence.override(t):this._persistence.for(t):this._persistence}constructor(e,t){super(e,t)}logCtx(e,t,r=!1,o){const a=this.clientContext.ctx;let i;o&&(o.headers||o.ip)&&(i=o,o={});try{o=a.get("overrides")}catch(e){}const n=this.persistence(a);let c,p;return n instanceof s.ModelService?c=n.repo._adapter:n instanceof s.Repository?c=n._adapter:n.context&&(c=n),r?c.logCtx(e,t,!0,o).then(e=>this.bindLoggerToRequest(e,i)):(p=c.logCtx(e,t,!1,o),this.bindLoggerToRequest(p,i))}}function te(e){if(e)return(Array.isArray(e)?e[0]:e).split(",").map(e=>e.trim()).filter(Boolean)[0]}const re=new Map;function oe(e,r){if(!s.TransactionOperationKeys.includes(e))return r;const o=(e=>(re.has(e)||re.set(e,new WeakMap),re.get(e)))(e),i=o.get(r);if(i)return i;const n=[c.OperationKeys.UPDATE,c.BulkCrudOperationKeys.UPDATE_ALL].includes(e);class p{}o.set(r,p),Object.defineProperty(p,"name",{value:`${l.toPascalCase(r.name)}${l.toPascalCase(e)}DTO`});const d=(()=>{try{return a.Model.pk(r)}catch{return}})(),u=d?a.Model.pkProps(r):void 0,h=d?Reflect.getMetadata("design:type",r.prototype,d):void 0,m=h===Number||h===BigInt,f=!!u?.generated||!!d&&(a.Model.generatedBySequence(r,d)||ie(r,d)||m),y=Array.from(new Set(t.Metadata.properties(r)||[])),g=new Set(a.Model.relations(r)||[]),_=[];for(const e of y)e&&(g.has(e)||e===d&&!n&&f||e!==d&&ie(r,e)||_.push(e));for(const e of _){const t=ne(r,e),o=!!t?.[a.ValidationKeys.REQUIRED],s=ce(r,e)??Reflect.getMetadata("design:type",r.prototype,e),i={required:o};s&&(i.type=s),w(i)(p.prototype,e);const n=Reflect.getMetadata("design:type",r.prototype,e)??s;void 0!==n&&Reflect.defineMetadata("design:type",n,p.prototype,e),Object.defineProperty(p.prototype,e,{value:void 0,writable:!0,enumerable:!0,configurable:!0})}for(const o of g){const s=t.Metadata.relations(r,o);if(!s)throw new c.InternalError(`Metadata for relation ${o} not found`);let i=s.class;if("function"!=typeof i||i.name||(i=i()),!i||"function"!=typeof i)throw new c.InternalError(`Type for relation ${o} not found`);if(!a.Model.get(i.name))continue;const d=t.Metadata.validationFor(r,o),l=!!d?.[a.ValidationKeys.LIST],u=!!d?.[a.ValidationKeys.REQUIRED],h=oe(e,i);n?se(p,o,i,h,l,u):ae(p,o,h,l,u)}return p}function ae(e,t,r,o,a){w({type:r,required:a,isArray:o})(e.prototype,t),Reflect.defineMetadata("design:type",o?Array:r,e.prototype,t),Object.defineProperty(e.prototype,t,{value:void 0,writable:!0,enumerable:!0,configurable:!0})}function se(e,t,r,o,s,i){const n=Reflect.getMetadata(E.API_EXTRA_MODELS,e)||[];n.includes(o)||Reflect.defineMetadata(E.API_EXTRA_MODELS,[...n,o],e);const c="#/components/schemas/"+o.name,p=(e=>{try{const t=a.Model.pkProps(e),r=t?.type;return r===Number||r===BigInt?"integer":"string"}catch{return"string"}})(r),d=[{$ref:c},{type:p}];w(s?{type:"array",required:i,oneOf:d}:{type:Object,required:i,oneOf:d})(e.prototype,t),Reflect.defineMetadata("design:type",s?Array:Object,e.prototype,t),Object.defineProperty(e.prototype,t,{value:void 0,writable:!0,enumerable:!0,configurable:!0})}function ie(e,t){let r=e;for(;r&&r!==Object&&r!==Function;){if(a.Model.generated(r,t))return!0;r=Object.getPrototypeOf(r)}return!1}function ne(e,r){let o=e;for(;o&&o!==Object&&o!==Function;){const e=t.Metadata.validationFor(o,r);if(e)return e;o=Object.getPrototypeOf(o)}}function ce(e,r){let o=e;for(;o&&o!==Object&&o!==Function;){const e=t.Metadata.type(o,r);if(e)return e;o=Object.getPrototypeOf(o)}}s.Adapter.transformerFor=(e=>{const r="string"==typeof e?e:e.alias;return t.Metadata.innerGet(Symbol.for("transformers"),r)}).bind(s.Adapter),s.Adapter.flavoursToTransform=(()=>{const e=t.Metadata.innerGet(Symbol.for("transformers"));if(e)return Object.keys(e)}).bind(s.Adapter),s.Context.prototype.toResponse=function(e){const t=this.pending();return t&&e.header("x-pending-task",JSON.stringify(t)),e};const pe=a.ModelBuilder.prototype;if(pe.decorateClass||(pe.decorateClass=function(e){return this._classDecorators||(this._classDecorators=[]),this._classDecorators.push(e),this}),pe.Auth=function(e){return this.decorateClass(H(e))},!pe.__hasClassDecoratorSupport){const e=pe.build;pe.build=function(){let t=e.call(this);const r=this._classDecorators;if(r?.length)for(const e of r){const r=e(t);r&&(t=r)}return t},pe.__hasClassDecoratorSupport=!0}class de{static{this.log=l.Logging.for(de.name)}static getPersistence(e){try{return s.Service.get(e)}catch(t){try{return s.ModelService.getService(e)}catch(t){return s.Repository.forModel(e)}}}static createQueryRoutesFromRepository(e,r=s.PersistenceKeys.QUERY){const o=de.log.for(de.createQueryRoutesFromRepository),a=e instanceof s.ModelService?e.repo:e,i=a.class,n=t.Metadata.get(a.constructor,t.Metadata.key(s.PersistenceKeys.QUERY))??{},c=t.Metadata.get(e.constructor,t.Metadata.key(N))??{};class p extends ee{get class(){throw Error("Method not implemented.")}constructor(e,t){super(e,t)}}for(const[e,t]of Object.entries(c)){const r=[t.path.replace(/^\/+|\/+$/g,"")].filter(e=>e&&e.trim()).join("/"),a=X(e);if(!a){const t=`Invalid or missing handler for model ${i.name} on decorated method ${e}`;throw o.error(t),Error(t)}const s=W(p,e,a);s&&Y(p,e,s,V(e,r,t.httpMethod))}for(const[e,t]of Object.entries(n)){const o=[r,e,...(t.fields??[]).map(e=>":"+e)].filter(e=>e&&e.trim()).join("/"),a=W(p,e,X(e));a&&Y(p,e,a,V(e,o,"GET",!0))}return p}static create(t){const r=de.log.for(de.create),i=a.Model.tableName(t),d=l.toKebabCase(i),u=t.name,h=de.getPersistence(t),{description:m,getPK:f,apiProperties:y,path:g}=de.getRouteParametersFromModel(t);r.debug("Creating controller for model: "+u);const _=de.createQueryRoutesFromRepository(h);let A=class extends _{static get class(){return t}get class(){return t}constructor(e){super(e),this.pk=a.Model.pk(t),r.info(`Registering dynamic controller for model: ${this.class.name} route: /${d}`)}async listBy(e,t){const{ctx:r}=(await this.logCtx([],s.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return this.persistence(r).listBy(e,t.direction,r)}async paginateBy(e,t){const{ctx:r}=(await this.logCtx([],s.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);return this.persistence(r).paginateBy(e,t.direction,t,r)}async find(e,t){const{ctx:r}=(await this.logCtx([],s.PreparedStatementKeys.FIND,!0)).for(this.find),o=t.direction??s.OrderDirection.ASC;return J(this.persistence(r),this.find.name,e,o,r)}async page(e,t){const{ctx:r}=(await this.logCtx([],s.PreparedStatementKeys.PAGE,!0)).for(this.page),{direction:o=s.OrderDirection.ASC,limit:a,offset:i,bookmark:n}=t,c={offset:i??1,limit:a??10,bookmark:n};return J(this.persistence(r),this.page.name,e,o,c,r)}async findOneBy(e,t){const{ctx:r}=(await this.logCtx([],s.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);return this.persistence(r).findOneBy(e,t,r)}async findBy(e,t,r){const{ctx:o}=(await this.logCtx([],s.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return this.persistence(o).for(o.toOverrides()).findBy(e,t,o)}async statement(e,t,r){const{ctx:o}=(await this.logCtx([],s.PersistenceKeys.STATEMENT,!0)).for(this.statement),{direction:a,offset:i,limit:n,bookmark:c}=r,p=(t=t.map(e=>("string"==typeof e?parseInt(e):e)||e)).length>1?t[1]:void 0,d=a??p;switch(d&&t.length>1&&(t[1]=d),e){case s.PreparedStatementKeys.FIND:case s.PreparedStatementKeys.FIND_BY:break;case s.PreparedStatementKeys.LIST_BY:t.push(a);break;case s.PreparedStatementKeys.PAGE:case s.PreparedStatementKeys.PAGE_BY:t=[t[0],d,{limit:n,offset:i,bookmark:c}];case s.PreparedStatementKeys.FIND_ONE_BY:case s.PreparedStatementKeys.COUNT_OF:case s.PreparedStatementKeys.MAX_OF:case s.PreparedStatementKeys.MIN_OF:case s.PreparedStatementKeys.AVG_OF:case s.PreparedStatementKeys.SUM_OF:case s.PreparedStatementKeys.DISTINCT_OF:case s.PreparedStatementKeys.GROUP_OF:}return this.persistence(o).statement(e,...t,o)}async createAll(e,r){const{ctx:o,log:a}=(await this.logCtx([],c.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAll);let s;a.verbose("creating new "+u);try{s=await this.persistence(o).createAll(e.map(e=>new t(e)),o)}catch(e){throw a.error("Failed to create new "+u,e),e}return a.info(`created new ${u} with id ${s[this.pk]}`),o.toResponse(r),s}async create(e,t){const{ctx:r,log:o}=(await this.logCtx([],c.OperationKeys.CREATE,!0)).for(this.create);let a;o.verbose("creating new "+u);try{const t=this.persistence(r);a=await t.create(e,r)}catch(e){throw o.error("Failed to create new "+u,e),e}return o.info(`created new ${u} with id ${a[this.pk]}`),r.toResponse(t),a}async readAll(e){const{ctx:t,log:r}=(await this.logCtx([],c.BulkCrudOperationKeys.READ_ALL,!0)).for(this.readAll),o=Array.isArray(e)?e:[e];let a;try{r.debug(`reading ${o} ${u}: ${o}`);const e=this.persistence(t);a=await e.readAll(o,t)}catch(e){throw r.error(`Failed to ${u} with id ${o}`,e),e}return r.info(`read ${a.length} ${u}`),a}async read(e){const{ctx:t,log:r}=(await this.logCtx([],c.OperationKeys.READ,!0)).for(this.read),o=f(...e.valuesInOrder);if(void 0===o)throw new c.ValidationError(`No ${this.pk} provided`);let a;try{r.debug(`reading ${u} with ${this.pk} ${o}`);const e=this.persistence(t);a=await e.read(o,t)}catch(e){throw r.error(`Failed to read ${u} with id ${o}`,e),e}return r.info(`read ${u} with id ${a[this.pk]}`),a}async updateAll(e,t){const{ctx:r,log:o}=(await this.logCtx([],c.BulkCrudOperationKeys.UPDATE_ALL,!0)).for(this.updateAll);let a;try{o.info(`updating ${e.length} ${u}`),a=await this.persistence(r).updateAll(e,r)}catch(e){throw o.error(e),e}return r.toResponse(t),a}async update(e,r,o){const{ctx:a,log:s}=(await this.logCtx([],c.OperationKeys.UPDATE,!0)).for(this.update),i=f(...e.valuesInOrder);if(void 0===i)throw new c.ValidationError(`No ${this.pk} provided`);let n;try{s.info(`updating ${u} with ${this.pk} ${i}`);const e=JSON.parse(JSON.stringify(r)),o=this.persistence(a);n=await o.update(new t({...e,[this.pk]:i}),a)}catch(e){throw s.error(e),e}return a.toResponse(o),n}async deleteAll(e,t){const{ctx:r,log:o}=(await this.logCtx([],c.BulkCrudOperationKeys.DELETE_ALL,!0)).for(this.deleteAll),a=Array.isArray(e)?e:[e];let s;try{o.debug(`deleting ${a.length} ${u}: ${a}`),s=await this.persistence(r).deleteAll(a,r)}catch(e){throw o.error(`Failed to delete ${u} with id ${a}`,e),e}return o.info(`deleted ${s.length} ${u}`),r.toResponse(t),s}async delete(e,t){const{ctx:r,log:o}=(await this.logCtx([],c.OperationKeys.DELETE,!0)).for(this.delete),a=f(...e.valuesInOrder);if(void 0===a)throw new c.ValidationError(`No ${this.pk} provided`);let s;try{o.debug(`deleting ${u} with ${this.pk} ${a}`),s=await this.persistence(r).delete(a,r)}catch(e){throw o.error(`Failed to delete ${u} with id ${a}`,e),e}return o.info(`deleted ${u} with id ${a}`),r.toResponse(t),s}};return p.__decorate([T(t,"GET","listBy/:key"),n.ApiOperation({summary:`Retrieve ${u} records by query.`}),n.ApiParam({name:"key",description:"the model key to sort by"}),n.ApiQuery({name:"direction",required:!0,enum:s.OrderDirection}),n.ApiOkResponse({description:u+" listed successfully."}),p.__param(0,o.Param("key")),p.__param(1,$()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"listBy",null),p.__decorate([T(t,"GET","paginateBy/:key/:page"),n.ApiOperation({summary:`Retrieve ${u} records by query.`}),n.ApiParam({name:"key",description:"the model key to sort by"}),n.ApiParam({name:"page",description:"the page to retrieve or the bookmark"}),n.ApiQuery({name:"direction",required:!0,enum:s.OrderDirection,description:"the sort order"}),n.ApiQuery({name:"limit",required:!0,description:"the page size"}),n.ApiQuery({name:"offset",description:"the bookmark when necessary"}),n.ApiOkResponse({description:u+" listed paginated."}),p.__param(0,o.Param("key")),p.__param(1,$()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"paginateBy",null),p.__decorate([T(t,"GET","find/:value"),n.ApiOperation({summary:`Find ${u} records using the default query attributes.`}),n.ApiParam({name:"value",description:"The string to match against the default query attributes"}),n.ApiQuery({name:"direction",required:!1,enum:s.OrderDirection,description:"the sort order for the matching results"}),n.ApiOkResponse({description:u+" records matching the provided prefix."}),p.__param(0,o.Param("value")),p.__param(1,$()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"find",null),p.__decorate([T(t,"GET","page/:value"),n.ApiOperation({summary:`Page ${u} records using the default query attributes.`}),n.ApiParam({name:"value",description:"The string to match against the default query attributes"}),n.ApiQuery({name:"direction",required:!1,enum:s.OrderDirection,description:"the sort order for the paged results"}),n.ApiQuery({name:"limit",required:!1,description:"page size"}),n.ApiQuery({name:"offset",required:!1,description:"page number"}),n.ApiQuery({name:"bookmark",required:!1,description:"bookmark for cursor pagination"}),n.ApiOkResponse({description:u+" records paged by the provided prefix."}),p.__param(0,o.Param("value")),p.__param(1,$()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"page",null),p.__decorate([T(t,"GET","findOneBy/:key"),n.ApiOperation({summary:`Retrieve ${u} records by query.`}),n.ApiParam({name:"key",description:"the model key to sort by"}),n.ApiOkResponse({description:u+" listed found."}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,o.Param("key")),p.__param(1,o.Param("value")),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"findOneBy",null),p.__decorate([T(t,"GET","findBy/:key/:value"),n.ApiOperation({summary:`Retrieve ${u} records by query.`}),n.ApiParam({name:"key",description:"the model key to compare"}),n.ApiParam({name:"value",description:"the value to match"}),n.ApiQuery({name:"direction",required:!0,enum:s.OrderDirection,description:"the sort order when applicable"}),n.ApiOkResponse({description:u+" listed found."}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,o.Param("key")),p.__param(1,o.Param("value")),p.__param(2,$()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"findBy",null),p.__decorate([T(t,"GET","statement/:method/*args"),n.ApiOperation({summary:`Executes a prepared statement on ${u}.`}),n.ApiParam({name:"method",description:"the prepared statement to execute"}),n.ApiParam({name:"args",description:"concatenated list of arguments the prepared statement can accept"}),n.ApiQuery({name:"direction",required:!0,enum:s.OrderDirection,description:"the sort order when applicable"}),n.ApiQuery({name:"limit",required:!0,description:"limit or page size when applicable"}),n.ApiQuery({name:"offset",required:!0,description:"offset or bookmark when applicable"}),n.ApiOkResponse({description:u+" listed found."}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,o.Param("method")),p.__param(1,o.Param("args")),p.__param(2,$()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Array,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"statement",null),p.__decorate([T(t,"POST","bulk"),n.ApiOperation({summary:`Create a new ${u}.`}),n.ApiBody({description:"Payload for "+u,schema:{type:"array",items:{$ref:n.getSchemaPath(t)}}}),n.ApiCreatedResponse({description:u+" created successfully.",schema:{type:"array",items:{$ref:n.getSchemaPath(t)}}}),n.ApiBadRequestResponse({description:"Payload validation failed."}),n.ApiUnprocessableEntityResponse({description:"Repository rejected the provided payload."}),p.__param(0,x()),p.__param(1,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Array,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"createAll",null),p.__decorate([T(t,"POST"),n.ApiOperation({summary:`Create a new ${u}.`}),n.ApiBody({description:"Payload for "+u,type:oe(c.OperationKeys.CREATE,t)}),n.ApiCreatedResponse({description:u+" created successfully.",schema:{$ref:n.getSchemaPath(t)}}),n.ApiBadRequestResponse({description:"Payload validation failed."}),n.ApiUnprocessableEntityResponse({description:"Repository rejected the provided payload."}),p.__param(0,x()),p.__param(1,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Object,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"create",null),p.__decorate([T(t,"GET","bulk"),n.ApiOperation({summary:`Retrieve a ${u} record by id.`}),n.ApiQuery({name:"ids",required:!0,type:"array"}),n.ApiOkResponse({description:u+" retrieved successfully.",schema:{type:"array",items:{$ref:n.getSchemaPath(t)}}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,o.Query("ids")),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Array]),p.__metadata("design:returntype",Promise)],A.prototype,"readAll",null),p.__decorate([T(t,"GET",g),C(y),n.ApiOperation({summary:`Retrieve a ${u} record by id.`}),n.ApiOkResponse({description:u+" retrieved successfully.",schema:{$ref:n.getSchemaPath(t)}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,I(y)),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Object]),p.__metadata("design:returntype",Promise)],A.prototype,"read",null),p.__decorate([T(t,"PUT","bulk"),C(y),n.ApiOperation({summary:`Replace an existing ${u} record with a new payload.`}),n.ApiBody({description:"Payload for replace a existing record of "+u,schema:{type:"array",$ref:n.getSchemaPath(oe(c.OperationKeys.UPDATE,t))}}),n.ApiOkResponse({description:u+" updated successfully.",schema:{type:"array",items:{$ref:n.getSchemaPath(t)}}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),n.ApiBadRequestResponse({description:"Payload validation failed."}),p.__param(0,x()),p.__param(1,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Array,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"updateAll",null),p.__decorate([T(t,"PUT",g),C(y),n.ApiOperation({summary:`Replace an existing ${u} record with a new payload.`}),n.ApiBody({description:"Payload for replace a existing record of "+u,type:oe(c.OperationKeys.UPDATE,t)}),n.ApiOkResponse({description:u+" updated successfully.",schema:{$ref:n.getSchemaPath(t)}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),n.ApiBadRequestResponse({description:"Payload validation failed."}),p.__param(0,I(y)),p.__param(1,x()),p.__param(2,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Object,Object,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"update",null),p.__decorate([T(t,"DELETE","bulk"),C(y),n.ApiOperation({summary:`Retrieve a ${u} record by id.`}),n.ApiQuery({name:"ids",required:!0,type:"array"}),n.ApiOkResponse({description:u+" deleted successfully.",schema:{type:"array",items:{$ref:n.getSchemaPath(t)}}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,o.Query("ids")),p.__param(1,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Array,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"deleteAll",null),p.__decorate([T(t,"DELETE",g),C(y),n.ApiOperation({summary:`Delete a ${u} record by id.`}),n.ApiOkResponse({description:u+" deleted successfully.",schema:{$ref:n.getSchemaPath(t)}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,I(y)),p.__param(1,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Object,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"delete",null),A=p.__decorate([o.Controller(d),n.ApiTags(u),n.ApiExtraModels(t),H(t),p.__metadata("design:paramtypes",[e.DecafRequestContext])],A),A}static getRouteParametersFromModel(e){const r=a.Model.pk(e),o=t.Metadata.get(e,t.Metadata.key(c.DBKeys.COMPOSED,r)),s=o?.args??[],i=Array.isArray(s)&&s.length>0?Array.from(new Set([...s])):Array.from(new Set([r])),n=t.Metadata.description(e);return{path:":"+i.join("/:"),description:n,apiProperties:i.map(r=>({name:r,description:t.Metadata.description(e,r),required:!0,type:String})),getPK:(...e)=>o?.separator?e.join(o.separator):e.join("")}}}function le(e){var t;let r=class{static{t=this}static{this.log=l.Logging.for(t.name).for(e)}static createModelServices(e){return e.map(e=>({provide:e.name+"Service",useFactory:()=>s.ModelService.forModel(e)}))}static forRoot(e,r={}){const o=this.log.for(this.forRoot);o.info("Generating controllers for flavour...");const a=s.Adapter.models(e);let i=[];r.autoServices&&(o.info("Auto-services enabled. Initializing service generation."),i=this.createModelServices(a),o.info(`Auto-services completed. ${i.length} services initialized.`));const n=a.map(de.create);return o.info(`Generated ${n.length} controllers`),{module:t,controllers:n,providers:[...i]}}};return r=t=p.__decorate([o.Module({})],r),Object.assign(r,"name",{value:"DecafModule"+e}),r}t.Decoration.for(r.InjectablesKeys.INJECTABLE).extend({decorator:(e,t)=>(t=t||("object"==typeof e?Object.assign(e,r.DefaultInjectablesConfig):r.DefaultInjectablesConfig),o.Injectable({scope:t.singleton?o.Scope.DEFAULT:o.Scope.REQUEST,durable:!t.singleton||void 0}))}).apply(),t.Decoration.for(r.InjectablesKeys.INJECT).extend({decorator:(e,t)=>(t,r,a)=>o.Inject(e||t)(t,r,a)}).apply(),t.Decoration.for(a.ValidationKeys.REQUIRED).extend(w({required:!0})).apply(),t.Decoration.for(a.ValidationKeys.MAX).extend({decorator:e=>w({maximum:e,required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.MIN).extend({decorator:e=>w({minimum:e,required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.MAX_LENGTH).extend({decorator:e=>w({maxLength:e,required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.MIN_LENGTH).extend({decorator:e=>w({minLength:e,required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.TYPE).extend({decorator:e=>(t,r)=>("function"!=typeof(e=Array.isArray(e)?e[0]:e)||e.name||(e=e()),w({type:e,required:!1})(t,r))}).apply(),t.Decoration.for(a.ValidationKeys.DATE).extend({decorator:e=>w({type:String,format:"date-time",required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.ENUM).extend({decorator:e=>w({enum:Array.isArray(e)?e:Object.values(e),required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.PATTERN).extend({decorator:e=>w({pattern:"string"==typeof e?e:e.source,required:!1})}).apply(),t.Decoration.for(s.PersistenceKeys.COLUMN).extend({decorator:e=>w({name:e,required:!1})}).apply(),t.Decoration.for(t.DecorationKeys.DESCRIPTION).extend({decorator:e=>w({description:e,required:!1})}).apply(),t.Decoration.for(s.PersistenceKeys.AUTH).extend({decorator:H}).apply();class ue extends s.ForbiddenError{constructor(e){super(e,ue.name)}}class he extends c.BaseError{constructor(e){super(he.name,e,429)}}e.DecafExceptionFilter=class{catch(e,t){const r=t.switchToHttp(),a=r.getResponse(),i=r.getRequest(),n="production"===l.LoggedEnvironment.env;let p;e instanceof o.NotFoundException||e instanceof s.UnsupportedError?p=(e=new o.NotAcceptableException(e.message)).getStatus():e instanceof c.BaseError||(e=429===e.status?new he(e.message):new c.InternalError(e.message)),a.status(e.code||p).json({status:e.code||p,error:n?e.name:e.message,timestamp:(new Date).toISOString(),path:i.url,method:i.method})}},e.DecafExceptionFilter=p.__decorate([o.Catch()],e.DecafExceptionFilter);const me={path:"docs",auth:{type:"http",scheme:"bearer",bearerFormat:"JWT",name:"Authorization",description:"Enter JWT token",in:"header"},topbarBgColor:"#000000"};class fe{constructor(e){this.options={...e}}customCSS(){let e="";return this.options.topbarIconPath&&(e+=`.topbar-wrapper { content: url('data:image/png;base64,${this.b64(this.options.topbarIconPath)}'); width: 200px; height: auto; }\n`),e+`\n .topbar-wrapper svg { visibility: hidden; }\n .swagger-ui .topbar { background-color: ${this.options.topbarBgColor||me.topbarBgColor}; }\n `}getCustomOptions(){const e={};return this.options.faviconPath&&(e.customfavIcon=this.b64(this.options.faviconPath,!0)),{customSiteTitle:this.options.title,...e,customCss:this.customCSS(),swaggerOptions:{persistAuthorization:this.options.persistAuthorization}}}b64(e,t=!1){const r=A.join(this.options.assetsPath||"",e),o=h.readFileSync(r,{encoding:"base64"});return t?"data:image/png;base64,"+o:o}}class ye{constructor(e,t){this.app=e,this.options=t}createDocument(){const e=this.options.path?this.options.description+""+`<br><br><a href="${this.options.openApiJsonPath}">OpenAPI JSON Spec</a> | `+`<a href="${this.options.openApiYamlPath}">OpenAPI YAML Spec</a>`:this.options.description,t=(new n.DocumentBuilder).setTitle(this.options.title).setDescription(e).setVersion(this.options.version||"0.0.1").addBearerAuth(this.options.auth||me.auth).build();return n.SwaggerModule.createDocument(this.app,t,{extraModels:this.options.extraModels||[]})}registerOpenApiRoute(e,t,r){if(!e)return;const o=this.app.getHttpAdapter();e=e.startsWith("/")?e:"/"+e,o.get(e,(e,a)=>{o.reply(a,r(),200,{"Content-Type":t})})}setupSwagger(){const e=this.createDocument(),t=new fe({title:this.options.title,path:this.options.path||me.path,persistAuthorization:this.options.persistAuthorization??!0,assetsPath:this.options.assetsPath,faviconPath:this.options.faviconFilePath,topbarIconPath:this.options.topbarIconFilePath,topbarBgColor:this.options.topbarBgColor});n.SwaggerModule.setup(this.options.path||me.path,this.app,e,{...t.getCustomOptions(),jsonDocumentUrl:this.options.openApiJsonPath?""+this.options.openApiJsonPath:void 0,yamlDocumentUrl:this.options.openApiYamlPath?""+this.options.openApiYamlPath:void 0}),this.registerOpenApiRoute(this.options.openApiJsonPath,"application/json",()=>e),this.registerOpenApiRoute(this.options.openApiYamlPath,"application/x-yaml",()=>f.stringify(e))}}var ge,_e;function Ae(e){return r=>(t.Metadata.set("transformers",e,r),"function"==typeof r?t.metadata("transformers",e)(r):r)}e.DecafRequestHandlerInterceptor=ge=class{constructor(e,t){this.requestContext=e,this.executor=t}async contextualize(e){const t={headers:e.headers,overrides:{}},r=s.Adapter.flavoursToTransform();if(r)for(const o of r)try{const r=s.Adapter.transformerFor(o),a=await r.from(e);Object.assign(t.overrides,a)}catch(e){throw new c.InternalError("Failed to contextualize request: "+e)}return(new s.Context).accumulate(Object.assign({},s.DefaultAdapterFlags,{logger:l.Logging.get(),timestamp:new Date},t))}async intercept(e,t){const r=e.switchToHttp().getRequest(),o=e.switchToHttp().getResponse(),a=l.Logging.for(ge).for(this.intercept);a.debug(`CONTEXT ${this.requestContext.uuid} - request: ${r.method} ${r.url}`);const s=await this.contextualize(r);return a.debug(`CONTEXT ${this.requestContext.uuid} contextualized - request: ${r.method} ${r.url}`),this.requestContext.applyCtx(s),a.debug(`CONTEXT ${this.requestContext.uuid} applied - request: ${r.method} ${r.url}`),await this.executor.exec(r,o),a.debug(`CONTEXT ${this.requestContext.uuid} executors finished - request: ${r.method} ${r.url}`),t.handle()}},e.DecafRequestHandlerInterceptor=ge=p.__decorate([o.Injectable({scope:o.Scope.REQUEST}),p.__metadata("design:paramtypes",[e.DecafRequestContext,e.DecafHandlerExecutor])],e.DecafRequestHandlerInterceptor),e.DecafCoreModule=class{static{_e=this}static get persistence(){if(!this._persistence)throw new c.InternalError("Persistence service not initialized");return this._persistence}static get log(){return this._logger||(this._logger=l.Logging.for(_e)),this._logger}constructor(e,t){this.options=e,this.moduleRef=t}static forRoot(t){const r=this.log.for(this.forRoot);return{module:_e,providers:[{provide:F,useValue:t},{provide:k,useValue:this.persistence?.client},{provide:j,useFactory:()=>t.handlers?.map(e=>(r.info("Registered request handler: "+e.name),new e))??[]},e.AuthInterceptor,{provide:d.APP_INTERCEPTOR,useExisting:e.AuthInterceptor},e.DecafRequestContext,e.DecafHandlerExecutor,{provide:d.APP_INTERCEPTOR,useClass:e.DecafRequestHandlerInterceptor}],exports:[F,k,j,e.DecafRequestContext,e.DecafHandlerExecutor]}}static async bootPersistence(e){const t=this.log.for(this.bootPersistence);if(!this._persistence){const r=e.conf.map(([e,t,...r])=>r.pop()?[e,t,...r]:[e,t]);this._persistence=new s.PersistenceService,await this._persistence.boot(r);const o=this._persistence.client;for(let t=0;t<o.length;t++){const r=e.conf[t];let a=r.slice(2,r.length).pop();if(!a||!a.from){const e=s.Adapter.transformerFor(o[t].flavour);if(!e)throw new c.InternalError(`No transformer found for flavour ${o[t].flavour}. you should either @requestToContextTransformer or provide a transformer in the config`);try{a=e.from?e:new e}catch(e){throw new c.InternalError(`Failed to boot transformer for ${o[t].flavour}: ${e}`)}}Ae(o[t].flavour)(a)}if(t.info("persistence layer created successfully!"),e.initialization)try{await e.initialization()}catch(e){throw new c.InternalError("Failed to initialize application: "+e)}}return this.persistence.client}async onApplicationShutdown(){const e=_e.log.for(this.onApplicationShutdown),t=this.moduleRef.get(k);for(const r of t)try{r&&(e.info("Shutting down "+r.toString()),await r.shutdown())}catch(t){e.error("Failed to shutdown application",t)}try{await s.Service.shutdown()}catch(t){e.error("Failed to shutdown services",t)}}},e.DecafCoreModule=_e=p.__decorate([o.Global(),o.Module({}),p.__param(0,o.Inject(F)),p.__metadata("design:paramtypes",[Object,d.ModuleRef])],e.DecafCoreModule);const be=Symbol("LISTENING_ADAPTERS_FLAVOURS");var Ee,Pe,Oe,Re;e.EventsController=Ee=class extends Z{constructor(e,t){super(e,Ee.name),this.adapters=t.map(e=>s.Adapter.get(e))}listen(){const e=l.Logging.for(Ee.name),t=new u.Observable(t=>{const r=("B-"+Math.random().toString(36).slice(2,8)).toUpperCase();e.info(`Creating SSE observer: ${r} for client ${this.clientContext.uuid}`);const o=new class{constructor(){this.observerId=r}refresh(...r){return e.debug(`SSE observer ${this.observerId} received refresh event`),Promise.resolve().then(()=>{const o=(e=>{const[t,r,o,a]=e;return[t?.name??t,r,o,Array.isArray(a)?a.map(e=>{try{return"function"==typeof e.serialize?e.serialize():"string"==typeof e?e:JSON.stringify(e)}catch(e){return}}):a&&"function"==typeof a.serialize?a.serialize():"string"==typeof a?a:JSON.stringify(a)]})(r);t.next({type:"message",data:o}),e.debug(`SSE observer ${this.observerId} event pushed to client`)})}};e.verbose(`Registering observer ${r} across ${this.adapters.length} adapter(s)`);for(const t of this.adapters){const a=t?.constructor?.name??"UnknownAdapter";try{e.debug(`Registering observer ${r} in adapter ${a}`),t.observe(o)}catch(t){e.debug(`Failed to register observer ${r} in adapter ${a}: ${t?.message||t}`),e.error(t)}}return()=>{e.debug("Cleaning up SSE observer "+r);for(const t of this.adapters){const a=t?.constructor?.name??"UnknownAdapter";try{e.debug(`Unregistering observer ${r} from adapter ${a}`),t.unObserve(o)}catch(t){e.debug(`Failed during cleanup of observer ${r} in adapter ${a}: ${t?.message||t}`),e.error(t)}}}}),r=u.interval(15e3).pipe(y.tap(()=>{e.debug("Sending heartbeat")}),y.map(()=>({type:"heartbeat",data:{ts:(new Date).toISOString()}})));return u.merge(t,r)}listenForModel(e){const t=l.Logging.for(Ee.name);return new u.Observable(e=>{const r=new class{refresh(...t){return Promise.resolve().then(()=>{e.next({data:t})})}};try{for(const e of this.adapters)e.observe(r)}catch(t){e.error("Failed to observe event: "+(t.message||t))}return()=>{try{for(const e of this.adapters)e.unObserve(r)}catch(e){t.error(e)}}})}},p.__decorate([o.Sse(),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[]),p.__metadata("design:returntype",u.Observable)],e.EventsController.prototype,"listen",null),p.__decorate([o.Sse("/:model"),p.__param(0,o.Query("model")),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String]),p.__metadata("design:returntype",u.Observable)],e.EventsController.prototype,"listenForModel",null),e.EventsController=Ee=p.__decorate([o.Controller(),p.__param(1,o.Inject(be)),p.__metadata("design:paramtypes",[e.DecafRequestContext,Array])],e.EventsController),e.DecafStreamModule=Pe=class{static forFlavours(t,r="events"){return{module:Pe,controllers:[e.EventsController],imports:[d.RouterModule.register([{path:r.replace(/^\//,""),module:Pe}])],providers:[e.DecafRequestContext,{provide:be,useValue:t??[]}]}}},e.DecafStreamModule=Pe=p.__decorate([o.Module({})],e.DecafStreamModule),e.DecafModule=Oe=class{static async forRootAsync(t){const{autoControllers:r,autoServices:o}=t,a=(await e.DecafCoreModule.bootPersistence(t)).map(e=>e.flavour),s=[e.DecafCoreModule.forRoot(t)];return r&&a.forEach(e=>{s.push(le(e).forRoot(e,{autoServices:o}))}),t.observerOptions?.enableObserverEvents&&s.push(e.DecafStreamModule.forFlavours(t.observerOptions.observerFlavours||a)),{module:Oe,imports:s}}},e.DecafModule=Oe=p.__decorate([o.Module({})],e.DecafModule);const ve=l.Logging.for("DecafMigrationModule");e.DecafMigrationModule=Re=class{static forRoot(){return{module:Re}}static async migrate(e,t){const r=ve.for(this.migrate);if(!t||0===t.length)throw new c.InternalError("No adapters provided. Make sure DecafCoreModule is configured and adapters are available.");return r.info("Running migrations with config: "+JSON.stringify(e)),g.MigrationService.migrateAdapters(t,e||{})}},e.DecafMigrationModule=Re=p.__decorate([o.Global(),o.Module({providers:[{provide:"MIGRATION_ADAPTERS",useFactory:e=>e,inject:[k]}],exports:["MIGRATION_ADAPTERS"]})],e.DecafMigrationModule);const we="##VERSION##",De="##PACKAGE##";t.Metadata.allowReregistration(!0),t.Metadata.registerLibrary(De,we),t.Metadata.allowReregistration(!1),e.AUTH_HANDLER=K,e.AUTH_META_KEY=B,e.ApiOperationFromModel=T,e.ApiParamsFromModel=C,e.ApiProperty=w,e.Auth=H,e.BulkApiOperationFromModel=(e,r,a)=>{const s={GET:[c.BulkCrudOperationKeys.READ_ALL,o.Get],POST:[c.BulkCrudOperationKeys.CREATE_ALL,o.Post],PUT:[c.BulkCrudOperationKeys.UPDATE_ALL,o.Put],PATCH:[c.BulkCrudOperationKeys.UPDATE_ALL,o.Patch],DELETE:[c.BulkCrudOperationKeys.DELETE_ALL,o.Delete]},[i,p]=s[r];return S(e,i)?t.apply(n.ApiExcludeEndpoint()):t.apply(p(a))},e.COMMIT="4deec24",e.CorsError=ue,e.DECAF_ADAPTER_ID=k,e.DECAF_ADAPTER_OPTIONS=L,e.DECAF_CONTEXT_KEY=U,e.DECAF_HANDLERS=j,e.DECAF_MODULE_OPTIONS=F,e.DECAF_ROUTE=N,e.DECAF_TASK_SERVICE_ID="DecafTaskService",e.DECORATORS=E,e.DECORATORS_PREFIX=b,e.DecafAuthHandler=G,e.DecafBody=x,e.DecafController=Z,e.DecafModelController=ee,e.DecafParams=I,e.DecafQuery=$,e.DecafRoleAuthHandler=class extends G{constructor(){super()}async authorize(e,r){const o=e.switchToHttp().getRequest(),i=this.parseRequest(o);if(!i)throw new s.AuthorizationError("Unauthenticated");const n=t.Metadata.get(a.Model.get(r),s.PersistenceKeys.AUTH_ROLE);if(!n.includes(i))throw new s.AuthorizationError("Missing role: "+i);return n}},e.DtoFor=oe,e.FULL_VERSION="0.11.1-4deec24",e.FromModelController=de,e.HttpVerbToDecorator=q,e.NestBootstraper=class{static get logger(){return this._logger||(this._logger=new o.Logger("NestBootstrap")),this._logger}static initialize(e){return this.app=e,this}static enableLogger(e){return this._logger=e||new o.Logger("NestBootstrap"),this.app.useLogger(this._logger),this}static enableCors(e=[],t=["GET","POST","PUT","DELETE"]){const r="*"===e?"*":e.map(e=>e.trim().toLowerCase()),o={origin:(e,t)=>e?"*"===r||Array.isArray(r)&&r.includes(e.toLowerCase())?t(null,!0):void t(new ue(`Origin ${e} not allowed`)):t(null,!0),credentials:!0,methods:t.join(",")};return this.app.enableCors(o),this}static useHelmet(e){try{const t=require("helmet");this.app.use(t(e)),this.logger.log("Helmet middleware enabled successfully.")}catch(e){this.logger.warn("Helmet not installed. Skipping middleware.")}return this}static setupSwagger(e){return new ye(this.app,{title:e.title,description:e.description,version:e.version,path:e.path||"api",persistAuthorization:e.persistAuthorization??!0,assetsPath:e.assetsPath,faviconFilePath:e.faviconPath,topbarIconFilePath:e.topbarIconPath,topbarBgColor:e.topbarBgColor,openApiJsonPath:e.openApiJsonPath,openApiYamlPath:e.openApiYamlPath}).setupSwagger(),this}static useGlobalPipes(...e){return e.length>0&&this.app.useGlobalPipes(...e),this}static useGlobalFilters(...t){return this.app.useGlobalFilters(...t.length>0?t:[new e.DecafExceptionFilter]),this}static useGlobalInterceptors(...e){return e.length>0&&this.app.useGlobalInterceptors(...e),this}static async start(e=Number(process.env.PORT)||3e3,t=void 0,r=!0){this.app.listen(e,t).then(async()=>{if(r){const e=await this.app.getUrl();this.logger.log("\ud83d\ude80 Application is running at: "+e)}})}},e.PACKAGE_NAME=De,e.RequestToContextTransformer=class{},e.SwaggerBuilder=ye,e.UseDecafFilter=()=>o.UseFilters(new e.DecafExceptionFilter),e.UseDecafHeaders=()=>o.UseInterceptors(e.DecafResponseInterceptor),e.VERSION=we,e.createApiPropertyDecorator=D,e.createPropertyDecorator=v,e.getEnumType=R,e.getEnumValues=O,e.getModuleFor=le,e.isOperationBlocked=S,e.isUndefined=P,e.repoForModel=e=>{const t=a.Model.get(e);if(!t)throw new c.InternalError("Failed to find repository for "+e);return s.Repository.forModel(t)},e.requestToContextTransformer=Ae,e.runMigrations=async()=>{}},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/decoration"),require("@decaf-ts/injectable-decorators"),require("@nestjs/common"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/core"),require("lodash"),require("@nestjs/swagger"),require("@decaf-ts/db-decorators"),require("tslib"),require("@nestjs/core"),require("@decaf-ts/logging"),require("rxjs"),require("fs"),require("path"),require("yaml"),require("rxjs/operators"),require("@decaf-ts/core/migrations")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/decoration","@decaf-ts/injectable-decorators","@nestjs/common","@decaf-ts/decorator-validation","@decaf-ts/core","lodash","@nestjs/swagger","@decaf-ts/db-decorators","tslib","@nestjs/core","@decaf-ts/logging","rxjs","fs","path","yaml","rxjs/operators","@decaf-ts/core/migrations"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["for-nest"]={},e.decafTsDecoration,e.decafTsInjectableDecorators,e.nestjsCommon,e.decafTsDecoratorValidation,e.decafTsCore,e.lodash,e.nestjsSwagger,e.decafTsDbDecorators,e.tslib,e.nestjsCore,e.decafTsLogging,e.rxjs,e.fs,e.path,e.yaml,e.operators,e.migrations);
|
|
1
|
+
var e,t;e=this,t=function(e,t,r,o,a,s,n,i,c,p,d,l,u,f,h,m,y,g){"use strict";function A(e){var t=Object.create(null);return e&&Object.keys(e).forEach(r=>{if("default"!==r){var o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,o.get?o:{enumerable:!0,get:()=>e[r]})}}),t.default=e,Object.freeze(t)}var E=A(m);const b="swagger",P={API_OPERATION:b+"/apiOperation",API_RESPONSE:b+"/apiResponse",API_PRODUCES:b+"/apiProduces",API_CONSUMES:b+"/apiConsumes",API_TAGS:b+"/apiUseTags",API_CALLBACKS:b+"/apiCallbacks",API_PARAMETERS:b+"/apiParameters",API_HEADERS:b+"/apiHeaders",API_MODEL_PROPERTIES:b+"/apiModelProperties",API_MODEL_PROPERTIES_ARRAY:b+"/apiModelPropertiesArray",API_SECURITY:b+"/apiSecurity",API_EXCLUDE_ENDPOINT:b+"/apiExcludeEndpoint",API_EXCLUDE_CONTROLLER:b+"/apiExcludeController",API_EXTRA_MODELS:b+"/apiExtraModels",API_EXTENSION:b+"/apiExtension",API_SCHEMA:b+"/apiSchema",API_DEFAULT_GETTER:b+"/apiDefaultGetter",API_LINK:b+"/apiLink"},v=e=>void 0===e;function R(e){if("function"==typeof e)return R(e());if(Array.isArray(e))return e;if("object"!=typeof e)return[];const t=Object.values(e).filter(e=>"number"==typeof e).map(e=>e.toString());return Object.keys(e).filter(e=>!t.includes(e)).map(t=>e[t])}function O(e){return e.filter(n.isString).length>0?"string":"number"}function D(e,t,r=!0){return(o,a)=>{const s=Reflect.getMetadata(P.API_MODEL_PROPERTIES_ARRAY,o)||[],i=":"+a;s.includes(i)||Reflect.defineMetadata(P.API_MODEL_PROPERTIES_ARRAY,[...s,":"+a],o);const c=Reflect.getMetadata(e,o,a);if(c){const s=n.pickBy(t,n.negate(v)),i=r?{...c,...s}:{...s,...c};Reflect.defineMetadata(e,i,o,a)}else{const r=o?.constructor?._OPENAPI_METADATA_FACTORY?.()[a]?.type??Reflect.getMetadata("design:type",o,a);Reflect.defineMetadata(e,{type:r,required:!1,...n.pickBy(t,n.negate(v))},o,a)}}}function S(e={}){return _(e)}function _(e={},t=!0){const[r,o]=((e,t)=>{if(!e)return[e,t];if(t)return[e,t];const r=n.isArray(e);return[r?e[0]:e,r]})(e.type,e.isArray);if((a=e={...e,type:r,isArray:o}).isArray&&"enum"in a&&void 0!==a.enum){e.type="array";const t=R(e.enum);e.items={type:O(t),enum:t},delete e.enum}else if("enum"in e&&void 0!==e.enum){const t=R(e.enum);e.enum=t,e.type=O(t)}var a;return Array.isArray(e.type)&&(e.type="array",e.items={type:"array",items:{type:e.type[0]}}),D(P.API_MODEL_PROPERTIES,e,t)}function C(e,r,a){const n={GET:[c.OperationKeys.READ,o.Get],POST:[c.OperationKeys.CREATE,o.Post],PUT:[c.OperationKeys.UPDATE,o.Put],PATCH:[c.OperationKeys.UPDATE,o.Patch],DELETE:[c.OperationKeys.DELETE,o.Delete]},[p,d]=n[r],l=T(r,a);return l?s.isOperationBlocked(e,l.kind,l.value)?t.apply(i.ApiExcludeEndpoint()):t.apply(d(a)):s.isOperationBlocked(e,p)?t.apply(i.ApiExcludeEndpoint()):t.apply(d(a))}function T(e,t){if(!t)return;const r=t.replace(/^\/+|\/+$/g,""),o={"listBy/:key":s.PreparedStatementKeys.LIST_BY,"paginateBy/:key/:page":s.PreparedStatementKeys.PAGE_BY,"find/:value":s.PreparedStatementKeys.FIND,"page/:value":s.PreparedStatementKeys.PAGE,"findOneBy/:key/:value":s.PreparedStatementKeys.FIND_ONE_BY,"findBy/:key/:value":s.PreparedStatementKeys.FIND_BY,"statement/:method/*args":"statement","countOf/:field":s.PreparedStatementKeys.COUNT_OF,"maxOf/:field":s.PreparedStatementKeys.MAX_OF,"minOf/:field":s.PreparedStatementKeys.MIN_OF,"avgOf/:field":s.PreparedStatementKeys.AVG_OF,"sumOf/:field":s.PreparedStatementKeys.SUM_OF,"distinctOf/:field":s.PreparedStatementKeys.DISTINCT_OF,"groupOf/:field":s.PreparedStatementKeys.GROUP_OF};if(r.startsWith("query/"))return{kind:"query",value:r.replace(/^query\//,"")};const a=o[r];return a?{kind:"statement",value:a}:"GET"===e&&""===r?{kind:"crud",value:c.OperationKeys.READ}:void 0}function M(e=[]){const t=e.map(e=>i.ApiParam({name:e.name,description:e.description??"Path parameter: "+e.name,required:e.required??!0,type:e.type??String}));return o.applyDecorators(...t)}const x=o.createParamDecorator((e,t)=>{const r=t.switchToHttp().getRequest().body,a=t.getClass(),s=a.class;if(!s)throw new o.InternalServerErrorException(`ModelConstructor not found on controller ${a.name}. Ensure the controller was created via FromModelController.`);return r?Array.isArray(r)?r.map(e=>new s(e)):new s(r):r}),I=o.createParamDecorator((e,t)=>{const r=t.switchToHttp().getRequest(),o=r?.params??{},a=e??Object.keys(o),s=a.map(e=>o[e]);return{raw:o,valuesInOrder:s,keysInOrder:a}});function w(e=[]){const t=e.map(e=>e.name);return I(t)}const q=o.createParamDecorator((e,t)=>{const r={...t.switchToHttp().getRequest().query??{}};if(void 0!==r.limit){const e=Number(r.limit);Number.isNaN(e)||(r.limit=e)}if(void 0!==r.offset){const e=Number(r.offset);Number.isNaN(e)||(r.offset=e)}if(void 0!==r.bookmark){const e=Number(r.bookmark);r.bookmark=Number.isNaN(e)?r.bookmark:e}return r}),N="DecafModuleOptions",k="DecafAdapter",F="DecafRoute",$=Symbol("DecafHandlers"),j="DecafExpose",B="DecafControllerConfig",L=Symbol("decaf:context"),U=Symbol("AUTH_HANDLER"),K="auth:meta",H="isPublic",G="requiredRoles",Q="skipModelRoles";function z(t){const r=t?"string"==typeof t?t:t.name:void 0,a=[i.ApiBearerAuth(),o.UseInterceptors(e.AuthInterceptor)];return r&&a.push(o.SetMetadata(K,r)),o.applyDecorators(...a)}function W(){return o.applyDecorators(o.SetMetadata(H,!0))}function Y(...t){return o.applyDecorators(i.ApiSecurity("bearer"),o.SetMetadata(G,t),o.UseInterceptors(e.AuthInterceptor))}function V(e){const t={GET:o.Get,POST:o.Post,PUT:o.Put,PATCH:o.Patch,DELETE:o.Delete}[e];if(!t)throw new s.UnsupportedError(`Unsupported HTTP verb "${e}". No NestJS decorator mapping was found.`);return t}e.DecafRequestContext=class extends u.RequestContext{constructor(e){super({headersOf:e=>e?.headers||void 0},e),this.req=e,this.uuid=s.UUID.instance.generate(),this.request=e}get headers(){return this.getOrUndefined("headers")}put(e){let t;try{t=this.get("overrides")}catch(e){t={}}this.accumulate({overrides:Object.assign(t,e)})}},e.DecafRequestContext=p.__decorate([o.Injectable({scope:o.Scope.REQUEST}),p.__param(0,o.Inject(d.REQUEST)),p.__metadata("design:paramtypes",[Object])],e.DecafRequestContext),e.AuthInterceptor=class{constructor(e,t,r){this.reflector=e,this.requestContext=t,this.authHandler=r}async intercept(e,t){const r=l.Logging.for(this).for(this.intercept),o=this.reflector.getAllAndOverride(H,[e.getHandler(),e.getClass()]),a=this.reflector.get(K,e.getHandler())??this.reflector.get(K,e.getClass()),s=this.reflector.getAllAndOverride(G,[e.getHandler(),e.getClass()]),n=this.reflector.getAllAndOverride(Q,[e.getHandler(),e.getClass()])?void 0:a;r.verbose("Intercepted request"+(a?" for "+a:"")),o?r.debug("Public route \u2014 skipping auth"):this.authHandler?await this.authHandler.authorize(e,n,s,this.requestContext):r.debug("No auth handler registered"),await this.applyTransformers();const i=this.requestContext.getOrUndefined("user"),c=this.requestContext.getOrUndefined("organization");if(i||c){const e=this.requestContext.get("logger").for({user:i,organization:c});this.requestContext.accumulate({logger:e})}return t.handle()}async applyTransformers(){const e=s.Adapter.flavoursToTransform();if(e)for(const t of e){const e=s.Adapter.transformerFor(t);if(!e)continue;const r=e.from?e:new e,o=await r.from(this.requestContext);o&&this.requestContext.accumulate(o)}}},e.AuthInterceptor=p.__decorate([o.Injectable({scope:o.Scope.REQUEST}),p.__param(2,o.Optional()),p.__param(2,o.Inject(U)),p.__metadata("design:paramtypes",[d.Reflector,e.DecafRequestContext,Object])],e.AuthInterceptor);const X=e=>({name:e,description:e+" parameter for the query",required:!0,type:String});function J(e,t,...r){if(e instanceof s.ModelService)return"function"==typeof e[t]?e[t](...r):e.statement(t,...r);if("function"==typeof e[t])return e[t](...r);throw new c.InternalError(`Persistence method "${t}" not found on ${e?.constructor?.name}`)}class Z extends u.AuthHandler{parseRequest(e){const t=e.headers.authorization?.split(" ")[1];return t}extractFromAuth(e){const t=e.switchToHttp().getRequest(),r=this.parseRequest(t);if(!r)throw new s.AuthorizationError("Unauthenticated");return{user:r,roles:[r]}}}var ee,te;e.DecafAuthModule=ee=class{static forRoot(t={}){const r=[e.AuthInterceptor];return t.handler&&(r.push(t.handler),r.push({provide:U,useClass:t.handler})),t.global&&r.push({provide:d.APP_INTERCEPTOR,useExisting:e.AuthInterceptor}),{module:ee,global:t.global??!1,providers:r,exports:[e.AuthInterceptor,U]}}},e.DecafAuthModule=ee=p.__decorate([o.Module({})],e.DecafAuthModule),e.DecafHandlerExecutor=te=class{constructor(e,t){this.handlers=e,this.context=t}async exec(e,t){l.Logging.for(te.name).for(this.exec).debug(`CONTEXT ${this.context.uuid} running ${this.handlers.length} handlers for request ${e.method} ${e.url}`);for(const r of this.handlers)await r.handle(this.context,e,t)}},e.DecafHandlerExecutor=te=p.__decorate([o.Injectable({scope:o.Scope.REQUEST}),p.__param(0,o.Inject($)),p.__metadata("design:paramtypes",[Array,e.DecafRequestContext])],e.DecafHandlerExecutor),e.DecafResponseInterceptor=class{constructor(e){this.ctx=e}intercept(e,t){let r=e.switchToHttp().getResponse();return t.handle().pipe(f.tap(e=>{r=this.ctx.toResponse(r)}))}},e.DecafResponseInterceptor=p.__decorate([o.Injectable(),p.__metadata("design:paramtypes",[e.DecafRequestContext])],e.DecafResponseInterceptor);class re extends u.DecafController{constructor(e,t){super(e),this.clientContext=e}}class oe extends re{constructor(e,t){super(e,t),this.clientContext=e}persistence(e){if(!this._persistence)try{this._persistence=s.Service.get(this.class)}catch{try{this._persistence=s.ModelService.getService(this.class)}catch{this._persistence=s.Repository.forModel(this.class)}}const t=(e??this.clientContext).toOverrides();return e?this._persistence instanceof s.Repository?this._persistence.override(t):this._persistence.for(t):this._persistence}}const ae=new Map;function se(e,r,o=new Set){if(!s.TransactionOperationKeys.includes(e))return r;const n=(e=>(ae.has(e)||ae.set(e,new WeakMap),ae.get(e)))(e),i=n.get(r);if(i)return i;const p=[c.OperationKeys.UPDATE,c.BulkCrudOperationKeys.UPDATE_ALL].includes(e);class d{}n.set(r,d),Object.defineProperty(d,"name",{value:`${l.toPascalCase(r.name)}${l.toPascalCase(e)}DTO`});const u=(()=>{try{return a.Model.pk(r)}catch{return}})(),f=u?a.Model.pkProps(r):void 0,h=u?Reflect.getMetadata("design:type",r.prototype,u):void 0,m=h===Number||h===BigInt,y=!!f?.generated||!!u&&(a.Model.generatedBySequence(r,u)||de(r,u)||m),g=Array.from(new Set(t.Metadata.properties(r)||[])),A=new Set(a.Model.relations(r)||[]),E=[];for(const e of g)e&&(A.has(e)||e===u&&!p&&y||e!==u&&de(r,e)||E.push(e));for(const e of E){const t=le(r,e),o=!!t?.[a.ValidationKeys.REQUIRED],s=ue(r,e)??Reflect.getMetadata("design:type",r.prototype,e),n={required:o};s&&(n.type=s),S(n)(d.prototype,e);const i=Reflect.getMetadata("design:type",r.prototype,e)??s;void 0!==i&&Reflect.defineMetadata("design:type",i,d.prototype,e),Object.defineProperty(d.prototype,e,{value:void 0,writable:!0,enumerable:!0,configurable:!0})}for(const s of A){const n=t.Metadata.relations(r,s);if(!n)throw new c.InternalError(`Metadata for relation ${s} not found`);let i=n.class;if("function"!=typeof i||i.name||(i=i()),!i||"function"!=typeof i)throw new c.InternalError(`Type for relation ${s} not found`);if(!a.Model.get(i.name))continue;const l=t.Metadata.validationFor(r,s),u=!!l?.[a.ValidationKeys.LIST],f=!!l?.[a.ValidationKeys.REQUIRED];if(o.has(i)){ie(d,s,pe(i),u,f);continue}const h=se(e,i,new Set(o).add(r));p?ce(d,s,i,h,u,f):ne(d,s,h,u,f)}return d}function ne(e,t,r,o,a){S({type:r,required:a,isArray:o})(e.prototype,t),Reflect.defineMetadata("design:type",o?Array:r,e.prototype,t),Object.defineProperty(e.prototype,t,{value:void 0,writable:!0,enumerable:!0,configurable:!0})}function ie(e,t,r,o,a){S(o?{type:"array",items:{type:r},required:a}:{type:"integer"===r?Number:String,required:a})(e.prototype,t),Reflect.defineMetadata("design:type",o?Array:"integer"===r?Number:String,e.prototype,t),Object.defineProperty(e.prototype,t,{value:void 0,writable:!0,enumerable:!0,configurable:!0})}function ce(e,t,r,o,a,s){const n=Reflect.getMetadata(P.API_EXTRA_MODELS,e)||[];n.includes(o)||Reflect.defineMetadata(P.API_EXTRA_MODELS,[...n,o],e);const i=[{$ref:"#/components/schemas/"+o.name},{type:pe(r)}];S(a?{type:"array",required:s,oneOf:i}:{type:Object,required:s,oneOf:i})(e.prototype,t),Reflect.defineMetadata("design:type",a?Array:Object,e.prototype,t),Object.defineProperty(e.prototype,t,{value:void 0,writable:!0,enumerable:!0,configurable:!0})}function pe(e){try{const t=a.Model.pkProps(e),r=t?.type;return r===Number||r===BigInt?"integer":"string"}catch{return"string"}}function de(e,t){let r=e;for(;r&&r!==Object&&r!==Function;){if(a.Model.generated(r,t))return!0;r=Object.getPrototypeOf(r)}return!1}function le(e,r){let o=e;for(;o&&o!==Object&&o!==Function;){const e=t.Metadata.validationFor(o,r);if(e)return e;o=Object.getPrototypeOf(o)}}function ue(e,r){let o=e;for(;o&&o!==Object&&o!==Function;){const e=t.Metadata.type(o,r);if(e)return e;o=Object.getPrototypeOf(o)}}s.Adapter.transformerFor=(e=>{const r="string"==typeof e?e:e.alias;return t.Metadata.innerGet(Symbol.for("transformers"),r)}).bind(s.Adapter),s.Adapter.flavoursToTransform=(()=>{const e=t.Metadata.innerGet(Symbol.for("transformers"));if(e)return Object.keys(e)}).bind(s.Adapter),s.Context.prototype.toResponse=function(e){const t=this.pending();return t&&e.header("x-pending-task",JSON.stringify(t)),e};const fe=a.ModelBuilder.prototype;if(fe.decorateClass||(fe.decorateClass=function(e){return this._classDecorators||(this._classDecorators=[]),this._classDecorators.push(e),this}),fe.Auth=function(e){return this.decorateClass(z(e))},!fe.__hasClassDecoratorSupport){const e=fe.build;fe.build=function(){let t=e.call(this);const r=this._classDecorators;if(r?.length)for(const e of r){const r=e(t);r&&(t=r)}return t},fe.__hasClassDecoratorSupport=!0}var he;class me{static{this.log=l.Logging.for(me.name)}static toDecafError(e,t){return e instanceof c.BaseError?e:new c.InternalError(e instanceof Error?`${t}: ${e.message}`:t)}static getPersistence(e){try{return s.Service.get(e)}catch(t){try{return s.ModelService.getService(e)}catch(t){return s.Repository.forModel(e)}}}static createQueryRoutesFromRepository(e,r=s.PersistenceKeys.QUERY){const o=e instanceof s.ModelService?e.repo:e,a=t.Metadata.get(o.constructor,t.Metadata.key(s.PersistenceKeys.QUERY))??{},n=t.Metadata.get(e.constructor,t.Metadata.key(F))??{};class i extends oe{get class(){throw new c.InternalError("Method not implemented.")}constructor(e,t){super(e,t)}}for(const[e,t]of Object.entries(n)){const r=[t.path.replace(/^\/+|\/+$/g,"")].filter(e=>e&&e.trim()).join("/"),o=me.createComplexQueryHandler(e);me.defineMethod(i,e,o);const a=V(t.httpMethod)(r||void 0),s=me.getQueryDecorators(e,r,t.httpMethod);me.applyDecorators(i,e,[a,...s])}for(const[e,t]of Object.entries(a)){const o=[r,e,...(t.fields??[]).map(e=>":"+e)].filter(e=>e&&e.trim()).join("/"),a=me.createComplexQueryHandler(e);me.defineMethod(i,e,a);const s=V("GET")(o||void 0),n=me.getQueryDecorators(e,o,"GET",!0);me.applyDecorators(i,e,[s,...n])}return i}static create(r,n,c){const d=me.log.for(me.create),f=a.Model.tableName(r),h=l.toKebabCase(f),m=r.name,y=me.getPersistence(r),g=y instanceof s.ModelService?y.repo:y,A=t.Metadata.get(r,t.Metadata.key(B)),E=n?.[r.name],b={...c||{},...A||{},...E||{}},P=u.ModelControllerFactory.create(r,g,b).__routes__,{getPK:v,apiProperties:R,path:O}=me.getRouteParametersFromModel(r);d.debug(`Creating controller for model: ${m} with ${P?.length??0} factory routes`);const D=b.auth;let S=he=class extends oe{static get class(){return r}get class(){return r}constructor(e){super(e,he.name),this.pk=a.Model.pk(r),d.info(`Registering dynamic controller for model: ${this.class.name} route: /${h}`)}};var _;if(S=he=p.__decorate([o.Controller(h),i.ApiTags(m),i.ApiExtraModels(r),p.__metadata("design:paramtypes",[e.DecafRequestContext])],S),_=S,D?.public?W()(_):D?.roles?.length?Y(...D.roles)(_):z(r)(_),D?.skipModelRoles&&o.SetMetadata(Q,!0)(_),P){const e=[...P].sort((e,t)=>{const r=e.path.split("/").filter(Boolean),o=t.path.split("/").filter(Boolean),a=r.filter(e=>e.startsWith(":")).length,s=o.filter(e=>e.startsWith(":")).length,n=r.length-a,i=o.length-s;return n!==i?i-n:a!==s?a-s:0});for(const t of e){const e=t.implementation?.name||t.method.toLowerCase(),o=me.matchRoute(e,t,O,R,v,r,m);if(!o)continue;const{methodName:a,handler:s,decorators:n,paramDecorators:i}=o;if(me.defineMethod(S,a,s)){const e=V(t.method)(t.path.replace(/^\/+|\/+$/g,"")||void 0);me.applyDecorators(S,a,[e,...n],i)}}}return S}static getRouteParametersFromModel(e){const r=a.Model.pk(e),o=t.Metadata.get(e,t.Metadata.key(c.DBKeys.COMPOSED,r)),s=o?.args??[],n=Array.isArray(s)&&s.length>0?Array.from(new Set([...s])):Array.from(new Set([r])),i=t.Metadata.description(e)??"";return{path:":"+n.join("/:"),description:i,apiProperties:n.map(r=>({name:r,description:t.Metadata.description(e,r),required:!0,type:String})),getPK:(...e)=>o?.separator?e.join(o.separator):e.join("")}}static routeParamDecorators(e){let t=0;return e.split("/").filter(Boolean).flatMap(e=>e.startsWith(":")||e.startsWith("*")?[{decorator:o.Param(e.slice(1)),index:t++}]:[])}static defineMethod(e,t,r){return Object.defineProperty(e.prototype||e,t,{value:r,writable:!1,configurable:!0,enumerable:!1}),Object.getOwnPropertyDescriptor(e.prototype||e,t)}static applyDecorators(e,t,r,o=[]){const a=e?.prototype??e,s=Object.getOwnPropertyDescriptor(a,t);r.forEach(e=>e(a,t,s)),o.forEach(({decorator:e,index:r})=>e(a,t,r))}static matchRoute(e,t,r,a,n,c,p){const{method:d,path:l}=t,u=l.replace(/^\/+|\/+$/g,""),f=t.implementation;if("POST"===d&&""===u)return me.createRegistration("create",f,me.createCreateDecorators(c,p),[{decorator:x(),index:0},{decorator:o.Response({passthrough:!0}),index:1}]);if("POST"===d&&"bulk"===u)return me.createRegistration("createAll",f,me.bulkCreateDecorators(c,p),[{decorator:x(),index:0},{decorator:o.Response({passthrough:!0}),index:1}]);if("GET"===d&&"bulk"===u)return me.createRegistration("readAll",f,me.bulkReadDecorators(c,p),[{decorator:o.Query("ids"),index:0}]);if("PUT"===d&&"bulk"===u)return me.createRegistration("updateAll",f,me.bulkUpdateDecorators(c,p,a),[{decorator:x(),index:0},{decorator:o.Response({passthrough:!0}),index:1}]);if("DELETE"===d&&"bulk"===u)return me.createRegistration("deleteAll",f,me.bulkDeleteDecorators(c,p,a),[{decorator:o.Query("ids"),index:0},{decorator:o.Response({passthrough:!0}),index:1}]);if("GET"===d&&u===r)return me.createRegistration("read",f,me.readDecorators(c,p,a,r),me.routeParamDecorators(u));if("PUT"===d&&u===r){const e=me.routeParamDecorators(u);return me.createRegistration("update",f,me.updateDecorators(c,p,a,r),[{decorator:x(),index:0},...e.map(({decorator:e,index:t})=>({decorator:e,index:t+1}))])}if("DELETE"===d&&u===r){const e=me.routeParamDecorators(u);return me.createRegistration("delete",f,me.deleteDecorators(c,p,a,r),e)}const h=u.split("/").filter(Boolean);if(h.length>0&&h.every(e=>e.startsWith(":"))&&u!==r){const e=h.map(e=>e.slice(1)).map(e=>({name:e,description:e+" parameter",required:!0,type:String})),t=h.map(e=>e.slice(1)).join("And"),r=me.routeParamDecorators(u);if("GET"===d)return me.createRegistration("readBy"+t,f,me.readDecorators(c,p,e,u),r);if("PUT"===d)return me.createRegistration("updateBy"+t,f,me.updateDecorators(c,p,e,u),[{decorator:x(),index:0},...r.map(({decorator:e,index:t})=>({decorator:e,index:t+1}))]);if("DELETE"===d)return me.createRegistration("deleteBy"+t,f,me.deleteDecorators(c,p,e,u),r)}if("GET"===d&&"statement/:method/*args"===u)return me.createRegistration("statement",f,me.statementDecorators(c,p),[{decorator:o.Param("method"),index:0},{decorator:o.Param("args"),index:1},{decorator:q(),index:2}]);if("GET"===d&&"findOneBy/:key/:value"===u)return me.createRegistration("findOneBy",f,me.statementShortcutDecorators(c,p,u,s.PreparedStatementKeys.FIND_ONE_BY),me.statementShortcutParams(u));const m={"listBy/:key":s.PreparedStatementKeys.LIST_BY,"paginateBy/:key/:page":s.PreparedStatementKeys.PAGE_BY,"find/:value":s.PreparedStatementKeys.FIND,"page/:value":s.PreparedStatementKeys.PAGE,"findOneBy/:key/:value":s.PreparedStatementKeys.FIND_ONE_BY,"findBy/:key/:value":s.PreparedStatementKeys.FIND_BY,"countOf/:field":s.PreparedStatementKeys.COUNT_OF,"maxOf/:field":s.PreparedStatementKeys.MAX_OF,"minOf/:field":s.PreparedStatementKeys.MIN_OF,"avgOf/:field":s.PreparedStatementKeys.AVG_OF,"sumOf/:field":s.PreparedStatementKeys.SUM_OF,"distinctOf/:field":s.PreparedStatementKeys.DISTINCT_OF,"groupOf/:field":s.PreparedStatementKeys.GROUP_OF}[u];if(m&&"GET"===d)return me.createRegistration(me.statementMethodName(u),f,me.statementShortcutDecorators(c,p,u,m),me.statementShortcutParams(u));if("GET"===d&&u.startsWith("query/")){const e=u.replace(/^query\//,"").split("/")[0];return me.createRegistration(e,f,me.getQueryDecorators(e,u,"GET",!0),me.complexQueryParams(u))}const y=u.split("/").filter(Boolean),g=new Set(["listBy","findBy","findByPaginate","findOneBy","paginateBy","find","page","countOf","maxOf","minOf","avgOf","sumOf","distinctOf","groupOf","statement","bulk","query"]);if(y.length>0&&!u.startsWith("query/")&&!u.startsWith("statement/")&&!g.has(y[0])){const t=y.filter(e=>e.startsWith(":")).map(e=>e.slice(1)).map(e=>({name:e,description:e+" parameter for the query",required:!0,type:String}));return me.createRegistration(e,f,[...t.map(e=>i.ApiParam(e)),i.ApiOperation({summary:`Retrieve records using "${e}".`}),i.ApiOkResponse({description:"Result successfully retrieved."}),i.ApiNoContentResponse({description:"No content returned by the method."})],me.routeParamDecorators(u))}}static createRegistration(e,t,r,o){return{methodName:e,handler:t,decorators:r,paramDecorators:o}}static statementMethodName(e){return e.split("/")[0]}static statementShortcutParams(e){const t=e.split("/").filter(e=>e.startsWith(":")),r=[];return t.forEach((e,t)=>{const a=e.replace(":","");r.push({decorator:o.Param(a),index:t})}),(e.startsWith("listBy/")||e.startsWith("paginateBy/")||e.startsWith("find/")||e.startsWith("page/"))&&r.push({decorator:q(),index:t.length}),r}static complexQueryParams(e){const t=e.split("/").filter(e=>e.startsWith(":")),r=[];return t.forEach((e,t)=>{const a=e.replace(":","");r.push({decorator:o.Param(a),index:t})}),e.startsWith("query/")&&r.push({decorator:q(),index:t.length}),r}static createComplexQueryHandler(e){return async function t(...r){const o=this.log?.for?.(t);try{o&&o.debug(`Invoking custom query "${e}"`);const{ctx:a}=(await this.logCtx([],e,!0)).for(t),s=this.persistence(a),n=me.normalizeQueryArgs(r);if(s?.repo&&"function"==typeof s.repo[e])return s.repo[e](...n);if("function"==typeof s[e])return s[e](...n);if(s?.query&&"function"==typeof s.query)return s.query(e,...n);if("function"==typeof s.statement)return s.statement(e,...n,a);throw new c.InternalError(`Persistence method "${e}" not found on ${s?.constructor?.name}`)}catch(t){throw o&&o.error(`Custom query "${e}" failed`,t),me.toDecafError(t,`Custom query "${e}" failed`)}}}static extractQueryArgs(e){if(0===e.length)return e;const t=e[e.length-1];if(t&&"object"==typeof t&&!Array.isArray(t)){const t=e.pop(),r=void 0!==t.direction,o=void 0!==t.limit,a=void 0!==t.offset;if(!r&&!o&&!a)return e;const s=[];return r?s.push(t.direction):(o||a)&&s.push(void 0),o&&s.push(t.limit),a&&s.push(t.offset),[...e,...s]}return e}static normalizeQueryArgs(e){const t=me.extractQueryArgs(e);if(0===t.length)return t;const r=t[t.length-1];if(!r||"object"!=typeof r||Array.isArray(r))return t;const o=r;return void 0!==o.direction||void 0!==o.limit||void 0!==o.offset||void 0!==o.bookmark?(t.pop(),void 0!==o.direction&&t.push(o.direction),void 0!==o.limit&&t.push(o.limit),void 0!==o.offset&&t.push(o.offset),void 0!==o.bookmark&&t.push(o.bookmark),t):(t.pop(),t)}static createCreateDecorators(e,t){return[C(e,"POST"),i.ApiOperation({summary:`Create a new ${t}.`}),i.ApiBody({description:"Payload for "+t,type:se(c.OperationKeys.CREATE,e)}),i.ApiCreatedResponse({description:t+" created successfully.",schema:{$ref:i.getSchemaPath(e)}}),i.ApiBadRequestResponse({description:"Payload validation failed."}),i.ApiUnprocessableEntityResponse({description:"Repository rejected the provided payload."})]}static bulkCreateDecorators(e,t){return[C(e,"POST","bulk"),i.ApiOperation({summary:`Create a new ${t}.`}),i.ApiBody({description:"Payload for "+t,schema:{type:"array",items:{$ref:i.getSchemaPath(e)}}}),i.ApiCreatedResponse({description:t+" created successfully.",schema:{type:"array",items:{$ref:i.getSchemaPath(e)}}}),i.ApiBadRequestResponse({description:"Payload validation failed."}),i.ApiUnprocessableEntityResponse({description:"Repository rejected the provided payload."})]}static bulkReadDecorators(e,t){return[C(e,"GET","bulk"),i.ApiOperation({summary:`Retrieve ${t} records by ids.`}),i.ApiQuery({name:"ids",required:!0,type:"array"}),i.ApiOkResponse({description:t+" retrieved successfully.",schema:{type:"array",items:{$ref:i.getSchemaPath(e)}}}),i.ApiNotFoundResponse({description:`No ${t} record matches the provided identifier.`})]}static bulkUpdateDecorators(e,t,r){return[C(e,"PUT","bulk"),M(r),i.ApiOperation({summary:`Replace existing ${t} records with new payloads.`}),i.ApiBody({description:"Payload for replacing existing records of "+t,schema:{type:"array",$ref:i.getSchemaPath(se(c.OperationKeys.UPDATE,e))}}),i.ApiOkResponse({description:t+" updated successfully.",schema:{type:"array",items:{$ref:i.getSchemaPath(e)}}}),i.ApiNotFoundResponse({description:`No ${t} record matches the provided identifier.`}),i.ApiBadRequestResponse({description:"Payload validation failed."})]}static bulkDeleteDecorators(e,t,r){return[C(e,"DELETE","bulk"),M(r),i.ApiOperation({summary:`Delete ${t} records by ids.`}),i.ApiQuery({name:"ids",required:!0,type:"array"}),i.ApiOkResponse({description:t+" deleted successfully.",schema:{type:"array",items:{$ref:i.getSchemaPath(e)}}}),i.ApiNotFoundResponse({description:`No ${t} record matches the provided identifier.`})]}static readDecorators(e,t,r,o){return[C(e,"GET",o),M(r),i.ApiOperation({summary:`Retrieve a ${t} record by id.`}),i.ApiOkResponse({description:t+" retrieved successfully.",schema:{$ref:i.getSchemaPath(e)}}),i.ApiNotFoundResponse({description:`No ${t} record matches the provided identifier.`})]}static updateDecorators(e,t,r,o){return[C(e,"PUT",o),M(r),i.ApiOperation({summary:`Replace an existing ${t} record with a new payload.`}),i.ApiBody({description:"Payload for replacing an existing record of "+t,type:se(c.OperationKeys.UPDATE,e)}),i.ApiOkResponse({description:t+" updated successfully.",schema:{$ref:i.getSchemaPath(e)}}),i.ApiNotFoundResponse({description:`No ${t} record matches the provided identifier.`}),i.ApiBadRequestResponse({description:"Payload validation failed."})]}static deleteDecorators(e,t,r,o){return[C(e,"DELETE",o),M(r),i.ApiOperation({summary:`Delete a ${t} record by id.`}),i.ApiOkResponse({description:t+" deleted successfully.",schema:{$ref:i.getSchemaPath(e)}}),i.ApiNotFoundResponse({description:`No ${t} record matches the provided identifier.`})]}static statementDecorators(e,t){return[C(e,"GET","statement/:method/*args"),i.ApiOperation({summary:`Executes a prepared statement on ${t}.`}),i.ApiParam({name:"method",description:"the prepared statement to execute"}),i.ApiParam({name:"args",description:"concatenated list of arguments the prepared statement can accept"}),i.ApiQuery({name:"direction",required:!0,enum:s.OrderDirection,description:"the sort order when applicable"}),i.ApiQuery({name:"limit",required:!0,description:"limit or page size when applicable"}),i.ApiQuery({name:"offset",required:!0,description:"offset or bookmark when applicable"}),i.ApiOkResponse({description:t+" listed found."}),i.ApiNotFoundResponse({description:`No ${t} record matches the provided identifier.`})]}static statementShortcutDecorators(e,t,r,o){const a=[C(e,"GET",r),i.ApiOperation({summary:`Retrieve ${t} records.`}),i.ApiOkResponse({description:t+" retrieved successfully."})];return r.split("/").filter(e=>e.startsWith(":")).forEach(e=>{const t=e.replace(":","");a.push(i.ApiParam({name:t,description:`The ${t} parameter`}))}),(r.startsWith("listBy/")||r.startsWith("paginateBy/")||r.startsWith("find/")||r.startsWith("page/"))&&a.push(i.ApiQuery({name:"direction",required:!0,enum:s.OrderDirection,description:"the sort order"})),(r.startsWith("paginateBy/")||r.startsWith("page/"))&&a.push(i.ApiQuery({name:"limit",required:!1,description:"page size"}),i.ApiQuery({name:"offset",required:!1,description:"page number"}),i.ApiQuery({name:"bookmark",required:!1,description:"bookmark for cursor pagination"})),(r.startsWith("findOneBy/")||r.startsWith("findBy/"))&&a.push(i.ApiNotFoundResponse({description:`No ${t} record matches the provided identifier.`})),o!==s.PreparedStatementKeys.COUNT_OF&&o!==s.PreparedStatementKeys.AVG_OF&&o!==s.PreparedStatementKeys.SUM_OF||a.push(i.ApiOkResponse({description:`Result for ${t}.`,type:Number})),o===s.PreparedStatementKeys.DISTINCT_OF&&a.push(i.ApiOkResponse({description:`Distinct values for ${t}.`,type:[String]})),a}static getQueryDecorators(e,t,r,o=!1){var a;const n=[...(a=t,a.split("/").filter(e=>e.startsWith(":")).map(e=>e.slice(1))).map(e=>({name:e,description:e+" parameter for the query",required:!0,type:String})).map(e=>i.ApiParam(e)),i.ApiOperation({summary:`Retrieve records using "${e}".`}),i.ApiOkResponse({description:"Result successfully retrieved."}),i.ApiNoContentResponse({description:"No content returned by the method."})];return"GET"===r&&o&&n.push(i.ApiQuery({name:"direction",required:!1,enum:s.OrderDirection,description:"the sort order when applicable"}),i.ApiQuery({name:"limit",required:!1,description:"limit or page size"}),i.ApiQuery({name:"offset",required:!1,description:"offset or bookmark"})),n}}function ye(e){var r;let a=class{static{r=this}static{this.log=l.Logging.for(r.name).for(e)}static createModelServices(e){return e.map(e=>({provide:e.name+"Service",useFactory:()=>s.ModelService.forModel(e)}))}static isExposed(r,o){const a=o?.[r.name],s=void 0!==a?a:t.Metadata.get(r,t.Metadata.key(j));return void 0===s||!0===s||!!Array.isArray(s)&&s.includes(e)}static forRoot(e,t={}){const o=this.log.for(this.forRoot);o.info("Generating controllers for flavour...");const a=s.Adapter.models(e).filter(e=>this.isExposed(e,t.controllerExposure));for(const e of a)s.ModelService.forModel(e);let n=[];t.autoServices&&(o.info("Auto-services enabled. Initializing service generation."),n=this.createModelServices(a),o.info(`Auto-services completed. ${n.length} services initialized.`));const i={};!1===t.aggregations&&(i.allowGroupingQueries=!1);const c=a.map(e=>me.create(e,t.controllerConfig,i));return o.info(`Generated ${c.length} controllers`),{module:r,controllers:c,providers:[...n]}}};return a=r=p.__decorate([o.Module({})],a),Object.assign(a,"name",{value:"DecafModule"+e}),a}t.Decoration.for(r.InjectablesKeys.INJECTABLE).extend({decorator:(e,t)=>(t=t||("object"==typeof e?Object.assign(e,r.DefaultInjectablesConfig):r.DefaultInjectablesConfig),o.Injectable({scope:t.singleton?o.Scope.DEFAULT:o.Scope.REQUEST,durable:!t.singleton||void 0}))}).apply(),t.Decoration.for(r.InjectablesKeys.INJECT).extend({decorator:(e,t)=>(t,r,a)=>o.Inject(e||t)(t,r,a)}).apply(),t.Decoration.for(a.ValidationKeys.REQUIRED).extend(S({required:!0})).apply(),t.Decoration.for(a.ValidationKeys.MAX).extend({decorator:e=>S({maximum:e,required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.MIN).extend({decorator:e=>S({minimum:e,required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.MAX_LENGTH).extend({decorator:e=>S({maxLength:e,required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.MIN_LENGTH).extend({decorator:e=>S({minLength:e,required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.TYPE).extend({decorator:e=>(t,r)=>("function"!=typeof(e=Array.isArray(e)?e[0]:e)||e.name||(e=e()),S({type:e,required:!1})(t,r))}).apply(),t.Decoration.for(a.ValidationKeys.DATE).extend({decorator:e=>S({type:String,format:"date-time",required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.ENUM).extend({decorator:e=>S({enum:Array.isArray(e)?e:Object.values(e),required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.PATTERN).extend({decorator:e=>S({pattern:"string"==typeof e?e:e.source,required:!1})}).apply(),t.Decoration.for(s.PersistenceKeys.COLUMN).extend({decorator:e=>S({name:e,required:!1})}).apply(),t.Decoration.for(t.DecorationKeys.DESCRIPTION).extend({decorator:e=>S({description:e,required:!1})}).apply(),t.Decoration.for(s.PersistenceKeys.AUTH).extend({decorator:z}).apply();class ge extends s.ForbiddenError{constructor(e){super(e,ge.name)}}class Ae extends c.BaseError{constructor(e){super(Ae.name,e,429)}}const Ee=new Map([[o.UnauthorizedException,e=>new s.AuthorizationError(e)],[o.ForbiddenException,e=>new s.ForbiddenError(e)],[o.BadRequestException,e=>new c.BadRequestError(e)],[o.ConflictException,e=>new c.ConflictError(e)],[o.UnprocessableEntityException,e=>new c.ValidationError(e)]]);e.DecafExceptionFilter=class{constructor(e){this.moduleRef=e}async catch(e,t){const r=t.switchToHttp(),a=r.getResponse(),n=r.getRequest(),i="production"===l.LoggedEnvironment.env;let p;if(e instanceof o.NotFoundException||e instanceof s.UnsupportedError)p=(e=new o.NotAcceptableException(e.message)).getStatus();else if(!(e instanceof c.BaseError)){const t=this.decafErrorFor(e);t?e=t(e.message):429===e.status?e=new Ae(e.message):e instanceof o.HttpException?p=e.getStatus():e=new c.InternalError(e.message)}await this.logError(n,e),a.status(e.code||p).json({status:e.code||p,error:i?e.name:e.message,timestamp:(new Date).toISOString(),path:n.url,method:n.method})}decafErrorFor(e){for(const[t,r]of Ee)if(e instanceof t)return r}async logError(e,t){const r=`Unhandled error on ${e?.method} ${e?.url}`;try{(await this.resolveLogger(e)).error(r,t)}catch{try{l.Logging.get().error(r,t)}catch{}}}async resolveLogger(t){if(this.moduleRef)try{const r=d.ContextIdFactory.getByRequest(t),o=await this.moduleRef.resolve(e.DecafRequestContext,r,{strict:!1});if(o?.logger)return o.logger}catch{}return l.Logging.get()}},e.DecafExceptionFilter=p.__decorate([o.Catch(),o.Injectable(),p.__param(0,o.Optional()),p.__metadata("design:paramtypes",[d.ModuleRef])],e.DecafExceptionFilter);const be={path:"docs",auth:{type:"http",scheme:"bearer",bearerFormat:"JWT",name:"Authorization",description:"Enter JWT token",in:"header"},topbarBgColor:"#000000"};class Pe{constructor(e){this.options={...e}}customCSS(){let e="";return this.options.topbarIconPath&&(e+=`.topbar-wrapper { content: url('data:image/png;base64,${this.b64(this.options.topbarIconPath)}'); width: 200px; height: auto; }\n`),e+`\n .topbar-wrapper svg { visibility: hidden; }\n .swagger-ui .topbar { background-color: ${this.options.topbarBgColor||be.topbarBgColor}; }\n `}getCustomOptions(){const e={};return this.options.faviconPath&&(e.customfavIcon=this.b64(this.options.faviconPath,!0)),{customSiteTitle:this.options.title,...e,customCss:this.customCSS(),swaggerOptions:{persistAuthorization:this.options.persistAuthorization}}}b64(e,t=!1){const r=E.join(this.options.assetsPath||"",e),o=h.readFileSync(r,{encoding:"base64"});return t?"data:image/png;base64,"+o:o}}class ve{constructor(e,t){this.app=e,this.options=t}createDocument(){const e=this.options.path?this.options.description+""+`<br><br><a href="${this.options.openApiJsonPath}">OpenAPI JSON Spec</a> | `+`<a href="${this.options.openApiYamlPath}">OpenAPI YAML Spec</a>`:this.options.description,t=(new i.DocumentBuilder).setTitle(this.options.title).setDescription(e).setVersion(this.options.version||"0.0.1").addBearerAuth(this.options.auth||be.auth).build();return i.SwaggerModule.createDocument(this.app,t,{extraModels:this.options.extraModels||[]})}registerOpenApiRoute(e,t,r){if(!e)return;const o=this.app.getHttpAdapter();e=e.startsWith("/")?e:"/"+e,o.get(e,(e,a)=>{o.reply(a,r(),200,{"Content-Type":t})})}setupSwagger(){const e=this.createDocument(),t=new Pe({title:this.options.title,path:this.options.path||be.path,persistAuthorization:this.options.persistAuthorization??!0,assetsPath:this.options.assetsPath,faviconPath:this.options.faviconFilePath,topbarIconPath:this.options.topbarIconFilePath,topbarBgColor:this.options.topbarBgColor});i.SwaggerModule.setup(this.options.path||be.path,this.app,e,{...t.getCustomOptions(),jsonDocumentUrl:this.options.openApiJsonPath?""+this.options.openApiJsonPath:void 0,yamlDocumentUrl:this.options.openApiYamlPath?""+this.options.openApiYamlPath:void 0}),this.registerOpenApiRoute(this.options.openApiJsonPath,"application/json",()=>e),this.registerOpenApiRoute(this.options.openApiYamlPath,"application/x-yaml",()=>y.stringify(e))}}var Re;e.DecafRequestHandlerInterceptor=Re=class{constructor(e,t){this.requestContext=e,this.executor=t}async contextualize(e){const t={headers:e.headers,overrides:{}},r=(e=>{const t=e.headers;function r(e){if(e)return(Array.isArray(e)?e[0]:e).split(",").map(e=>e.trim()).filter(Boolean)[0]}return r(t?.["x-forwarded-for"])??r(t?.["x-real-ip"])??r(t?.["X-Forwarded-For"])??r(t?.["X-Real-IP"])??e.ip})(e),o=l.Logging.get().for({ip:r});this.requestContext.accumulate(Object.assign({},s.DefaultAdapterFlags,{logger:o,timestamp:new Date,operation:`${e.method} ${e.url}`},t))}async intercept(e,t){const r=e.switchToHttp().getRequest(),o=e.switchToHttp().getResponse(),a=l.Logging.for(Re).for(this.intercept);return a.debug(`CONTEXT ${this.requestContext.uuid} - request: ${r.method} ${r.url}`),await this.contextualize(r),a.debug(`CONTEXT ${this.requestContext.uuid} contextualized - request: ${r.method} ${r.url}`),await this.executor.exec(r,o),a.debug(`CONTEXT ${this.requestContext.uuid} executors finished - request: ${r.method} ${r.url}`),t.handle()}},e.DecafRequestHandlerInterceptor=Re=p.__decorate([o.Injectable({scope:o.Scope.REQUEST}),p.__metadata("design:paramtypes",[e.DecafRequestContext,e.DecafHandlerExecutor])],e.DecafRequestHandlerInterceptor);const Oe=new Map;function De(){return Array.from(Oe.values())}function Se(e,t){Oe.has(e)||Oe.set(e,{provide:e,useFactory:t})}var _e;e.DecafCoreModule=class{static{_e=this}static get persistence(){if(!this._persistence)throw new c.InternalError("Persistence service not initialized");return this._persistence}static get log(){return this._logger||(this._logger=l.Logging.for(_e)),this._logger}constructor(e,t){this.options=e,this.moduleRef=t}static forRoot(t){const r=this.log.for(this.forRoot),o=De();return{module:_e,providers:[{provide:N,useValue:t},{provide:k,useValue:this.persistence?.client},{provide:$,useFactory:()=>t.handlers?.map(e=>(r.info("Registered request handler: "+e.name),new e))??[]},e.DecafRequestContext,e.DecafHandlerExecutor,{provide:d.APP_INTERCEPTOR,useClass:e.DecafRequestHandlerInterceptor},...o],exports:[N,k,$,e.DecafRequestContext,e.DecafHandlerExecutor,...o.map(e=>e.provide)]}}static async bootPersistence(e){const t=this.log.for(this.bootPersistence);if(!this._persistence){const r=e.conf.map(([e,t,...r])=>r.pop()?[e,t,...r]:[e,t]);this._persistence=new s.PersistenceService,await this._persistence.boot(r);const o=this._persistence.client;for(let t=0;t<o.length;t++){const r=e.conf[t];let a=r.slice(2,r.length).pop();if(!a||!a.from){const e=s.Adapter.transformerFor(o[t].flavour);if(!e)throw new c.InternalError(`No transformer found for flavour ${o[t].flavour}. you should either @requestToContextTransformer or provide a transformer in the config`);try{a=e.from?e:new e}catch(e){throw new c.InternalError(`Failed to boot transformer for ${o[t].flavour}: ${e}`)}}u.requestToContextTransformer(o[t].flavour)(a)}if(t.info("persistence layer created successfully!"),e.initialization)try{await e.initialization()}catch(e){throw new c.InternalError("Failed to initialize application: "+e)}}return this.persistence.client}async onApplicationShutdown(){const e=_e.log.for(this.onApplicationShutdown),t=this.moduleRef.get(k);for(const r of t)try{r&&(e.info("Shutting down "+r.toString()),await r.shutdown())}catch(t){e.error("Failed to shutdown application",t)}try{await s.Service.shutdown()}catch(t){e.error("Failed to shutdown services",t)}}},e.DecafCoreModule=_e=p.__decorate([o.Global(),o.Module({}),p.__param(0,o.Inject(N)),p.__metadata("design:paramtypes",[Object,d.ModuleRef])],e.DecafCoreModule);const Ce=Symbol("LISTENING_ADAPTERS_FLAVOURS");var Te,Me,xe;e.EventsController=Te=class extends re{constructor(e,t){super(e,Te.name),this.adapters=t.map(e=>s.Adapter.get(e))}listen(){const e=l.Logging.for(Te.name),t=new f.Observable(t=>{const r=("B-"+Math.random().toString(36).slice(2,8)).toUpperCase();e.info(`Creating SSE observer: ${r} for client ${this.clientContext.uuid}`);const o=new class{constructor(){this.observerId=r}refresh(...r){return e.debug(`SSE observer ${this.observerId} received refresh event`),Promise.resolve().then(()=>{const o=(e=>{const[t,r,o,a]=e;return[t?.name??t,r,o,Array.isArray(a)?a.map(e=>{try{return"function"==typeof e.serialize?e.serialize():"string"==typeof e?e:JSON.stringify(e)}catch(e){return}}):a&&"function"==typeof a.serialize?a.serialize():"string"==typeof a?a:JSON.stringify(a)]})(r);t.next({type:"message",data:o}),e.debug(`SSE observer ${this.observerId} event pushed to client`)})}};e.verbose(`Registering observer ${r} across ${this.adapters.length} adapter(s)`);for(const t of this.adapters){const a=t?.constructor?.name??"UnknownAdapter";try{e.debug(`Registering observer ${r} in adapter ${a}`),t.observe(o)}catch(t){e.debug(`Failed to register observer ${r} in adapter ${a}: ${t?.message||t}`),e.error(t)}}return()=>{e.debug("Cleaning up SSE observer "+r);for(const t of this.adapters){const a=t?.constructor?.name??"UnknownAdapter";try{e.debug(`Unregistering observer ${r} from adapter ${a}`),t.unObserve(o)}catch(t){e.debug(`Failed during cleanup of observer ${r} in adapter ${a}: ${t?.message||t}`),e.error(t)}}}}),r=f.interval(15e3).pipe(g.tap(()=>{e.debug("Sending heartbeat")}),g.map(()=>({type:"heartbeat",data:{ts:(new Date).toISOString()}})));return f.merge(t,r)}listenForModel(e){const t=l.Logging.for(Te.name);return new f.Observable(e=>{const r=new class{refresh(...t){return Promise.resolve().then(()=>{e.next({data:t})})}};try{for(const e of this.adapters)e.observe(r)}catch(t){e.error("Failed to observe event: "+(t.message||t))}return()=>{try{for(const e of this.adapters)e.unObserve(r)}catch(e){t.error(e)}}})}},p.__decorate([o.Sse(),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[]),p.__metadata("design:returntype",f.Observable)],e.EventsController.prototype,"listen",null),p.__decorate([o.Sse("/:model"),p.__param(0,o.Query("model")),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String]),p.__metadata("design:returntype",f.Observable)],e.EventsController.prototype,"listenForModel",null),e.EventsController=Te=p.__decorate([o.Controller(),p.__param(1,o.Inject(Ce)),p.__metadata("design:paramtypes",[e.DecafRequestContext,Array])],e.EventsController),e.DecafStreamModule=Me=class{static forFlavours(t,r="events"){return{module:Me,controllers:[e.EventsController],imports:[d.RouterModule.register([{path:r.replace(/^\//,""),module:Me}])],providers:[e.DecafRequestContext,{provide:Ce,useValue:t??[]}]}}},e.DecafStreamModule=Me=p.__decorate([o.Module({})],e.DecafStreamModule),e.DecafModule=xe=class{static async forRootAsync(t){const{autoControllers:r,autoServices:o}=t,a=(await e.DecafCoreModule.bootPersistence(t)).map(e=>e.flavour),s=[e.DecafCoreModule.forRoot(t)];return r&&a.forEach(e=>{s.push(ye(e).forRoot(e,{autoServices:o,controllerExposure:t.controllerExposure,controllerConfig:t.controllerConfig,aggregations:t.aggregations}))}),t.observerOptions?.enableObserverEvents&&s.push(e.DecafStreamModule.forFlavours(t.observerOptions.observerFlavours||a)),{module:xe,imports:s}}},e.DecafModule=xe=p.__decorate([o.Module({})],e.DecafModule);const Ie="##VERSION##",we="##PACKAGE##";t.Metadata.allowReregistration(!0),t.Metadata.registerLibrary(we,Ie),t.Metadata.allowReregistration(!1),e.AUTH_HANDLER=U,e.AUTH_META_KEY=K,e.ApiOperationFromModel=C,e.ApiParamsFromModel=M,e.ApiProperty=S,e.Auth=z,e.BulkApiOperationFromModel=(e,r,a)=>{const n={GET:[c.BulkCrudOperationKeys.READ_ALL,o.Get],POST:[c.BulkCrudOperationKeys.CREATE_ALL,o.Post],PUT:[c.BulkCrudOperationKeys.UPDATE_ALL,o.Put],PATCH:[c.BulkCrudOperationKeys.UPDATE_ALL,o.Patch],DELETE:[c.BulkCrudOperationKeys.DELETE_ALL,o.Delete]},[p,d]=n[r],l=a?T(r,a):void 0;return l?s.isOperationBlocked(e,l.kind,l.value)?t.apply(i.ApiExcludeEndpoint()):t.apply(d(a)):s.isOperationBlocked(e,"bulk",p)?t.apply(i.ApiExcludeEndpoint()):t.apply(d(a))},e.COMMIT="3ac17fe",e.CorsError=ge,e.DECAF_ADAPTER_ID=k,e.DECAF_CONTEXT_KEY=L,e.DECAF_CONTROLLER_CONFIG=B,e.DECAF_EXPOSE=j,e.DECAF_HANDLERS=$,e.DECAF_MODULE_OPTIONS=N,e.DECAF_ROUTE=F,e.DECAF_TASK_SERVICE_ID="DecafTaskService",e.DECORATORS=P,e.DECORATORS_PREFIX=b,e.DecafAuthHandler=Z,e.DecafBody=x,e.DecafController=re,e.DecafModelController=oe,e.DecafParams=w,e.DecafRoleAuthHandler=class extends Z{},e.DtoFor=se,e.FULL_VERSION="0.12.0-3ac17fe",e.FromModelController=me,e.IS_PUBLIC_KEY=H,e.NestBootstraper=class{static get logger(){return this._logger||(this._logger=new o.Logger("NestBootstrap")),this._logger}static initialize(e){return this.app=e,this}static enableLogger(e){return this._logger=e||new o.Logger("NestBootstrap"),this.app.useLogger(this._logger),this}static enableCors(e=[],t=["GET","POST","PUT","DELETE"]){const r="*"===e?"*":e.map(e=>e.trim().toLowerCase()),o={origin:(e,t)=>e?"*"===r||Array.isArray(r)&&r.includes(e.toLowerCase())?t(null,!0):void t(new ge(`Origin ${e} not allowed`)):t(null,!0),credentials:!0,methods:t.join(",")};return this.app.enableCors(o),this}static useHelmet(e){try{const t=require("helmet");this.app.use(t(e)),this.logger.log("Helmet middleware enabled successfully.")}catch{this.logger.warn("Helmet not installed. Skipping middleware.")}return this}static setupSwagger(e){return new ve(this.app,{title:e.title,description:e.description,version:e.version,path:e.path||"api",persistAuthorization:e.persistAuthorization??!0,assetsPath:e.assetsPath,faviconFilePath:e.faviconPath,topbarIconFilePath:e.topbarIconPath,topbarBgColor:e.topbarBgColor,openApiJsonPath:e.openApiJsonPath,openApiYamlPath:e.openApiYamlPath}).setupSwagger(),this}static useGlobalPipes(...e){return e.length>0&&this.app.useGlobalPipes(...e),this}static useGlobalFilters(...t){return this.app.useGlobalFilters(...t.length>0?t:[new e.DecafExceptionFilter(this.app.get(d.ModuleRef,{strict:!1}))]),this}static useGlobalInterceptors(...e){return e.length>0&&this.app.useGlobalInterceptors(...e),this}static async start(e=Number(process.env.PORT)||3e3,t=void 0,r=!0){this.app.listen(e,t).then(async()=>{if(r){const e=await this.app.getUrl();this.logger.log("\ud83d\ude80 Application is running at: "+e)}})}},e.PACKAGE_NAME=we,e.Public=W,e.REQUIRED_ROLES_KEY=G,e.Repository=(e,t)=>(r,a,n)=>{const i=((e,t)=>t?`${e.name}Repository@${t}`:e.name+"Repository")(e,t);return Se(i,()=>s.Repository.forModel(e,t)),o.Inject(i)(r,a,n)},e.RequireRoles=Y,e.SKIP_MODEL_ROLES_KEY=Q,e.Service=e=>(t,r,n)=>{let i=e;if(void 0===i){const e=Reflect.getMetadata("design:paramtypes",t)||[];i=e[n]}if(void 0===i)throw new c.InternalError(`@Service() could not determine an injection type for parameter ${n} of ${t.name}. Provide an explicit argument, e.g. @Service(SomeService).`);const p="string"!=typeof i&&"function"==typeof(d=i)&&d.prototype instanceof a.Model;var d;const l=p?i.name+"Service":s.injectableServiceKey(i);return Se(l,()=>{if(p)try{return s.Service.get(i)}catch{return s.ModelService.forModel(i)}return s.Service.get(i)}),o.Inject(l)(t,r,n)},e.SwaggerBuilder=ve,e.UseDecafFilter=()=>o.UseFilters(new e.DecafExceptionFilter),e.UseDecafHeaders=()=>o.UseInterceptors(e.DecafResponseInterceptor),e.VERSION=Ie,e.applyApiDecorators=(e,t,r,o)=>{const a=e?.prototype??e;o.method.forEach(e=>e(a,t,r)),o.params?.forEach((e,r)=>e(a,t,r))},e.controllerConfig=e=>r=>(t.Metadata.set(r,B,e),r),e.createApiPropertyDecorator=_,e.createPropertyDecorator=D,e.createRouteHandler=function(e){return async function(t,r){const o=this.log.for(e);try{o.debug(`Invoking persistence method "${e}" given parameters: ${JSON.stringify(t.valuesInOrder)}`);const{direction:a,limit:s,offset:n}=r;return await J(this.persistence(this.ctx),e,...t.valuesInOrder,a,s,n)}catch(t){throw o.error(`Custom query "${e}" failed`,t),s=`Custom query "${e}" failed`,(a=t)instanceof c.BaseError?a:new c.InternalError(a instanceof Error?`${s}: ${a.message}`:s)}var a,s}},e.defineRouteMethod=(e,t,r)=>(Object.defineProperty(e.prototype||e,t,{value:r,writable:!1}),Object.getOwnPropertyDescriptor(e.prototype||e,t)),e.expose=(...e)=>r=>(t.Metadata.set(r,j,!e.length||e),r),e.getApiDecorators=(e,t,r,a=!1)=>{const n=V(r),c=(e=>e.split("/").filter(e=>e.startsWith(":")).map(e=>e.slice(1)))(t).map(X),p=[];return"GET"===r&&a&&p.push(i.ApiQuery({name:"direction",required:!1,enum:s.OrderDirection,description:"the sort order when applicable"}),i.ApiQuery({name:"limit",required:!1,description:"limit or page size when applicable"}),i.ApiQuery({name:"offset",required:!1,description:"offset or bookmark when applicable"})),{method:[n(t),...c.map(i.ApiParam),...p,i.ApiOperation({summary:`Retrieve records using according to "${e}".`}),i.ApiOkResponse({description:"Result successfully retrieved."}),i.ApiNoContentResponse({description:"No content returned by the method."})],params:[w(c),o.Query()]}},e.getEnumType=O,e.getEnumValues=R,e.getModuleFor=ye,e.getRegisteredDecafProviders=De,e.isUndefined=v,e.repoForModel=e=>{const t=a.Model.get(e);if(!t)throw new c.InternalError("Failed to find repository for "+e);return s.Repository.forModel(t)},e.resolvePersistenceMethod=J,e.runMigrations=async()=>{}},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/decoration"),require("@decaf-ts/injectable-decorators"),require("@nestjs/common"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/core"),require("lodash"),require("@nestjs/swagger"),require("@decaf-ts/db-decorators"),require("tslib"),require("@nestjs/core"),require("@decaf-ts/logging"),require("@decaf-ts/for-http/server"),require("rxjs"),require("fs"),require("path"),require("yaml"),require("rxjs/operators")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/decoration","@decaf-ts/injectable-decorators","@nestjs/common","@decaf-ts/decorator-validation","@decaf-ts/core","lodash","@nestjs/swagger","@decaf-ts/db-decorators","tslib","@nestjs/core","@decaf-ts/logging","@decaf-ts/for-http/server","rxjs","fs","path","yaml","rxjs/operators"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["for-nest"]={},e.decafTsDecoration,e.decafTsInjectableDecorators,e.nestjsCommon,e.decafTsDecoratorValidation,e.decafTsCore,e.lodash,e.nestjsSwagger,e.decafTsDbDecorators,e.tslib,e.nestjsCore,e.decafTsLogging,e.server,e.rxjs,e.fs,e.path,e.yaml,e.operators);
|
|
2
2
|
//# sourceMappingURL=for-nest.cjs.map
|