jimpex 10.0.2 → 11.0.0
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/CHANGELOG.md +29 -0
- package/README.md +7 -9
- package/dist/app/index.d.ts +1 -1
- package/dist/app/index.js +1 -22
- package/dist/app/index.js.map +1 -1
- package/dist/app/jimpex.d.ts +1 -1
- package/dist/app/jimpex.js +100 -131
- package/dist/app/jimpex.js.map +1 -1
- package/dist/controllers/common/config.d.ts +2 -2
- package/dist/controllers/common/config.js +12 -39
- package/dist/controllers/common/config.js.map +1 -1
- package/dist/controllers/common/health.d.ts +4 -4
- package/dist/controllers/common/health.js +20 -47
- package/dist/controllers/common/health.js.map +1 -1
- package/dist/controllers/common/index.d.ts +1 -1
- package/dist/controllers/common/index.js +3 -26
- package/dist/controllers/common/index.js.map +1 -1
- package/dist/controllers/common/statics.d.ts +3 -3
- package/dist/controllers/common/statics.js +32 -65
- package/dist/controllers/common/statics.js.map +1 -1
- package/dist/controllers/index.d.ts +1 -1
- package/dist/controllers/index.js +2 -24
- package/dist/controllers/index.js.map +1 -1
- package/dist/controllers/utils/gateway.d.ts +5 -5
- package/dist/controllers/utils/gateway.js +70 -91
- package/dist/controllers/utils/gateway.js.map +1 -1
- package/dist/controllers/utils/index.d.ts +1 -1
- package/dist/controllers/utils/index.js +1 -22
- package/dist/controllers/utils/index.js.map +1 -1
- package/dist/{index-C6I3NCC-.d.ts → index-BlSpNHox.d.ts} +13 -13
- package/dist/index.d.ts +3 -3
- package/dist/index.js +6 -32
- package/dist/index.js.map +1 -1
- package/dist/middlewares/common/errorHandler.d.ts +5 -5
- package/dist/middlewares/common/errorHandler.js +31 -56
- package/dist/middlewares/common/errorHandler.js.map +1 -1
- package/dist/middlewares/common/forceHTTPS.d.ts +1 -1
- package/dist/middlewares/common/forceHTTPS.js +8 -35
- package/dist/middlewares/common/forceHTTPS.js.map +1 -1
- package/dist/middlewares/common/hsts.d.ts +1 -1
- package/dist/middlewares/common/hsts.js +12 -39
- package/dist/middlewares/common/hsts.js.map +1 -1
- package/dist/middlewares/common/index.d.ts +3 -3
- package/dist/middlewares/common/index.js +3 -26
- package/dist/middlewares/common/index.js.map +1 -1
- package/dist/middlewares/html/fastHTML.d.ts +4 -4
- package/dist/middlewares/html/fastHTML.js +43 -66
- package/dist/middlewares/html/fastHTML.js.map +1 -1
- package/dist/middlewares/html/index.d.ts +2 -2
- package/dist/middlewares/html/index.js +2 -24
- package/dist/middlewares/html/index.js.map +1 -1
- package/dist/middlewares/html/showHTML.d.ts +3 -3
- package/dist/middlewares/html/showHTML.js +25 -52
- package/dist/middlewares/html/showHTML.js.map +1 -1
- package/dist/middlewares/index.d.ts +4 -4
- package/dist/middlewares/index.js +3 -26
- package/dist/middlewares/index.js.map +1 -1
- package/dist/middlewares/utils/index.d.ts +3 -3
- package/dist/middlewares/utils/index.js +1 -22
- package/dist/middlewares/utils/index.js.map +1 -1
- package/dist/middlewares/utils/versionValidator.d.ts +5 -5
- package/dist/middlewares/utils/versionValidator.js +24 -51
- package/dist/middlewares/utils/versionValidator.js.map +1 -1
- package/dist/services/common/appError.d.ts +2 -2
- package/dist/services/common/appError.js +18 -46
- package/dist/services/common/appError.js.map +1 -1
- package/dist/services/common/httpError.d.ts +2 -2
- package/dist/services/common/httpError.js +7 -33
- package/dist/services/common/httpError.js.map +1 -1
- package/dist/services/common/index.d.ts +1 -1
- package/dist/services/common/index.js +14 -42
- package/dist/services/common/index.js.map +1 -1
- package/dist/services/common/sendFile.d.ts +1 -1
- package/dist/services/common/sendFile.js +4 -29
- package/dist/services/common/sendFile.js.map +1 -1
- package/dist/services/frontend/frontendFs.d.ts +2 -2
- package/dist/services/frontend/frontendFs.js +12 -49
- package/dist/services/frontend/frontendFs.js.map +1 -1
- package/dist/services/frontend/index.d.ts +2 -2
- package/dist/services/frontend/index.js +8 -34
- package/dist/services/frontend/index.js.map +1 -1
- package/dist/services/html/htmlGenerator.d.ts +5 -5
- package/dist/services/html/htmlGenerator.js +46 -75
- package/dist/services/html/htmlGenerator.js.map +1 -1
- package/dist/services/html/index.d.ts +2 -2
- package/dist/services/html/index.js +8 -34
- package/dist/services/html/index.js.map +1 -1
- package/dist/services/http/apiClient.d.ts +1 -1
- package/dist/services/http/apiClient.js +23 -48
- package/dist/services/http/apiClient.js.map +1 -1
- package/dist/services/http/http.d.ts +5 -5
- package/dist/services/http/http.js +23 -60
- package/dist/services/http/http.js.map +1 -1
- package/dist/services/http/index.d.ts +2 -2
- package/dist/services/http/index.js +14 -42
- package/dist/services/http/index.js.map +1 -1
- package/dist/services/http/responsesBuilder.d.ts +4 -4
- package/dist/services/http/responsesBuilder.js +13 -40
- package/dist/services/http/responsesBuilder.js.map +1 -1
- package/dist/services/index.d.ts +3 -3
- package/dist/services/index.js +5 -30
- package/dist/services/index.js.map +1 -1
- package/dist/services/utils/ensureBearerToken.d.ts +2 -2
- package/dist/services/utils/ensureBearerToken.js +15 -42
- package/dist/services/utils/ensureBearerToken.js.map +1 -1
- package/dist/services/utils/index.d.ts +1 -1
- package/dist/services/utils/index.js +8 -34
- package/dist/services/utils/index.js.map +1 -1
- package/dist/types/events.d.ts +1 -1
- package/dist/types/events.js +0 -16
- package/dist/types/events.js.map +1 -1
- package/dist/types/express.js +0 -16
- package/dist/types/express.js.map +1 -1
- package/dist/types/http.js +0 -16
- package/dist/types/http.js.map +1 -1
- package/dist/types/index.d.ts +1 -1
- package/dist/types/index.js +6 -32
- package/dist/types/index.js.map +1 -1
- package/dist/types/options.d.ts +1 -1
- package/dist/types/options.js +0 -16
- package/dist/types/options.js.map +1 -1
- package/dist/types/utils.js +0 -16
- package/dist/types/utils.js.map +1 -1
- package/dist/types/wootils.js +0 -16
- package/dist/types/wootils.js.map +1 -1
- package/dist/utils/fns/index.js +4 -28
- package/dist/utils/fns/index.js.map +1 -1
- package/dist/utils/fns/others.js +2 -26
- package/dist/utils/fns/others.js.map +1 -1
- package/dist/utils/fns/routes.js +4 -31
- package/dist/utils/fns/routes.js.map +1 -1
- package/dist/utils/fns/statuses.js +3 -37
- package/dist/utils/fns/statuses.js.map +1 -1
- package/dist/utils/fns/text.js +2 -26
- package/dist/utils/fns/text.js.map +1 -1
- package/dist/utils/index.d.ts +1 -1
- package/dist/utils/index.js +2 -24
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/wrappers.d.ts +1 -1
- package/dist/utils/wrappers.js +20 -48
- package/dist/utils/wrappers.js.map +1 -1
- package/eslint.config.js +19 -0
- package/examples/basic/app.ts +4 -4
- package/examples/basic/controller.ts +2 -2
- package/examples/basic/index.ts +4 -4
- package/examples/basic/middleware.ts +2 -2
- package/examples/basic/service.ts +1 -1
- package/package.json +61 -49
- package/pnpm-workspace.yaml +4 -0
- package/src/app/index.ts +1 -1
- package/src/app/jimpex.ts +23 -20
- package/src/controllers/common/config.ts +4 -4
- package/src/controllers/common/health.ts +9 -5
- package/src/controllers/common/index.ts +3 -3
- package/src/controllers/common/statics.ts +12 -7
- package/src/controllers/index.ts +2 -2
- package/src/controllers/utils/gateway.ts +8 -8
- package/src/controllers/utils/index.ts +1 -1
- package/src/index.ts +6 -6
- package/src/middlewares/common/errorHandler.ts +9 -5
- package/src/middlewares/common/forceHTTPS.ts +2 -2
- package/src/middlewares/common/hsts.ts +2 -2
- package/src/middlewares/common/index.ts +3 -3
- package/src/middlewares/html/fastHTML.ts +14 -5
- package/src/middlewares/html/index.ts +2 -2
- package/src/middlewares/html/showHTML.ts +8 -4
- package/src/middlewares/index.ts +3 -3
- package/src/middlewares/utils/index.ts +1 -1
- package/src/middlewares/utils/versionValidator.ts +6 -6
- package/src/services/common/appError.ts +1 -1
- package/src/services/common/httpError.ts +2 -2
- package/src/services/common/index.ts +7 -7
- package/src/services/common/sendFile.ts +2 -2
- package/src/services/frontend/frontendFs.ts +3 -3
- package/src/services/frontend/index.ts +3 -3
- package/src/services/html/htmlGenerator.ts +11 -13
- package/src/services/html/index.ts +3 -3
- package/src/services/http/apiClient.ts +3 -3
- package/src/services/http/http.ts +5 -5
- package/src/services/http/index.ts +7 -7
- package/src/services/http/responsesBuilder.ts +5 -5
- package/src/services/index.ts +5 -5
- package/src/services/utils/ensureBearerToken.ts +4 -4
- package/src/services/utils/index.ts +3 -3
- package/src/types/events.ts +8 -8
- package/src/types/http.ts +1 -1
- package/src/types/index.ts +6 -6
- package/src/types/options.ts +2 -2
- package/src/types/utils.ts +4 -4
- package/src/utils/fns/index.ts +4 -4
- package/src/utils/fns/routes.ts +1 -1
- package/src/utils/index.ts +2 -2
- package/src/utils/wrappers.ts +6 -6
- package/tsconfig.json +9 -4
- package/tsup.config.ts +1 -2
- package/vitest.config.ts +24 -0
- package/dist/app/index.d.mts +0 -14
- package/dist/app/jimpex.d.mts +0 -14
- package/dist/controllers/common/config.d.mts +0 -79
- package/dist/controllers/common/health.d.mts +0 -83
- package/dist/controllers/common/index.d.mts +0 -22
- package/dist/controllers/common/statics.d.mts +0 -223
- package/dist/controllers/index.d.mts +0 -25
- package/dist/controllers/utils/gateway.d.mts +0 -725
- package/dist/controllers/utils/index.d.mts +0 -17
- package/dist/esm/app/index.js +0 -2
- package/dist/esm/app/index.js.map +0 -1
- package/dist/esm/app/jimpex.js +0 -640
- package/dist/esm/app/jimpex.js.map +0 -1
- package/dist/esm/chunk-V6TY7KAL.js +0 -8
- package/dist/esm/chunk-V6TY7KAL.js.map +0 -1
- package/dist/esm/controllers/common/config.js +0 -80
- package/dist/esm/controllers/common/config.js.map +0 -1
- package/dist/esm/controllers/common/health.js +0 -88
- package/dist/esm/controllers/common/health.js.map +0 -1
- package/dist/esm/controllers/common/index.js +0 -4
- package/dist/esm/controllers/common/index.js.map +0 -1
- package/dist/esm/controllers/common/statics.js +0 -226
- package/dist/esm/controllers/common/statics.js.map +0 -1
- package/dist/esm/controllers/index.js +0 -3
- package/dist/esm/controllers/index.js.map +0 -1
- package/dist/esm/controllers/utils/gateway.js +0 -559
- package/dist/esm/controllers/utils/gateway.js.map +0 -1
- package/dist/esm/controllers/utils/index.js +0 -2
- package/dist/esm/controllers/utils/index.js.map +0 -1
- package/dist/esm/index.js +0 -7
- package/dist/esm/index.js.map +0 -1
- package/dist/esm/middlewares/common/errorHandler.js +0 -116
- package/dist/esm/middlewares/common/errorHandler.js.map +0 -1
- package/dist/esm/middlewares/common/forceHTTPS.js +0 -52
- package/dist/esm/middlewares/common/forceHTTPS.js.map +0 -1
- package/dist/esm/middlewares/common/hsts.js +0 -74
- package/dist/esm/middlewares/common/hsts.js.map +0 -1
- package/dist/esm/middlewares/common/index.js +0 -4
- package/dist/esm/middlewares/common/index.js.map +0 -1
- package/dist/esm/middlewares/html/fastHTML.js +0 -157
- package/dist/esm/middlewares/html/fastHTML.js.map +0 -1
- package/dist/esm/middlewares/html/index.js +0 -3
- package/dist/esm/middlewares/html/index.js.map +0 -1
- package/dist/esm/middlewares/html/showHTML.js +0 -100
- package/dist/esm/middlewares/html/showHTML.js.map +0 -1
- package/dist/esm/middlewares/index.js +0 -4
- package/dist/esm/middlewares/index.js.map +0 -1
- package/dist/esm/middlewares/utils/index.js +0 -2
- package/dist/esm/middlewares/utils/index.js.map +0 -1
- package/dist/esm/middlewares/utils/versionValidator.js +0 -135
- package/dist/esm/middlewares/utils/versionValidator.js.map +0 -1
- package/dist/esm/services/common/appError.js +0 -98
- package/dist/esm/services/common/appError.js.map +0 -1
- package/dist/esm/services/common/httpError.js +0 -28
- package/dist/esm/services/common/httpError.js.map +0 -1
- package/dist/esm/services/common/index.js +0 -17
- package/dist/esm/services/common/index.js.map +0 -1
- package/dist/esm/services/common/sendFile.js +0 -27
- package/dist/esm/services/common/sendFile.js.map +0 -1
- package/dist/esm/services/frontend/frontendFs.js +0 -66
- package/dist/esm/services/frontend/frontendFs.js.map +0 -1
- package/dist/esm/services/frontend/index.js +0 -11
- package/dist/esm/services/frontend/index.js.map +0 -1
- package/dist/esm/services/html/htmlGenerator.js +0 -192
- package/dist/esm/services/html/htmlGenerator.js.map +0 -1
- package/dist/esm/services/html/index.js +0 -11
- package/dist/esm/services/html/index.js.map +0 -1
- package/dist/esm/services/http/apiClient.js +0 -94
- package/dist/esm/services/http/apiClient.js.map +0 -1
- package/dist/esm/services/http/http.js +0 -180
- package/dist/esm/services/http/http.js.map +0 -1
- package/dist/esm/services/http/index.js +0 -17
- package/dist/esm/services/http/index.js.map +0 -1
- package/dist/esm/services/http/responsesBuilder.js +0 -152
- package/dist/esm/services/http/responsesBuilder.js.map +0 -1
- package/dist/esm/services/index.js +0 -6
- package/dist/esm/services/index.js.map +0 -1
- package/dist/esm/services/utils/ensureBearerToken.js +0 -94
- package/dist/esm/services/utils/ensureBearerToken.js.map +0 -1
- package/dist/esm/services/utils/index.js +0 -11
- package/dist/esm/services/utils/index.js.map +0 -1
- package/dist/esm/types/events.js +0 -1
- package/dist/esm/types/events.js.map +0 -1
- package/dist/esm/types/express.js +0 -1
- package/dist/esm/types/express.js.map +0 -1
- package/dist/esm/types/http.js +0 -1
- package/dist/esm/types/http.js.map +0 -1
- package/dist/esm/types/index.js +0 -7
- package/dist/esm/types/index.js.map +0 -1
- package/dist/esm/types/options.js +0 -1
- package/dist/esm/types/options.js.map +0 -1
- package/dist/esm/types/utils.js +0 -1
- package/dist/esm/types/utils.js.map +0 -1
- package/dist/esm/types/wootils.js +0 -1
- package/dist/esm/types/wootils.js.map +0 -1
- package/dist/esm/utils/fns/index.js +0 -5
- package/dist/esm/utils/fns/index.js.map +0 -1
- package/dist/esm/utils/fns/others.js +0 -6
- package/dist/esm/utils/fns/others.js.map +0 -1
- package/dist/esm/utils/fns/routes.js +0 -25
- package/dist/esm/utils/fns/routes.js.map +0 -1
- package/dist/esm/utils/fns/statuses.js +0 -6
- package/dist/esm/utils/fns/statuses.js.map +0 -1
- package/dist/esm/utils/fns/text.js +0 -6
- package/dist/esm/utils/fns/text.js.map +0 -1
- package/dist/esm/utils/index.js +0 -3
- package/dist/esm/utils/index.js.map +0 -1
- package/dist/esm/utils/wrappers.js +0 -41
- package/dist/esm/utils/wrappers.js.map +0 -1
- package/dist/index-Bwf7JHu9.d.mts +0 -1287
- package/dist/index.d.mts +0 -47
- package/dist/middlewares/common/errorHandler.d.mts +0 -132
- package/dist/middlewares/common/forceHTTPS.d.mts +0 -69
- package/dist/middlewares/common/hsts.d.mts +0 -110
- package/dist/middlewares/common/index.d.mts +0 -22
- package/dist/middlewares/html/fastHTML.d.mts +0 -180
- package/dist/middlewares/html/index.d.mts +0 -21
- package/dist/middlewares/html/showHTML.d.mts +0 -127
- package/dist/middlewares/index.d.mts +0 -30
- package/dist/middlewares/utils/index.d.mts +0 -20
- package/dist/middlewares/utils/versionValidator.d.mts +0 -215
- package/dist/services/common/appError.d.mts +0 -139
- package/dist/services/common/httpError.d.mts +0 -80
- package/dist/services/common/index.d.mts +0 -47
- package/dist/services/common/sendFile.d.mts +0 -102
- package/dist/services/frontend/frontendFs.d.mts +0 -96
- package/dist/services/frontend/index.d.mts +0 -40
- package/dist/services/html/htmlGenerator.d.mts +0 -237
- package/dist/services/html/index.d.mts +0 -43
- package/dist/services/http/apiClient.d.mts +0 -170
- package/dist/services/http/http.d.mts +0 -182
- package/dist/services/http/index.d.mts +0 -51
- package/dist/services/http/responsesBuilder.d.mts +0 -179
- package/dist/services/index.d.mts +0 -33
- package/dist/services/utils/ensureBearerToken.d.mts +0 -158
- package/dist/services/utils/index.d.mts +0 -44
- package/dist/types/events.d.mts +0 -14
- package/dist/types/express.d.mts +0 -10
- package/dist/types/http.d.mts +0 -82
- package/dist/types/index.d.mts +0 -14
- package/dist/types/options.d.mts +0 -14
- package/dist/types/utils.d.mts +0 -48
- package/dist/types/wootils.d.mts +0 -4
- package/dist/utils/fns/index.d.mts +0 -5
- package/dist/utils/fns/others.d.mts +0 -17
- package/dist/utils/fns/routes.d.mts +0 -39
- package/dist/utils/fns/statuses.d.mts +0 -45
- package/dist/utils/fns/text.d.mts +0 -9
- package/dist/utils/index.d.mts +0 -19
- package/dist/utils/wrappers.d.mts +0 -14
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/controllers/utils/gateway.ts"],"sourcesContent":["import { deepAssignWithOverwrite } from '@homer0/deep-assign';\nimport { flat, unflat } from '@homer0/object-utils';\nimport type { APIClientOptions } from '@homer0/api-utils';\nimport {\n controllerProviderCreator,\n controller,\n createRouteExpression,\n removeSlashes,\n notUndefined,\n type MiddlewareLike,\n} from '../../utils';\nimport type { HTTP, HTTPFetchOptions } from '../../services';\nimport type { Jimpex } from '../../app';\nimport {\n RouterMethod,\n DeepPartial,\n Request,\n Response,\n NextFunction,\n HTTPResponse,\n Router,\n ExpressMiddleware,\n AsyncExpressMiddleware,\n} from '../../types';\n/**\n * The extended definition for endpoints.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayConfigEndpointProps = {\n /**\n * The path to the endpoint relative to the entry point. It can include placeholders for\n * parameters like `/:parameter/`.\n */\n path: string;\n /**\n * The router (HTTP) method for the endpoint.\n *\n * @default 'all'\n */\n method?: RouterMethod;\n};\n/**\n * The definition of an endpoint: it can be just the path, relative to the entry point, or\n * an object in which you can also specify things like the method.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayConfigEndpointDefinition = string | GatewayConfigEndpointProps;\n/**\n * The dictionary of endpoints the controller uses. The reason for this type is that this\n * could be a flat dictionary, or a nested one.\n *\n * @example\n *\n * <caption>A flat dictionary</caption>\n *\n * {\n * random: '/random',\n * users: '/users',\n * userById: {\n * path: '/users/:id',\n * method: 'get',\n * },\n * }\n *\n * @example\n *\n * <caption>A nested dictionary</caption>\n *\n * {\n * random: '/random',\n * users: {\n * list: '/users',\n * byId: {\n * path: '/users/:id',\n * method: 'get',\n * },\n * },\n * }\n *\n * @group Controllers/Gateway\n */\nexport type GatewayConfigEndpoints = {\n [key: string]: GatewayConfigEndpointDefinition | GatewayConfigEndpoints;\n};\n/**\n * The configuration for the gateway the controller uses.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayConfig = {\n /**\n * The entry point to the API the controller will make the requests to.\n */\n url: string;\n /**\n * The dictionary of enpoints the gateway will make available.\n */\n gateway: GatewayConfigEndpoints;\n};\n/**\n * The options for how the gateway will handle the headers from the requests and the\n * responses.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerHeaderOptions = {\n /**\n * Whether or not to include the header with the request's IP address.\n *\n * @default true\n */\n useXForwardedFor: boolean;\n /**\n * Whether or not to copy all custom headers from the request. By custom header, it\n * means all the headers which names start with `x-`.\n *\n * @default true\n */\n copyCustomHeaders: boolean;\n /**\n * A list of \"known\" headers the gateway will try to copy from the incoming request.\n *\n * @default ['authorization','content-type', 'referer', 'user-agent']\n */\n copy: string[];\n /**\n * A list of \"known\" headers the gateway will try to remove the response.\n *\n * @default ['server', 'x-powered-by']\n */\n remove: string[];\n};\n/**\n * The extra options for the gateway controller. They are \"extra\" because they are mostly\n * helpers for when used with an API client, or for optional features.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerExtraOptions = {\n /**\n * This is really a helper for when the gateway is used with an API client. The idea is\n * that, by default, the routes are mounted on the controller route, but with this\n * option, you can specify another sub path. For example: The controller is mounted on\n * `/routes`, and if you set `root` to `gateway`, all the routes will be on\n * `/routes/gateway`.\n *\n * This become important (and useful) when you get the API client configuration (with\n * `getAPIConfig`): The `url` will be the controller route, but all the endpoints will\n * be modified and prefixed with the `root`, that way, you can have multiple gateways in\n * the same \"base route\".\n *\n * It can also includes placeholders for parameters like `/:parameter/`, that will be\n * replaced with the `placeholders` option when `getAPIConfig` gets called.\n *\n * @default ''\n */\n root: string;\n /**\n * This is another option for when the gateway is used with an API client. When calling\n * `getAPIConfig`, all the endpoints will be wrapped inside an object named after this\n * option. For example: `{ url: '...', endpoints: { api: { ... } } }`.\n *\n * @default 'api'\n */\n apiConfigSetting: string;\n /**\n * The options for how the gateway will handle the headers from the requests and the\n * responses.\n */\n headers: GatewayControllerHeaderOptions;\n};\n/**\n * The required options for the gateway controller.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerOptions = {\n /**\n * The configuration for the API the gateway will make the requests to.\n */\n gatewayConfig: GatewayConfig;\n /**\n * The route where the controller is mounted.\n */\n route: string;\n} & DeepPartial<GatewayControllerExtraOptions>;\n/**\n * The information for a request the controller will make.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerRequest = {\n /**\n * The URL for the request.\n */\n url: string;\n /**\n * The options for the fetch client that will make the requests.\n */\n options: HTTPFetchOptions;\n};\n/**\n * The information for an endpoint the gateway is calling.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerEndpointInfo = {\n /**\n * The name of the endpoint in the configuration.\n */\n name: string;\n /**\n * The properties (path and method) of the endpoint.\n */\n definition: GatewayConfigEndpointDefinition;\n};\n/**\n * These are the base options sent to all the helper service functions.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceBaseFnOptions = {\n /**\n * The information of the endpoint the gateway is calling.\n */\n endpoint: GatewayControllerEndpointInfo;\n /**\n * The request recived by the application.\n */\n req: Request;\n /**\n * The response object created by the application.\n */\n res: Response;\n /**\n * The function to call the next middleware in the chain.\n */\n next: NextFunction;\n};\n/**\n * The information sent to the helper service in order to modify, or not, a request before\n * it is sent.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceRequestReducerOptions =\n GatewayHelperServiceBaseFnOptions & {\n /**\n * The options the controller created for the fetch client.\n */\n endpointReq: GatewayControllerRequest;\n };\n/**\n * A function that can be used to modify the information of an endpoint before making a\n * request.\n *\n * @param options The information of the request.\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceRequestReducer = (\n options: GatewayHelperServiceRequestReducerOptions,\n) => Promise<GatewayControllerRequest>;\n/**\n * The information sent to the helper service in order to modify a response before\n * processing it, decide if it should be streamed or not, and even handle it.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceResponseReducerOptions =\n GatewayHelperServiceBaseFnOptions & {\n /**\n * The response from the endpoint request.\n */\n endpointRes: HTTPResponse;\n };\n/**\n * A function that can be used to modify the response of an endpoint before the controller\n * processes it.\n *\n * @param options The information of the response.\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceResponseReducer = (\n options: GatewayHelperServiceResponseReducerOptions,\n) => Promise<HTTPResponse>;\n/**\n * A function that can be used to tell the controller to stream the response of an\n * endpoint or not.\n * If it returns `false`, the function to handle responses should be defined, otherwise,\n * an error will be generated.\n *\n * @param options The information of the response.\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceStreamVerification = (\n options: GatewayHelperServiceResponseReducerOptions,\n) => Promise<boolean>;\n/**\n * A function to handle the response of an endpoint. This is called when the helper\n * service tells the controller that the endpoint shouldn't be streamed, so this method\n * should handle the response.\n *\n * @param options The information of the response.\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceResponseHandler = (\n options: GatewayHelperServiceResponseReducerOptions,\n) => Promise<void>;\n/**\n * The information sent to the helper service in order to handle a failed request for an\n * endpoint.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceErrorHandlerOptions =\n GatewayHelperServiceBaseFnOptions & {\n /**\n * The error generated during the request.\n */\n error: Error;\n };\n/**\n * A function to handle the error of an endpoint request.\n *\n * @param options The information of the error.\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceErrorHandler = (\n options: GatewayHelperServiceErrorHandlerOptions,\n) => void;\n/**\n * The interface of a helper service that can intercept/modify the requests and responses\n * the gateway makes.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayHelperService = Partial<{\n /**\n * A function that is called before an endpoint request is made.\n */\n reduceEndpointRequest: GatewayHelperServiceRequestReducer;\n /**\n * A function that is called with the response of an endpoint request.\n */\n reduceEndpointResponse: GatewayHelperServiceResponseReducer;\n /**\n * A function called in order to validate if an endpoint response should be streamed or\n * not. If the function returns `false`, `handleEndpointResponse` will be called.\n */\n shouldStreamEndpointResponse: GatewayHelperServiceStreamVerification;\n /**\n * A function called when `shouldStreamEndpointResponse` returns `false`. The function\n * should handle the response for the application.\n */\n handleEndpointResponse: GatewayHelperServiceResponseHandler;\n /**\n * A function called when an error is generated during an endpoint request/processing.\n */\n handleEndpointError: GatewayHelperServiceErrorHandler;\n}>;\n/**\n * Utility type for the options object sent to the \"proxy methods\" the controller has for\n * the helper service.\n *\n * @template T The type of the options for a specific helper service function.\n * @access protected\n * @group Controllers/Gateway\n */\nexport type GatewayControllerHelperOptions<T> = T & {\n /**\n * The reference for the helper service.\n */\n helper: GatewayHelperService;\n};\n/**\n * The information for a single HTTP method an endpoint can handle.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerRouteMethod = {\n /**\n * The method for the route.\n */\n method: RouterMethod;\n /**\n * The information of the endpoint.\n */\n endpoint: GatewayControllerEndpointInfo;\n};\n/**\n * The information for all the HTTP methods that can be handled for an endpoint.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerRoute = {\n /**\n * The path to the endpoint, relative to the entry point.\n */\n path: string;\n /**\n * The path for the route in the controller. This is different from `path` as it's possible for\n * the gateway to be implemented using the `root` option.\n */\n route: string;\n /**\n * A list with all the methods the controller uses on the route.\n */\n methods: GatewayControllerRouteMethod[];\n};\n/**\n * The API client configuration the gateway can generate for its endpoints.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerAPIConfig = {\n /**\n * The base URL for the API.\n */\n url: string;\n /**\n * The dictionary of endpoints the controller handles.\n */\n endpoints: APIClientOptions['endpoints'];\n};\n/**\n * The options sent to {@link GatewayController.getAPIConfig}.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerAPIConfigOptions = {\n /**\n * This can be used to overwrite the gateway's `apiConfigSetting` option, and set a new\n * setting as a wrapper for the endpoints.\n */\n setting?: string;\n /**\n * A dictionary of values for possible placeholders that were sent using the `root`\n * option.\n */\n placeholders?: Record<string, string>;\n};\n/**\n * The options to construct a {@link GatewayController}.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerConstructorOptions = GatewayControllerOptions & {\n /**\n * A dictionary with the dependencies to inject.\n */\n inject: {\n http: HTTP;\n /**\n * A function to get a possible helper service. This is injected as a \"getter\" to not\n * interrupt the DIC \"lifecycle\": controllers are initialized right when the app\n * starts, and injecting a reference would force the service to be initialized too,\n * even if a request is not being made.\n */\n getHelperService?: () => GatewayHelperService | undefined;\n };\n};\n/**\n * The options for {@link GatewayController._addRoute}.\n *\n * @access protected\n * @group Controllers/Gateway\n */\nexport type AddGatewayRouteOptions = {\n /**\n * The reference for the router in which the middlewares will be added.\n */\n router: Router;\n /**\n * The router method in which the middlewares will be added.\n */\n method: RouterMethod;\n /**\n * The route in which the middlewares will be added.\n */\n route: string;\n /**\n * The middleware created by {@link GatewayController}, that makes the request.\n */\n gatewayMiddleware: AsyncExpressMiddleware;\n /**\n * A list of extra middlewares to prepend to the gateway middleware.\n */\n middlewares: ExpressMiddleware[];\n};\n/**\n * A utility controller that generates routes that act as a gateway for a specific API.\n *\n * @group Controller Classes\n * @group Controllers/Gateway\n * @prettierignore\n */\nexport class GatewayController {\n /**\n * The service that makes HTTP requests.\n */\n protected readonly http: HTTP;\n /**\n * A function to get a possible helper service. This is injected as a \"getter\" to not\n * interrupt the DIC \"lifecycle\": controllers are initialized right when the app\n * starts, and injecting a reference would force the service to be initialized too,\n * even if a request is not being made.\n */\n protected readonly _getHelperService: () => GatewayHelperService | undefined;\n /**\n * The information, url and endpoints, for the gateway the controller will make requests to.\n */\n protected readonly _gatewayConfig: GatewayConfig;\n /**\n * The route in which the controller is mounted.\n */\n protected readonly _route: string;\n /**\n * A regular expression that will be used to remove the controller route from a\n * request path. This will allow the main middleware to extract the path to where the\n * request should be made.\n */\n protected readonly _routeExpression: RegExp;\n /**\n * The controller customization options.\n */\n protected readonly _options: GatewayControllerExtraOptions;\n /**\n * A flat dictionary with the endpoints information.\n */\n protected readonly _endpoints: Record<string, GatewayConfigEndpointDefinition>;\n /**\n * The entry URL for the API client configuration the controller can generate.\n */\n protected readonly _apiConfigUrl: string;\n /**\n * The generated endpoints for the API client configuration the controller can generate.\n */\n protected readonly _apiConfigEndpoints: APIClientOptions['endpoints'];\n /**\n * The list of routes the controller can handle.\n */\n protected readonly _routes: GatewayControllerRoute[];\n /**\n * @param options The options to construct the controller.\n */\n constructor({\n inject,\n route,\n gatewayConfig,\n ...options\n }: GatewayControllerConstructorOptions) {\n this.http = inject.http;\n this._getHelperService = inject.getHelperService || (() => undefined);\n this._route = removeSlashes(route);\n this._options = this._formatOptions(\n deepAssignWithOverwrite(\n {\n root: '',\n apiConfigSetting: 'api',\n headers: {\n useXForwardedFor: true,\n copyCustomHeaders: true,\n copy: ['authorization', 'content-type', 'referer', 'user-agent'],\n remove: ['server', 'x-powered-by', 'content-encoding'],\n },\n },\n options,\n ),\n );\n this._gatewayConfig = {\n ...gatewayConfig,\n url: removeSlashes(gatewayConfig.url, false, true),\n };\n this._routeExpression = createRouteExpression(\n this._options.root ? `${this._route}/${this._options.root}` : this._route,\n true,\n true,\n );\n this._endpoints = this._formatEndpoints();\n this._routes = this._createRoutes();\n const { url, endpoints } = this._createAPIConfig();\n this._apiConfigUrl = url;\n this._apiConfigEndpoints = endpoints;\n }\n /**\n * Generates an API client configuration based on the controller routes.\n *\n * @param options The options to customize the generated configuration.\n */\n getAPIConfig({\n setting,\n placeholders = {},\n }: GatewayControllerAPIConfigOptions = {}): Readonly<GatewayControllerAPIConfig> {\n const useSetting = setting || this._options.apiConfigSetting;\n let url: string;\n const placeholdersEntries = Object.entries(placeholders);\n if (placeholdersEntries.length) {\n url = placeholdersEntries.reduce<string>(\n (acc, [key, value]) => acc.replace(`:${key}`, value),\n this._apiConfigUrl,\n );\n } else {\n url = this._apiConfigUrl;\n }\n\n return {\n url,\n endpoints: {\n [useSetting]: this._apiConfigEndpoints,\n },\n };\n }\n /**\n * Mounts the middlewares in the router in order to make the requests.\n *\n * @param router A reference to the application router.\n * @param middlewares A list of extra middlewares to execute before the gateway\n * middleware.\n */\n addRoutes(router: Router, middlewares: ExpressMiddleware[] = []): Router {\n this._routes.forEach((route) => {\n route.methods.forEach((info) => {\n this._addRoute({\n router,\n method: info.method,\n route: route.route,\n gatewayMiddleware: this._createGatewayMiddleware(info.endpoint),\n middlewares,\n });\n });\n });\n\n return router;\n }\n /**\n * The customization options.\n */\n get options(): Readonly<GatewayControllerExtraOptions> {\n return { ...this._options };\n }\n /**\n * The configuration for the gateway the controller will make requests to.\n */\n get gatewayConfig(): Readonly<GatewayConfig> {\n return { ...this._gatewayConfig };\n }\n /**\n * Generates a middleware that will make the request to an endpoint and stream the\n * response.\n *\n * @param endpoint The information of the endpoint the middleware will handle.\n */\n protected _createGatewayMiddleware(\n endpoint: GatewayControllerEndpointInfo,\n ): AsyncExpressMiddleware {\n return async (req, res, next) => {\n const {\n _options: { headers: headersOptions },\n _gatewayConfig: { url: gatewayUrl },\n _routeExpression: routeExpression,\n } = this;\n // Remove the controller route from the requested URL.\n const reqPath = req.originalUrl.replace(routeExpression, '');\n // Process the headers for the request.\n let headers: Record<string, string> = {};\n // - Copy the headers from the incoming request.\n headersOptions.copy.forEach((name) => {\n if (req.headers[name]) {\n headers[name] = req.headers[name] as string;\n }\n });\n // - Copy the custom headers.\n if (headersOptions.copyCustomHeaders) {\n headers = deepAssignWithOverwrite<Record<string, string>>(\n headers,\n this.http.getCustomHeadersFromRequest(req),\n );\n }\n // - Include the IP on the X-Forwarded-For header, if enabled.\n if (headersOptions.useXForwardedFor) {\n const ip = this.http.getIPFromRequest(req);\n if (ip) {\n headers['x-forwarded-for'] = ip;\n }\n }\n\n const method = req.method.toUpperCase();\n // If the request has a body and the method is not `GET`, stringify it.\n let body: string | undefined;\n if (method !== 'GET' && typeof req.body === 'object') {\n body = JSON.stringify(req.body);\n // If there's no `content-type`, let's assume it's JSON.\n if (!headers['content-type']) {\n headers['content-type'] = 'application/json';\n }\n }\n\n /**\n * Get the helper service, if there's one, and define the base options for its\n * methods.\n */\n const helper = this._getHelperService() || {};\n const helperBasePayload = {\n endpoint,\n req,\n res,\n next,\n helper,\n };\n\n try {\n // Reduce the request information before using it.\n const request = await this._reduceEndpointRequest({\n endpointReq: {\n url: `${gatewayUrl}/${reqPath}`,\n options: {\n method,\n headers,\n body,\n },\n },\n ...helperBasePayload,\n });\n // Make the actual request.\n const responseRaw = await this.http.fetch(request.url, request.options);\n // Reduce the response information before using it.\n const response = await this._reduceEndpointResponse({\n endpointRes: responseRaw,\n ...helperBasePayload,\n });\n // Validate if the response should be streamed.\n const shouldStream = await this._shouldStreamEndpointResponse({\n endpointRes: responseRaw,\n ...helperBasePayload,\n });\n\n if (shouldStream) {\n if (response.body === null) {\n throw new Error('The response body is null');\n }\n\n /**\n * If the response should be streamed, set the status, remove unwanted headers,\n * and pipe it to the application response object.\n */\n res.status(response.status);\n response.headers.forEach((value, name) => {\n if (!headersOptions.remove.includes(name)) {\n res.setHeader(name, value);\n }\n });\n\n response.body.pipe(res).on('error', (error) => {\n next(error);\n });\n } else {\n /**\n * If the response should not be streamed, send it to the helper method to\n * handle it.\n */\n await this._handleEndpointResponse({\n endpointRes: response,\n ...helperBasePayload,\n });\n }\n } catch (error) {\n // Something failed, so let's pass the error to the helper service.\n this._handleEndpointError({\n error: error as Error,\n ...helperBasePayload,\n });\n }\n };\n }\n /**\n * Mounts the middleware(s) for an endpoint in the router.\n *\n * @param options The information of the endpoint and how it needs to be added.\n */\n protected _addRoute({\n router,\n method,\n route,\n gatewayMiddleware,\n middlewares,\n }: AddGatewayRouteOptions): void {\n router[method](route, [...middlewares, gatewayMiddleware]);\n }\n /**\n * Formats the endpoints for the gateway into a flat dictionary without nesting.\n */\n protected _formatEndpoints(): Record<string, GatewayConfigEndpointDefinition> {\n return flat({\n target: this._gatewayConfig.gateway,\n shouldFlatten: (_, value) => {\n const useValue = value as { path?: string };\n return typeof useValue.path === 'undefined';\n },\n });\n }\n /**\n * Based on the information from the endpoints, this method will create the routes the\n * controller will later add on a router.\n *\n * @throws If there's more than one endpoint using the same path with the same HTTP\n * method.\n */\n protected _createRoutes(): GatewayControllerRoute[] {\n const routes: Record<\n string,\n {\n path: string;\n methods: Partial<Record<RouterMethod, string>>;\n }\n > = {};\n Object.keys(this._endpoints).forEach((name) => {\n const endpoint = this._endpoints[name]!;\n let endpointPath: string;\n let endpointMethod: RouterMethod;\n if (typeof endpoint === 'string') {\n endpointPath = endpoint;\n endpointMethod = 'all';\n } else {\n endpointPath = endpoint.path;\n endpointMethod = endpoint.method\n ? this._validateHTTPMethod(endpoint.method)\n : 'all';\n }\n\n endpointPath = removeSlashes(endpointPath);\n if (!routes[endpointPath]) {\n routes[endpointPath] = {\n path: endpointPath,\n methods: {},\n };\n }\n\n if (routes[endpointPath]!.methods[endpointMethod]) {\n const repeatedEndpoint = routes[endpointPath]!.methods[endpointMethod];\n throw new Error(\n \"You can't have two gateway endpoints to the same path and with the same \" +\n `HTTP method: '${repeatedEndpoint}' and '${name}'`,\n );\n }\n\n routes[endpointPath]!.methods[endpointMethod] = name;\n });\n\n const routePrefixes = this._options.root ? `/${this._options.root}/` : '/';\n return Object.keys(routes).map((endpointPath) => {\n const info = routes[endpointPath]!;\n return {\n path: info.path,\n route: `${routePrefixes}${info.path}`,\n methods: Object.keys(info.methods).map((methodNameRaw) => {\n const methodName = methodNameRaw as RouterMethod;\n const endpointName = info.methods[methodName]!;\n const endpointDefinition = this._endpoints[endpointName]!;\n return {\n method: methodName,\n endpoint: {\n name: endpointName,\n definition: endpointDefinition,\n },\n };\n }),\n };\n });\n }\n /**\n * This is a \"proxy method\" to call the helper service's function that can modify an\n * endpoint request before it gets made.\n *\n * The reason this is a \"proxy method\" is in case the controller gets subclassed and\n * \"used itself as a helper\" instead of relying on a difference one.\n *\n * If the helper doesn't implement `reduceEndpointRequest`, it will just return\n * information for the request.\n *\n * @param options The information of the request and the reference to the helper.\n */\n protected _reduceEndpointRequest({\n helper,\n ...options\n }: GatewayControllerHelperOptions<GatewayHelperServiceRequestReducerOptions>): Promise<GatewayControllerRequest> {\n if (helper.reduceEndpointRequest) {\n return helper.reduceEndpointRequest(options);\n }\n\n return Promise.resolve(options.endpointReq);\n }\n /**\n * This is a \"proxy method\" to call the helper service's function that can modify an\n * endpoint response before it gets processed.\n *\n * The reason this is a \"proxy method\" is in case the controller gets subclassed and\n * \"used itself as a helper\" instead of relying on a difference one.\n *\n * If the helper doesn't implement `reduceEndpointResponse`, it will just return\n * information for the response.\n *\n * @param options The information of the response and the reference to the helper.\n */\n protected _reduceEndpointResponse({\n helper,\n ...options\n }: GatewayControllerHelperOptions<GatewayHelperServiceResponseReducerOptions>): Promise<HTTPResponse> {\n if (helper.reduceEndpointResponse) {\n return helper.reduceEndpointResponse(options);\n }\n\n return Promise.resolve(options.endpointRes);\n }\n /**\n * This is a \"proxy method\" to call the helper service's function that can decide if an\n * endpoint response should be streamed or not.\n *\n * The reason this is a \"proxy method\" is in case the controller gets subclassed and\n * \"used itself as a helper\" instead of relying on a difference one.\n *\n * If the helper doesn't implement `shouldStreamEndpointResponse`, it will just return\n * `true`.\n *\n * @param options The information of the response and the reference to the helper.\n */\n protected _shouldStreamEndpointResponse({\n helper,\n ...options\n }: GatewayControllerHelperOptions<GatewayHelperServiceResponseReducerOptions>): Promise<boolean> {\n if (helper.shouldStreamEndpointResponse) {\n return helper.shouldStreamEndpointResponse(options);\n }\n\n return Promise.resolve(true);\n }\n /**\n * This is a \"proxy method\" to call the helper service's function that handles a\n * response in case it already said that a response shouldn't be streamed.\n *\n * The reason this is a \"proxy method\" is in case the controller gets subclassed and\n * \"used itself as a helper\" instead of relying on a difference one.\n *\n * If the helper doesn't implement `shouldStreamEndpointResponse`, it will throw an\n * error.\n *\n * @param options The information of the response and the reference to the helper.\n * @throws If the helper doesn't implement `handleEndpointResponse`.\n */\n protected _handleEndpointResponse({\n helper,\n ...options\n }: GatewayControllerHelperOptions<GatewayHelperServiceResponseReducerOptions>): Promise<void> {\n if (!helper.handleEndpointResponse) {\n throw new Error('You must implement handleEndpointResponse');\n }\n\n return helper.handleEndpointResponse(options);\n }\n /**\n * This is a \"proxy method\" to call the helper service's function that handles an error\n * on an endpoint request.\n *\n * The reason this is a \"proxy method\" is in case the controller gets subclassed and\n * \"used itself as a helper\" instead of relying on a difference one.\n *\n * If the helper doesn't implement `handleEndpointError`, it will just send the error to\n * the next middleware/error handler.\n *\n * @param options The information of the response and the reference to the helper.\n */\n protected _handleEndpointError({\n helper,\n ...options\n }: GatewayControllerHelperOptions<GatewayHelperServiceErrorHandlerOptions>): void {\n if (helper.handleEndpointError) {\n return helper.handleEndpointError(options);\n }\n\n return options.next(options.error);\n }\n /**\n * Validates and formats the customization options sent to the controller.\n *\n * @param options The options sent to the constructor.\n */\n protected _formatOptions(\n options: GatewayControllerExtraOptions,\n ): GatewayControllerExtraOptions {\n if (options.root) {\n const root = removeSlashes(options.root).trim();\n return { ...options, root };\n }\n\n return options;\n }\n /**\n * Validates a router/HTTP method that the controller intends to use for an endpoint. If\n * it's not valid, it will return `all`.\n *\n * @param method The HTTP method for the endpoint.\n */\n protected _validateHTTPMethod(method: string): RouterMethod {\n const newMethod = method.toLowerCase();\n return [\n 'get',\n 'head',\n 'post',\n 'patch',\n 'put',\n 'delete',\n 'connect',\n 'options',\n 'trace',\n ].includes(newMethod)\n ? (newMethod as RouterMethod)\n : 'all';\n }\n /**\n * Creates the API client configuration based on the controller routes.\n */\n protected _createAPIConfig(): GatewayControllerAPIConfig {\n let endpoints: APIClientOptions['endpoints'];\n const { root } = this._options;\n if (root) {\n endpoints = Object.keys(this._endpoints).reduce<\n Record<string, GatewayConfigEndpointDefinition>\n >((acc, name) => {\n const endpoint = this._endpoints[name]!;\n let newEndpoint;\n if (typeof endpoint === 'string') {\n newEndpoint = removeSlashes(endpoint);\n newEndpoint = `${root}/${newEndpoint}`;\n } else {\n const endpointPath = removeSlashes(endpoint.path);\n newEndpoint = {\n ...endpoint,\n path: `${root}/${endpointPath}`,\n };\n }\n\n acc[name] = newEndpoint;\n return acc;\n }, {});\n } else {\n endpoints = this._endpoints;\n }\n\n return {\n url: `/${this._route}`,\n endpoints: unflat({ target: endpoints }),\n };\n }\n}\n/**\n * A function to generate a list of middlewares that can be executed before the tontroller\n * main middleware.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerGetMiddlewaresFn = (app: Jimpex) => MiddlewareLike[];\n/**\n * The options for the controller creator that mounts the {@link GatewayController}.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerCreatorOptions =\n DeepPartial<GatewayControllerExtraOptions> & {\n /**\n * The name the creator will use to register the controller in the container. No,\n * this is not a typo. The creator will register the controller so other services can\n * access the `getAPIConfig` method. The service will be available after the app\n * routes are mounted.\n * If this is overwritten, the creator will ensure that the name ends with `Gateway`;\n * and if overwritten, but it doesn't include `Gateway` at the end, and no\n * `gatewaySettingName` was defined, the creator will use the custom name (without\n * `Gatway`) for `gatewaySettingName`.\n *\n * @default 'apiGateway'\n */\n serviceName?: string;\n /**\n * The name of the helper service the creator will try to obtain from the container.\n * If `serviceName` is overwritten, the default for this will be\n * `${serviceName}Helper`.\n *\n * @default 'apiGatewayHelper'\n */\n helperServiceName?: string;\n /**\n * The name of the configuration setting where the gateway configuration is stored. If\n * not overwritten, check the description of `serviceName` to understand which will be\n * its default value.\n *\n * @default 'api'\n */\n gatewaySettingName?: string;\n /**\n * The class the creator will instantiate. Similar to the API Client, this allows for\n * extra customization as you can send a custom subclass of the\n * {@link GatewayController}.\n *\n * @default GatewayController\n */\n gatewayClass?: typeof GatewayController;\n /**\n * A function to generate a list of middlewares that can be executed before the\n * controller main middleware.\n */\n getMiddlewares?: GatewayControllerGetMiddlewaresFn;\n };\n/**\n * Creates a controller that allows the application to mount routes that will work like\n * gateway to a specific API.\n *\n * @group Controllers\n * @group Controllers/Gateway\n */\nexport const gatewayController = controllerProviderCreator(\n (options: GatewayControllerCreatorOptions = {}) =>\n (app, route) => {\n /**\n * Formats the name in order to keep consistency with the helper service and the\n * configuration setting: If the `serviceName` is different from the default, make\n * sure it ends with `Gateway`, set the default helper service name to\n * `${serviceName}Helper`, and the default configuration setting to the same as the\n * service name (without the `Gateway`).\n * This way, if you just use `myApi`, the service name will be `myApiGateway`, the\n * helper name will be `myApiGatewayHelper` and the configuration setting `myApi`.\n */\n const defaultServiceName = 'apiGateway';\n let defaultHelperServiceName = 'apiGatewayHelper';\n let defaultConfigSetting = 'api';\n let { serviceName = defaultServiceName } = options;\n if (serviceName !== defaultServiceName) {\n defaultConfigSetting = serviceName;\n if (!serviceName.match(/gateway$/i)) {\n serviceName = `${serviceName}Gateway`;\n }\n defaultHelperServiceName = `${serviceName}Helper`;\n }\n // Register the service.\n app.set(serviceName, () => {\n const {\n helperServiceName = defaultHelperServiceName,\n gatewaySettingName = defaultConfigSetting,\n gatewayClass: GatewayClass = GatewayController,\n } = options;\n\n const gtConfig = app.getConfig<GatewayConfig>(gatewaySettingName);\n\n return new GatewayClass({\n ...options,\n apiConfigSetting: gatewaySettingName,\n gatewayConfig: gtConfig,\n route,\n inject: {\n http: app.get('http'),\n getHelperService: () => app.try(helperServiceName),\n },\n });\n });\n\n return controller(() => {\n // Get the controller.\n const ctrl = app.get<GatewayController>(serviceName);\n /**\n * Check if there are actual middlewares to be included, and in case there are\n * Jimpex middlewares, connect them.\n */\n let useMiddlewares: ExpressMiddleware[] | undefined;\n if (options.getMiddlewares) {\n useMiddlewares = options\n .getMiddlewares(app)\n .map((middleware) => {\n if ('middleware' in middleware) {\n return middleware.connect(app) as ExpressMiddleware | undefined;\n }\n\n return middleware as ExpressMiddleware;\n })\n .filter(notUndefined);\n }\n\n // Add the routes to the router and return it.\n return ctrl.addRoutes(app.get('router'), useMiddlewares);\n });\n },\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAAwC;AACxC,0BAA6B;AAE7B,mBAOO;AAweA,MAAM,kBAAkB;AAAA;AAAA;AAAA;AAAA,EAiD7B,YAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAG;AAAA,EACL,GAAwC;AAlDxC;AAAA;AAAA;AAAA,wBAAmB;AAOnB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAmB;AAInB;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;AAC/B,QAAI,uBAAuB;AAC3B,QAAI,EAAE,cAAc,mBAAmB,IAAI;AAC3C,QAAI,gBAAgB,oBAAoB;AACtC,6BAAuB;AACvB,UAAI,CAAC,YAAY,MAAM,WAAW,GAAG;AACnC,sBAAc,GAAG,WAAW;AAAA,MAC9B;AACA,iCAA2B,GAAG,WAAW;AAAA,IAC3C;AAEA,QAAI,IAAI,aAAa,MAAM;AACzB,YAAM;AAAA,QACJ,oBAAoB;AAAA,QACpB,qBAAqB;AAAA,QACrB,cAAc,eAAe;AAAA,MAC/B,IAAI;AAEJ,YAAM,WAAW,IAAI,UAAyB,kBAAkB;AAEhE,aAAO,IAAI,aAAa;AAAA,QACtB,GAAG;AAAA,QACH,kBAAkB;AAAA,QAClB,eAAe;AAAA,QACf;AAAA,QACA,QAAQ;AAAA,UACN,MAAM,IAAI,IAAI,MAAM;AAAA,UACpB,kBAAkB,MAAM,IAAI,IAAI,iBAAiB;AAAA,QACnD;AAAA,MACF,CAAC;AAAA,IACH,CAAC;AAED,eAAO,yBAAW,MAAM;AAEtB,YAAM,OAAO,IAAI,IAAuB,WAAW;AAKnD,UAAI;AACJ,UAAI,QAAQ,gBAAgB;AAC1B,yBAAiB,QACd,eAAe,GAAG,EAClB,IAAI,CAAC,eAAe;AACnB,cAAI,gBAAgB,YAAY;AAC9B,mBAAO,WAAW,QAAQ,GAAG;AAAA,UAC/B;AAEA,iBAAO;AAAA,QACT,CAAC,EACA,OAAO,yBAAY;AAAA,MACxB;AAGA,aAAO,KAAK,UAAU,IAAI,IAAI,QAAQ,GAAG,cAAc;AAAA,IACzD,CAAC;AAAA,EACH;AACJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/controllers/utils/gateway.ts"],"sourcesContent":["import { deepAssignWithOverwrite } from '@homer0/deep-assign';\nimport { flat, unflat } from '@homer0/object-utils';\nimport type { APIClientOptions } from '@homer0/api-utils';\nimport {\n controllerProviderCreator,\n controller,\n createRouteExpression,\n removeSlashes,\n notUndefined,\n type MiddlewareLike,\n} from '../../utils/index.js';\nimport type { HTTP, HTTPFetchOptions } from '../../services/index.js';\nimport type { Jimpex } from '../../app/index.js';\nimport {\n RouterMethod,\n DeepPartial,\n Request,\n Response,\n NextFunction,\n HTTPResponse,\n Router,\n ExpressMiddleware,\n AsyncExpressMiddleware,\n} from '../../types/index.js';\n/**\n * The extended definition for endpoints.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayConfigEndpointProps = {\n /**\n * The path to the endpoint relative to the entry point. It can include placeholders for\n * parameters like `/:parameter/`.\n */\n path: string;\n /**\n * The router (HTTP) method for the endpoint.\n *\n * @default 'all'\n */\n method?: RouterMethod;\n};\n/**\n * The definition of an endpoint: it can be just the path, relative to the entry point, or\n * an object in which you can also specify things like the method.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayConfigEndpointDefinition = string | GatewayConfigEndpointProps;\n/**\n * The dictionary of endpoints the controller uses. The reason for this type is that this\n * could be a flat dictionary, or a nested one.\n *\n * @example\n *\n * <caption>A flat dictionary</caption>\n *\n * {\n * random: '/random',\n * users: '/users',\n * userById: {\n * path: '/users/:id',\n * method: 'get',\n * },\n * }\n *\n * @example\n *\n * <caption>A nested dictionary</caption>\n *\n * {\n * random: '/random',\n * users: {\n * list: '/users',\n * byId: {\n * path: '/users/:id',\n * method: 'get',\n * },\n * },\n * }\n *\n * @group Controllers/Gateway\n */\nexport type GatewayConfigEndpoints = {\n [key: string]: GatewayConfigEndpointDefinition | GatewayConfigEndpoints;\n};\n/**\n * The configuration for the gateway the controller uses.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayConfig = {\n /**\n * The entry point to the API the controller will make the requests to.\n */\n url: string;\n /**\n * The dictionary of endpoints the gateway will make available.\n */\n gateway: GatewayConfigEndpoints;\n};\n/**\n * The options for how the gateway will handle the headers from the requests and the\n * responses.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerHeaderOptions = {\n /**\n * Whether or not to include the header with the request's IP address.\n *\n * @default true\n */\n useXForwardedFor: boolean;\n /**\n * Whether or not to copy all custom headers from the request. By custom header, it\n * means all the headers which names start with `x-`.\n *\n * @default true\n */\n copyCustomHeaders: boolean;\n /**\n * A list of \"known\" headers the gateway will try to copy from the incoming request.\n *\n * @default ['authorization','content-type', 'referer', 'user-agent']\n */\n copy: string[];\n /**\n * A list of \"known\" headers the gateway will try to remove the response.\n *\n * @default ['server', 'x-powered-by']\n */\n remove: string[];\n};\n/**\n * The extra options for the gateway controller. They are \"extra\" because they are mostly\n * helpers for when used with an API client, or for optional features.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerExtraOptions = {\n /**\n * This is really a helper for when the gateway is used with an API client. The idea is\n * that, by default, the routes are mounted on the controller route, but with this\n * option, you can specify another sub path. For example: The controller is mounted on\n * `/routes`, and if you set `root` to `gateway`, all the routes will be on\n * `/routes/gateway`.\n *\n * This become important (and useful) when you get the API client configuration (with\n * `getAPIConfig`): The `url` will be the controller route, but all the endpoints will\n * be modified and prefixed with the `root`, that way, you can have multiple gateways in\n * the same \"base route\".\n *\n * It can also includes placeholders for parameters like `/:parameter/`, that will be\n * replaced with the `placeholders` option when `getAPIConfig` gets called.\n *\n * @default ''\n */\n root: string;\n /**\n * This is another option for when the gateway is used with an API client. When calling\n * `getAPIConfig`, all the endpoints will be wrapped inside an object named after this\n * option. For example: `{ url: '...', endpoints: { api: { ... } } }`.\n *\n * @default 'api'\n */\n apiConfigSetting: string;\n /**\n * The options for how the gateway will handle the headers from the requests and the\n * responses.\n */\n headers: GatewayControllerHeaderOptions;\n};\n/**\n * The required options for the gateway controller.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerOptions = {\n /**\n * The configuration for the API the gateway will make the requests to.\n */\n gatewayConfig: GatewayConfig;\n /**\n * The route where the controller is mounted.\n */\n route: string;\n} & DeepPartial<GatewayControllerExtraOptions>;\n/**\n * The information for a request the controller will make.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerRequest = {\n /**\n * The URL for the request.\n */\n url: string;\n /**\n * The options for the fetch client that will make the requests.\n */\n options: HTTPFetchOptions;\n};\n/**\n * The information for an endpoint the gateway is calling.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerEndpointInfo = {\n /**\n * The name of the endpoint in the configuration.\n */\n name: string;\n /**\n * The properties (path and method) of the endpoint.\n */\n definition: GatewayConfigEndpointDefinition;\n};\n/**\n * These are the base options sent to all the helper service functions.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceBaseFnOptions = {\n /**\n * The information of the endpoint the gateway is calling.\n */\n endpoint: GatewayControllerEndpointInfo;\n /**\n * The request received by the application.\n */\n req: Request;\n /**\n * The response object created by the application.\n */\n res: Response;\n /**\n * The function to call the next middleware in the chain.\n */\n next: NextFunction;\n};\n/**\n * The information sent to the helper service in order to modify, or not, a request before\n * it is sent.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceRequestReducerOptions =\n GatewayHelperServiceBaseFnOptions & {\n /**\n * The options the controller created for the fetch client.\n */\n endpointReq: GatewayControllerRequest;\n };\n/**\n * A function that can be used to modify the information of an endpoint before making a\n * request.\n *\n * @param options The information of the request.\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceRequestReducer = (\n options: GatewayHelperServiceRequestReducerOptions,\n) => Promise<GatewayControllerRequest>;\n/**\n * The information sent to the helper service in order to modify a response before\n * processing it, decide if it should be streamed or not, and even handle it.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceResponseReducerOptions =\n GatewayHelperServiceBaseFnOptions & {\n /**\n * The response from the endpoint request.\n */\n endpointRes: HTTPResponse;\n };\n/**\n * A function that can be used to modify the response of an endpoint before the controller\n * processes it.\n *\n * @param options The information of the response.\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceResponseReducer = (\n options: GatewayHelperServiceResponseReducerOptions,\n) => Promise<HTTPResponse>;\n/**\n * A function that can be used to tell the controller to stream the response of an\n * endpoint or not.\n * If it returns `false`, the function to handle responses should be defined, otherwise,\n * an error will be generated.\n *\n * @param options The information of the response.\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceStreamVerification = (\n options: GatewayHelperServiceResponseReducerOptions,\n) => Promise<boolean>;\n/**\n * A function to handle the response of an endpoint. This is called when the helper\n * service tells the controller that the endpoint shouldn't be streamed, so this method\n * should handle the response.\n *\n * @param options The information of the response.\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceResponseHandler = (\n options: GatewayHelperServiceResponseReducerOptions,\n) => Promise<void>;\n/**\n * The information sent to the helper service in order to handle a failed request for an\n * endpoint.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceErrorHandlerOptions =\n GatewayHelperServiceBaseFnOptions & {\n /**\n * The error generated during the request.\n */\n error: Error;\n };\n/**\n * A function to handle the error of an endpoint request.\n *\n * @param options The information of the error.\n * @group Controllers/Gateway\n */\nexport type GatewayHelperServiceErrorHandler = (\n options: GatewayHelperServiceErrorHandlerOptions,\n) => void;\n/**\n * The interface of a helper service that can intercept/modify the requests and responses\n * the gateway makes.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayHelperService = Partial<{\n /**\n * A function that is called before an endpoint request is made.\n */\n reduceEndpointRequest: GatewayHelperServiceRequestReducer;\n /**\n * A function that is called with the response of an endpoint request.\n */\n reduceEndpointResponse: GatewayHelperServiceResponseReducer;\n /**\n * A function called in order to validate if an endpoint response should be streamed or\n * not. If the function returns `false`, `handleEndpointResponse` will be called.\n */\n shouldStreamEndpointResponse: GatewayHelperServiceStreamVerification;\n /**\n * A function called when `shouldStreamEndpointResponse` returns `false`. The function\n * should handle the response for the application.\n */\n handleEndpointResponse: GatewayHelperServiceResponseHandler;\n /**\n * A function called when an error is generated during an endpoint request/processing.\n */\n handleEndpointError: GatewayHelperServiceErrorHandler;\n}>;\n/**\n * Utility type for the options object sent to the \"proxy methods\" the controller has for\n * the helper service.\n *\n * @template T The type of the options for a specific helper service function.\n * @access protected\n * @group Controllers/Gateway\n */\nexport type GatewayControllerHelperOptions<T> = T & {\n /**\n * The reference for the helper service.\n */\n helper: GatewayHelperService;\n};\n/**\n * The information for a single HTTP method an endpoint can handle.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerRouteMethod = {\n /**\n * The method for the route.\n */\n method: RouterMethod;\n /**\n * The information of the endpoint.\n */\n endpoint: GatewayControllerEndpointInfo;\n};\n/**\n * The information for all the HTTP methods that can be handled for an endpoint.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerRoute = {\n /**\n * The path to the endpoint, relative to the entry point.\n */\n path: string;\n /**\n * The path for the route in the controller. This is different from `path` as it's possible for\n * the gateway to be implemented using the `root` option.\n */\n route: string;\n /**\n * A list with all the methods the controller uses on the route.\n */\n methods: GatewayControllerRouteMethod[];\n};\n/**\n * The API client configuration the gateway can generate for its endpoints.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerAPIConfig = {\n /**\n * The base URL for the API.\n */\n url: string;\n /**\n * The dictionary of endpoints the controller handles.\n */\n endpoints: APIClientOptions['endpoints'];\n};\n/**\n * The options sent to {@link GatewayController.getAPIConfig}.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerAPIConfigOptions = {\n /**\n * This can be used to overwrite the gateway's `apiConfigSetting` option, and set a new\n * setting as a wrapper for the endpoints.\n */\n setting?: string;\n /**\n * A dictionary of values for possible placeholders that were sent using the `root`\n * option.\n */\n placeholders?: Record<string, string>;\n};\n/**\n * The options to construct a {@link GatewayController}.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerConstructorOptions = GatewayControllerOptions & {\n /**\n * A dictionary with the dependencies to inject.\n */\n inject: {\n http: HTTP;\n /**\n * A function to get a possible helper service. This is injected as a \"getter\" to not\n * interrupt the DIC \"lifecycle\": controllers are initialized right when the app\n * starts, and injecting a reference would force the service to be initialized too,\n * even if a request is not being made.\n */\n getHelperService?: () => GatewayHelperService | undefined;\n };\n};\n/**\n * The options for {@link GatewayController._addRoute}.\n *\n * @access protected\n * @group Controllers/Gateway\n */\nexport type AddGatewayRouteOptions = {\n /**\n * The reference for the router in which the middlewares will be added.\n */\n router: Router;\n /**\n * The router method in which the middlewares will be added.\n */\n method: RouterMethod;\n /**\n * The route in which the middlewares will be added.\n */\n route: string;\n /**\n * The middleware created by {@link GatewayController}, that makes the request.\n */\n gatewayMiddleware: AsyncExpressMiddleware;\n /**\n * A list of extra middlewares to prepend to the gateway middleware.\n */\n middlewares: ExpressMiddleware[];\n};\n/**\n * A utility controller that generates routes that act as a gateway for a specific API.\n *\n * @group Controller Classes\n * @group Controllers/Gateway\n * @prettierignore\n */\nexport class GatewayController {\n /**\n * The service that makes HTTP requests.\n */\n protected readonly http: HTTP;\n /**\n * A function to get a possible helper service. This is injected as a \"getter\" to not\n * interrupt the DIC \"lifecycle\": controllers are initialized right when the app\n * starts, and injecting a reference would force the service to be initialized too,\n * even if a request is not being made.\n */\n protected readonly _getHelperService: () => GatewayHelperService | undefined;\n /**\n * The information, url and endpoints, for the gateway the controller will make requests to.\n */\n protected readonly _gatewayConfig: GatewayConfig;\n /**\n * The route in which the controller is mounted.\n */\n protected readonly _route: string;\n /**\n * A regular expression that will be used to remove the controller route from a\n * request path. This will allow the main middleware to extract the path to where the\n * request should be made.\n */\n protected readonly _routeExpression: RegExp;\n /**\n * The controller customization options.\n */\n protected readonly _options: GatewayControllerExtraOptions;\n /**\n * A flat dictionary with the endpoints information.\n */\n protected readonly _endpoints: Record<string, GatewayConfigEndpointDefinition>;\n /**\n * The entry URL for the API client configuration the controller can generate.\n */\n protected readonly _apiConfigUrl: string;\n /**\n * The generated endpoints for the API client configuration the controller can generate.\n */\n protected readonly _apiConfigEndpoints: APIClientOptions['endpoints'];\n /**\n * The list of routes the controller can handle.\n */\n protected readonly _routes: GatewayControllerRoute[];\n /**\n * @param options The options to construct the controller.\n */\n constructor({\n inject,\n route,\n gatewayConfig,\n ...options\n }: GatewayControllerConstructorOptions) {\n this.http = inject.http;\n this._getHelperService = inject.getHelperService || (() => undefined);\n this._route = removeSlashes(route);\n this._options = this._formatOptions(\n deepAssignWithOverwrite(\n {\n root: '',\n apiConfigSetting: 'api',\n headers: {\n useXForwardedFor: true,\n copyCustomHeaders: true,\n copy: ['authorization', 'content-type', 'referer', 'user-agent'],\n remove: ['server', 'x-powered-by', 'content-encoding'],\n },\n },\n options,\n ),\n );\n this._gatewayConfig = {\n ...gatewayConfig,\n url: removeSlashes(gatewayConfig.url, false, true),\n };\n this._routeExpression = createRouteExpression(\n this._options.root ? `${this._route}/${this._options.root}` : this._route,\n true,\n true,\n );\n this._endpoints = this._formatEndpoints();\n this._routes = this._createRoutes();\n const { url, endpoints } = this._createAPIConfig();\n this._apiConfigUrl = url;\n this._apiConfigEndpoints = endpoints;\n }\n /**\n * Generates an API client configuration based on the controller routes.\n *\n * @param options The options to customize the generated configuration.\n */\n getAPIConfig({\n setting,\n placeholders = {},\n }: GatewayControllerAPIConfigOptions = {}): Readonly<GatewayControllerAPIConfig> {\n const useSetting = setting || this._options.apiConfigSetting;\n let url: string;\n const placeholdersEntries = Object.entries(placeholders);\n if (placeholdersEntries.length) {\n url = placeholdersEntries.reduce<string>(\n (acc, [key, value]) => acc.replace(`:${key}`, value),\n this._apiConfigUrl,\n );\n } else {\n url = this._apiConfigUrl;\n }\n\n return {\n url,\n endpoints: {\n [useSetting]: this._apiConfigEndpoints,\n },\n };\n }\n /**\n * Mounts the middlewares in the router in order to make the requests.\n *\n * @param router A reference to the application router.\n * @param middlewares A list of extra middlewares to execute before the gateway\n * middleware.\n */\n addRoutes(router: Router, middlewares: ExpressMiddleware[] = []): Router {\n this._routes.forEach((route) => {\n route.methods.forEach((info) => {\n this._addRoute({\n router,\n method: info.method,\n route: route.route,\n gatewayMiddleware: this._createGatewayMiddleware(info.endpoint),\n middlewares,\n });\n });\n });\n\n return router;\n }\n /**\n * The customization options.\n */\n get options(): Readonly<GatewayControllerExtraOptions> {\n return { ...this._options };\n }\n /**\n * The configuration for the gateway the controller will make requests to.\n */\n get gatewayConfig(): Readonly<GatewayConfig> {\n return { ...this._gatewayConfig };\n }\n /**\n * Generates a middleware that will make the request to an endpoint and stream the\n * response.\n *\n * @param endpoint The information of the endpoint the middleware will handle.\n */\n protected _createGatewayMiddleware(\n endpoint: GatewayControllerEndpointInfo,\n ): AsyncExpressMiddleware {\n return async (req, res, next) => {\n const {\n _options: { headers: headersOptions },\n _gatewayConfig: { url: gatewayUrl },\n _routeExpression: routeExpression,\n } = this;\n // Remove the controller route from the requested URL.\n const reqPath = req.originalUrl.replace(routeExpression, '');\n // Process the headers for the request.\n let headers: Record<string, string> = {};\n // - Copy the headers from the incoming request.\n headersOptions.copy.forEach((name) => {\n if (req.headers[name]) {\n headers[name] = req.headers[name] as string;\n }\n });\n // - Copy the custom headers.\n if (headersOptions.copyCustomHeaders) {\n headers = deepAssignWithOverwrite<Record<string, string>>(\n headers,\n this.http.getCustomHeadersFromRequest(req),\n );\n }\n // - Include the IP on the X-Forwarded-For header, if enabled.\n if (headersOptions.useXForwardedFor) {\n const ip = this.http.getIPFromRequest(req);\n if (ip) {\n headers['x-forwarded-for'] = ip;\n }\n }\n\n const method = req.method.toUpperCase();\n // If the request has a body and the method is not `GET`, stringify it.\n let body: string | undefined;\n if (method !== 'GET' && typeof req.body === 'object') {\n body = JSON.stringify(req.body);\n // If there's no `content-type`, let's assume it's JSON.\n if (!headers['content-type']) {\n headers['content-type'] = 'application/json';\n }\n }\n\n /**\n * Get the helper service, if there's one, and define the base options for its\n * methods.\n */\n const helper = this._getHelperService() || {};\n const helperBasePayload = {\n endpoint,\n req,\n res,\n next,\n helper,\n };\n\n try {\n // Reduce the request information before using it.\n const request = await this._reduceEndpointRequest({\n endpointReq: {\n url: `${gatewayUrl}/${reqPath}`,\n options: {\n method,\n headers,\n body,\n },\n },\n ...helperBasePayload,\n });\n // Make the actual request.\n const responseRaw = await this.http.fetch(request.url, request.options);\n // Reduce the response information before using it.\n const response = await this._reduceEndpointResponse({\n endpointRes: responseRaw,\n ...helperBasePayload,\n });\n // Validate if the response should be streamed.\n const shouldStream = await this._shouldStreamEndpointResponse({\n endpointRes: responseRaw,\n ...helperBasePayload,\n });\n\n if (shouldStream) {\n if (response.body === null) {\n throw new Error('The response body is null');\n }\n\n /**\n * If the response should be streamed, set the status, remove unwanted headers,\n * and pipe it to the application response object.\n */\n res.status(response.status);\n response.headers.forEach((value, name) => {\n if (!headersOptions.remove.includes(name)) {\n res.setHeader(name, value);\n }\n });\n\n response.body.pipe(res).on('error', (error) => {\n next(error);\n });\n } else {\n /**\n * If the response should not be streamed, send it to the helper method to\n * handle it.\n */\n await this._handleEndpointResponse({\n endpointRes: response,\n ...helperBasePayload,\n });\n }\n } catch (error) {\n // Something failed, so let's pass the error to the helper service.\n this._handleEndpointError({\n error: error as Error,\n ...helperBasePayload,\n });\n }\n };\n }\n /**\n * Mounts the middleware(s) for an endpoint in the router.\n *\n * @param options The information of the endpoint and how it needs to be added.\n */\n protected _addRoute({\n router,\n method,\n route,\n gatewayMiddleware,\n middlewares,\n }: AddGatewayRouteOptions): void {\n router[method](route, [...middlewares, gatewayMiddleware]);\n }\n /**\n * Formats the endpoints for the gateway into a flat dictionary without nesting.\n */\n protected _formatEndpoints(): Record<string, GatewayConfigEndpointDefinition> {\n return flat({\n target: this._gatewayConfig.gateway,\n shouldFlatten: (_, value) => {\n const useValue = value as { path?: string };\n return typeof useValue.path === 'undefined';\n },\n });\n }\n /**\n * Based on the information from the endpoints, this method will create the routes the\n * controller will later add on a router.\n *\n * @throws If there's more than one endpoint using the same path with the same HTTP\n * method.\n */\n protected _createRoutes(): GatewayControllerRoute[] {\n const routes: Record<\n string,\n {\n path: string;\n methods: Partial<Record<RouterMethod, string>>;\n }\n > = {};\n Object.keys(this._endpoints).forEach((name) => {\n const endpoint = this._endpoints[name]!;\n let endpointPath: string;\n let endpointMethod: RouterMethod;\n if (typeof endpoint === 'string') {\n endpointPath = endpoint;\n endpointMethod = 'all';\n } else {\n endpointPath = endpoint.path;\n endpointMethod = endpoint.method\n ? this._validateHTTPMethod(endpoint.method)\n : 'all';\n }\n\n endpointPath = removeSlashes(endpointPath);\n if (!routes[endpointPath]) {\n routes[endpointPath] = {\n path: endpointPath,\n methods: {},\n };\n }\n\n if (routes[endpointPath]!.methods[endpointMethod]) {\n const repeatedEndpoint = routes[endpointPath]!.methods[endpointMethod];\n throw new Error(\n \"You can't have two gateway endpoints to the same path and with the same \" +\n `HTTP method: '${repeatedEndpoint}' and '${name}'`,\n );\n }\n\n routes[endpointPath]!.methods[endpointMethod] = name;\n });\n\n const routePrefixes = this._options.root ? `/${this._options.root}/` : '/';\n return Object.keys(routes).map((endpointPath) => {\n const info = routes[endpointPath]!;\n return {\n path: info.path,\n route: `${routePrefixes}${info.path}`,\n methods: Object.keys(info.methods).map((methodNameRaw) => {\n const methodName = methodNameRaw as RouterMethod;\n const endpointName = info.methods[methodName]!;\n const endpointDefinition = this._endpoints[endpointName]!;\n return {\n method: methodName,\n endpoint: {\n name: endpointName,\n definition: endpointDefinition,\n },\n };\n }),\n };\n });\n }\n /**\n * This is a \"proxy method\" to call the helper service's function that can modify an\n * endpoint request before it gets made.\n *\n * The reason this is a \"proxy method\" is in case the controller gets subclassed and\n * \"used itself as a helper\" instead of relying on a difference one.\n *\n * If the helper doesn't implement `reduceEndpointRequest`, it will just return\n * information for the request.\n *\n * @param options The information of the request and the reference to the helper.\n */\n protected _reduceEndpointRequest({\n helper,\n ...options\n }: GatewayControllerHelperOptions<GatewayHelperServiceRequestReducerOptions>): Promise<GatewayControllerRequest> {\n if (helper.reduceEndpointRequest) {\n return helper.reduceEndpointRequest(options);\n }\n\n return Promise.resolve(options.endpointReq);\n }\n /**\n * This is a \"proxy method\" to call the helper service's function that can modify an\n * endpoint response before it gets processed.\n *\n * The reason this is a \"proxy method\" is in case the controller gets subclassed and\n * \"used itself as a helper\" instead of relying on a difference one.\n *\n * If the helper doesn't implement `reduceEndpointResponse`, it will just return\n * information for the response.\n *\n * @param options The information of the response and the reference to the helper.\n */\n protected _reduceEndpointResponse({\n helper,\n ...options\n }: GatewayControllerHelperOptions<GatewayHelperServiceResponseReducerOptions>): Promise<HTTPResponse> {\n if (helper.reduceEndpointResponse) {\n return helper.reduceEndpointResponse(options);\n }\n\n return Promise.resolve(options.endpointRes);\n }\n /**\n * This is a \"proxy method\" to call the helper service's function that can decide if an\n * endpoint response should be streamed or not.\n *\n * The reason this is a \"proxy method\" is in case the controller gets subclassed and\n * \"used itself as a helper\" instead of relying on a difference one.\n *\n * If the helper doesn't implement `shouldStreamEndpointResponse`, it will just return\n * `true`.\n *\n * @param options The information of the response and the reference to the helper.\n */\n protected _shouldStreamEndpointResponse({\n helper,\n ...options\n }: GatewayControllerHelperOptions<GatewayHelperServiceResponseReducerOptions>): Promise<boolean> {\n if (helper.shouldStreamEndpointResponse) {\n return helper.shouldStreamEndpointResponse(options);\n }\n\n return Promise.resolve(true);\n }\n /**\n * This is a \"proxy method\" to call the helper service's function that handles a\n * response in case it already said that a response shouldn't be streamed.\n *\n * The reason this is a \"proxy method\" is in case the controller gets subclassed and\n * \"used itself as a helper\" instead of relying on a difference one.\n *\n * If the helper doesn't implement `shouldStreamEndpointResponse`, it will throw an\n * error.\n *\n * @param options The information of the response and the reference to the helper.\n * @throws If the helper doesn't implement `handleEndpointResponse`.\n */\n protected _handleEndpointResponse({\n helper,\n ...options\n }: GatewayControllerHelperOptions<GatewayHelperServiceResponseReducerOptions>): Promise<void> {\n if (!helper.handleEndpointResponse) {\n throw new Error('You must implement handleEndpointResponse');\n }\n\n return helper.handleEndpointResponse(options);\n }\n /**\n * This is a \"proxy method\" to call the helper service's function that handles an error\n * on an endpoint request.\n *\n * The reason this is a \"proxy method\" is in case the controller gets subclassed and\n * \"used itself as a helper\" instead of relying on a difference one.\n *\n * If the helper doesn't implement `handleEndpointError`, it will just send the error to\n * the next middleware/error handler.\n *\n * @param options The information of the response and the reference to the helper.\n */\n protected _handleEndpointError({\n helper,\n ...options\n }: GatewayControllerHelperOptions<GatewayHelperServiceErrorHandlerOptions>): void {\n if (helper.handleEndpointError) {\n return helper.handleEndpointError(options);\n }\n\n return options.next(options.error);\n }\n /**\n * Validates and formats the customization options sent to the controller.\n *\n * @param options The options sent to the constructor.\n */\n protected _formatOptions(\n options: GatewayControllerExtraOptions,\n ): GatewayControllerExtraOptions {\n if (options.root) {\n const root = removeSlashes(options.root).trim();\n return { ...options, root };\n }\n\n return options;\n }\n /**\n * Validates a router/HTTP method that the controller intends to use for an endpoint. If\n * it's not valid, it will return `all`.\n *\n * @param method The HTTP method for the endpoint.\n */\n protected _validateHTTPMethod(method: string): RouterMethod {\n const newMethod = method.toLowerCase();\n return [\n 'get',\n 'head',\n 'post',\n 'patch',\n 'put',\n 'delete',\n 'connect',\n 'options',\n 'trace',\n ].includes(newMethod)\n ? (newMethod as RouterMethod)\n : 'all';\n }\n /**\n * Creates the API client configuration based on the controller routes.\n */\n protected _createAPIConfig(): GatewayControllerAPIConfig {\n let endpoints: APIClientOptions['endpoints'];\n const { root } = this._options;\n if (root) {\n endpoints = Object.keys(this._endpoints).reduce<\n Record<string, GatewayConfigEndpointDefinition>\n >((acc, name) => {\n const endpoint = this._endpoints[name]!;\n let newEndpoint;\n if (typeof endpoint === 'string') {\n newEndpoint = removeSlashes(endpoint);\n newEndpoint = `${root}/${newEndpoint}`;\n } else {\n const endpointPath = removeSlashes(endpoint.path);\n newEndpoint = {\n ...endpoint,\n path: `${root}/${endpointPath}`,\n };\n }\n\n acc[name] = newEndpoint;\n return acc;\n }, {});\n } else {\n endpoints = this._endpoints;\n }\n\n return {\n url: `/${this._route}`,\n endpoints: unflat({ target: endpoints }),\n };\n }\n}\n/**\n * A function to generate a list of middlewares that can be executed before the controller\n * main middleware.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerGetMiddlewaresFn = (app: Jimpex) => MiddlewareLike[];\n/**\n * The options for the controller creator that mounts the {@link GatewayController}.\n *\n * @group Controllers/Gateway\n */\nexport type GatewayControllerCreatorOptions =\n DeepPartial<GatewayControllerExtraOptions> & {\n /**\n * The name the creator will use to register the controller in the container. No,\n * this is not a typo. The creator will register the controller so other services can\n * access the `getAPIConfig` method. The service will be available after the app\n * routes are mounted.\n * If this is overwritten, the creator will ensure that the name ends with `Gateway`;\n * and if overwritten, but it doesn't include `Gateway` at the end, and no\n * `gatewaySettingName` was defined, the creator will use the custom name (without\n * `Gateway`) for `gatewaySettingName`.\n *\n * @default 'apiGateway'\n */\n serviceName?: string;\n /**\n * The name of the helper service the creator will try to obtain from the container.\n * If `serviceName` is overwritten, the default for this will be\n * `${serviceName}Helper`.\n *\n * @default 'apiGatewayHelper'\n */\n helperServiceName?: string;\n /**\n * The name of the configuration setting where the gateway configuration is stored. If\n * not overwritten, check the description of `serviceName` to understand which will be\n * its default value.\n *\n * @default 'api'\n */\n gatewaySettingName?: string;\n /**\n * The class the creator will instantiate. Similar to the API Client, this allows for\n * extra customization as you can send a custom subclass of the\n * {@link GatewayController}.\n *\n * @default GatewayController\n */\n gatewayClass?: typeof GatewayController;\n /**\n * A function to generate a list of middlewares that can be executed before the\n * controller main middleware.\n */\n getMiddlewares?: GatewayControllerGetMiddlewaresFn;\n };\n/**\n * Creates a controller that allows the application to mount routes that will work like\n * gateway to a specific API.\n *\n * @group Controllers\n * @group Controllers/Gateway\n */\nexport const gatewayController = controllerProviderCreator(\n (options: GatewayControllerCreatorOptions = {}) =>\n (app, route) => {\n /**\n * Formats the name in order to keep consistency with the helper service and the\n * configuration setting: If the `serviceName` is different from the default, make\n * sure it ends with `Gateway`, set the default helper service name to\n * `${serviceName}Helper`, and the default configuration setting to the same as the\n * service name (without the `Gateway`).\n * This way, if you just use `myApi`, the service name will be `myApiGateway`, the\n * helper name will be `myApiGatewayHelper` and the configuration setting `myApi`.\n */\n const defaultServiceName = 'apiGateway';\n let defaultHelperServiceName = 'apiGatewayHelper';\n let defaultConfigSetting = 'api';\n let { serviceName = defaultServiceName } = options;\n if (serviceName !== defaultServiceName) {\n defaultConfigSetting = serviceName;\n if (!serviceName.match(/gateway$/i)) {\n serviceName = `${serviceName}Gateway`;\n }\n defaultHelperServiceName = `${serviceName}Helper`;\n }\n // Register the service.\n app.set(serviceName, () => {\n const {\n helperServiceName = defaultHelperServiceName,\n gatewaySettingName = defaultConfigSetting,\n gatewayClass: GatewayClass = GatewayController,\n } = options;\n\n const gtConfig = app.getConfig<GatewayConfig>(gatewaySettingName);\n\n return new GatewayClass({\n ...options,\n apiConfigSetting: gatewaySettingName,\n gatewayConfig: gtConfig,\n route,\n inject: {\n http: app.get('http'),\n getHelperService: () => app.try(helperServiceName),\n },\n });\n });\n\n return controller(() => {\n // Get the controller.\n const ctrl = app.get<GatewayController>(serviceName);\n /**\n * Check if there are actual middlewares to be included, and in case there are\n * Jimpex middlewares, connect them.\n */\n let useMiddlewares: ExpressMiddleware[] | undefined;\n if (options.getMiddlewares) {\n useMiddlewares = options\n .getMiddlewares(app)\n .map((middleware) => {\n if ('middleware' in middleware) {\n return middleware.connect(app) as ExpressMiddleware | undefined;\n }\n\n return middleware as ExpressMiddleware;\n })\n .filter(notUndefined);\n }\n\n // Add the routes to the router and return it.\n return ctrl.addRoutes(app.get('router'), useMiddlewares);\n });\n },\n);\n"],"mappings":"AAAA,SAAS,+BAA+B;AACxC,SAAS,MAAM,cAAc;AAE7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAweA,MAAM,kBAAkB;AAAA;AAAA;AAAA;AAAA,EAIV;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA;AAAA;AAAA;AAAA;AAAA,EAIA;AAAA;AAAA;AAAA;AAAA,EAIA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA;AAAA;AAAA;AAAA;AAAA,EAIA;AAAA;AAAA;AAAA;AAAA,EAIA;AAAA;AAAA;AAAA;AAAA,EAIA;AAAA;AAAA;AAAA;AAAA,EAIA;AAAA;AAAA;AAAA;AAAA,EAIA;AAAA;AAAA;AAAA;AAAA,EAInB,YAAY;AA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AAA,IAC3C;AAEA,QAAI,IAAI,aAAa,MAAM;AACzB,YAAM;AAAA,QACJ,oBAAoB;AAAA,QACpB,qBAAqB;AAAA,QACrB,cAAc,eAAe;AAAA,MAC/B,IAAI;AAEJ,YAAM,WAAW,IAAI,UAAyB,kBAAkB;AAEhE,aAAO,IAAI,aAAa;AAAA,QACtB,GAAG;AAAA,QACH,kBAAkB;AAAA,QAClB,eAAe;AAAA,QACf;AAAA,QACA,QAAQ;AAAA,UACN,MAAM,IAAI,IAAI,MAAM;AAAA,UACpB,kBAAkB,MAAM,IAAI,IAAI,iBAAiB;AAAA,QACnD;AAAA,MACF,CAAC;AAAA,IACH,CAAC;AAED,WAAO,WAAW,MAAM;AAEtB,YAAM,OAAO,IAAI,IAAuB,WAAW;AAKnD,UAAI;AACJ,UAAI,QAAQ,gBAAgB;AAC1B,yBAAiB,QACd,eAAe,GAAG,EAClB,IAAI,CAAC,eAAe;AACnB,cAAI,gBAAgB,YAAY;AAC9B,mBAAO,WAAW,QAAQ,GAAG;AAAA,UAC/B;AAEA,iBAAO;AAAA,QACT,CAAC,EACA,OAAO,YAAY;AAAA,MACxB;AAGA,aAAO,KAAK,UAAU,IAAI,IAAI,QAAQ,GAAG,cAAc;AAAA,IACzD,CAAC;AAAA,EACH;AACJ;","names":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { AddGatewayRouteOptions, GatewayConfig, GatewayConfigEndpointDefinition, GatewayConfigEndpointProps, GatewayConfigEndpoints, GatewayController, GatewayControllerAPIConfig, GatewayControllerAPIConfigOptions, GatewayControllerConstructorOptions, GatewayControllerCreatorOptions, GatewayControllerEndpointInfo, GatewayControllerExtraOptions, GatewayControllerGetMiddlewaresFn, GatewayControllerHeaderOptions, GatewayControllerHelperOptions, GatewayControllerOptions, GatewayControllerRequest, GatewayControllerRoute, GatewayControllerRouteMethod, GatewayHelperService, GatewayHelperServiceBaseFnOptions, GatewayHelperServiceErrorHandler, GatewayHelperServiceErrorHandlerOptions, GatewayHelperServiceRequestReducer, GatewayHelperServiceRequestReducerOptions, GatewayHelperServiceResponseHandler, GatewayHelperServiceResponseReducer, GatewayHelperServiceResponseReducerOptions, GatewayHelperServiceStreamVerification, gatewayController } from './gateway.js';
|
|
2
2
|
import '@homer0/jimple';
|
|
3
|
-
import '../../index-
|
|
3
|
+
import '../../index-BlSpNHox.js';
|
|
4
4
|
import '../../types/express.js';
|
|
5
5
|
import 'express';
|
|
6
6
|
import '../../types/http.js';
|
|
@@ -1,23 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
var __defProp = Object.defineProperty;
|
|
3
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
-
var __copyProps = (to, from, except, desc) => {
|
|
7
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
8
|
-
for (let key of __getOwnPropNames(from))
|
|
9
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
10
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
11
|
-
}
|
|
12
|
-
return to;
|
|
13
|
-
};
|
|
14
|
-
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
|
|
15
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
16
|
-
var utils_exports = {};
|
|
17
|
-
module.exports = __toCommonJS(utils_exports);
|
|
18
|
-
__reExport(utils_exports, require("./gateway"), module.exports);
|
|
19
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
20
|
-
0 && (module.exports = {
|
|
21
|
-
...require("./gateway")
|
|
22
|
-
});
|
|
1
|
+
export * from "./gateway.js";
|
|
23
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/controllers/utils/index.ts"],"sourcesContent":["export * from './gateway';\n"],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../../../src/controllers/utils/index.ts"],"sourcesContent":["export * from './gateway.js';\n"],"mappings":"AAAA,cAAc;","names":[]}
|
|
@@ -805,9 +805,9 @@ type ControllerProviderCreator = ReturnType<typeof controllerProviderCreator>;
|
|
|
805
805
|
*
|
|
806
806
|
* @param container The reference to the Jimpex container.
|
|
807
807
|
* @param route This is optional because the implementation can use it as a
|
|
808
|
-
* "global
|
|
809
|
-
* @returns The resource can choose to be enabled or not by returning the function,
|
|
810
|
-
* `undefined`.
|
|
808
|
+
* "global middleware", or for a specific route.
|
|
809
|
+
* @returns The resource can choose to be enabled or not by returning the function,
|
|
810
|
+
* or `undefined`.
|
|
811
811
|
* @group Wrappers
|
|
812
812
|
*/
|
|
813
813
|
type MiddlewareConnectFn = <ContainerType extends Jimpex = Jimpex>(app: ContainerType, route?: string) => Router | ExpressMiddlewareLike | undefined;
|
|
@@ -890,7 +890,7 @@ type Middleware = ReturnType<typeof middleware>;
|
|
|
890
890
|
*/
|
|
891
891
|
type MiddlewareCreator = ReturnType<typeof middlewareCreator>;
|
|
892
892
|
/**
|
|
893
|
-
* The function a
|
|
893
|
+
* The function a middleware provider uses to configure/extend the container before
|
|
894
894
|
* returning an actual middleware.
|
|
895
895
|
*
|
|
896
896
|
* @param container The reference to the Jimpex container.
|
|
@@ -1032,7 +1032,7 @@ declare class Jimpex extends Jimple {
|
|
|
1032
1032
|
*/
|
|
1033
1033
|
protected _configReady: boolean;
|
|
1034
1034
|
/**
|
|
1035
|
-
* A reference to the
|
|
1035
|
+
* A reference to the actual HTTP the application will use. This can vary depending on
|
|
1036
1036
|
* whether HTTPS, or HTTP2 are enabled. If HTTPS is not enabled, it will be the same as
|
|
1037
1037
|
* the `express` property; if HTTPS is enabled, it will be an `https` server; and if
|
|
1038
1038
|
* HTTP2 is enabled, it will be an `spdy` server.
|
|
@@ -1059,7 +1059,7 @@ declare class Jimpex extends Jimple {
|
|
|
1059
1059
|
/**
|
|
1060
1060
|
* @param options Preferences to customize the application.
|
|
1061
1061
|
* @param config The default settings for the configuration service. It's a
|
|
1062
|
-
*
|
|
1062
|
+
* short-circuit for `options.config.default`
|
|
1063
1063
|
*/
|
|
1064
1064
|
constructor(options?: DeepPartial<JimpexOptions>, config?: unknown);
|
|
1065
1065
|
/**
|
|
@@ -1147,7 +1147,7 @@ declare class Jimpex extends Jimple {
|
|
|
1147
1147
|
*/
|
|
1148
1148
|
on<EventName extends JimpexEventNameLike>(eventName: EventName, listener: JimpexEventListener<EventName>): () => boolean;
|
|
1149
1149
|
/**
|
|
1150
|
-
* Adds a listener for an application event that will only be
|
|
1150
|
+
* Adds a listener for an application event that will only be executed once: the first
|
|
1151
1151
|
* time the event is triggered.
|
|
1152
1152
|
*
|
|
1153
1153
|
* @param eventName The name of the event to listen for.
|
|
@@ -1158,14 +1158,14 @@ declare class Jimpex extends Jimple {
|
|
|
1158
1158
|
*/
|
|
1159
1159
|
once<EventName extends JimpexEventNameLike>(eventName: EventName, listener: JimpexEventListener<EventName>): () => boolean;
|
|
1160
1160
|
/**
|
|
1161
|
-
* Based on the application options, it returns
|
|
1161
|
+
* Based on the application options, it returns whether the application is healthy or
|
|
1162
1162
|
* not.
|
|
1163
1163
|
*/
|
|
1164
1164
|
isHealthy(): ReturnType<JimpexHealthCheckFn>;
|
|
1165
1165
|
/**
|
|
1166
1166
|
* This method is like a "lifecycle method", it gets executed on the constructor right
|
|
1167
1167
|
* before the "boot step". The idea is for the method to be a helper when the
|
|
1168
|
-
* application is defined by
|
|
1168
|
+
* application is defined by sub-classing {@link Jimpex}: the application could register
|
|
1169
1169
|
* all important services here and the routes on boot, then, if the implementation needs
|
|
1170
1170
|
* to access or overwrite a something, it can send `boot: false`, access/register what
|
|
1171
1171
|
* it needs, and then call `boot()`. That would be impossible for an application without
|
|
@@ -1174,7 +1174,7 @@ declare class Jimpex extends Jimple {
|
|
|
1174
1174
|
protected _init(): void;
|
|
1175
1175
|
/**
|
|
1176
1176
|
* It generates overwrites for the application options when it gets created. This method
|
|
1177
|
-
* is a helper for when the application is defined by
|
|
1177
|
+
* is a helper for when the application is defined by sub-classing {@link Jimpex}: It's
|
|
1178
1178
|
* highly probable that if the application needs to change the default options, it would
|
|
1179
1179
|
* want to do it right from the class, instead of having to do it on every
|
|
1180
1180
|
* implementation. A way to do it would be overwriting the constructor and calling
|
|
@@ -1208,7 +1208,7 @@ declare class Jimpex extends Jimple {
|
|
|
1208
1208
|
* This helper method validates the `path` options in order to register the `app`
|
|
1209
1209
|
* location in the `pathUtils` service. The `app` location should be the path to where
|
|
1210
1210
|
* the application executable is located, but due to how ESM works, we can't infer it
|
|
1211
|
-
* from the `module` object, so we need either
|
|
1211
|
+
* from the `module` object, so we need either received as the `appPath` setting, or try
|
|
1212
1212
|
* to get it from the parent module.
|
|
1213
1213
|
*
|
|
1214
1214
|
* @throws If the method should use the path from the parent module, but can't find
|
|
@@ -1269,7 +1269,7 @@ declare class Jimpex extends Jimple {
|
|
|
1269
1269
|
* @returns {Server}
|
|
1270
1270
|
* @throws {Error} If HTTP2 is enabled but HTTPS is not.
|
|
1271
1271
|
* @throws {Error} If HTTPS is enabled but there's no `https.credentials` object.
|
|
1272
|
-
* @throws {Error} If HTTPS is enabled and no
|
|
1272
|
+
* @throws {Error} If HTTPS is enabled and no credentials are found.
|
|
1273
1273
|
* @access protected
|
|
1274
1274
|
* @ignore
|
|
1275
1275
|
*/
|
|
@@ -1282,6 +1282,6 @@ declare class Jimpex extends Jimple {
|
|
|
1282
1282
|
* @returns A new instance of {@link Jimpex}.
|
|
1283
1283
|
* @group Jimpex
|
|
1284
1284
|
*/
|
|
1285
|
-
declare const jimpex: (
|
|
1285
|
+
declare const jimpex: (...args: ConstructorParameters<typeof Jimpex>) => Jimpex;
|
|
1286
1286
|
|
|
1287
1287
|
export { type MiddlewareProvider as $, type Providers as A, type ProviderLike as B, type ControllerConnectFn as C, controller as D, type EventPayload as E, type ControllerCreatorFn as F, controllerCreator as G, type Controller as H, type ControllerCreator as I, Jimpex as J, type ControllerProviderRegisterFn as K, controllerProvider as L, type ControllerProviderCreatorFn as M, controllerProviderCreator as N, type ControllerProvider as O, type ProviderRegisterFn as P, type ControllerProviderCreator as Q, type MiddlewareConnectFn as R, middleware as S, type MiddlewareCreatorFn as T, middlewareCreator as U, type Middleware as V, type MiddlewareCreator as W, type MiddlewareProviderRegisterFn as X, middlewareProvider as Y, type MiddlewareProviderCreatorFn as Z, middlewareProviderCreator as _, type JimpexEvents as a, type MiddlewareProviderCreator as a0, type MiddlewareLike as a1, type ControllerLike as a2, type JimpexEventName as b, type JimpexEventPayload as c, type JimpexReducerEventTargets as d, type JimpexReducerEventPayloads as e, type JimpexReducerEventName as f, type JimpexReducerEventTarget as g, type JimpexReducerEventPayload as h, type JimpexEventNameLike as i, jimpex as j, type JimpexEventListener as k, type Events as l, type JimpexConfigOptions as m, type JimpexStaticsOptions as n, type JimpexExpressOptions as o, type JimpexPathOptions as p, type JimpexServicesOptions as q, type JimpexHealthStatus as r, type JimpexHealthCheckFn as s, type JimpexOptions as t, type JimpexStartCallback as u, provider as v, providerCreator as w, providers as x, type Provider as y, type ProviderCreator as z };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { H as Controller, C as ControllerConnectFn, I as ControllerCreator, F as ControllerCreatorFn, a2 as ControllerLike, O as ControllerProvider, Q as ControllerProviderCreator, M as ControllerProviderCreatorFn, K as ControllerProviderRegisterFn, E as EventPayload, l as Events, J as Jimpex, m as JimpexConfigOptions, k as JimpexEventListener, b as JimpexEventName, i as JimpexEventNameLike, c as JimpexEventPayload, a as JimpexEvents, o as JimpexExpressOptions, s as JimpexHealthCheckFn, r as JimpexHealthStatus, t as JimpexOptions, p as JimpexPathOptions, f as JimpexReducerEventName, h as JimpexReducerEventPayload, e as JimpexReducerEventPayloads, g as JimpexReducerEventTarget, d as JimpexReducerEventTargets, q as JimpexServicesOptions, u as JimpexStartCallback, n as JimpexStaticsOptions, V as Middleware, R as MiddlewareConnectFn, W as MiddlewareCreator, T as MiddlewareCreatorFn, a1 as MiddlewareLike, $ as MiddlewareProvider, a0 as MiddlewareProviderCreator, Z as MiddlewareProviderCreatorFn, X as MiddlewareProviderRegisterFn, y as Provider, z as ProviderCreator, B as ProviderLike, P as ProviderRegisterFn, A as Providers, D as controller, G as controllerCreator, L as controllerProvider, N as controllerProviderCreator, j as jimpex, S as middleware, U as middlewareCreator, Y as middlewareProvider, _ as middlewareProviderCreator, v as provider, w as providerCreator, x as providers } from './index-
|
|
1
|
+
export { H as Controller, C as ControllerConnectFn, I as ControllerCreator, F as ControllerCreatorFn, a2 as ControllerLike, O as ControllerProvider, Q as ControllerProviderCreator, M as ControllerProviderCreatorFn, K as ControllerProviderRegisterFn, E as EventPayload, l as Events, J as Jimpex, m as JimpexConfigOptions, k as JimpexEventListener, b as JimpexEventName, i as JimpexEventNameLike, c as JimpexEventPayload, a as JimpexEvents, o as JimpexExpressOptions, s as JimpexHealthCheckFn, r as JimpexHealthStatus, t as JimpexOptions, p as JimpexPathOptions, f as JimpexReducerEventName, h as JimpexReducerEventPayload, e as JimpexReducerEventPayloads, g as JimpexReducerEventTarget, d as JimpexReducerEventTargets, q as JimpexServicesOptions, u as JimpexStartCallback, n as JimpexStaticsOptions, V as Middleware, R as MiddlewareConnectFn, W as MiddlewareCreator, T as MiddlewareCreatorFn, a1 as MiddlewareLike, $ as MiddlewareProvider, a0 as MiddlewareProviderCreator, Z as MiddlewareProviderCreatorFn, X as MiddlewareProviderRegisterFn, y as Provider, z as ProviderCreator, B as ProviderLike, P as ProviderRegisterFn, A as Providers, D as controller, G as controllerCreator, L as controllerProvider, N as controllerProviderCreator, j as jimpex, S as middleware, U as middlewareCreator, Y as middlewareProvider, _ as middlewareProviderCreator, v as provider, w as providerCreator, x as providers } from './index-BlSpNHox.js';
|
|
2
2
|
export { AsyncExpressMiddleware, ExpressErrorHandler, ExpressMiddleware, ExpressMiddlewareLike, RouterMethod } from './types/express.js';
|
|
3
3
|
export { JimpexHTTP2Options, JimpexHTTPSCredentials, JimpexHTTPSOptions, JimpexServer, JimpexServerInstance, NodeFetch } from './types/http.js';
|
|
4
4
|
export { DeepPartial, DeepReadonly, Dict, NoStringIndex } from './types/utils.js';
|
|
@@ -36,12 +36,12 @@ export { FrontendFs, FrontendFsOptions, frontendFsProvider } from './services/fr
|
|
|
36
36
|
export { HTMLGenerator, HTMLGeneratorConstructorOptions, HTMLGeneratorOptions, HTMLGeneratorProviderOptions, HTMLGeneratorValuesService, htmlGeneratorProvider } from './services/html/htmlGenerator.js';
|
|
37
37
|
export { ErrorResponse } from '@homer0/api-utils';
|
|
38
38
|
export { APIClient, APIClientConfig, APIClientConstructorOptions, APIClientProviderOptions, APIClientSettings, EndpointsType, apiClientProvider } from './services/http/apiClient.js';
|
|
39
|
-
export { GetCustomHeadersFromRequestOptions, HTTP,
|
|
39
|
+
export { GetCustomHeadersFromRequestOptions, HTTP, HTTPConstructorOptions, HTTPFetchBody, HTTPFetchOptions, HTTPOptions, httpProvider } from './services/http/http.js';
|
|
40
40
|
export { HTMLPostMessageResponseOptions, JSONResponseOptions, ResponsesBuilder, ResponsesBuilderConstructorOptions, responsesBuilderProvider } from './services/http/responsesBuilder.js';
|
|
41
41
|
export { EnsureBearerConstructorOptions, EnsureBearerToken, EnsureBearerTokenErrorOptions, EnsureBearerTokenOptions, EnsureBearerTokenProviderOptions, ensureBearerTokenProvider } from './services/utils/ensureBearerToken.js';
|
|
42
42
|
export { default as statuses } from 'statuses';
|
|
43
43
|
import '@homer0/jimple';
|
|
44
44
|
import 'spdy';
|
|
45
45
|
import 'mime';
|
|
46
|
-
import 'fs/promises';
|
|
46
|
+
import 'node:fs/promises';
|
|
47
47
|
import '@homer0/deferred';
|
package/dist/index.js
CHANGED
|
@@ -1,33 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
8
|
-
for (let key of __getOwnPropNames(from))
|
|
9
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
10
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
11
|
-
}
|
|
12
|
-
return to;
|
|
13
|
-
};
|
|
14
|
-
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
|
|
15
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
16
|
-
var src_exports = {};
|
|
17
|
-
module.exports = __toCommonJS(src_exports);
|
|
18
|
-
__reExport(src_exports, require("./app"), module.exports);
|
|
19
|
-
__reExport(src_exports, require("./types"), module.exports);
|
|
20
|
-
__reExport(src_exports, require("./controllers"), module.exports);
|
|
21
|
-
__reExport(src_exports, require("./middlewares"), module.exports);
|
|
22
|
-
__reExport(src_exports, require("./services"), module.exports);
|
|
23
|
-
__reExport(src_exports, require("./utils"), module.exports);
|
|
24
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
25
|
-
0 && (module.exports = {
|
|
26
|
-
...require("./app"),
|
|
27
|
-
...require("./types"),
|
|
28
|
-
...require("./controllers"),
|
|
29
|
-
...require("./middlewares"),
|
|
30
|
-
...require("./services"),
|
|
31
|
-
...require("./utils")
|
|
32
|
-
});
|
|
1
|
+
export * from "./app/index.js";
|
|
2
|
+
export * from "./types/index.js";
|
|
3
|
+
export * from "./controllers/index.js";
|
|
4
|
+
export * from "./middlewares/index.js";
|
|
5
|
+
export * from "./services/index.js";
|
|
6
|
+
export * from "./utils/index.js";
|
|
33
7
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './app';\nexport * from './types';\nexport * from './controllers';\nexport * from './middlewares';\nexport * from './services';\nexport * from './utils';\n"],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './app/index.js';\nexport * from './types/index.js';\nexport * from './controllers/index.js';\nexport * from './middlewares/index.js';\nexport * from './services/index.js';\nexport * from './utils/index.js';\n"],"mappings":"AAAA,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;","names":[]}
|
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
import * as _homer0_jimple from '@homer0/jimple';
|
|
2
|
-
import {
|
|
3
|
-
import { J as Jimpex, R as MiddlewareConnectFn } from '../../index-C6I3NCC-.js';
|
|
2
|
+
import { J as Jimpex, R as MiddlewareConnectFn } from '../../index-BlSpNHox.js';
|
|
4
3
|
import { ExpressErrorHandler } from '../../types/express.js';
|
|
4
|
+
import { Statuses } from '../../utils/fns/statuses.js';
|
|
5
5
|
import { SimpleLogger } from '@homer0/simple-logger';
|
|
6
6
|
import { DeepPartial } from '../../types/utils.js';
|
|
7
7
|
import { HTTPErrorClass } from '../../services/common/httpError.js';
|
|
8
8
|
import { ResponsesBuilder } from '../../services/http/responsesBuilder.js';
|
|
9
|
-
import 'statuses';
|
|
10
9
|
import '../../types/http.js';
|
|
11
10
|
import 'https';
|
|
12
11
|
import 'http';
|
|
@@ -16,6 +15,7 @@ import 'express';
|
|
|
16
15
|
import '@homer0/path-utils';
|
|
17
16
|
import '@homer0/simple-config';
|
|
18
17
|
import '@homer0/events-hub';
|
|
18
|
+
import 'statuses';
|
|
19
19
|
import '../../services/common/appError.js';
|
|
20
20
|
|
|
21
21
|
/**
|
|
@@ -49,7 +49,7 @@ type ErrorHandlerOptions = {
|
|
|
49
49
|
* if `true`, it will not only show all kind of errors but it will also show the error
|
|
50
50
|
* stack.
|
|
51
51
|
*
|
|
52
|
-
* By "
|
|
52
|
+
* By "unknown errors", it means that are not `AppError` nor `HTTPError`.
|
|
53
53
|
*/
|
|
54
54
|
showErrors: boolean;
|
|
55
55
|
/**
|
|
@@ -97,7 +97,7 @@ declare class ErrorHandler {
|
|
|
97
97
|
*/
|
|
98
98
|
protected readonly _responsesBuilder: ResponsesBuilder;
|
|
99
99
|
/**
|
|
100
|
-
* The
|
|
100
|
+
* The utility service to get HTTP status codes.
|
|
101
101
|
*/
|
|
102
102
|
protected readonly _statuses: Statuses;
|
|
103
103
|
/**
|
|
@@ -1,33 +1,29 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
7
|
-
var __export = (target, all) => {
|
|
8
|
-
for (var name in all)
|
|
9
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
-
};
|
|
11
|
-
var __copyProps = (to, from, except, desc) => {
|
|
12
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
-
for (let key of __getOwnPropNames(from))
|
|
14
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
-
}
|
|
17
|
-
return to;
|
|
18
|
-
};
|
|
19
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
20
|
-
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
21
|
-
var errorHandler_exports = {};
|
|
22
|
-
__export(errorHandler_exports, {
|
|
23
|
-
ErrorHandler: () => ErrorHandler,
|
|
24
|
-
errorHandlerMiddleware: () => errorHandlerMiddleware
|
|
25
|
-
});
|
|
26
|
-
module.exports = __toCommonJS(errorHandler_exports);
|
|
27
|
-
var import_deep_assign = require("@homer0/deep-assign");
|
|
28
|
-
var import_utils = require("../../utils");
|
|
29
|
-
var import_services = require("../../services");
|
|
1
|
+
import { deepAssignWithOverwrite } from "@homer0/deep-assign";
|
|
2
|
+
import { middlewareCreator } from "../../utils/index.js";
|
|
3
|
+
import {
|
|
4
|
+
AppError
|
|
5
|
+
} from "../../services/index.js";
|
|
30
6
|
class ErrorHandler {
|
|
7
|
+
/**
|
|
8
|
+
* The service that will log the messages in the console.
|
|
9
|
+
*/
|
|
10
|
+
_logger;
|
|
11
|
+
/**
|
|
12
|
+
* The service to generate the responses.
|
|
13
|
+
*/
|
|
14
|
+
_responsesBuilder;
|
|
15
|
+
/**
|
|
16
|
+
* The utility service to get HTTP status codes.
|
|
17
|
+
*/
|
|
18
|
+
_statuses;
|
|
19
|
+
/**
|
|
20
|
+
* The Error class used by the "known errors".
|
|
21
|
+
*/
|
|
22
|
+
_HTTPError;
|
|
23
|
+
/**
|
|
24
|
+
* The customization options.
|
|
25
|
+
*/
|
|
26
|
+
_options;
|
|
31
27
|
/**
|
|
32
28
|
* @param options The options to construct the class.
|
|
33
29
|
*/
|
|
@@ -35,31 +31,11 @@ class ErrorHandler {
|
|
|
35
31
|
inject: { logger, responsesBuilder, statuses, HTTPError },
|
|
36
32
|
...options
|
|
37
33
|
}) {
|
|
38
|
-
/**
|
|
39
|
-
* The service that will log the messages in the console.
|
|
40
|
-
*/
|
|
41
|
-
__publicField(this, "_logger");
|
|
42
|
-
/**
|
|
43
|
-
* The service to generate the responses.
|
|
44
|
-
*/
|
|
45
|
-
__publicField(this, "_responsesBuilder");
|
|
46
|
-
/**
|
|
47
|
-
* The uility service to get HTTP status codes.
|
|
48
|
-
*/
|
|
49
|
-
__publicField(this, "_statuses");
|
|
50
|
-
/**
|
|
51
|
-
* The Error class used by the "known errors".
|
|
52
|
-
*/
|
|
53
|
-
__publicField(this, "_HTTPError");
|
|
54
|
-
/**
|
|
55
|
-
* The customization options.
|
|
56
|
-
*/
|
|
57
|
-
__publicField(this, "_options");
|
|
58
34
|
this._logger = logger;
|
|
59
35
|
this._responsesBuilder = responsesBuilder;
|
|
60
36
|
this._statuses = statuses;
|
|
61
37
|
this._HTTPError = HTTPError;
|
|
62
|
-
this._options =
|
|
38
|
+
this._options = deepAssignWithOverwrite(
|
|
63
39
|
{
|
|
64
40
|
showErrors: false,
|
|
65
41
|
response: {
|
|
@@ -85,7 +61,7 @@ class ErrorHandler {
|
|
|
85
61
|
error: true,
|
|
86
62
|
message: response.message
|
|
87
63
|
};
|
|
88
|
-
const knownError = err instanceof
|
|
64
|
+
const knownError = err instanceof AppError;
|
|
89
65
|
if (showErrors || knownError) {
|
|
90
66
|
data.message = err.message;
|
|
91
67
|
if (knownError) {
|
|
@@ -114,10 +90,10 @@ class ErrorHandler {
|
|
|
114
90
|
* The handler customization options.
|
|
115
91
|
*/
|
|
116
92
|
get options() {
|
|
117
|
-
return
|
|
93
|
+
return deepAssignWithOverwrite({}, this._options);
|
|
118
94
|
}
|
|
119
95
|
}
|
|
120
|
-
const errorHandlerMiddleware =
|
|
96
|
+
const errorHandlerMiddleware = middlewareCreator(
|
|
121
97
|
(options = {}) => (app) => {
|
|
122
98
|
const showErrors = app.getConfig("debug.showErrors") === true;
|
|
123
99
|
return new ErrorHandler({
|
|
@@ -132,9 +108,8 @@ const errorHandlerMiddleware = (0, import_utils.middlewareCreator)(
|
|
|
132
108
|
}).getMiddleware();
|
|
133
109
|
}
|
|
134
110
|
);
|
|
135
|
-
|
|
136
|
-
0 && (module.exports = {
|
|
111
|
+
export {
|
|
137
112
|
ErrorHandler,
|
|
138
113
|
errorHandlerMiddleware
|
|
139
|
-
}
|
|
114
|
+
};
|
|
140
115
|
//# sourceMappingURL=errorHandler.js.map
|