arkos 1.1.60-test → 1.1.62-test
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/dist/cjs/app.js +1 -1
- package/dist/cjs/app.js.map +1 -1
- package/dist/cjs/modules/base/utils/helpers/base.service.helpers.js.map +1 -1
- package/dist/cjs/modules/swagger/swagger.router.js +139 -0
- package/dist/cjs/modules/swagger/swagger.router.js.map +1 -1
- package/dist/cjs/types/arkos-config.js.map +1 -1
- package/dist/es2020/app.js +1 -1
- package/dist/es2020/app.js.map +1 -1
- package/dist/es2020/modules/base/utils/helpers/base.service.helpers.js.map +1 -1
- package/dist/es2020/modules/swagger/swagger.router.js +134 -1
- package/dist/es2020/modules/swagger/swagger.router.js.map +1 -1
- package/dist/es2020/types/arkos-config.js.map +1 -1
- package/dist/types/modules/swagger/swagger.router.d.ts +3 -0
- package/dist/types/types/arkos-config.d.ts +42 -0
- package/package.json +7 -3
package/dist/cjs/app.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.app=void 0,exports.bootstrap=bootstrap;const express_1=__importDefault(require("express")),cors_1=__importDefault(require("cors")),cookie_parser_1=__importDefault(require("cookie-parser")),auth_router_1=require("./modules/auth/auth.router"),base_router_1=require("./modules/base/base.router"),error_handler_controller_1=__importDefault(require("./modules/error-handler/error-handler.controller")),express_rate_limit_1=require("express-rate-limit"),compression_1=__importDefault(require("compression")),base_middlewares_1=require("./modules/base/base.middlewares"),prisma_helpers_1=require("./utils/helpers/prisma.helpers"),file_uploader_router_1=require("./modules/file-uploader/file-uploader.router"),query_parser_helpers_1=require("./utils/helpers/query-parser.helpers"),deepmerge_helper_1=__importDefault(require("./utils/helpers/deepmerge.helper"));exports.app=(0,express_1.default)();async function bootstrap(e){await(0,prisma_helpers_1.loadPrismaModule)(),e?.configureApp&&await e.configureApp(exports.app);const i=e?.middlewares,s=i?.disable||[],t=i?.replace||{};s?.includes?.("compression")||exports.app.use(t.compression||(0,compression_1.default)(e?.compressionOptions)),s?.includes?.("global-rate-limit")||exports.app.use(t.globalRateLimit||(0,express_rate_limit_1.rateLimit)((0,deepmerge_helper_1.default)({windowMs:60*1e3,limit:1e3,standardHeaders:"draft-7",legacyHeaders:!1},e?.globalRequestRateLimitOptions||{}))),s?.includes?.("cors")||exports.app.use(t.cors||(0,cors_1.default)(e?.cors?.customHandler?e.cors.customHandler:(0,deepmerge_helper_1.default)({origin:(r,o)=>{const l=e?.cors?.allowedOrigins;l==="*"?o(null,!0):Array.isArray(l)?o(null,!r||l?.includes?.(r)):typeof l=="string"?o(null,!r||l===r):o(null,!1)},methods:["GET","POST","PUT","DELETE","PATCH","OPTIONS"],allowedHeaders:["Content-Type","Authorization","Connection"],credentials:!0},e?.cors?.options||{}))),s?.includes?.("express-json")||exports.app.use(t.expressJson||express_1.default.json(e?.jsonBodyParserOptions)),s?.includes?.("cookie-parser")||exports.app.use(t.cookieParser||(0,cookie_parser_1.default)(...e?.cookieParserParameters||[])),s?.includes?.("query-parser")||exports.app.use(t.queryParser||(0,query_parser_helpers_1.queryParser)((0,deepmerge_helper_1.default)({parseNull:!0,parseUndefined:!0,parseBoolean:!0},e?.queryParserOptions||{}))),s?.includes?.("database-connection")||exports.app.use(t.databaseConnection||prisma_helpers_1.checkDatabaseConnection),s?.includes?.("request-logger")||exports.app.use(t.requestLogger||base_middlewares_1.handleRequestLogs),e?.middlewares?.additional&&e.middlewares.additional.forEach(r=>{exports.app.use(r)});const u=e?.routers,p=u?.disable||[],a=u?.replace||{};if(p?.includes?.("welcome-endpoint")||exports.app.get("/api",a.welcomeEndpoint||((r,o)=>{o.status(200).json({message:e.welcomeMessage})})),!p?.includes?.("file-uploader")){const r=a.fileUploader?await a.fileUploader(e):await(0,file_uploader_router_1.getFileUploaderRouter)(e);exports.app.use(r)}if(!p?.includes?.("auth-router")&&e.authentication){const r=a.authRouter?await a.authRouter(e):await(0,auth_router_1.getAuthRouter)(e);exports.app.use("/api",r)}if(!p?.includes?.("prisma-models-router")){const r=a.prismaModelsRouter?await a.prismaModelsRouter(e):await(0,base_router_1.getPrismaModelsRouter)(e);exports.app.use("/api",r)}return exports.app.use("/api",(0,base_router_1.getAvailableResourcesAndRoutesRouter)()),u?.additional&&u.additional.forEach(r=>{exports.app.use(r)}),s?.includes?.("global-error-handler")||exports.app.use(t.globalErrorHandler||error_handler_controller_1.default),exports.app}
|
|
1
|
+
"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.app=void 0,exports.bootstrap=bootstrap;const express_1=__importDefault(require("express")),cors_1=__importDefault(require("cors")),cookie_parser_1=__importDefault(require("cookie-parser")),auth_router_1=require("./modules/auth/auth.router"),base_router_1=require("./modules/base/base.router"),error_handler_controller_1=__importDefault(require("./modules/error-handler/error-handler.controller")),express_rate_limit_1=require("express-rate-limit"),compression_1=__importDefault(require("compression")),base_middlewares_1=require("./modules/base/base.middlewares"),prisma_helpers_1=require("./utils/helpers/prisma.helpers"),file_uploader_router_1=require("./modules/file-uploader/file-uploader.router"),query_parser_helpers_1=require("./utils/helpers/query-parser.helpers"),deepmerge_helper_1=__importDefault(require("./utils/helpers/deepmerge.helper")),swagger_router_1=require("./modules/swagger/swagger.router");exports.app=(0,express_1.default)();async function bootstrap(e){await(0,prisma_helpers_1.loadPrismaModule)(),e?.configureApp&&await e.configureApp(exports.app);const i=e?.middlewares,s=i?.disable||[],t=i?.replace||{};s?.includes?.("compression")||exports.app.use(t.compression||(0,compression_1.default)(e?.compressionOptions)),s?.includes?.("global-rate-limit")||exports.app.use(t.globalRateLimit||(0,express_rate_limit_1.rateLimit)((0,deepmerge_helper_1.default)({windowMs:60*1e3,limit:1e3,standardHeaders:"draft-7",legacyHeaders:!1},e?.globalRequestRateLimitOptions||{}))),s?.includes?.("cors")||exports.app.use(t.cors||(0,cors_1.default)(e?.cors?.customHandler?e.cors.customHandler:(0,deepmerge_helper_1.default)({origin:(r,o)=>{const l=e?.cors?.allowedOrigins;l==="*"?o(null,!0):Array.isArray(l)?o(null,!r||l?.includes?.(r)):typeof l=="string"?o(null,!r||l===r):o(null,!1)},methods:["GET","POST","PUT","DELETE","PATCH","OPTIONS"],allowedHeaders:["Content-Type","Authorization","Connection"],credentials:!0},e?.cors?.options||{}))),s?.includes?.("express-json")||exports.app.use(t.expressJson||express_1.default.json(e?.jsonBodyParserOptions)),s?.includes?.("cookie-parser")||exports.app.use(t.cookieParser||(0,cookie_parser_1.default)(...e?.cookieParserParameters||[])),s?.includes?.("query-parser")||exports.app.use(t.queryParser||(0,query_parser_helpers_1.queryParser)((0,deepmerge_helper_1.default)({parseNull:!0,parseUndefined:!0,parseBoolean:!0},e?.queryParserOptions||{}))),s?.includes?.("database-connection")||exports.app.use(t.databaseConnection||prisma_helpers_1.checkDatabaseConnection),s?.includes?.("request-logger")||exports.app.use(t.requestLogger||base_middlewares_1.handleRequestLogs),e?.middlewares?.additional&&e.middlewares.additional.forEach(r=>{exports.app.use(r)});const u=e?.routers,p=u?.disable||[],a=u?.replace||{};if(p?.includes?.("welcome-endpoint")||exports.app.get("/api",a.welcomeEndpoint||((r,o)=>{o.status(200).json({message:e.welcomeMessage})})),!p?.includes?.("file-uploader")){const r=a.fileUploader?await a.fileUploader(e):await(0,file_uploader_router_1.getFileUploaderRouter)(e);exports.app.use(r)}if(!p?.includes?.("auth-router")&&e.authentication){const r=a.authRouter?await a.authRouter(e):await(0,auth_router_1.getAuthRouter)(e);exports.app.use("/api",r)}if(!p?.includes?.("prisma-models-router")){const r=a.prismaModelsRouter?await a.prismaModelsRouter(e):await(0,base_router_1.getPrismaModelsRouter)(e);exports.app.use("/api",r)}return exports.app.use("/api",(0,base_router_1.getAvailableResourcesAndRoutesRouter)()),exports.app.use("/api",(0,swagger_router_1.getSwaggerRouter)(e)),u?.additional&&u.additional.forEach(r=>{exports.app.use(r)}),s?.includes?.("global-error-handler")||exports.app.use(t.globalErrorHandler||error_handler_controller_1.default),exports.app}
|
package/dist/cjs/app.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":";;;;;;AAuBA,8BA6KC;AApMD,sDAA8B;AAC9B,gDAAwB;AACxB,kEAAyC;AACzC,4DAA2D;AAC3D,4DAGoC;AACpC,gHAA4E;AAC5E,2DAA+C;AAC/C,8DAAsC;AACtC,sEAAoE;AACpE,mEAGwC;AACxC,uFAAqF;AAErF,+EAAmE;AACnE,wFAAyD;AAE5C,QAAA,GAAG,GAAoB,IAAA,iBAAO,GAAE,CAAC;AAEvC,KAAK,UAAU,SAAS,CAC7B,WAAwB;IAExB,MAAM,IAAA,iCAAgB,GAAE,CAAC;IAEzB,IAAI,WAAW,EAAE,YAAY;QAAE,MAAM,WAAW,CAAC,YAAY,CAAC,WAAG,CAAC,CAAC;IAEnE,MAAM,iBAAiB,GAAG,WAAW,EAAE,WAAW,CAAC;IACnD,MAAM,mBAAmB,GAAG,iBAAiB,EAAE,OAAO,IAAI,EAAE,CAAC;IAC7D,MAAM,mBAAmB,GAAG,iBAAiB,EAAE,OAAO,IAAI,EAAE,CAAC;IAG7D,IAAI,CAAC,mBAAmB,EAAE,QAAQ,EAAE,CAAC,aAAa,CAAC;QACjD,WAAG,CAAC,GAAG,CACL,mBAAmB,CAAC,WAAW;YAC7B,IAAA,qBAAW,EAAC,WAAW,EAAE,kBAAkB,CAAC,CAC/C,CAAC;IAGJ,IAAI,CAAC,mBAAmB,EAAE,QAAQ,EAAE,CAAC,mBAAmB,CAAC;QACvD,WAAG,CAAC,GAAG,CACL,mBAAmB,CAAC,eAAe;YACjC,IAAA,8BAAS,EACP,IAAA,0BAAS,EACP;gBACE,QAAQ,EAAE,EAAE,GAAG,IAAI;gBACnB,KAAK,EAAE,IAAI;gBACX,eAAe,EAA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D,CAAC,CAAC,MAAM,eAAe,CAAC,kBAAkB,CAAC,WAAW,CAAC;YACvD,CAAC,CAAC,MAAM,IAAA,mCAAqB,EAAC,WAAW,CAAC,CAAC;QAC7C,WAAG,CAAC,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;IAChC,CAAC;IAED,WAAG,CAAC,GAAG,CAAC,MAAM,EAAE,IAAA,kDAAoC,GAAE,CAAC,CAAC;IAGxD,IAAI,aAAa,EAAE,UAAU,EAAE,CAAC;QAC9B,aAAa,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;YAC1C,WAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAClB,CAAC,CAAC,CAAC;IACL,CAAC;IAGD,IAAI,CAAC,mBAAmB,EAAE,QAAQ,EAAE,CAAC,sBAAsB,CAAC;QAC1D,WAAG,CAAC,GAAG,CAAC,mBAAmB,CAAC,kBAAkB,IAAI,kCAAY,CAAC,CAAC;IAElE,OAAO,WAAG,CAAC;AACb,CAAC","sourcesContent":["import express from \"express\";\nimport cors from \"cors\";\nimport cookieParser from \"cookie-parser\";\nimport { getAuthRouter } from \"./modules/auth/auth.router\";\nimport {\n getPrismaModelsRouter,\n getAvailableResourcesAndRoutesRouter,\n} from \"./modules/base/base.router\";\nimport errorHandler from \"./modules/error-handler/error-handler.controller\";\nimport { rateLimit } from \"express-rate-limit\";\nimport compression from \"compression\";\nimport { handleRequestLogs } from \"./modules/base/base.middlewares\";\nimport {\n checkDatabaseConnection,\n loadPrismaModule,\n} from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploaderRouter } from \"./modules/file-uploader/file-uploader.router\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport { queryParser } from \"./utils/helpers/query-parser.helpers\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\n\nexport const app: express.Express = express();\n\nexport async function bootstrap(\n arkosConfig: ArkosConfig\n): Promise<express.Express> {\n await loadPrismaModule();\n\n if (arkosConfig?.configureApp) await arkosConfig.configureApp(app);\n\n const middlewaresConfig = arkosConfig?.middlewares;\n const disabledMiddlewares = middlewaresConfig?.disable || [];\n const replacedMiddlewares = middlewaresConfig?.replace || {};\n\n // Compression middleware\n if (!disabledMiddlewares?.includes?.(\"compression\"))\n app.use(\n replacedMiddlewares.compression ||\n compression(arkosConfig?.compressionOptions)\n );\n\n // Global rate limit middleware\n if (!disabledMiddlewares?.includes?.(\"global-rate-limit\"))\n app.use(\n replacedMiddlewares.globalRateLimit ||\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n },\n arkosConfig?.globalRequestRateLimitOptions || {}\n )\n )\n );\n\n // CORS middleware\n if (!disabledMiddlewares?.includes?.(\"cors\"))\n app.use(\n replacedMiddlewares.cors ||\n cors(\n arkosConfig?.cors?.customHandler\n ? arkosConfig.cors.customHandler\n : deepmerge(\n {\n origin: (\n origin: string,\n cb: (err: Error | null, allow?: boolean) => void\n ) => {\n const allowed = arkosConfig?.cors?.allowedOrigins;\n\n if (allowed === \"*\") {\n cb(null, true);\n } else if (Array.isArray(allowed)) {\n cb(null, !origin || allowed?.includes?.(origin));\n } else if (typeof allowed === \"string\") {\n cb(null, !origin || allowed === origin);\n } else {\n cb(null, false);\n }\n },\n methods: [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\n \"Content-Type\",\n \"Authorization\",\n \"Connection\",\n ],\n credentials: true,\n },\n arkosConfig?.cors?.options || {}\n )\n )\n );\n\n // JSON body parser middleware\n if (!disabledMiddlewares?.includes?.(\"express-json\"))\n app.use(\n replacedMiddlewares.expressJson ||\n express.json(arkosConfig?.jsonBodyParserOptions)\n );\n\n // Cookie parser middleware\n if (!disabledMiddlewares?.includes?.(\"cookie-parser\"))\n app.use(\n replacedMiddlewares.cookieParser ||\n cookieParser(...[...(arkosConfig?.cookieParserParameters || [])])\n );\n\n // Query parser middleware\n if (!disabledMiddlewares?.includes?.(\"query-parser\"))\n app.use(\n replacedMiddlewares.queryParser ||\n queryParser(\n deepmerge(\n {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n },\n arkosConfig?.queryParserOptions || {}\n )\n )\n );\n\n // Database connection check middleware\n if (!disabledMiddlewares?.includes?.(\"database-connection\"))\n app.use(replacedMiddlewares.databaseConnection || checkDatabaseConnection);\n\n // Request logger middleware\n if (!disabledMiddlewares?.includes?.(\"request-logger\"))\n app.use(replacedMiddlewares.requestLogger || handleRequestLogs);\n\n // Additional custom middlewares\n if (arkosConfig?.middlewares?.additional)\n arkosConfig.middlewares.additional.forEach((middleware) => {\n app.use(middleware);\n });\n\n // Configure routers\n const routersConfig = arkosConfig?.routers;\n const disabledRouters = routersConfig?.disable || [];\n const replacedRouters = routersConfig?.replace || {};\n\n // Welcome endpoint\n if (!disabledRouters?.includes?.(\"welcome-endpoint\"))\n app.get(\n \"/api\",\n replacedRouters.welcomeEndpoint ||\n ((req, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n })\n );\n\n // File uploader router\n if (!disabledRouters?.includes?.(\"file-uploader\")) {\n const fileUploaderRouter = replacedRouters.fileUploader\n ? await replacedRouters.fileUploader(arkosConfig)\n : await getFileUploaderRouter(arkosConfig);\n app.use(fileUploaderRouter);\n }\n\n // Auth router\n if (\n !disabledRouters?.includes?.(\"auth-router\") &&\n arkosConfig.authentication\n ) {\n const authRouter = replacedRouters.authRouter\n ? await replacedRouters.authRouter(arkosConfig)\n : await getAuthRouter(arkosConfig);\n app.use(\"/api\", authRouter);\n }\n\n // Prisma models router\n if (!disabledRouters?.includes?.(\"prisma-models-router\")) {\n const modelsRouter = replacedRouters.prismaModelsRouter\n ? await replacedRouters.prismaModelsRouter(arkosConfig)\n : await getPrismaModelsRouter(arkosConfig);\n app.use(\"/api\", modelsRouter);\n }\n\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n // Additional custom routers\n if (routersConfig?.additional) {\n routersConfig.additional.forEach((router) => {\n app.use(router);\n });\n }\n\n // Global error handler middleware (must be last)\n if (!disabledMiddlewares?.includes?.(\"global-error-handler\"))\n app.use(replacedMiddlewares.globalErrorHandler || errorHandler);\n\n return app;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":";;;;;;AAwBA,8BA+KC;AAvMD,sDAA8B;AAC9B,gDAAwB;AACxB,kEAAyC;AACzC,4DAA2D;AAC3D,4DAGoC;AACpC,gHAA4E;AAC5E,2DAA+C;AAC/C,8DAAsC;AACtC,sEAAoE;AACpE,mEAGwC;AACxC,uFAAqF;AAErF,+EAAmE;AACnE,wFAAyD;AACzD,qEAAoE;AAEvD,QAAA,GAAG,GAAoB,IAAA,iBAAO,GAAE,CAAC;AAEvC,KAAK,UAAU,SAAS,CAC7B,WAAwB;IAExB,MAAM,IAAA,iCAAgB,GAAE,CAAC;IAEzB,IAAI,WAAW,EAAE,YAAY;QAAE,MAAM,WAAW,CAAC,YAAY,CAAC,WAAG,CAAC,CAAC;IAEnE,MAAM,iBAAiB,GAAG,WAAW,EAAE,WAAW,CAAC;IACnD,MAAM,mBAAmB,GAAG,iBAAiB,EAAE,OAAO,IAAI,EAAE,CAAC;IAC7D,MAAM,mBAAmB,GAAG,iBAAiB,EAAE,OAAO,IAAI,EAAE,CAAC;IAG7D,IAAI,CAAC,mBAAmB,EAAE,QAAQ,EAAE,CAAC,aAAa,CAAC;QACjD,WAAG,CAAC,GAAG,CACL,mBAAmB,CAAC,WAAW;YAC7B,IAAA,qBAAW,EAAC,WAAW,EAAE,kBAAkB,CAAC,CAC/C,CAAC;IAGJ,IAAI,CAAC,mBAAmB,EAAE,QAAQ,EAAE,CAAC,mBAAmB,CAAC;QACvD,WAAG,CAAC,GAAG,CACL,mBAAmB,CAAC,eAAe;YACjC,IAAA,8BAAS,EACP,IAAA,0BAAS,EACP;gBACE,QAAQ,EAAE,EAAE,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AAC;QACzD,MAAM,YAAY,GAAG,eAAe,CAAC,kBAAkB;YACrD,CAAC,CAAC,MAAM,eAAe,CAAC,kBAAkB,CAAC,WAAW,CAAC;YACvD,CAAC,CAAC,MAAM,IAAA,mCAAqB,EAAC,WAAW,CAAC,CAAC;QAC7C,WAAG,CAAC,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;IAChC,CAAC;IAED,WAAG,CAAC,GAAG,CAAC,MAAM,EAAE,IAAA,kDAAoC,GAAE,CAAC,CAAC;IAExD,WAAG,CAAC,GAAG,CAAC,MAAM,EAAE,IAAA,iCAAgB,EAAC,WAAW,CAAC,CAAC,CAAC;IAG/C,IAAI,aAAa,EAAE,UAAU,EAAE,CAAC;QAC9B,aAAa,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;YAC1C,WAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAClB,CAAC,CAAC,CAAC;IACL,CAAC;IAGD,IAAI,CAAC,mBAAmB,EAAE,QAAQ,EAAE,CAAC,sBAAsB,CAAC;QAC1D,WAAG,CAAC,GAAG,CAAC,mBAAmB,CAAC,kBAAkB,IAAI,kCAAY,CAAC,CAAC;IAElE,OAAO,WAAG,CAAC;AACb,CAAC","sourcesContent":["import express from \"express\";\nimport cors from \"cors\";\nimport cookieParser from \"cookie-parser\";\nimport { getAuthRouter } from \"./modules/auth/auth.router\";\nimport {\n getPrismaModelsRouter,\n getAvailableResourcesAndRoutesRouter,\n} from \"./modules/base/base.router\";\nimport errorHandler from \"./modules/error-handler/error-handler.controller\";\nimport { rateLimit } from \"express-rate-limit\";\nimport compression from \"compression\";\nimport { handleRequestLogs } from \"./modules/base/base.middlewares\";\nimport {\n checkDatabaseConnection,\n loadPrismaModule,\n} from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploaderRouter } from \"./modules/file-uploader/file-uploader.router\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport { queryParser } from \"./utils/helpers/query-parser.helpers\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport { getSwaggerRouter } from \"./modules/swagger/swagger.router\";\n\nexport const app: express.Express = express();\n\nexport async function bootstrap(\n arkosConfig: ArkosConfig\n): Promise<express.Express> {\n await loadPrismaModule();\n\n if (arkosConfig?.configureApp) await arkosConfig.configureApp(app);\n\n const middlewaresConfig = arkosConfig?.middlewares;\n const disabledMiddlewares = middlewaresConfig?.disable || [];\n const replacedMiddlewares = middlewaresConfig?.replace || {};\n\n // Compression middleware\n if (!disabledMiddlewares?.includes?.(\"compression\"))\n app.use(\n replacedMiddlewares.compression ||\n compression(arkosConfig?.compressionOptions)\n );\n\n // Global rate limit middleware\n if (!disabledMiddlewares?.includes?.(\"global-rate-limit\"))\n app.use(\n replacedMiddlewares.globalRateLimit ||\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n },\n arkosConfig?.globalRequestRateLimitOptions || {}\n )\n )\n );\n\n // CORS middleware\n if (!disabledMiddlewares?.includes?.(\"cors\"))\n app.use(\n replacedMiddlewares.cors ||\n cors(\n arkosConfig?.cors?.customHandler\n ? arkosConfig.cors.customHandler\n : deepmerge(\n {\n origin: (\n origin: string,\n cb: (err: Error | null, allow?: boolean) => void\n ) => {\n const allowed = arkosConfig?.cors?.allowedOrigins;\n\n if (allowed === \"*\") {\n cb(null, true);\n } else if (Array.isArray(allowed)) {\n cb(null, !origin || allowed?.includes?.(origin));\n } else if (typeof allowed === \"string\") {\n cb(null, !origin || allowed === origin);\n } else {\n cb(null, false);\n }\n },\n methods: [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\n \"Content-Type\",\n \"Authorization\",\n \"Connection\",\n ],\n credentials: true,\n },\n arkosConfig?.cors?.options || {}\n )\n )\n );\n\n // JSON body parser middleware\n if (!disabledMiddlewares?.includes?.(\"express-json\"))\n app.use(\n replacedMiddlewares.expressJson ||\n express.json(arkosConfig?.jsonBodyParserOptions)\n );\n\n // Cookie parser middleware\n if (!disabledMiddlewares?.includes?.(\"cookie-parser\"))\n app.use(\n replacedMiddlewares.cookieParser ||\n cookieParser(...[...(arkosConfig?.cookieParserParameters || [])])\n );\n\n // Query parser middleware\n if (!disabledMiddlewares?.includes?.(\"query-parser\"))\n app.use(\n replacedMiddlewares.queryParser ||\n queryParser(\n deepmerge(\n {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n },\n arkosConfig?.queryParserOptions || {}\n )\n )\n );\n\n // Database connection check middleware\n if (!disabledMiddlewares?.includes?.(\"database-connection\"))\n app.use(replacedMiddlewares.databaseConnection || checkDatabaseConnection);\n\n // Request logger middleware\n if (!disabledMiddlewares?.includes?.(\"request-logger\"))\n app.use(replacedMiddlewares.requestLogger || handleRequestLogs);\n\n // Additional custom middlewares\n if (arkosConfig?.middlewares?.additional)\n arkosConfig.middlewares.additional.forEach((middleware) => {\n app.use(middleware);\n });\n\n // Configure routers\n const routersConfig = arkosConfig?.routers;\n const disabledRouters = routersConfig?.disable || [];\n const replacedRouters = routersConfig?.replace || {};\n\n // Welcome endpoint\n if (!disabledRouters?.includes?.(\"welcome-endpoint\"))\n app.get(\n \"/api\",\n replacedRouters.welcomeEndpoint ||\n ((req, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n })\n );\n\n // File uploader router\n if (!disabledRouters?.includes?.(\"file-uploader\")) {\n const fileUploaderRouter = replacedRouters.fileUploader\n ? await replacedRouters.fileUploader(arkosConfig)\n : await getFileUploaderRouter(arkosConfig);\n app.use(fileUploaderRouter);\n }\n\n // Auth router\n if (\n !disabledRouters?.includes?.(\"auth-router\") &&\n arkosConfig.authentication\n ) {\n const authRouter = replacedRouters.authRouter\n ? await replacedRouters.authRouter(arkosConfig)\n : await getAuthRouter(arkosConfig);\n app.use(\"/api\", authRouter);\n }\n\n // Prisma models router\n if (!disabledRouters?.includes?.(\"prisma-models-router\")) {\n const modelsRouter = replacedRouters.prismaModelsRouter\n ? await replacedRouters.prismaModelsRouter(arkosConfig)\n : await getPrismaModelsRouter(arkosConfig);\n app.use(\"/api\", modelsRouter);\n }\n\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n app.use(\"/api\", getSwaggerRouter(arkosConfig));\n\n // Additional custom routers\n if (routersConfig?.additional) {\n routersConfig.additional.forEach((router) => {\n app.use(router);\n });\n }\n\n // Global error handler middleware (must be last)\n if (!disabledMiddlewares?.includes?.(\"global-error-handler\"))\n app.use(replacedMiddlewares.globalErrorHandler || errorHandler);\n\n return app;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.service.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.service.helpers.ts"],"names":[],"mappings":";;AAYA,0CAoBC;AAQD,wDAkBC;AA8BD,gEA4JC;AAUD,gDAgCC;AA9RD,6EAIkD;AAQlD,SAAgB,eAAe,CAAC,GAAwB;IACtD,IAAI,CAAC,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ;QAAE,OAAO,GAAG,CAAC;IAEhD,MAAM,MAAM,GAAwB,EAAE,CAAC;IAEvC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;QAC/C,IAAI,GAAG,KAAK,WAAW;YAAE,SAAS;QAElC,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;YACzB,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAC/B,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CACzE,CAAC;QACJ,CAAC;aAAM,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,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,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;QAC5C,OAAO,YAAY,EAAE,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC;IACjE,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import {\n getPrismaModelRelations,\n RelationFields,\n getModelUniqueFields,\n} from \"../../../../utils/helpers/models.helpers\";\n\n/**\n * Removes apiAction field from an object and all nested objects\n *\n * @param {Record<string, any>} obj - The object to clean\n * @returns {Record<string, any>} - The cleaned object\n */\nexport function removeApiAction(obj: Record<string, any>): Record<string, any> {\n if (!obj || typeof obj !== \"object\") return obj;\n\n const result: Record<string, any> = {};\n\n for (const [key, value] of Object.entries(obj)) {\n if (key === \"apiAction\") continue;\n\n if (Array.isArray(value)) {\n result[key] = value.map((item) =>\n typeof item === \"object\" && item !== null ? removeApiAction(item) : item\n );\n } else if (typeof value === \"object\" && value !== null) {\n result[key] = removeApiAction(value);\n } else {\n result[key] = value;\n }\n }\n\n return result;\n}\n\n/**\n * Checks if an object is already formatted as a Prisma relation operation\n *\n * @param {Record<string, any>} obj - The object to check\n * @returns {boolean} - True if the object contains Prisma relation operations\n */\nexport function isPrismaRelationFormat(obj: Record<string, any>): boolean {\n if (!obj || typeof obj !== \"object\") return false;\n\n // Common Prisma relation operations\n const prismaOperations = [\n \"create\",\n \"connect\",\n \"update\",\n \"delete\",\n \"disconnect\",\n \"deleteMany\",\n \"connectOrCreate\",\n \"upsert\",\n \"set\",\n ];\n\n // Check if any key is a Prisma operation\n return prismaOperations.some((op) => op in obj);\n}\n\n/**\n * Determines the appropriate Prisma operation (`create`, `connect`, `update`, `delete`, or `disconnect`)\n * for each relation field in the provided body based on its nested data and recursively does the same for each relation field.\n *\n * This function handles the following types of relations:\n * - **One-to-one**\n * - **One-to-many**\n *\n *\n * ### Operation Rules:\n *\n *\n * - **Create**: Used when the nested relation data is provided **without an `id` or unique field**.\n * - **Connect**: Used when the nested relation data contains **only an `id` or a unique field** (e.g., email).\n * - **Update**: Used when the nested relation data contains **both an `id` and additional fields**.\n * - **Delete**: Used when the nested relation data includes **`apiAction: \"delete\"`**.\n * - **Disconnect**: Used when the nested relation data includes **`apiAction: \"disconnect\"`**.\n *\n * The function will preserve existing Prisma operation formats if detected,\n * allowing developers to manually structure relation operations when needed.\n *\n * @param {Record<string, any>} body - The object containing relation fields to be processed.\n * @param {Object} relationFields - Defines relation field types.\n * @param {RelationFields[]} relationFields.singular - List of one-side relation field names (one-to-one).\n * @param {RelationFields[]} relationFields.list - List of many-side relation field names (one-to-many).\n * @param {string[]} ignoreActions - Optional list of apiAction values to ignore.\n * @returns {Record<string, any>} The transformed data with appropriate Prisma operations applied.\n */\nexport function handleRelationFieldsInBody(\n body: Record<string, any>,\n relationFields: RelationFields,\n ignoreActions: string[] = []\n) {\n let mutableBody = { ...body };\n\n relationFields?.list?.forEach((field) => {\n if (!body[field.name]) return;\n\n // Skip if the field is already in Prisma relation format\n if (isPrismaRelationFormat(body[field.name])) {\n return;\n }\n\n // Skip if the field is not an array (likely already handled manually)\n if (!Array.isArray(body[field.name])) {\n return;\n }\n\n const createData: any[] = [];\n const connectData: any[] = [];\n const updateData: any[] = [];\n const disconnectData: any[] = [];\n const deleteManyIds: any[] = [];\n\n body[field.name]?.forEach((bodyField: any) => {\n if (ignoreActions?.includes?.(bodyField?.apiAction)) return;\n\n const apiAction = bodyField?.apiAction;\n\n if (apiAction === \"delete\") {\n deleteManyIds.push(bodyField.id);\n } else if (apiAction === \"disconnect\") {\n disconnectData.push({ id: bodyField.id });\n } else if (canBeUsedToConnect(field.type, bodyField)) {\n // Handle connection with unique fields or ID\n const { apiAction: _, ...cleanedData } = bodyField;\n connectData.push(cleanedData);\n } else if (!bodyField?.id) {\n // If no ID, assume create operation\n let nestedRelations = getPrismaModelRelations(field.type);\n\n let dataToPush = { ...bodyField };\n\n if (nestedRelations) {\n dataToPush = handleRelationFieldsInBody(\n dataToPush,\n nestedRelations,\n ignoreActions\n );\n }\n\n // Ensure apiAction is removed\n if (\"apiAction\" in dataToPush) {\n const { apiAction: _, ...rest } = dataToPush;\n dataToPush = rest;\n }\n\n createData.push(dataToPush);\n } else {\n // If ID and other fields, assume update operation\n const { id, apiAction: _, ...data } = bodyField;\n\n let nestedRelations = getPrismaModelRelations(field.type);\n\n let dataToPush = data;\n if (nestedRelations) {\n dataToPush = handleRelationFieldsInBody(\n data,\n nestedRelations,\n ignoreActions\n );\n }\n\n updateData.push({\n where: { id },\n data: dataToPush,\n });\n }\n });\n\n mutableBody[field.name] = {\n ...(createData.length ? { create: createData } : {}),\n ...(connectData.length ? { connect: connectData } : {}),\n ...(updateData.length ? { update: updateData } : {}),\n ...(disconnectData.length ? { disconnect: disconnectData } : {}),\n ...(deleteManyIds.length\n ? { deleteMany: { id: { in: deleteManyIds } } }\n : {}),\n };\n });\n\n relationFields?.singular?.forEach((field) => {\n if (!body[field.name]) return;\n if (ignoreActions?.includes?.(body[field.name]?.apiAction)) return;\n\n // Skip if the field is already in Prisma relation format\n if (isPrismaRelationFormat(body[field.name])) {\n return;\n }\n\n const relationData = body[field.name];\n let nestedRelations = getPrismaModelRelations(field.type);\n\n if (canBeUsedToConnect(field.type, relationData)) {\n // Handle connection with unique fields or ID\n const { apiAction: _, ...cleanedData } = relationData;\n mutableBody[field.name] = { connect: cleanedData };\n } else if (!relationData?.id) {\n // If no ID, assume create operation\n let dataToCreate = { ...relationData };\n\n if (\"apiAction\" in dataToCreate) {\n const { apiAction: _, ...rest } = dataToCreate;\n dataToCreate = rest;\n }\n\n if (nestedRelations) {\n dataToCreate = handleRelationFieldsInBody(\n dataToCreate,\n nestedRelations,\n ignoreActions\n );\n }\n\n mutableBody[field.name] = { create: dataToCreate };\n } else {\n // If ID and other fields, assume update operation\n const { id, apiAction: _, ...data } = relationData;\n\n let dataToUpdate = data;\n if (nestedRelations) {\n dataToUpdate = handleRelationFieldsInBody(\n data,\n nestedRelations,\n ignoreActions\n );\n }\n\n mutableBody[field.name] = {\n update: {\n data: dataToUpdate,\n },\n };\n }\n });\n\n // Remove any remaining apiAction fields from the top level\n if (\"apiAction\" in mutableBody) {\n const { apiAction, ...rest } = mutableBody;\n mutableBody = rest;\n }\n\n // As a final step, recursively remove any remaining apiAction fields\n return removeApiAction(mutableBody);\n}\n\n/**\n * Checks if a field value can be used to connect to a model\n * This happens when the field contains only an ID or a single unique field\n *\n * @param {string} modelName - The model name to get unique fields for\n * @param {Record<string, any>} bodyField - The field value from the body\n * @returns {boolean} True if the field can be used for a connect operation\n */\nexport function canBeUsedToConnect(\n modelName: string,\n bodyField: Record<string, any> | undefined | null\n): boolean {\n // If the field is null or undefined, it can't be used to connect\n if (!bodyField) return false;\n\n // If the field has an apiAction that's not for connecting, return false\n if (bodyField.apiAction && ![\"connect\"]?.includes?.(bodyField.apiAction)) {\n return false;\n }\n\n // If explicitly marked for connect, allow it\n if (bodyField.apiAction === \"connect\") {\n return true;\n }\n\n // If only ID is present, it can be used to connect\n if (Object.keys(bodyField)?.length === 1 && bodyField?.id) {\n return true;\n }\n\n // Get unique fields for the model\n const uniqueFields = getModelUniqueFields(modelName);\n\n // If the field has exactly one property and it's a unique field, it can be used to connect\n if (Object.keys(bodyField).length === 1) {\n const fieldName = Object.keys(bodyField)[0];\n return uniqueFields?.some((field) => field.name === fieldName);\n }\n\n return false;\n}\n\n// /**\n// * Checks if a list field is actually an array\n// *\n// * @param {any} field - The field to check\n// * @returns {boolean} - True if the field is an array\n// */\n// export function isListFieldAnArray(field: any): boolean {\n// return Array.isArray(field);\n// }\n"]}
|
|
1
|
+
{"version":3,"file":"base.service.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.service.helpers.ts"],"names":[],"mappings":";;AAYA,0CAoBC;AAQD,wDAkBC;AA8BD,gEA4JC;AAUD,gDAgCC;AA9RD,6EAIkD;AAQlD,SAAgB,eAAe,CAAC,GAAwB;IACtD,IAAI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C,SAAS;QAAE,OAAO,KAAK,CAAC;IAG7B,IAAI,SAAS,CAAC,SAAS,IAAI,CAAC,CAAC,SAAS,CAAC,EAAE,QAAQ,EAAE,CAAC,SAAS,CAAC,SAAS,CAAC,EAAE,CAAC;QACzE,OAAO,KAAK,CAAC;IACf,CAAC;IAGD,IAAI,SAAS,CAAC,SAAS,KAAK,SAAS,EAAE,CAAC;QACtC,OAAO,IAAI,CAAC;IACd,CAAC;IAGD,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,MAAM,KAAK,CAAC,IAAI,SAAS,EAAE,EAAE,EAAE,CAAC;QAC1D,OAAO,IAAI,CAAC;IACd,CAAC;IAGD,MAAM,YAAY,GAAG,IAAA,qCAAoB,EAAC,SAAS,CAAC,CAAC;IAGrD,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACxC,MAAM,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;QAC5C,OAAO,YAAY,EAAE,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC;IACjE,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import {\n getPrismaModelRelations,\n RelationFields,\n getModelUniqueFields,\n} from \"../../../../utils/helpers/models.helpers\";\n\n/**\n * Removes apiAction field from an object and all nested objects\n *\n * @param {Record<string, any>} obj - The object to clean\n * @returns {Record<string, any>} - The cleaned object\n */\nexport function removeApiAction(obj: Record<string, any>): Record<string, any> {\n if (!obj || typeof obj !== \"object\") return obj;\n\n const result: Record<string, any> = {};\n\n for (const [key, value] of Object.entries(obj)) {\n if (key === \"apiAction\") continue;\n\n if (Array.isArray(value)) {\n result[key] = value.map((item) =>\n typeof item === \"object\" && item !== null ? removeApiAction(item) : item\n );\n } else if (typeof value === \"object\" && value !== null) {\n result[key] = removeApiAction(value);\n } else {\n result[key] = value;\n }\n }\n\n return result;\n}\n\n/**\n * Checks if an object is already formatted as a Prisma relation operation\n *\n * @param {Record<string, any>} obj - The object to check\n * @returns {boolean} - True if the object contains Prisma relation operations\n */\nexport function isPrismaRelationFormat(obj: Record<string, any>): boolean {\n if (!obj || typeof obj !== \"object\") return false;\n\n // Common Prisma relation operations\n const prismaOperations = [\n \"create\",\n \"connect\",\n \"update\",\n \"delete\",\n \"disconnect\",\n \"deleteMany\",\n \"connectOrCreate\",\n \"upsert\",\n \"set\",\n ];\n\n // Check if any key is a Prisma operation\n return prismaOperations.some((op) => op in obj);\n}\n\n/**\n * Determines the appropriate Prisma operation (`create`, `connect`, `update`, `delete`, or `disconnect`)\n * for each relation field in the provided body based on its nested data and recursively does the same for each relation field.\n *\n * This function handles the following types of relations:\n * - **One-to-one**\n * - **One-to-many**\n *\n *\n * ### Operation Rules:\n *\n *\n * - **Create**: Used when the nested relation data is provided **without an `id` or unique field**.\n * - **Connect**: Used when the nested relation data contains **only an `id` or a unique field** (e.g., email).\n * - **Update**: Used when the nested relation data contains **both an `id` and additional fields**.\n * - **Delete**: Used when the nested relation data includes **`apiAction: \"delete\"`**.\n * - **Disconnect**: Used when the nested relation data includes **`apiAction: \"disconnect\"`**.\n *\n * The function will preserve existing Prisma operation formats if detected,\n * allowing developers to manually structure relation operations when needed.\n *\n * @param {Record<string, any>} body - The object containing relation fields to be processed.\n * @param {Object} relationFields - Defines relation field types.\n * @param {RelationFields[]} relationFields.singular - List of one-side relation field names (one-to-one).\n * @param {RelationFields[]} relationFields.list - List of many-side relation field names (one-to-many).\n * @param {string[]} ignoreActions - Optional list of apiAction values to ignore.\n * @returns {Record<string, any>} The transformed data with appropriate Prisma operations applied.\n */\nexport function handleRelationFieldsInBody(\n body: Record<string, any>,\n relationFields: RelationFields,\n ignoreActions: string[] = []\n) {\n let mutableBody = { ...body };\n\n relationFields?.list?.forEach((field) => {\n if (!body[field.name]) return;\n\n // Skip if the field is already in Prisma relation format\n if (isPrismaRelationFormat(body[field.name])) {\n return;\n }\n\n // Skip if the field is not an array (likely already handled manually)\n if (!Array.isArray(body[field.name])) {\n return;\n }\n\n const createData: any[] = [];\n const connectData: any[] = [];\n const updateData: any[] = [];\n const disconnectData: any[] = [];\n const deleteManyIds: any[] = [];\n\n body[field.name]?.forEach((bodyField: any) => {\n if (ignoreActions?.includes?.(bodyField?.apiAction)) return;\n\n const apiAction = bodyField?.apiAction;\n\n if (apiAction === \"delete\") {\n deleteManyIds.push(bodyField.id);\n } else if (apiAction === \"disconnect\") {\n disconnectData.push({ id: bodyField.id });\n } else if (canBeUsedToConnect(field.type, bodyField)) {\n // Handle connection with unique fields or ID\n const { apiAction: _, ...cleanedData } = bodyField;\n connectData.push(cleanedData);\n } else if (!bodyField?.id) {\n // If no ID, assume create operation\n let nestedRelations = getPrismaModelRelations(field.type);\n\n let dataToPush = { ...bodyField };\n\n if (nestedRelations) {\n dataToPush = handleRelationFieldsInBody(\n dataToPush,\n nestedRelations,\n ignoreActions\n );\n }\n\n // Ensure apiAction is removed\n if (\"apiAction\" in dataToPush) {\n const { apiAction: _, ...rest } = dataToPush;\n dataToPush = rest;\n }\n\n createData.push(dataToPush);\n } else {\n // If ID and other fields, assume update operation\n const { id, apiAction: _, ...data } = bodyField;\n\n let nestedRelations = getPrismaModelRelations(field.type);\n\n let dataToPush = data;\n if (nestedRelations) {\n dataToPush = handleRelationFieldsInBody(\n data,\n nestedRelations,\n ignoreActions\n );\n }\n\n updateData.push({\n where: { id },\n data: dataToPush,\n });\n }\n });\n\n mutableBody[field.name] = {\n ...(createData.length ? { create: createData } : {}),\n ...(connectData.length ? { connect: connectData } : {}),\n ...(updateData.length ? { update: updateData } : {}),\n ...(disconnectData.length ? { disconnect: disconnectData } : {}),\n ...(deleteManyIds.length\n ? { deleteMany: { id: { in: deleteManyIds } } }\n : {}),\n };\n });\n\n relationFields?.singular?.forEach((field) => {\n if (!body[field.name]) return;\n if (ignoreActions?.includes?.(body[field.name]?.apiAction)) return;\n\n // Skip if the field is already in Prisma relation format\n if (isPrismaRelationFormat(body[field.name])) {\n return;\n }\n\n const relationData = body[field.name];\n let nestedRelations = getPrismaModelRelations(field.type);\n\n if (canBeUsedToConnect(field.type, relationData)) {\n // Handle connection with unique fields or ID\n const { apiAction: _, ...cleanedData } = relationData;\n mutableBody[field.name] = { connect: cleanedData };\n } else if (!relationData?.id) {\n // If no ID, assume create operation\n let dataToCreate = { ...relationData };\n\n if (\"apiAction\" in dataToCreate) {\n const { apiAction: _, ...rest } = dataToCreate;\n dataToCreate = rest;\n }\n\n if (nestedRelations) {\n dataToCreate = handleRelationFieldsInBody(\n dataToCreate,\n nestedRelations,\n ignoreActions\n );\n }\n\n mutableBody[field.name] = { create: dataToCreate };\n } else {\n // If ID and other fields, assume update operation\n const { id, apiAction: _, ...data } = relationData;\n\n let dataToUpdate = data;\n if (nestedRelations) {\n dataToUpdate = handleRelationFieldsInBody(\n data,\n nestedRelations,\n ignoreActions\n );\n }\n\n mutableBody[field.name] = {\n update: {\n data: dataToUpdate,\n },\n };\n }\n });\n\n // Remove any remaining apiAction fields from the top level\n if (\"apiAction\" in mutableBody) {\n const { apiAction, ...rest } = mutableBody;\n mutableBody = rest;\n }\n\n // As a final step, recursively remove any remaining apiAction fields\n return removeApiAction(mutableBody);\n}\n\n/**\n * Checks if a field value can be used to connect to a model\n * This happens when the field contains only an ID or a single unique field\n *\n * @param {string} modelName - The model name to get unique fields for\n * @param {Record<string, any>} bodyField - The field value from the body\n * @returns {boolean} True if the field can be used for a connect operation\n */\nexport function canBeUsedToConnect(\n modelName: string,\n bodyField: Record<string, any> | undefined | null\n): boolean {\n // If the field is null or undefined, it can't be used to connect\n if (!bodyField) return false;\n\n // If the field has an apiAction that's not for connecting, return false\n if (bodyField.apiAction && ![\"connect\"]?.includes?.(bodyField.apiAction)) {\n return false;\n }\n\n // If explicitly marked for connect, allow it\n if (bodyField.apiAction === \"connect\") {\n return true;\n }\n\n // If only ID is present, it can be used to connect\n if (Object.keys(bodyField)?.length === 1 && bodyField?.id) {\n return true;\n }\n\n // Get unique fields for the model\n const uniqueFields = getModelUniqueFields(modelName);\n\n // If the field has exactly one property and it's a unique field, it can be used to connect\n if (Object.keys(bodyField).length === 1) {\n const fieldName = Object.keys(bodyField)[0];\n return uniqueFields?.some((field) => field.name === fieldName);\n }\n\n return false;\n}\n"]}
|
|
@@ -1,2 +1,141 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.getSwaggerRouter = getSwaggerRouter;
|
|
7
|
+
const express_1 = require("express");
|
|
8
|
+
const swagger_ui_express_1 = __importDefault(require("swagger-ui-express"));
|
|
9
|
+
const swagger_jsdoc_1 = __importDefault(require("swagger-jsdoc"));
|
|
10
|
+
const deepmerge_helper_1 = __importDefault(require("../../utils/helpers/deepmerge.helper"));
|
|
11
|
+
const swaggerRouter = (0, express_1.Router)();
|
|
12
|
+
function generateSchemasByMode(swaggerConfig) {
|
|
13
|
+
const schemas = {};
|
|
14
|
+
switch (swaggerConfig.mode) {
|
|
15
|
+
case "prisma":
|
|
16
|
+
break;
|
|
17
|
+
case "class-validator":
|
|
18
|
+
break;
|
|
19
|
+
case "zod":
|
|
20
|
+
break;
|
|
21
|
+
case "json-schema":
|
|
22
|
+
default:
|
|
23
|
+
break;
|
|
24
|
+
}
|
|
25
|
+
return schemas;
|
|
26
|
+
}
|
|
27
|
+
function getSwaggerRouter(arkosConfig) {
|
|
28
|
+
const defaultSwaggerConfig = {
|
|
29
|
+
endpoint: "/docs",
|
|
30
|
+
mode: "json-schema",
|
|
31
|
+
options: {
|
|
32
|
+
definition: {
|
|
33
|
+
openapi: "3.0.0",
|
|
34
|
+
info: {
|
|
35
|
+
title: "API Generated By Arkos.js",
|
|
36
|
+
version: "1.0.0",
|
|
37
|
+
description: "This API was automatically generated by Arkos.js read more about at www.arkosjs.com",
|
|
38
|
+
},
|
|
39
|
+
servers: [
|
|
40
|
+
{
|
|
41
|
+
url: `http://${arkosConfig.host}:${arkosConfig.port}`,
|
|
42
|
+
description: "Local server",
|
|
43
|
+
},
|
|
44
|
+
],
|
|
45
|
+
components: {
|
|
46
|
+
schemas: {},
|
|
47
|
+
securitySchemes: {
|
|
48
|
+
BearerAuth: {
|
|
49
|
+
type: "http",
|
|
50
|
+
scheme: "bearer",
|
|
51
|
+
bearerFormat: "JWT",
|
|
52
|
+
},
|
|
53
|
+
ApiKeyAuth: {
|
|
54
|
+
type: "apiKey",
|
|
55
|
+
in: "header",
|
|
56
|
+
name: "X-API-Key",
|
|
57
|
+
},
|
|
58
|
+
},
|
|
59
|
+
},
|
|
60
|
+
security: [],
|
|
61
|
+
},
|
|
62
|
+
apis: [
|
|
63
|
+
"./src/routers/*.router.{ts,js}",
|
|
64
|
+
"./src/modules/**/*.router.{ts,js}",
|
|
65
|
+
],
|
|
66
|
+
swaggerUiOptions: {
|
|
67
|
+
explorer: true,
|
|
68
|
+
customCss: `
|
|
69
|
+
.swagger-ui .topbar { display: none; }
|
|
70
|
+
.swagger-ui .info { margin: 20px 0; }
|
|
71
|
+
`,
|
|
72
|
+
swaggerOptions: {
|
|
73
|
+
filter: true,
|
|
74
|
+
displayRequestDuration: true,
|
|
75
|
+
showExtensions: true,
|
|
76
|
+
showCommonExtensions: true,
|
|
77
|
+
},
|
|
78
|
+
},
|
|
79
|
+
deepLinking: true,
|
|
80
|
+
tryItOutEnabled: true,
|
|
81
|
+
persistAuthorization: false,
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
const swaggerConfigs = (0, deepmerge_helper_1.default)(defaultSwaggerConfig, arkosConfig.swagger || {});
|
|
85
|
+
const modeSchemas = generateSchemasByMode(swaggerConfigs);
|
|
86
|
+
if (swaggerConfigs.options.definition.components?.schemas) {
|
|
87
|
+
swaggerConfigs.options.definition.components.schemas = {
|
|
88
|
+
...swaggerConfigs.options.definition.components.schemas,
|
|
89
|
+
...modeSchemas,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
const swaggerSpecification = (0, swagger_jsdoc_1.default)({
|
|
93
|
+
definition: swaggerConfigs.options
|
|
94
|
+
.definition,
|
|
95
|
+
apis: swaggerConfigs.options.apis || [],
|
|
96
|
+
});
|
|
97
|
+
const swaggerUiOptions = {
|
|
98
|
+
explorer: swaggerConfigs.options.swaggerUiOptions?.explorer ?? true,
|
|
99
|
+
customCss: swaggerConfigs.options.swaggerUiOptions?.customCss,
|
|
100
|
+
customSiteTitle: swaggerConfigs.options.swaggerUiOptions?.customSiteTitle ||
|
|
101
|
+
"API Documentation",
|
|
102
|
+
customfavIcon: swaggerConfigs.options.swaggerUiOptions?.customfavIcon,
|
|
103
|
+
swaggerOptions: {
|
|
104
|
+
filter: swaggerConfigs.options.swaggerUiOptions?.swaggerOptions?.filter ?? true,
|
|
105
|
+
displayRequestDuration: swaggerConfigs.options.swaggerUiOptions?.swaggerOptions
|
|
106
|
+
?.displayRequestDuration ?? true,
|
|
107
|
+
deepLinking: swaggerConfigs.options.deepLinking ?? true,
|
|
108
|
+
tryItOutEnabled: swaggerConfigs.options.tryItOutEnabled ?? true,
|
|
109
|
+
persistAuthorization: swaggerConfigs.options.persistAuthorization ?? false,
|
|
110
|
+
showExtensions: swaggerConfigs.options.swaggerUiOptions?.swaggerOptions
|
|
111
|
+
?.showExtensions ?? true,
|
|
112
|
+
showCommonExtensions: swaggerConfigs.options.swaggerUiOptions?.swaggerOptions
|
|
113
|
+
?.showCommonExtensions ?? true,
|
|
114
|
+
...swaggerConfigs.options.swaggerUiOptions?.swaggerOptions,
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
swaggerRouter.use(swaggerConfigs.endpoint, swagger_ui_express_1.default.serve);
|
|
118
|
+
swaggerRouter.get(swaggerConfigs.endpoint, swagger_ui_express_1.default.setup(swaggerSpecification, swaggerUiOptions));
|
|
119
|
+
swaggerRouter.get(`${swaggerConfigs.endpoint}/json`, (req, res) => {
|
|
120
|
+
res.setHeader("Content-Type", "application/json");
|
|
121
|
+
res.json(swaggerSpecification);
|
|
122
|
+
});
|
|
123
|
+
swaggerRouter.get(`${swaggerConfigs.endpoint}/yaml`, (req, res) => {
|
|
124
|
+
const yaml = require("js-yaml");
|
|
125
|
+
res.setHeader("Content-Type", "text/yaml");
|
|
126
|
+
res.send(yaml.dump(swaggerSpecification));
|
|
127
|
+
});
|
|
128
|
+
swaggerRouter.get(`${swaggerConfigs.endpoint}/health`, (req, res) => {
|
|
129
|
+
res.json({
|
|
130
|
+
status: "ok",
|
|
131
|
+
swagger: {
|
|
132
|
+
version: swaggerConfigs.options.definition.openapi,
|
|
133
|
+
title: swaggerConfigs.options.definition.info?.title,
|
|
134
|
+
endpoint: swaggerConfigs.endpoint,
|
|
135
|
+
mode: swaggerConfigs.mode,
|
|
136
|
+
},
|
|
137
|
+
});
|
|
138
|
+
});
|
|
139
|
+
return swaggerRouter;
|
|
140
|
+
}
|
|
2
141
|
//# sourceMappingURL=swagger.router.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"swagger.router.js","sourceRoot":"","sources":["../../../../src/modules/swagger/swagger.router.ts"],"names":[],"mappings":"","sourcesContent":[""]}
|
|
1
|
+
{"version":3,"file":"swagger.router.js","sourceRoot":"","sources":["../../../../src/modules/swagger/swagger.router.ts"],"names":[],"mappings":";;;;;AAqFA,4CAoJC;AA1LD,qCAAiC;AACjC,4EAA2C;AAC3C,kEAAyC;AAEzC,4FAA6D;AAE7D,MAAM,aAAa,GAAG,IAAA,gBAAM,GAAE,CAAC;AAG/B,SAAS,qBAAqB,CAAC,aAAqC;IAClE,MAAM,OAAO,GAAwB,EAAE,CAAC;IAExC,QAAQ,aAAc,CAAC,IAAI,EAAE,CAAC;QAC5B,KAAK,QAAQ;YAGX,MAAM;QAER,KA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,OAAO,EAAE;gBACP,OAAO,EAAE,cAAc,CAAC,OAAO,CAAC,UAAU,CAAC,OAAO;gBAClD,KAAK,EAAE,cAAc,CAAC,OAAO,CAAC,UAAU,CAAC,IAAI,EAAE,KAAK;gBACpD,QAAQ,EAAE,cAAc,CAAC,QAAQ;gBACjC,IAAI,EAAE,cAAc,CAAC,IAAI;aAC1B;SACF,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,aAAa,CAAC;AACvB,CAAC","sourcesContent":["// import { Router } from \"express\";\n// import swaggerUi from \"swagger-ui-express\";\n// import { ArkosConfig } from \"../../types/arkos-config\";\n// import deepmerge from \"../../utils/helpers/deepmerge.helper\";\n\n// const swaggerRouter = Router();\n\n// export function getSwaggerRouter(arkosConfig: ArkosConfig) {\n// const swaggerConfigs: ArkosConfig[\"swagger\"] = deepmerge(\n// {\n// endpoint: \"/docs\",\n// options: {\n// definition: {\n// openapi: \"3.0.0\",\n// info: {\n// title: \"API Generated By Arkos.js\",\n// version: \"1.0.0\",\n// description:\n// \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\",\n// },\n// servers: [\n// {\n// url: `http://${arkosConfig.host}:${arkosConfig.port}`,\n// description: \"Local server\",\n// },\n// ],\n// },\n// apis: [\n// \"./src/routers/*.router.{ts,js}\",\n// \"./src/modules/**/*.router.{ts,js}\",\n// ],\n// deepLinking: true,\n// tryItOutEnabled: true,\n// },\n// },\n// arkosConfig.swagger || {}\n// );\n\n// swaggerRouter.get(\n// swaggerConfigs.endpoint!,\n// swaggerUi.serve,\n// swaggerUi.setup(swaggerConfigs.options)\n// );\n\n// return swaggerRouter;\n// }\n\nimport { Router } from \"express\";\nimport swaggerUi from \"swagger-ui-express\";\nimport swaggerJsdoc from \"swagger-jsdoc\";\nimport { ArkosConfig } from \"../../types/arkos-config\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\n\nconst swaggerRouter = Router();\n\n// Helper function to generate schemas based on mode\nfunction generateSchemasByMode(swaggerConfig: ArkosConfig[\"swagger\"]) {\n const schemas: Record<string, any> = {};\n\n switch (swaggerConfig!.mode) {\n case \"prisma\":\n // In a real implementation, you'd generate schemas from Prisma models\n // This would require additional logic to parse Prisma schema files\n break;\n\n case \"class-validator\":\n // Generate schemas from class-validator decorators\n // This would require reflection or build-time generation\n break;\n\n case \"zod\":\n // Generate schemas from Zod definitions\n // This could be done through custom transformations\n break;\n\n case \"json-schema\":\n default:\n // Use manually defined JSON schemas\n // This is the default behavior with JSDoc comments\n break;\n }\n\n return schemas;\n}\n\nexport function getSwaggerRouter(arkosConfig: ArkosConfig): Router {\n // Default swagger configuration\n const defaultSwaggerConfig: ArkosConfig[\"swagger\"] = {\n endpoint: \"/docs\",\n mode: \"json-schema\",\n options: {\n definition: {\n openapi: \"3.0.0\",\n info: {\n title: \"API Generated By Arkos.js\",\n version: \"1.0.0\",\n description:\n \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\",\n },\n servers: [\n {\n url: `http://${arkosConfig.host}:${arkosConfig.port}`,\n description: \"Local server\",\n },\n ],\n components: {\n schemas: {},\n securitySchemes: {\n BearerAuth: {\n type: \"http\",\n scheme: \"bearer\",\n bearerFormat: \"JWT\",\n },\n ApiKeyAuth: {\n type: \"apiKey\",\n in: \"header\",\n name: \"X-API-Key\",\n },\n },\n },\n security: [],\n },\n apis: [\n \"./src/routers/*.router.{ts,js}\",\n \"./src/modules/**/*.router.{ts,js}\",\n ],\n swaggerUiOptions: {\n explorer: true,\n customCss: `\n .swagger-ui .topbar { display: none; }\n .swagger-ui .info { margin: 20px 0; }\n `,\n swaggerOptions: {\n filter: true,\n displayRequestDuration: true,\n showExtensions: true,\n showCommonExtensions: true,\n },\n },\n deepLinking: true,\n tryItOutEnabled: true,\n persistAuthorization: false,\n },\n };\n\n // Merge default config with user config\n const swaggerConfigs = deepmerge(\n defaultSwaggerConfig,\n arkosConfig.swagger || {}\n );\n\n // Generate additional schemas based on mode\n const modeSchemas = generateSchemasByMode(swaggerConfigs);\n\n // Merge mode-generated schemas with existing schemas\n if (swaggerConfigs.options.definition.components?.schemas) {\n swaggerConfigs.options.definition.components.schemas = {\n ...swaggerConfigs.options.definition.components.schemas,\n ...modeSchemas,\n };\n }\n\n // Generate OpenAPI specification using swagger-jsdoc\n const swaggerSpecification = swaggerJsdoc({\n definition: swaggerConfigs.options\n .definition as swaggerJsdoc.SwaggerDefinition,\n apis: swaggerConfigs.options.apis || [],\n });\n\n // Setup Swagger UI options\n const swaggerUiOptions = {\n explorer: swaggerConfigs.options.swaggerUiOptions?.explorer ?? true,\n customCss: swaggerConfigs.options.swaggerUiOptions?.customCss,\n customSiteTitle:\n swaggerConfigs.options.swaggerUiOptions?.customSiteTitle ||\n \"API Documentation\",\n customfavIcon: swaggerConfigs.options.swaggerUiOptions?.customfavIcon,\n swaggerOptions: {\n filter:\n swaggerConfigs.options.swaggerUiOptions?.swaggerOptions?.filter ?? true,\n displayRequestDuration:\n swaggerConfigs.options.swaggerUiOptions?.swaggerOptions\n ?.displayRequestDuration ?? true,\n deepLinking: swaggerConfigs.options.deepLinking ?? true,\n tryItOutEnabled: swaggerConfigs.options.tryItOutEnabled ?? true,\n persistAuthorization:\n swaggerConfigs.options.persistAuthorization ?? false,\n showExtensions:\n swaggerConfigs.options.swaggerUiOptions?.swaggerOptions\n ?.showExtensions ?? true,\n showCommonExtensions:\n swaggerConfigs.options.swaggerUiOptions?.swaggerOptions\n ?.showCommonExtensions ?? true,\n ...swaggerConfigs.options.swaggerUiOptions?.swaggerOptions,\n },\n };\n\n // Serve Swagger UI static assets\n swaggerRouter.use(swaggerConfigs.endpoint!, swaggerUi.serve);\n\n // Serve Swagger documentation\n swaggerRouter.get(\n swaggerConfigs.endpoint!,\n swaggerUi.setup(swaggerSpecification, swaggerUiOptions)\n );\n\n // Serve raw OpenAPI spec as JSON\n swaggerRouter.get(`${swaggerConfigs.endpoint}/json`, (req, res) => {\n res.setHeader(\"Content-Type\", \"application/json\");\n res.json(swaggerSpecification);\n });\n\n // Serve raw OpenAPI spec as YAML (optional)\n swaggerRouter.get(`${swaggerConfigs.endpoint}/yaml`, (req, res) => {\n const yaml = require(\"js-yaml\");\n res.setHeader(\"Content-Type\", \"text/yaml\");\n res.send(yaml.dump(swaggerSpecification));\n });\n\n // Health check endpoint for Swagger itself\n swaggerRouter.get(`${swaggerConfigs.endpoint}/health`, (req, res) => {\n res.json({\n status: \"ok\",\n swagger: {\n version: swaggerConfigs.options.definition.openapi,\n title: swaggerConfigs.options.definition.info?.title,\n endpoint: swaggerConfigs.endpoint,\n mode: swaggerConfigs.mode,\n },\n });\n });\n\n return swaggerRouter;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"arkos-config.js","sourceRoot":"","sources":["../../../src/types/arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import http from \"http\";\nimport cors from \"cors\";\nimport express from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for passing prisma query options.\n *\n * See more\n */\n allowDangerousPrismaQueryOptions?: boolean;\n };\n };\n /** Message you would like to send, as Json and 200 response when\n * ```curl\n * GET /api\n * ```\n *\n * ```json\n * { \"message\": \"Welcome to YourAppName\" }\n * ```\n *\n * default message is: Welcome to our Rest API generated by Arkos, find more about Arkos at www.arkosjs.com.\n *\n *\n * */\n welcomeMessage?: string;\n /**\n * Port where the application will run, can be set in 3 ways:\n *\n * 1. default is 8000\n * 2. PORT under environment variables (Lower precedence)\n * 3. this config option (Higher precedence)\n */\n port?: number | undefined;\n /**\n * Allows to listen on a different host than localhost only\n */\n host?: string;\n /**\n * Defines authentication related configurations, by default is undefined.\n *\n * See [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for details.\n */\n authentication?: {\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /**\n * Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * See more at [www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field)\n *\n * By specifing here another field for username, for example passing \"email\", \"companyCode\" or something else your json will be like:\n *\n * **Example with email**\n *\n * ```json\n * {\n * \"email\": \"john.doe@example.com\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n */\n allowedUsernames?: string[];\n /** Defines wether to send the access token in response after login or only send as cookie, defeault is both.*/\n sendAccessTokenThrough?: \"cookie-only\" | \"response-only\" | \"both\";\n };\n /**\n * Specifies the regex pattern used by the authentication system to enforce password strength requirements.\n *\n * **Important**: If using validation libraries like Zod or class-validator, this will be completely overwritten.\n *\n * **Default**: ```/^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/``` - Ensures the password contains at least one uppercase letter, one lowercase letter, and one numeric digit.\n *\n * **message**: (Optional) A custom error message to display when the password does not meet the required strength criteria.\n */\n passwordValidation?: { regex: RegExp; message?: string };\n /**\n * Allows to specify the request rate limit for all authentication endpoints but `/api/users/me`.\n * \n * #### Default\n *{\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n *@see This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n requestRateLimitOptions?: RateLimitOptions;\n /**\n * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n * ⚠️ Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n */\n secure?: boolean;\n\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n */\n httpOnly?: boolean;\n\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n };\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * @See [www.arkosjs.com/docs/core-concepts/request-data-validation](https://www.arkosjs.com/docs/core-concepts/request-data-validation) for more details.\n */\n validation?:\n | {\n resolver?: \"class-validator\";\n /**\n * ValidatorOptions to used while validating request data.\n *\n * **Default**:\n * ```ts\n * {\n * whitelist: true\n * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver?: \"zod\";\n validationOptions?: Record<string, any>;\n };\n /**\n * Defines file upload configurations\n *\n * See [www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations](https://www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations)\n */\n fileUpload?: {\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n expressStaticOptions?: Parameters<typeof express.static>[1];\n /**\n * Defines upload restrictions for each file type: image, video, document or other.\n *\n * #### Important:\n * Passing an object without overriding everything will only cause it\n * to be deepmerged with the default options.\n *\n * See [www.arkosjs.com/docs/api-reference/default-supported-upload-files](https://www.arkosjs.com/docs/api-reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n restrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n files?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * Allows to specify the request rate limit for all endpoints.\n * \n * #### Default\n *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n ```\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n globalRequestRateLimitOptions?: Partial<RateLimitOptions>;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n jsonBodyParserOptions?: Parameters<typeof express.json>[0];\n /**\n * Allows to pass paremeters to cookieParser from npm package cookie-parser\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/cookie-parser](https://www.npmjs.com/package/cookie-parser) for further details.\n */\n cookieParserParameters?: Parameters<typeof cookieParser>;\n /**\n * Allows to define options for npm package compression\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/compression](https://www.npmjs.com/package/compression) for further details.\n */\n compressionOptions?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * #### for example:\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n * \n * #### Default:\n * \n * {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n }\n * \n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n * \n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParserOptions?: QueryParserOptions;\n /**\n * Configuration for CORS (Cross-Origin Resource Sharing).\n *\n * @property {string | string[] | \"all\"} [allowedOrigins] - List of allowed origins. If set to `\"all\"`, all origins are accepted.\n * @property {import('cors').CorsOptions} [options] - Additional CORS options passed directly to the `cors` middleware.\n * @property {import('cors').CorsOptionsDelegate} [customMiddleware] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customMiddleware` is provided, both `allowedOrigins` and `options` will be ignored in favor of the custom logic.\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?: {\n allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware\n *\n * see\n */\n customHandler?: cors.CorsOptionsDelegate;\n };\n /**\n * Defines express/arkos middlewares configurations\n */\n middlewares?: {\n /**\n * Allows to add an array of custom express middlewares into the default middleware stack.\n *\n * **Tip**: If you would like to acess the express app before everthing use `configureApp` and pass a function.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order](https://www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order)\n *\n * **Note**: If you want to use custom global error handler middleware use `middlewares.replace.globalErrorHandler`.\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.RequestHandler[];\n /**\n * An array containing a list of defaults middlewares to be disabled\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n disable?: (\n | \"compression\"\n | \"global-rate-limit\"\n | \"auth-rate-limit\"\n | \"cors\"\n | \"express-json\"\n | \"cookie-parser\"\n | \"query-parser\"\n | \"database-connection\"\n | \"request-logger\"\n | \"global-error-handler\"\n )[];\n /**\n * Allows you to replace each of the built-in middlewares with your own implementation\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default compression middleware\n */\n compression?: express.RequestHandler;\n /**\n * Replace the default global rate limit middleware\n */\n globalRateLimit?: express.RequestHandler;\n /**\n * Replace the default authentication rate limit middleware\n */\n authRateLimit?: express.RequestHandler;\n /**\n * Replace the default CORS middleware\n */\n cors?: express.RequestHandler;\n /**\n * Replace the default JSON body parser middleware\n */\n expressJson?: express.RequestHandler;\n /**\n * Replace the default cookie parser middleware\n */\n cookieParser?: express.RequestHandler;\n /**\n * Replace the default query parser middleware\n */\n queryParser?: express.RequestHandler;\n /**\n * Replace the default database connection check middleware\n */\n databaseConnection?: express.RequestHandler;\n /**\n * Replace the default request logger middleware\n */\n requestLogger?: express.RequestHandler;\n /**\n * Replace the default global error handler middleware\n */\n globalErrorHandler?: express.ErrorRequestHandler;\n };\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Allows to add an array of custom express routers into the default middleware/router stack.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/adding-custom-routers](https://www.arkosjs.com/docs/advanced-guide/adding-custom-routers)\n *\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.Router[];\n disable?: (\n | \"auth-router\"\n | \"prisma-models-router\"\n | \"file-uploader\"\n | \"welcome-endpoint\"\n )[];\n /**\n * Allows you to replace each of the built-in routers with your own implementation.\n *\n * **Note**: Doing this you will lose all default middleware chaining, auth control, handlers from the specific router.\n *\n * **Tip**: I you want to disable some prisma models specific endpoint\n * see [www.arkosjs.com/docs/guide/adding-custom-routers#disabling-auto-generated-endpoints](https://www.arkosjs.com/docs/guide/adding-custom-routers#disabling-auto-generated-endpoints)\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default authentication router\n * @param config The original Arkos configuration\n * @returns A router handling authentication endpoints\n */\n authRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default Prisma models router\n * @param config The original Arkos configuration\n * @returns A router handling Prisma model endpoints\n */\n prismaModelsRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default file uploader router\n * @param config The original Arkos configuration\n * @returns A router handling file upload endpoints\n */\n fileUploader?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default welcome endpoint handler\n * @param req Express request object\n * @param res Express response object\n * @param next Express next function\n */\n welcomeEndpoint?: express.RequestHandler;\n };\n };\n /**\n * Gives acess to the underlying express app so that you can add custom configurations beyong **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `app.listen` for you.\n *\n * If you want to call `app.listen` by yourself pass port as `undefined` and then use the return app from `arkos.init()`.\n *\n * See how to call `app.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app](https://www.arkosjs.com/docs/guide/accessing-the-express-app) for further details on the method configureApp.\n *\n * @param {express.Express} app\n * @returns {any}\n */\n configureApp?: (app: express.Express) => Promise<any> | any;\n /**\n * Gives access to the underlying HTTP server so that you can add custom configurations beyond **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `server.listen` for you.\n *\n * If you want to call `server.listen` by yourself pass port as `undefined` and then use the return server from `arkos.init()`.\n *\n * See how to call `server.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#creating-your-own-http-server](https://www.arkosjs.com/docs/guide/accessing-the-express-app#creating-your-own-http-server)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app#accessing-the-http-server](https://www.arkosjs.com/docs/guide/accessing-the-express-app#accessing-the-http-server) for further details on the method configureServer.\n *\n * @param {http.Server} server - The HTTP server instance\n * @returns {any}\n */\n configureServer?: (server: http.Server) => Promise<any> | any;\n /**\n * Allows to configure email configurations for sending emails through `emailService`\n *\n * See [www.arkosjs.com/docs/core-concepts/sending-emails](https://www.arkosjs.com/docs/core-concepts/sending-emails)\n */\n email?: {\n /**\n * Your email provider url\n */\n host: string;\n /**\n * Email provider SMTP port, Default is `465`\n */\n port?: number;\n /**\n * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n };\n};\n"]}
|
|
1
|
+
{"version":3,"file":"arkos-config.js","sourceRoot":"","sources":["../../../src/types/arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import http from \"http\";\nimport cors from \"cors\";\nimport express from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for passing prisma query options.\n *\n * See more\n */\n allowDangerousPrismaQueryOptions?: boolean;\n };\n };\n /** Message you would like to send, as Json and 200 response when\n * ```curl\n * GET /api\n * ```\n *\n * ```json\n * { \"message\": \"Welcome to YourAppName\" }\n * ```\n *\n * default message is: Welcome to our Rest API generated by Arkos, find more about Arkos at www.arkosjs.com.\n *\n *\n * */\n welcomeMessage?: string;\n /**\n * Port where the application will run, can be set in 3 ways:\n *\n * 1. default is 8000\n * 2. PORT under environment variables (Lower precedence)\n * 3. this config option (Higher precedence)\n */\n port?: number | undefined;\n /**\n * Allows to listen on a different host than localhost only\n */\n host?: string;\n /**\n * Defines authentication related configurations, by default is undefined.\n *\n * See [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for details.\n */\n authentication?: {\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /**\n * Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * See more at [www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field)\n *\n * By specifing here another field for username, for example passing \"email\", \"companyCode\" or something else your json will be like:\n *\n * **Example with email**\n *\n * ```json\n * {\n * \"email\": \"john.doe@example.com\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n */\n allowedUsernames?: string[];\n /** Defines wether to send the access token in response after login or only send as cookie, defeault is both.*/\n sendAccessTokenThrough?: \"cookie-only\" | \"response-only\" | \"both\";\n };\n /**\n * Specifies the regex pattern used by the authentication system to enforce password strength requirements.\n *\n * **Important**: If using validation libraries like Zod or class-validator, this will be completely overwritten.\n *\n * **Default**: ```/^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/``` - Ensures the password contains at least one uppercase letter, one lowercase letter, and one numeric digit.\n *\n * **message**: (Optional) A custom error message to display when the password does not meet the required strength criteria.\n */\n passwordValidation?: { regex: RegExp; message?: string };\n /**\n * Allows to specify the request rate limit for all authentication endpoints but `/api/users/me`.\n * \n * #### Default\n *{\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n *@see This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n requestRateLimitOptions?: RateLimitOptions;\n /**\n * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n * ⚠️ Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n */\n secure?: boolean;\n\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n */\n httpOnly?: boolean;\n\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n };\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * @See [www.arkosjs.com/docs/core-concepts/request-data-validation](https://www.arkosjs.com/docs/core-concepts/request-data-validation) for more details.\n */\n validation?:\n | {\n resolver?: \"class-validator\";\n /**\n * ValidatorOptions to used while validating request data.\n *\n * **Default**:\n * ```ts\n * {\n * whitelist: true\n * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver?: \"zod\";\n validationOptions?: Record<string, any>;\n };\n /**\n * Defines file upload configurations\n *\n * See [www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations](https://www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations)\n */\n fileUpload?: {\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n expressStaticOptions?: Parameters<typeof express.static>[1];\n /**\n * Defines upload restrictions for each file type: image, video, document or other.\n *\n * #### Important:\n * Passing an object without overriding everything will only cause it\n * to be deepmerged with the default options.\n *\n * See [www.arkosjs.com/docs/api-reference/default-supported-upload-files](https://www.arkosjs.com/docs/api-reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n restrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n files?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * Allows to specify the request rate limit for all endpoints.\n * \n * #### Default\n *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n ```\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n globalRequestRateLimitOptions?: Partial<RateLimitOptions>;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n jsonBodyParserOptions?: Parameters<typeof express.json>[0];\n /**\n * Allows to pass paremeters to cookieParser from npm package cookie-parser\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/cookie-parser](https://www.npmjs.com/package/cookie-parser) for further details.\n */\n cookieParserParameters?: Parameters<typeof cookieParser>;\n /**\n * Allows to define options for npm package compression\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/compression](https://www.npmjs.com/package/compression) for further details.\n */\n compressionOptions?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * #### for example:\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n * \n * #### Default:\n * \n * {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n }\n * \n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n * \n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParserOptions?: QueryParserOptions;\n /**\n * Configuration for CORS (Cross-Origin Resource Sharing).\n *\n * @property {string | string[] | \"all\"} [allowedOrigins] - List of allowed origins. If set to `\"all\"`, all origins are accepted.\n * @property {import('cors').CorsOptions} [options] - Additional CORS options passed directly to the `cors` middleware.\n * @property {import('cors').CorsOptionsDelegate} [customMiddleware] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customMiddleware` is provided, both `allowedOrigins` and `options` will be ignored in favor of the custom logic.\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?: {\n /**\n * Defines allowed origins to acess the API.\n */\n allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware\n *\n * see\n */\n customHandler?: cors.CorsOptionsDelegate;\n };\n /**\n * Defines express/arkos middlewares configurations\n */\n middlewares?: {\n /**\n * Allows to add an array of custom express middlewares into the default middleware stack.\n *\n * **Tip**: If you would like to acess the express app before everthing use `configureApp` and pass a function.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order](https://www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order)\n *\n * **Note**: If you want to use custom global error handler middleware use `middlewares.replace.globalErrorHandler`.\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.RequestHandler[];\n /**\n * An array containing a list of defaults middlewares to be disabled\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n disable?: (\n | \"compression\"\n | \"global-rate-limit\"\n | \"auth-rate-limit\"\n | \"cors\"\n | \"express-json\"\n | \"cookie-parser\"\n | \"query-parser\"\n | \"database-connection\"\n | \"request-logger\"\n | \"global-error-handler\"\n )[];\n /**\n * Allows you to replace each of the built-in middlewares with your own implementation\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default compression middleware\n */\n compression?: express.RequestHandler;\n /**\n * Replace the default global rate limit middleware\n */\n globalRateLimit?: express.RequestHandler;\n /**\n * Replace the default authentication rate limit middleware\n */\n authRateLimit?: express.RequestHandler;\n /**\n * Replace the default CORS middleware\n */\n cors?: express.RequestHandler;\n /**\n * Replace the default JSON body parser middleware\n */\n expressJson?: express.RequestHandler;\n /**\n * Replace the default cookie parser middleware\n */\n cookieParser?: express.RequestHandler;\n /**\n * Replace the default query parser middleware\n */\n queryParser?: express.RequestHandler;\n /**\n * Replace the default database connection check middleware\n */\n databaseConnection?: express.RequestHandler;\n /**\n * Replace the default request logger middleware\n */\n requestLogger?: express.RequestHandler;\n /**\n * Replace the default global error handler middleware\n */\n globalErrorHandler?: express.ErrorRequestHandler;\n };\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Allows to add an array of custom express routers into the default middleware/router stack.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/adding-custom-routers](https://www.arkosjs.com/docs/advanced-guide/adding-custom-routers)\n *\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.Router[];\n disable?: (\n | \"auth-router\"\n | \"prisma-models-router\"\n | \"file-uploader\"\n | \"welcome-endpoint\"\n )[];\n /**\n * Allows you to replace each of the built-in routers with your own implementation.\n *\n * **Note**: Doing this you will lose all default middleware chaining, auth control, handlers from the specific router.\n *\n * **Tip**: I you want to disable some prisma models specific endpoint\n * see [www.arkosjs.com/docs/guide/adding-custom-routers#disabling-auto-generated-endpoints](https://www.arkosjs.com/docs/guide/adding-custom-routers#disabling-auto-generated-endpoints)\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default authentication router\n * @param config The original Arkos configuration\n * @returns A router handling authentication endpoints\n */\n authRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default Prisma models router\n * @param config The original Arkos configuration\n * @returns A router handling Prisma model endpoints\n */\n prismaModelsRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default file uploader router\n * @param config The original Arkos configuration\n * @returns A router handling file upload endpoints\n */\n fileUploader?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default welcome endpoint handler\n * @param req Express request object\n * @param res Express response object\n * @param next Express next function\n */\n welcomeEndpoint?: express.RequestHandler;\n };\n };\n /**\n * Gives acess to the underlying express app so that you can add custom configurations beyong **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `app.listen` for you.\n *\n * If you want to call `app.listen` by yourself pass port as `undefined` and then use the return app from `arkos.init()`.\n *\n * See how to call `app.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app](https://www.arkosjs.com/docs/guide/accessing-the-express-app) for further details on the method configureApp.\n *\n * @param {express.Express} app\n * @returns {any}\n */\n configureApp?: (app: express.Express) => Promise<any> | any;\n /**\n * Gives access to the underlying HTTP server so that you can add custom configurations beyond **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `server.listen` for you.\n *\n * If you want to call `server.listen` by yourself pass port as `undefined` and then use the return server from `arkos.init()`.\n *\n * See how to call `server.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#creating-your-own-http-server](https://www.arkosjs.com/docs/guide/accessing-the-express-app#creating-your-own-http-server)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app#accessing-the-http-server](https://www.arkosjs.com/docs/guide/accessing-the-express-app#accessing-the-http-server) for further details on the method configureServer.\n *\n * @param {http.Server} server - The HTTP server instance\n * @returns {any}\n */\n configureServer?: (server: http.Server) => Promise<any> | any;\n /**\n * Allows to configure email configurations for sending emails through `emailService`\n *\n * See [www.arkosjs.com/docs/core-concepts/sending-emails](https://www.arkosjs.com/docs/core-concepts/sending-emails)\n */\n email?: {\n /**\n * Your email provider url\n */\n host: string;\n /**\n * Email provider SMTP port, Default is `465`\n */\n port?: number;\n /**\n * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n };\n /**\n * Defines Swagger and OpenApi specifications for auto generating swagger documentation UI using whether it is Prisma Schemas, Class-validator DTOs, Zod Schemas or JSON-Schemas\n *\n * **Usage**\n *\n * ```ts\n * // src/app.ts\n *\n * import arkos from \"arkos\"\n *\n * arkos.init({\n * // other configs\n * swagger: {\n * mode: \"zod\",\n * options: {\n * openapi: \"3.0.0\",\n * title: \"API Generated By Arkos.js\",\n * description: \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n * }\n * }\n * })\n * ```\n *\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/swagger-api-documentation}\n */\n swagger?: {\n /**\n * Endpoint where the Swagger UI will be available.\n *\n * @default \"/api/docs\"\n */\n endpoint?: string;\n /**\n * Determines how your API schemas should be generated.\n *\n * - \"prisma\": Generates schemas based on Prisma models\n * - \"class-validator\": Uses class-validator and class-transformer DTO classes\n * - \"zod`\": Uses OpenAPI-compliant schemas directly\n * - \"json-schema\": Uses OpenAPI-compliant schemas directly\n */\n mode: \"prisma\" | \"class-validator\" | \"zod\" | \"json-schema\";\n /**\n *\n */\n options: {\n /**\n * Swagger definition according to OpenAPI Specification.\n */\n definition: {\n /**\n * OpenAPI version.\n *\n * @default \"3.0.0\"\n */\n openapi?: string;\n\n /**\n * Information about your API.\n */\n info?: {\n /**\n * Title of the API documentation.\n *\n *\n * @example \"My API\"\n *\n * @default \"API Generated By Arkos.js\"\n */\n title?: string;\n\n /**\n * Version of the API.\n *\n * @example \"1.0.0\"\n */\n version?: string;\n\n /**\n * Description of the API.\n *\n * @default \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n */\n description?: string;\n };\n\n /**\n * Server configurations for the API.\n *\n * @default [{ url: \"http://localhost:8000\", description: \"Local server\" }]\n *\n * This can be overridden automatically by Arkos based on CLI, .env, or `arkos.init()`.\n */\n servers?: {\n /**\n * Base URL of the server.\n *\n * @example \"http://localhost:8000\"\n */\n url: string;\n\n /**\n * Human-readable description of the server.\n *\n * @example \"Development Server\"\n */\n description: string;\n }[];\n\n /**\n * (Optional) Additional metadata such as terms of service, contact, or license.\n *\n * See: https://swagger.io/specification/#infoObject\n */\n termsOfService?: string;\n contact?: {\n name?: string;\n url?: string;\n email?: string;\n };\n license?: {\n name: string;\n url?: string;\n };\n\n /**\n * Tags to group and describe endpoints.\n */\n tags?: {\n name: string;\n description?: string;\n }[];\n\n /**\n * Security definitions (e.g., Bearer Auth).\n */\n components?: {\n securitySchemes?: Record<string, any>;\n schemas?: Record<string, any>;\n };\n\n /**\n * Global security requirements.\n */\n security?: Array<Record<string, string[]>>;\n };\n\n /**\n * Glob patterns defining where Swagger should look for API route definitions and comments.\n *\n * @default \n * ```ts\n * [\"./src/routers/*.router.{ts,js}\", \"./src/modules/**\\/*.router.{ts,js}\"]\n ```\n *\n * Adjust depending on TypeScript or JavaScript usage.\n */\n apis?: string[];\n\n /**\n * Custom Swagger UI options.\n *\n * See: https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/configuration.md\n */\n swaggerUiOptions?: Record<string, any>;\n\n /**\n * Enables deep linking in the Swagger UI.\n *\n * @default true\n */\n deepLinking?: boolean;\n\n /**\n * Enable/disable the \"Try it out\" button globally.\n *\n * @default true\n */\n tryItOutEnabled?: boolean;\n\n /**\n * Whether to persist authorization data across page reloads.\n *\n * @default false\n */\n persistAuthorization?: boolean;\n };\n };\n};\n"]}
|
package/dist/es2020/app.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import c from"express";import p from"cors";import m from"cookie-parser";import{getAuthRouter as f}from"./modules/auth/auth.router";import{getPrismaModelsRouter as w,getAvailableResourcesAndRoutesRouter as R}from"./modules/base/base.router";import P from"./modules/error-handler/error-handler.controller";import{rateLimit as h}from"express-rate-limit";import b from"compression";import{handleRequestLogs as y}from"./modules/base/base.middlewares";import{checkDatabaseConnection as q,loadPrismaModule as A}from"./utils/helpers/prisma.helpers";import{getFileUploaderRouter as E}from"./modules/file-uploader/file-uploader.router";import{queryParser as H}from"./utils/helpers/query-parser.helpers";import d from"./utils/helpers/deepmerge.helper";export const app=c();export async function bootstrap(e){await A(),e?.configureApp&&await e.configureApp(app);const n=e?.middlewares,
|
|
1
|
+
"use strict";import c from"express";import p from"cors";import m from"cookie-parser";import{getAuthRouter as f}from"./modules/auth/auth.router";import{getPrismaModelsRouter as w,getAvailableResourcesAndRoutesRouter as R}from"./modules/base/base.router";import P from"./modules/error-handler/error-handler.controller";import{rateLimit as h}from"express-rate-limit";import b from"compression";import{handleRequestLogs as y}from"./modules/base/base.middlewares";import{checkDatabaseConnection as q,loadPrismaModule as A}from"./utils/helpers/prisma.helpers";import{getFileUploaderRouter as E}from"./modules/file-uploader/file-uploader.router";import{queryParser as H}from"./utils/helpers/query-parser.helpers";import d from"./utils/helpers/deepmerge.helper";import{getSwaggerRouter as M}from"./modules/swagger/swagger.router";export const app=c();export async function bootstrap(e){await A(),e?.configureApp&&await e.configureApp(app);const n=e?.middlewares,t=n?.disable||[],s=n?.replace||{};t?.includes?.("compression")||app.use(s.compression||b(e?.compressionOptions)),t?.includes?.("global-rate-limit")||app.use(s.globalRateLimit||h(d({windowMs:60*1e3,limit:1e3,standardHeaders:"draft-7",legacyHeaders:!1},e?.globalRequestRateLimitOptions||{}))),t?.includes?.("cors")||app.use(s.cors||p(e?.cors?.customHandler?e.cors.customHandler:d({origin:(r,i)=>{const a=e?.cors?.allowedOrigins;a==="*"?i(null,!0):Array.isArray(a)?i(null,!r||a?.includes?.(r)):typeof a=="string"?i(null,!r||a===r):i(null,!1)},methods:["GET","POST","PUT","DELETE","PATCH","OPTIONS"],allowedHeaders:["Content-Type","Authorization","Connection"],credentials:!0},e?.cors?.options||{}))),t?.includes?.("express-json")||app.use(s.expressJson||c.json(e?.jsonBodyParserOptions)),t?.includes?.("cookie-parser")||app.use(s.cookieParser||m(...e?.cookieParserParameters||[])),t?.includes?.("query-parser")||app.use(s.queryParser||H(d({parseNull:!0,parseUndefined:!0,parseBoolean:!0},e?.queryParserOptions||{}))),t?.includes?.("database-connection")||app.use(s.databaseConnection||q),t?.includes?.("request-logger")||app.use(s.requestLogger||y),e?.middlewares?.additional&&e.middlewares.additional.forEach(r=>{app.use(r)});const l=e?.routers,u=l?.disable||[],o=l?.replace||{};if(u?.includes?.("welcome-endpoint")||app.get("/api",o.welcomeEndpoint||((r,i)=>{i.status(200).json({message:e.welcomeMessage})})),!u?.includes?.("file-uploader")){const r=o.fileUploader?await o.fileUploader(e):await E(e);app.use(r)}if(!u?.includes?.("auth-router")&&e.authentication){const r=o.authRouter?await o.authRouter(e):await f(e);app.use("/api",r)}if(!u?.includes?.("prisma-models-router")){const r=o.prismaModelsRouter?await o.prismaModelsRouter(e):await w(e);app.use("/api",r)}return app.use("/api",R()),app.use("/api",M(e)),l?.additional&&l.additional.forEach(r=>{app.use(r)}),t?.includes?.("global-error-handler")||app.use(s.globalErrorHandler||P),app}
|
package/dist/es2020/app.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app.js","sourceRoot":"","sources":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AAM,EAAE,UAAU,CAAC,CAAC;IAC9B,CAAC;IAGD,IAAI,CAAC,eAAe,EAAE,QAAQ,EAAE,CAAC,sBAAsB,CAAC,EAAE,CAAC;QACzD,MAAM,YAAY,GAAG,eAAe,CAAC,kBAAkB;YACrD,CAAC,CAAC,MAAM,eAAe,CAAC,kBAAkB,CAAC,WAAW,CAAC;YACvD,CAAC,CAAC,MAAM,qBAAqB,CAAC,WAAW,CAAC,CAAC;QAC7C,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;IAChC,CAAC;IAED,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,oCAAoC,EAAE,CAAC,CAAC;IAGxD,IAAI,aAAa,EAAE,UAAU,EAAE,CAAC;QAC9B,aAAa,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;YAC1C,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAClB,CAAC,CAAC,CAAC;IACL,CAAC;IAGD,IAAI,CAAC,mBAAmB,EAAE,QAAQ,EAAE,CAAC,sBAAsB,CAAC;QAC1D,GAAG,CAAC,GAAG,CAAC,mBAAmB,CAAC,kBAAkB,IAAI,YAAY,CAAC,CAAC;IAElE,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import express from \"express\";\nimport cors from \"cors\";\nimport cookieParser from \"cookie-parser\";\nimport { getAuthRouter } from \"./modules/auth/auth.router\";\nimport {\n getPrismaModelsRouter,\n getAvailableResourcesAndRoutesRouter,\n} from \"./modules/base/base.router\";\nimport errorHandler from \"./modules/error-handler/error-handler.controller\";\nimport { rateLimit } from \"express-rate-limit\";\nimport compression from \"compression\";\nimport { handleRequestLogs } from \"./modules/base/base.middlewares\";\nimport {\n checkDatabaseConnection,\n loadPrismaModule,\n} from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploaderRouter } from \"./modules/file-uploader/file-uploader.router\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport { queryParser } from \"./utils/helpers/query-parser.helpers\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\n\nexport const app: express.Express = express();\n\nexport async function bootstrap(\n arkosConfig: ArkosConfig\n): Promise<express.Express> {\n await loadPrismaModule();\n\n if (arkosConfig?.configureApp) await arkosConfig.configureApp(app);\n\n const middlewaresConfig = arkosConfig?.middlewares;\n const disabledMiddlewares = middlewaresConfig?.disable || [];\n const replacedMiddlewares = middlewaresConfig?.replace || {};\n\n // Compression middleware\n if (!disabledMiddlewares?.includes?.(\"compression\"))\n app.use(\n replacedMiddlewares.compression ||\n compression(arkosConfig?.compressionOptions)\n );\n\n // Global rate limit middleware\n if (!disabledMiddlewares?.includes?.(\"global-rate-limit\"))\n app.use(\n replacedMiddlewares.globalRateLimit ||\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n },\n arkosConfig?.globalRequestRateLimitOptions || {}\n )\n )\n );\n\n // CORS middleware\n if (!disabledMiddlewares?.includes?.(\"cors\"))\n app.use(\n replacedMiddlewares.cors ||\n cors(\n arkosConfig?.cors?.customHandler\n ? arkosConfig.cors.customHandler\n : deepmerge(\n {\n origin: (\n origin: string,\n cb: (err: Error | null, allow?: boolean) => void\n ) => {\n const allowed = arkosConfig?.cors?.allowedOrigins;\n\n if (allowed === \"*\") {\n cb(null, true);\n } else if (Array.isArray(allowed)) {\n cb(null, !origin || allowed?.includes?.(origin));\n } else if (typeof allowed === \"string\") {\n cb(null, !origin || allowed === origin);\n } else {\n cb(null, false);\n }\n },\n methods: [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\n \"Content-Type\",\n \"Authorization\",\n \"Connection\",\n ],\n credentials: true,\n },\n arkosConfig?.cors?.options || {}\n )\n )\n );\n\n // JSON body parser middleware\n if (!disabledMiddlewares?.includes?.(\"express-json\"))\n app.use(\n replacedMiddlewares.expressJson ||\n express.json(arkosConfig?.jsonBodyParserOptions)\n );\n\n // Cookie parser middleware\n if (!disabledMiddlewares?.includes?.(\"cookie-parser\"))\n app.use(\n replacedMiddlewares.cookieParser ||\n cookieParser(...[...(arkosConfig?.cookieParserParameters || [])])\n );\n\n // Query parser middleware\n if (!disabledMiddlewares?.includes?.(\"query-parser\"))\n app.use(\n replacedMiddlewares.queryParser ||\n queryParser(\n deepmerge(\n {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n },\n arkosConfig?.queryParserOptions || {}\n )\n )\n );\n\n // Database connection check middleware\n if (!disabledMiddlewares?.includes?.(\"database-connection\"))\n app.use(replacedMiddlewares.databaseConnection || checkDatabaseConnection);\n\n // Request logger middleware\n if (!disabledMiddlewares?.includes?.(\"request-logger\"))\n app.use(replacedMiddlewares.requestLogger || handleRequestLogs);\n\n // Additional custom middlewares\n if (arkosConfig?.middlewares?.additional)\n arkosConfig.middlewares.additional.forEach((middleware) => {\n app.use(middleware);\n });\n\n // Configure routers\n const routersConfig = arkosConfig?.routers;\n const disabledRouters = routersConfig?.disable || [];\n const replacedRouters = routersConfig?.replace || {};\n\n // Welcome endpoint\n if (!disabledRouters?.includes?.(\"welcome-endpoint\"))\n app.get(\n \"/api\",\n replacedRouters.welcomeEndpoint ||\n ((req, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n })\n );\n\n // File uploader router\n if (!disabledRouters?.includes?.(\"file-uploader\")) {\n const fileUploaderRouter = replacedRouters.fileUploader\n ? await replacedRouters.fileUploader(arkosConfig)\n : await getFileUploaderRouter(arkosConfig);\n app.use(fileUploaderRouter);\n }\n\n // Auth router\n if (\n !disabledRouters?.includes?.(\"auth-router\") &&\n arkosConfig.authentication\n ) {\n const authRouter = replacedRouters.authRouter\n ? await replacedRouters.authRouter(arkosConfig)\n : await getAuthRouter(arkosConfig);\n app.use(\"/api\", authRouter);\n }\n\n // Prisma models router\n if (!disabledRouters?.includes?.(\"prisma-models-router\")) {\n const modelsRouter = replacedRouters.prismaModelsRouter\n ? await replacedRouters.prismaModelsRouter(arkosConfig)\n : await getPrismaModelsRouter(arkosConfig);\n app.use(\"/api\", modelsRouter);\n }\n\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n // Additional custom routers\n if (routersConfig?.additional) {\n routersConfig.additional.forEach((router) => {\n app.use(router);\n });\n }\n\n // Global error handler middleware (must be last)\n if (!disabledMiddlewares?.includes?.(\"global-error-handler\"))\n app.use(replacedMiddlewares.globalErrorHandler || errorHandler);\n\n return app;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,SAAS,CAAC;AAC9B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,YAAY,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EACL,qBAAqB,EACrB,oCAAoC,GACrC,MAAM,4BAA4B,CAAC;AACpC,OAAO,YAAY,MAAM,kDAAkD,CAAC;AAC5E,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,WAAW,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACpE,OAAO,EACL,uBAAuB,EACvB,gBAAgB,GACjB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,qBAAqB,EAAE,MAAM,8CAA8C,CAAC;AAErF,OAAO,EAAE,WAAW,EAAE,MAAM,sCAAsC,CAAC;AACnE,OAAO,SAAS,MAAM,kCAAkC,CAAC;AACzD,OAAO,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AAEpE,MAAM,CAAC,MAAM,GAAG,GAAoB,OAAO,EAAE,CAAC;AAE9C,MAAM,CAAC,KAAK,UAAU,SAAS,CAC7B,WAAwB;IAExB,MAAM,gBAAgB,EAAE,CAAC;IAEzB,IAAI,WAAW,EAAE,YAAY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AkB,IAAI,YAAY,CAAC,CAAC;IAElE,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import express from \"express\";\nimport cors from \"cors\";\nimport cookieParser from \"cookie-parser\";\nimport { getAuthRouter } from \"./modules/auth/auth.router\";\nimport {\n getPrismaModelsRouter,\n getAvailableResourcesAndRoutesRouter,\n} from \"./modules/base/base.router\";\nimport errorHandler from \"./modules/error-handler/error-handler.controller\";\nimport { rateLimit } from \"express-rate-limit\";\nimport compression from \"compression\";\nimport { handleRequestLogs } from \"./modules/base/base.middlewares\";\nimport {\n checkDatabaseConnection,\n loadPrismaModule,\n} from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploaderRouter } from \"./modules/file-uploader/file-uploader.router\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport { queryParser } from \"./utils/helpers/query-parser.helpers\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport { getSwaggerRouter } from \"./modules/swagger/swagger.router\";\n\nexport const app: express.Express = express();\n\nexport async function bootstrap(\n arkosConfig: ArkosConfig\n): Promise<express.Express> {\n await loadPrismaModule();\n\n if (arkosConfig?.configureApp) await arkosConfig.configureApp(app);\n\n const middlewaresConfig = arkosConfig?.middlewares;\n const disabledMiddlewares = middlewaresConfig?.disable || [];\n const replacedMiddlewares = middlewaresConfig?.replace || {};\n\n // Compression middleware\n if (!disabledMiddlewares?.includes?.(\"compression\"))\n app.use(\n replacedMiddlewares.compression ||\n compression(arkosConfig?.compressionOptions)\n );\n\n // Global rate limit middleware\n if (!disabledMiddlewares?.includes?.(\"global-rate-limit\"))\n app.use(\n replacedMiddlewares.globalRateLimit ||\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n },\n arkosConfig?.globalRequestRateLimitOptions || {}\n )\n )\n );\n\n // CORS middleware\n if (!disabledMiddlewares?.includes?.(\"cors\"))\n app.use(\n replacedMiddlewares.cors ||\n cors(\n arkosConfig?.cors?.customHandler\n ? arkosConfig.cors.customHandler\n : deepmerge(\n {\n origin: (\n origin: string,\n cb: (err: Error | null, allow?: boolean) => void\n ) => {\n const allowed = arkosConfig?.cors?.allowedOrigins;\n\n if (allowed === \"*\") {\n cb(null, true);\n } else if (Array.isArray(allowed)) {\n cb(null, !origin || allowed?.includes?.(origin));\n } else if (typeof allowed === \"string\") {\n cb(null, !origin || allowed === origin);\n } else {\n cb(null, false);\n }\n },\n methods: [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\n \"Content-Type\",\n \"Authorization\",\n \"Connection\",\n ],\n credentials: true,\n },\n arkosConfig?.cors?.options || {}\n )\n )\n );\n\n // JSON body parser middleware\n if (!disabledMiddlewares?.includes?.(\"express-json\"))\n app.use(\n replacedMiddlewares.expressJson ||\n express.json(arkosConfig?.jsonBodyParserOptions)\n );\n\n // Cookie parser middleware\n if (!disabledMiddlewares?.includes?.(\"cookie-parser\"))\n app.use(\n replacedMiddlewares.cookieParser ||\n cookieParser(...[...(arkosConfig?.cookieParserParameters || [])])\n );\n\n // Query parser middleware\n if (!disabledMiddlewares?.includes?.(\"query-parser\"))\n app.use(\n replacedMiddlewares.queryParser ||\n queryParser(\n deepmerge(\n {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n },\n arkosConfig?.queryParserOptions || {}\n )\n )\n );\n\n // Database connection check middleware\n if (!disabledMiddlewares?.includes?.(\"database-connection\"))\n app.use(replacedMiddlewares.databaseConnection || checkDatabaseConnection);\n\n // Request logger middleware\n if (!disabledMiddlewares?.includes?.(\"request-logger\"))\n app.use(replacedMiddlewares.requestLogger || handleRequestLogs);\n\n // Additional custom middlewares\n if (arkosConfig?.middlewares?.additional)\n arkosConfig.middlewares.additional.forEach((middleware) => {\n app.use(middleware);\n });\n\n // Configure routers\n const routersConfig = arkosConfig?.routers;\n const disabledRouters = routersConfig?.disable || [];\n const replacedRouters = routersConfig?.replace || {};\n\n // Welcome endpoint\n if (!disabledRouters?.includes?.(\"welcome-endpoint\"))\n app.get(\n \"/api\",\n replacedRouters.welcomeEndpoint ||\n ((req, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n })\n );\n\n // File uploader router\n if (!disabledRouters?.includes?.(\"file-uploader\")) {\n const fileUploaderRouter = replacedRouters.fileUploader\n ? await replacedRouters.fileUploader(arkosConfig)\n : await getFileUploaderRouter(arkosConfig);\n app.use(fileUploaderRouter);\n }\n\n // Auth router\n if (\n !disabledRouters?.includes?.(\"auth-router\") &&\n arkosConfig.authentication\n ) {\n const authRouter = replacedRouters.authRouter\n ? await replacedRouters.authRouter(arkosConfig)\n : await getAuthRouter(arkosConfig);\n app.use(\"/api\", authRouter);\n }\n\n // Prisma models router\n if (!disabledRouters?.includes?.(\"prisma-models-router\")) {\n const modelsRouter = replacedRouters.prismaModelsRouter\n ? await replacedRouters.prismaModelsRouter(arkosConfig)\n : await getPrismaModelsRouter(arkosConfig);\n app.use(\"/api\", modelsRouter);\n }\n\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n app.use(\"/api\", getSwaggerRouter(arkosConfig));\n\n // Additional custom routers\n if (routersConfig?.additional) {\n routersConfig.additional.forEach((router) => {\n app.use(router);\n });\n }\n\n // Global error handler middleware (must be last)\n if (!disabledMiddlewares?.includes?.(\"global-error-handler\"))\n app.use(replacedMiddlewares.globalErrorHandler || errorHandler);\n\n return app;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.service.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.service.helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,oBAAoB,GACrB,MAAM,0CAA0C,CAAC;AAQlD,MAAM,UAAU,eAAe,CAAC,GAAwB;IACtD,IAAI,CAAC,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ;QAAE,OAAO,GAAG,CAAC;IAEhD,MAAM,MAAM,GAA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AAE,QAAQ,EAAE,CAAC,SAAS,CAAC,SAAS,CAAC,EAAE,CAAC;QACzE,OAAO,KAAK,CAAC;IACf,CAAC;IAGD,IAAI,SAAS,CAAC,SAAS,KAAK,SAAS,EAAE,CAAC;QACtC,OAAO,IAAI,CAAC;IACd,CAAC;IAGD,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,MAAM,KAAK,CAAC,IAAI,SAAS,EAAE,EAAE,EAAE,CAAC;QAC1D,OAAO,IAAI,CAAC;IACd,CAAC;IAGD,MAAM,YAAY,GAAG,oBAAoB,CAAC,SAAS,CAAC,CAAC;IAGrD,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACxC,MAAM,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;QAC5C,OAAO,YAAY,EAAE,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC;IACjE,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import {\n getPrismaModelRelations,\n RelationFields,\n getModelUniqueFields,\n} from \"../../../../utils/helpers/models.helpers\";\n\n/**\n * Removes apiAction field from an object and all nested objects\n *\n * @param {Record<string, any>} obj - The object to clean\n * @returns {Record<string, any>} - The cleaned object\n */\nexport function removeApiAction(obj: Record<string, any>): Record<string, any> {\n if (!obj || typeof obj !== \"object\") return obj;\n\n const result: Record<string, any> = {};\n\n for (const [key, value] of Object.entries(obj)) {\n if (key === \"apiAction\") continue;\n\n if (Array.isArray(value)) {\n result[key] = value.map((item) =>\n typeof item === \"object\" && item !== null ? removeApiAction(item) : item\n );\n } else if (typeof value === \"object\" && value !== null) {\n result[key] = removeApiAction(value);\n } else {\n result[key] = value;\n }\n }\n\n return result;\n}\n\n/**\n * Checks if an object is already formatted as a Prisma relation operation\n *\n * @param {Record<string, any>} obj - The object to check\n * @returns {boolean} - True if the object contains Prisma relation operations\n */\nexport function isPrismaRelationFormat(obj: Record<string, any>): boolean {\n if (!obj || typeof obj !== \"object\") return false;\n\n // Common Prisma relation operations\n const prismaOperations = [\n \"create\",\n \"connect\",\n \"update\",\n \"delete\",\n \"disconnect\",\n \"deleteMany\",\n \"connectOrCreate\",\n \"upsert\",\n \"set\",\n ];\n\n // Check if any key is a Prisma operation\n return prismaOperations.some((op) => op in obj);\n}\n\n/**\n * Determines the appropriate Prisma operation (`create`, `connect`, `update`, `delete`, or `disconnect`)\n * for each relation field in the provided body based on its nested data and recursively does the same for each relation field.\n *\n * This function handles the following types of relations:\n * - **One-to-one**\n * - **One-to-many**\n *\n *\n * ### Operation Rules:\n *\n *\n * - **Create**: Used when the nested relation data is provided **without an `id` or unique field**.\n * - **Connect**: Used when the nested relation data contains **only an `id` or a unique field** (e.g., email).\n * - **Update**: Used when the nested relation data contains **both an `id` and additional fields**.\n * - **Delete**: Used when the nested relation data includes **`apiAction: \"delete\"`**.\n * - **Disconnect**: Used when the nested relation data includes **`apiAction: \"disconnect\"`**.\n *\n * The function will preserve existing Prisma operation formats if detected,\n * allowing developers to manually structure relation operations when needed.\n *\n * @param {Record<string, any>} body - The object containing relation fields to be processed.\n * @param {Object} relationFields - Defines relation field types.\n * @param {RelationFields[]} relationFields.singular - List of one-side relation field names (one-to-one).\n * @param {RelationFields[]} relationFields.list - List of many-side relation field names (one-to-many).\n * @param {string[]} ignoreActions - Optional list of apiAction values to ignore.\n * @returns {Record<string, any>} The transformed data with appropriate Prisma operations applied.\n */\nexport function handleRelationFieldsInBody(\n body: Record<string, any>,\n relationFields: RelationFields,\n ignoreActions: string[] = []\n) {\n let mutableBody = { ...body };\n\n relationFields?.list?.forEach((field) => {\n if (!body[field.name]) return;\n\n // Skip if the field is already in Prisma relation format\n if (isPrismaRelationFormat(body[field.name])) {\n return;\n }\n\n // Skip if the field is not an array (likely already handled manually)\n if (!Array.isArray(body[field.name])) {\n return;\n }\n\n const createData: any[] = [];\n const connectData: any[] = [];\n const updateData: any[] = [];\n const disconnectData: any[] = [];\n const deleteManyIds: any[] = [];\n\n body[field.name]?.forEach((bodyField: any) => {\n if (ignoreActions?.includes?.(bodyField?.apiAction)) return;\n\n const apiAction = bodyField?.apiAction;\n\n if (apiAction === \"delete\") {\n deleteManyIds.push(bodyField.id);\n } else if (apiAction === \"disconnect\") {\n disconnectData.push({ id: bodyField.id });\n } else if (canBeUsedToConnect(field.type, bodyField)) {\n // Handle connection with unique fields or ID\n const { apiAction: _, ...cleanedData } = bodyField;\n connectData.push(cleanedData);\n } else if (!bodyField?.id) {\n // If no ID, assume create operation\n let nestedRelations = getPrismaModelRelations(field.type);\n\n let dataToPush = { ...bodyField };\n\n if (nestedRelations) {\n dataToPush = handleRelationFieldsInBody(\n dataToPush,\n nestedRelations,\n ignoreActions\n );\n }\n\n // Ensure apiAction is removed\n if (\"apiAction\" in dataToPush) {\n const { apiAction: _, ...rest } = dataToPush;\n dataToPush = rest;\n }\n\n createData.push(dataToPush);\n } else {\n // If ID and other fields, assume update operation\n const { id, apiAction: _, ...data } = bodyField;\n\n let nestedRelations = getPrismaModelRelations(field.type);\n\n let dataToPush = data;\n if (nestedRelations) {\n dataToPush = handleRelationFieldsInBody(\n data,\n nestedRelations,\n ignoreActions\n );\n }\n\n updateData.push({\n where: { id },\n data: dataToPush,\n });\n }\n });\n\n mutableBody[field.name] = {\n ...(createData.length ? { create: createData } : {}),\n ...(connectData.length ? { connect: connectData } : {}),\n ...(updateData.length ? { update: updateData } : {}),\n ...(disconnectData.length ? { disconnect: disconnectData } : {}),\n ...(deleteManyIds.length\n ? { deleteMany: { id: { in: deleteManyIds } } }\n : {}),\n };\n });\n\n relationFields?.singular?.forEach((field) => {\n if (!body[field.name]) return;\n if (ignoreActions?.includes?.(body[field.name]?.apiAction)) return;\n\n // Skip if the field is already in Prisma relation format\n if (isPrismaRelationFormat(body[field.name])) {\n return;\n }\n\n const relationData = body[field.name];\n let nestedRelations = getPrismaModelRelations(field.type);\n\n if (canBeUsedToConnect(field.type, relationData)) {\n // Handle connection with unique fields or ID\n const { apiAction: _, ...cleanedData } = relationData;\n mutableBody[field.name] = { connect: cleanedData };\n } else if (!relationData?.id) {\n // If no ID, assume create operation\n let dataToCreate = { ...relationData };\n\n if (\"apiAction\" in dataToCreate) {\n const { apiAction: _, ...rest } = dataToCreate;\n dataToCreate = rest;\n }\n\n if (nestedRelations) {\n dataToCreate = handleRelationFieldsInBody(\n dataToCreate,\n nestedRelations,\n ignoreActions\n );\n }\n\n mutableBody[field.name] = { create: dataToCreate };\n } else {\n // If ID and other fields, assume update operation\n const { id, apiAction: _, ...data } = relationData;\n\n let dataToUpdate = data;\n if (nestedRelations) {\n dataToUpdate = handleRelationFieldsInBody(\n data,\n nestedRelations,\n ignoreActions\n );\n }\n\n mutableBody[field.name] = {\n update: {\n data: dataToUpdate,\n },\n };\n }\n });\n\n // Remove any remaining apiAction fields from the top level\n if (\"apiAction\" in mutableBody) {\n const { apiAction, ...rest } = mutableBody;\n mutableBody = rest;\n }\n\n // As a final step, recursively remove any remaining apiAction fields\n return removeApiAction(mutableBody);\n}\n\n/**\n * Checks if a field value can be used to connect to a model\n * This happens when the field contains only an ID or a single unique field\n *\n * @param {string} modelName - The model name to get unique fields for\n * @param {Record<string, any>} bodyField - The field value from the body\n * @returns {boolean} True if the field can be used for a connect operation\n */\nexport function canBeUsedToConnect(\n modelName: string,\n bodyField: Record<string, any> | undefined | null\n): boolean {\n // If the field is null or undefined, it can't be used to connect\n if (!bodyField) return false;\n\n // If the field has an apiAction that's not for connecting, return false\n if (bodyField.apiAction && ![\"connect\"]?.includes?.(bodyField.apiAction)) {\n return false;\n }\n\n // If explicitly marked for connect, allow it\n if (bodyField.apiAction === \"connect\") {\n return true;\n }\n\n // If only ID is present, it can be used to connect\n if (Object.keys(bodyField)?.length === 1 && bodyField?.id) {\n return true;\n }\n\n // Get unique fields for the model\n const uniqueFields = getModelUniqueFields(modelName);\n\n // If the field has exactly one property and it's a unique field, it can be used to connect\n if (Object.keys(bodyField).length === 1) {\n const fieldName = Object.keys(bodyField)[0];\n return uniqueFields?.some((field) => field.name === fieldName);\n }\n\n return false;\n}\n\n// /**\n// * Checks if a list field is actually an array\n// *\n// * @param {any} field - The field to check\n// * @returns {boolean} - True if the field is an array\n// */\n// export function isListFieldAnArray(field: any): boolean {\n// return Array.isArray(field);\n// }\n"]}
|
|
1
|
+
{"version":3,"file":"base.service.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.service.helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,oBAAoB,GACrB,MAAM,0CAA0C,CAAC;AAQlD,MAAM,UAAU,eAAe,CAAC,GAAwB;IACtD,IAAI,CAAC,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ;QAAE,OAAO,GAAG,CAAC;IAEhD,MAAM,MAAM,GAAwB,EAAE,CAAC;IAEvC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;QAC/C,IAAI,GAAG,KAAK,WAAW;YAAE,SAAS;QAElC,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;YACzB,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAC/B,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CACzE,CAAC;QACJ,CAAC;aAAM,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;YACvD,MAAM,CAAC,GAAG,CAAC,GAAG,eAAe,CAAC,KAAK,CAAC,CAAC;QACvC,CAAC;aAAM,CAAC;YACN,MAAM,CAAC,GAAG,CAAC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,SAAS,CAAC,CAAC;IACjE,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import {\n getPrismaModelRelations,\n RelationFields,\n getModelUniqueFields,\n} from \"../../../../utils/helpers/models.helpers\";\n\n/**\n * Removes apiAction field from an object and all nested objects\n *\n * @param {Record<string, any>} obj - The object to clean\n * @returns {Record<string, any>} - The cleaned object\n */\nexport function removeApiAction(obj: Record<string, any>): Record<string, any> {\n if (!obj || typeof obj !== \"object\") return obj;\n\n const result: Record<string, any> = {};\n\n for (const [key, value] of Object.entries(obj)) {\n if (key === \"apiAction\") continue;\n\n if (Array.isArray(value)) {\n result[key] = value.map((item) =>\n typeof item === \"object\" && item !== null ? removeApiAction(item) : item\n );\n } else if (typeof value === \"object\" && value !== null) {\n result[key] = removeApiAction(value);\n } else {\n result[key] = value;\n }\n }\n\n return result;\n}\n\n/**\n * Checks if an object is already formatted as a Prisma relation operation\n *\n * @param {Record<string, any>} obj - The object to check\n * @returns {boolean} - True if the object contains Prisma relation operations\n */\nexport function isPrismaRelationFormat(obj: Record<string, any>): boolean {\n if (!obj || typeof obj !== \"object\") return false;\n\n // Common Prisma relation operations\n const prismaOperations = [\n \"create\",\n \"connect\",\n \"update\",\n \"delete\",\n \"disconnect\",\n \"deleteMany\",\n \"connectOrCreate\",\n \"upsert\",\n \"set\",\n ];\n\n // Check if any key is a Prisma operation\n return prismaOperations.some((op) => op in obj);\n}\n\n/**\n * Determines the appropriate Prisma operation (`create`, `connect`, `update`, `delete`, or `disconnect`)\n * for each relation field in the provided body based on its nested data and recursively does the same for each relation field.\n *\n * This function handles the following types of relations:\n * - **One-to-one**\n * - **One-to-many**\n *\n *\n * ### Operation Rules:\n *\n *\n * - **Create**: Used when the nested relation data is provided **without an `id` or unique field**.\n * - **Connect**: Used when the nested relation data contains **only an `id` or a unique field** (e.g., email).\n * - **Update**: Used when the nested relation data contains **both an `id` and additional fields**.\n * - **Delete**: Used when the nested relation data includes **`apiAction: \"delete\"`**.\n * - **Disconnect**: Used when the nested relation data includes **`apiAction: \"disconnect\"`**.\n *\n * The function will preserve existing Prisma operation formats if detected,\n * allowing developers to manually structure relation operations when needed.\n *\n * @param {Record<string, any>} body - The object containing relation fields to be processed.\n * @param {Object} relationFields - Defines relation field types.\n * @param {RelationFields[]} relationFields.singular - List of one-side relation field names (one-to-one).\n * @param {RelationFields[]} relationFields.list - List of many-side relation field names (one-to-many).\n * @param {string[]} ignoreActions - Optional list of apiAction values to ignore.\n * @returns {Record<string, any>} The transformed data with appropriate Prisma operations applied.\n */\nexport function handleRelationFieldsInBody(\n body: Record<string, any>,\n relationFields: RelationFields,\n ignoreActions: string[] = []\n) {\n let mutableBody = { ...body };\n\n relationFields?.list?.forEach((field) => {\n if (!body[field.name]) return;\n\n // Skip if the field is already in Prisma relation format\n if (isPrismaRelationFormat(body[field.name])) {\n return;\n }\n\n // Skip if the field is not an array (likely already handled manually)\n if (!Array.isArray(body[field.name])) {\n return;\n }\n\n const createData: any[] = [];\n const connectData: any[] = [];\n const updateData: any[] = [];\n const disconnectData: any[] = [];\n const deleteManyIds: any[] = [];\n\n body[field.name]?.forEach((bodyField: any) => {\n if (ignoreActions?.includes?.(bodyField?.apiAction)) return;\n\n const apiAction = bodyField?.apiAction;\n\n if (apiAction === \"delete\") {\n deleteManyIds.push(bodyField.id);\n } else if (apiAction === \"disconnect\") {\n disconnectData.push({ id: bodyField.id });\n } else if (canBeUsedToConnect(field.type, bodyField)) {\n // Handle connection with unique fields or ID\n const { apiAction: _, ...cleanedData } = bodyField;\n connectData.push(cleanedData);\n } else if (!bodyField?.id) {\n // If no ID, assume create operation\n let nestedRelations = getPrismaModelRelations(field.type);\n\n let dataToPush = { ...bodyField };\n\n if (nestedRelations) {\n dataToPush = handleRelationFieldsInBody(\n dataToPush,\n nestedRelations,\n ignoreActions\n );\n }\n\n // Ensure apiAction is removed\n if (\"apiAction\" in dataToPush) {\n const { apiAction: _, ...rest } = dataToPush;\n dataToPush = rest;\n }\n\n createData.push(dataToPush);\n } else {\n // If ID and other fields, assume update operation\n const { id, apiAction: _, ...data } = bodyField;\n\n let nestedRelations = getPrismaModelRelations(field.type);\n\n let dataToPush = data;\n if (nestedRelations) {\n dataToPush = handleRelationFieldsInBody(\n data,\n nestedRelations,\n ignoreActions\n );\n }\n\n updateData.push({\n where: { id },\n data: dataToPush,\n });\n }\n });\n\n mutableBody[field.name] = {\n ...(createData.length ? { create: createData } : {}),\n ...(connectData.length ? { connect: connectData } : {}),\n ...(updateData.length ? { update: updateData } : {}),\n ...(disconnectData.length ? { disconnect: disconnectData } : {}),\n ...(deleteManyIds.length\n ? { deleteMany: { id: { in: deleteManyIds } } }\n : {}),\n };\n });\n\n relationFields?.singular?.forEach((field) => {\n if (!body[field.name]) return;\n if (ignoreActions?.includes?.(body[field.name]?.apiAction)) return;\n\n // Skip if the field is already in Prisma relation format\n if (isPrismaRelationFormat(body[field.name])) {\n return;\n }\n\n const relationData = body[field.name];\n let nestedRelations = getPrismaModelRelations(field.type);\n\n if (canBeUsedToConnect(field.type, relationData)) {\n // Handle connection with unique fields or ID\n const { apiAction: _, ...cleanedData } = relationData;\n mutableBody[field.name] = { connect: cleanedData };\n } else if (!relationData?.id) {\n // If no ID, assume create operation\n let dataToCreate = { ...relationData };\n\n if (\"apiAction\" in dataToCreate) {\n const { apiAction: _, ...rest } = dataToCreate;\n dataToCreate = rest;\n }\n\n if (nestedRelations) {\n dataToCreate = handleRelationFieldsInBody(\n dataToCreate,\n nestedRelations,\n ignoreActions\n );\n }\n\n mutableBody[field.name] = { create: dataToCreate };\n } else {\n // If ID and other fields, assume update operation\n const { id, apiAction: _, ...data } = relationData;\n\n let dataToUpdate = data;\n if (nestedRelations) {\n dataToUpdate = handleRelationFieldsInBody(\n data,\n nestedRelations,\n ignoreActions\n );\n }\n\n mutableBody[field.name] = {\n update: {\n data: dataToUpdate,\n },\n };\n }\n });\n\n // Remove any remaining apiAction fields from the top level\n if (\"apiAction\" in mutableBody) {\n const { apiAction, ...rest } = mutableBody;\n mutableBody = rest;\n }\n\n // As a final step, recursively remove any remaining apiAction fields\n return removeApiAction(mutableBody);\n}\n\n/**\n * Checks if a field value can be used to connect to a model\n * This happens when the field contains only an ID or a single unique field\n *\n * @param {string} modelName - The model name to get unique fields for\n * @param {Record<string, any>} bodyField - The field value from the body\n * @returns {boolean} True if the field can be used for a connect operation\n */\nexport function canBeUsedToConnect(\n modelName: string,\n bodyField: Record<string, any> | undefined | null\n): boolean {\n // If the field is null or undefined, it can't be used to connect\n if (!bodyField) return false;\n\n // If the field has an apiAction that's not for connecting, return false\n if (bodyField.apiAction && ![\"connect\"]?.includes?.(bodyField.apiAction)) {\n return false;\n }\n\n // If explicitly marked for connect, allow it\n if (bodyField.apiAction === \"connect\") {\n return true;\n }\n\n // If only ID is present, it can be used to connect\n if (Object.keys(bodyField)?.length === 1 && bodyField?.id) {\n return true;\n }\n\n // Get unique fields for the model\n const uniqueFields = getModelUniqueFields(modelName);\n\n // If the field has exactly one property and it's a unique field, it can be used to connect\n if (Object.keys(bodyField).length === 1) {\n const fieldName = Object.keys(bodyField)[0];\n return uniqueFields?.some((field) => field.name === fieldName);\n }\n\n return false;\n}\n"]}
|
|
@@ -1,2 +1,135 @@
|
|
|
1
|
-
|
|
1
|
+
import { Router } from "express";
|
|
2
|
+
import swaggerUi from "swagger-ui-express";
|
|
3
|
+
import swaggerJsdoc from "swagger-jsdoc";
|
|
4
|
+
import deepmerge from "../../utils/helpers/deepmerge.helper";
|
|
5
|
+
const swaggerRouter = Router();
|
|
6
|
+
function generateSchemasByMode(swaggerConfig) {
|
|
7
|
+
const schemas = {};
|
|
8
|
+
switch (swaggerConfig.mode) {
|
|
9
|
+
case "prisma":
|
|
10
|
+
break;
|
|
11
|
+
case "class-validator":
|
|
12
|
+
break;
|
|
13
|
+
case "zod":
|
|
14
|
+
break;
|
|
15
|
+
case "json-schema":
|
|
16
|
+
default:
|
|
17
|
+
break;
|
|
18
|
+
}
|
|
19
|
+
return schemas;
|
|
20
|
+
}
|
|
21
|
+
export function getSwaggerRouter(arkosConfig) {
|
|
22
|
+
const defaultSwaggerConfig = {
|
|
23
|
+
endpoint: "/docs",
|
|
24
|
+
mode: "json-schema",
|
|
25
|
+
options: {
|
|
26
|
+
definition: {
|
|
27
|
+
openapi: "3.0.0",
|
|
28
|
+
info: {
|
|
29
|
+
title: "API Generated By Arkos.js",
|
|
30
|
+
version: "1.0.0",
|
|
31
|
+
description: "This API was automatically generated by Arkos.js read more about at www.arkosjs.com",
|
|
32
|
+
},
|
|
33
|
+
servers: [
|
|
34
|
+
{
|
|
35
|
+
url: `http://${arkosConfig.host}:${arkosConfig.port}`,
|
|
36
|
+
description: "Local server",
|
|
37
|
+
},
|
|
38
|
+
],
|
|
39
|
+
components: {
|
|
40
|
+
schemas: {},
|
|
41
|
+
securitySchemes: {
|
|
42
|
+
BearerAuth: {
|
|
43
|
+
type: "http",
|
|
44
|
+
scheme: "bearer",
|
|
45
|
+
bearerFormat: "JWT",
|
|
46
|
+
},
|
|
47
|
+
ApiKeyAuth: {
|
|
48
|
+
type: "apiKey",
|
|
49
|
+
in: "header",
|
|
50
|
+
name: "X-API-Key",
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
},
|
|
54
|
+
security: [],
|
|
55
|
+
},
|
|
56
|
+
apis: [
|
|
57
|
+
"./src/routers/*.router.{ts,js}",
|
|
58
|
+
"./src/modules/**/*.router.{ts,js}",
|
|
59
|
+
],
|
|
60
|
+
swaggerUiOptions: {
|
|
61
|
+
explorer: true,
|
|
62
|
+
customCss: `
|
|
63
|
+
.swagger-ui .topbar { display: none; }
|
|
64
|
+
.swagger-ui .info { margin: 20px 0; }
|
|
65
|
+
`,
|
|
66
|
+
swaggerOptions: {
|
|
67
|
+
filter: true,
|
|
68
|
+
displayRequestDuration: true,
|
|
69
|
+
showExtensions: true,
|
|
70
|
+
showCommonExtensions: true,
|
|
71
|
+
},
|
|
72
|
+
},
|
|
73
|
+
deepLinking: true,
|
|
74
|
+
tryItOutEnabled: true,
|
|
75
|
+
persistAuthorization: false,
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
const swaggerConfigs = deepmerge(defaultSwaggerConfig, arkosConfig.swagger || {});
|
|
79
|
+
const modeSchemas = generateSchemasByMode(swaggerConfigs);
|
|
80
|
+
if (swaggerConfigs.options.definition.components?.schemas) {
|
|
81
|
+
swaggerConfigs.options.definition.components.schemas = {
|
|
82
|
+
...swaggerConfigs.options.definition.components.schemas,
|
|
83
|
+
...modeSchemas,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
const swaggerSpecification = swaggerJsdoc({
|
|
87
|
+
definition: swaggerConfigs.options
|
|
88
|
+
.definition,
|
|
89
|
+
apis: swaggerConfigs.options.apis || [],
|
|
90
|
+
});
|
|
91
|
+
const swaggerUiOptions = {
|
|
92
|
+
explorer: swaggerConfigs.options.swaggerUiOptions?.explorer ?? true,
|
|
93
|
+
customCss: swaggerConfigs.options.swaggerUiOptions?.customCss,
|
|
94
|
+
customSiteTitle: swaggerConfigs.options.swaggerUiOptions?.customSiteTitle ||
|
|
95
|
+
"API Documentation",
|
|
96
|
+
customfavIcon: swaggerConfigs.options.swaggerUiOptions?.customfavIcon,
|
|
97
|
+
swaggerOptions: {
|
|
98
|
+
filter: swaggerConfigs.options.swaggerUiOptions?.swaggerOptions?.filter ?? true,
|
|
99
|
+
displayRequestDuration: swaggerConfigs.options.swaggerUiOptions?.swaggerOptions
|
|
100
|
+
?.displayRequestDuration ?? true,
|
|
101
|
+
deepLinking: swaggerConfigs.options.deepLinking ?? true,
|
|
102
|
+
tryItOutEnabled: swaggerConfigs.options.tryItOutEnabled ?? true,
|
|
103
|
+
persistAuthorization: swaggerConfigs.options.persistAuthorization ?? false,
|
|
104
|
+
showExtensions: swaggerConfigs.options.swaggerUiOptions?.swaggerOptions
|
|
105
|
+
?.showExtensions ?? true,
|
|
106
|
+
showCommonExtensions: swaggerConfigs.options.swaggerUiOptions?.swaggerOptions
|
|
107
|
+
?.showCommonExtensions ?? true,
|
|
108
|
+
...swaggerConfigs.options.swaggerUiOptions?.swaggerOptions,
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
swaggerRouter.use(swaggerConfigs.endpoint, swaggerUi.serve);
|
|
112
|
+
swaggerRouter.get(swaggerConfigs.endpoint, swaggerUi.setup(swaggerSpecification, swaggerUiOptions));
|
|
113
|
+
swaggerRouter.get(`${swaggerConfigs.endpoint}/json`, (req, res) => {
|
|
114
|
+
res.setHeader("Content-Type", "application/json");
|
|
115
|
+
res.json(swaggerSpecification);
|
|
116
|
+
});
|
|
117
|
+
swaggerRouter.get(`${swaggerConfigs.endpoint}/yaml`, (req, res) => {
|
|
118
|
+
const yaml = require("js-yaml");
|
|
119
|
+
res.setHeader("Content-Type", "text/yaml");
|
|
120
|
+
res.send(yaml.dump(swaggerSpecification));
|
|
121
|
+
});
|
|
122
|
+
swaggerRouter.get(`${swaggerConfigs.endpoint}/health`, (req, res) => {
|
|
123
|
+
res.json({
|
|
124
|
+
status: "ok",
|
|
125
|
+
swagger: {
|
|
126
|
+
version: swaggerConfigs.options.definition.openapi,
|
|
127
|
+
title: swaggerConfigs.options.definition.info?.title,
|
|
128
|
+
endpoint: swaggerConfigs.endpoint,
|
|
129
|
+
mode: swaggerConfigs.mode,
|
|
130
|
+
},
|
|
131
|
+
});
|
|
132
|
+
});
|
|
133
|
+
return swaggerRouter;
|
|
134
|
+
}
|
|
2
135
|
//# sourceMappingURL=swagger.router.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"swagger.router.js","sourceRoot":"","sources":["../../../../src/modules/swagger/swagger.router.ts"],"names":[],"mappings":"","sourcesContent":[""]}
|
|
1
|
+
{"version":3,"file":"swagger.router.js","sourceRoot":"","sources":["../../../../src/modules/swagger/swagger.router.ts"],"names":[],"mappings":"AA+CA,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,SAAS,MAAM,oBAAoB,CA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AC3C,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC,CAAC;IAC5C,CAAC,CAAC,CAAC;IAGH,aAAa,CAAC,GAAG,CAAC,GAAG,cAAc,CAAC,QAAQ,SAAS,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;QAClE,GAAG,CAAC,IAAI,CAAC;YACP,MAAM,EAAE,IAAI;YACZ,OAAO,EAAE;gBACP,OAAO,EAAE,cAAc,CAAC,OAAO,CAAC,UAAU,CAAC,OAAO;gBAClD,KAAK,EAAE,cAAc,CAAC,OAAO,CAAC,UAAU,CAAC,IAAI,EAAE,KAAK;gBACpD,QAAQ,EAAE,cAAc,CAAC,QAAQ;gBACjC,IAAI,EAAE,cAAc,CAAC,IAAI;aAC1B;SACF,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,aAAa,CAAC;AACvB,CAAC","sourcesContent":["// import { Router } from \"express\";\n// import swaggerUi from \"swagger-ui-express\";\n// import { ArkosConfig } from \"../../types/arkos-config\";\n// import deepmerge from \"../../utils/helpers/deepmerge.helper\";\n\n// const swaggerRouter = Router();\n\n// export function getSwaggerRouter(arkosConfig: ArkosConfig) {\n// const swaggerConfigs: ArkosConfig[\"swagger\"] = deepmerge(\n// {\n// endpoint: \"/docs\",\n// options: {\n// definition: {\n// openapi: \"3.0.0\",\n// info: {\n// title: \"API Generated By Arkos.js\",\n// version: \"1.0.0\",\n// description:\n// \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\",\n// },\n// servers: [\n// {\n// url: `http://${arkosConfig.host}:${arkosConfig.port}`,\n// description: \"Local server\",\n// },\n// ],\n// },\n// apis: [\n// \"./src/routers/*.router.{ts,js}\",\n// \"./src/modules/**/*.router.{ts,js}\",\n// ],\n// deepLinking: true,\n// tryItOutEnabled: true,\n// },\n// },\n// arkosConfig.swagger || {}\n// );\n\n// swaggerRouter.get(\n// swaggerConfigs.endpoint!,\n// swaggerUi.serve,\n// swaggerUi.setup(swaggerConfigs.options)\n// );\n\n// return swaggerRouter;\n// }\n\nimport { Router } from \"express\";\nimport swaggerUi from \"swagger-ui-express\";\nimport swaggerJsdoc from \"swagger-jsdoc\";\nimport { ArkosConfig } from \"../../types/arkos-config\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\n\nconst swaggerRouter = Router();\n\n// Helper function to generate schemas based on mode\nfunction generateSchemasByMode(swaggerConfig: ArkosConfig[\"swagger\"]) {\n const schemas: Record<string, any> = {};\n\n switch (swaggerConfig!.mode) {\n case \"prisma\":\n // In a real implementation, you'd generate schemas from Prisma models\n // This would require additional logic to parse Prisma schema files\n break;\n\n case \"class-validator\":\n // Generate schemas from class-validator decorators\n // This would require reflection or build-time generation\n break;\n\n case \"zod\":\n // Generate schemas from Zod definitions\n // This could be done through custom transformations\n break;\n\n case \"json-schema\":\n default:\n // Use manually defined JSON schemas\n // This is the default behavior with JSDoc comments\n break;\n }\n\n return schemas;\n}\n\nexport function getSwaggerRouter(arkosConfig: ArkosConfig): Router {\n // Default swagger configuration\n const defaultSwaggerConfig: ArkosConfig[\"swagger\"] = {\n endpoint: \"/docs\",\n mode: \"json-schema\",\n options: {\n definition: {\n openapi: \"3.0.0\",\n info: {\n title: \"API Generated By Arkos.js\",\n version: \"1.0.0\",\n description:\n \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\",\n },\n servers: [\n {\n url: `http://${arkosConfig.host}:${arkosConfig.port}`,\n description: \"Local server\",\n },\n ],\n components: {\n schemas: {},\n securitySchemes: {\n BearerAuth: {\n type: \"http\",\n scheme: \"bearer\",\n bearerFormat: \"JWT\",\n },\n ApiKeyAuth: {\n type: \"apiKey\",\n in: \"header\",\n name: \"X-API-Key\",\n },\n },\n },\n security: [],\n },\n apis: [\n \"./src/routers/*.router.{ts,js}\",\n \"./src/modules/**/*.router.{ts,js}\",\n ],\n swaggerUiOptions: {\n explorer: true,\n customCss: `\n .swagger-ui .topbar { display: none; }\n .swagger-ui .info { margin: 20px 0; }\n `,\n swaggerOptions: {\n filter: true,\n displayRequestDuration: true,\n showExtensions: true,\n showCommonExtensions: true,\n },\n },\n deepLinking: true,\n tryItOutEnabled: true,\n persistAuthorization: false,\n },\n };\n\n // Merge default config with user config\n const swaggerConfigs = deepmerge(\n defaultSwaggerConfig,\n arkosConfig.swagger || {}\n );\n\n // Generate additional schemas based on mode\n const modeSchemas = generateSchemasByMode(swaggerConfigs);\n\n // Merge mode-generated schemas with existing schemas\n if (swaggerConfigs.options.definition.components?.schemas) {\n swaggerConfigs.options.definition.components.schemas = {\n ...swaggerConfigs.options.definition.components.schemas,\n ...modeSchemas,\n };\n }\n\n // Generate OpenAPI specification using swagger-jsdoc\n const swaggerSpecification = swaggerJsdoc({\n definition: swaggerConfigs.options\n .definition as swaggerJsdoc.SwaggerDefinition,\n apis: swaggerConfigs.options.apis || [],\n });\n\n // Setup Swagger UI options\n const swaggerUiOptions = {\n explorer: swaggerConfigs.options.swaggerUiOptions?.explorer ?? true,\n customCss: swaggerConfigs.options.swaggerUiOptions?.customCss,\n customSiteTitle:\n swaggerConfigs.options.swaggerUiOptions?.customSiteTitle ||\n \"API Documentation\",\n customfavIcon: swaggerConfigs.options.swaggerUiOptions?.customfavIcon,\n swaggerOptions: {\n filter:\n swaggerConfigs.options.swaggerUiOptions?.swaggerOptions?.filter ?? true,\n displayRequestDuration:\n swaggerConfigs.options.swaggerUiOptions?.swaggerOptions\n ?.displayRequestDuration ?? true,\n deepLinking: swaggerConfigs.options.deepLinking ?? true,\n tryItOutEnabled: swaggerConfigs.options.tryItOutEnabled ?? true,\n persistAuthorization:\n swaggerConfigs.options.persistAuthorization ?? false,\n showExtensions:\n swaggerConfigs.options.swaggerUiOptions?.swaggerOptions\n ?.showExtensions ?? true,\n showCommonExtensions:\n swaggerConfigs.options.swaggerUiOptions?.swaggerOptions\n ?.showCommonExtensions ?? true,\n ...swaggerConfigs.options.swaggerUiOptions?.swaggerOptions,\n },\n };\n\n // Serve Swagger UI static assets\n swaggerRouter.use(swaggerConfigs.endpoint!, swaggerUi.serve);\n\n // Serve Swagger documentation\n swaggerRouter.get(\n swaggerConfigs.endpoint!,\n swaggerUi.setup(swaggerSpecification, swaggerUiOptions)\n );\n\n // Serve raw OpenAPI spec as JSON\n swaggerRouter.get(`${swaggerConfigs.endpoint}/json`, (req, res) => {\n res.setHeader(\"Content-Type\", \"application/json\");\n res.json(swaggerSpecification);\n });\n\n // Serve raw OpenAPI spec as YAML (optional)\n swaggerRouter.get(`${swaggerConfigs.endpoint}/yaml`, (req, res) => {\n const yaml = require(\"js-yaml\");\n res.setHeader(\"Content-Type\", \"text/yaml\");\n res.send(yaml.dump(swaggerSpecification));\n });\n\n // Health check endpoint for Swagger itself\n swaggerRouter.get(`${swaggerConfigs.endpoint}/health`, (req, res) => {\n res.json({\n status: \"ok\",\n swagger: {\n version: swaggerConfigs.options.definition.openapi,\n title: swaggerConfigs.options.definition.info?.title,\n endpoint: swaggerConfigs.endpoint,\n mode: swaggerConfigs.mode,\n },\n });\n });\n\n return swaggerRouter;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"arkos-config.js","sourceRoot":"","sources":["../../../src/types/arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import http from \"http\";\nimport cors from \"cors\";\nimport express from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for passing prisma query options.\n *\n * See more\n */\n allowDangerousPrismaQueryOptions?: boolean;\n };\n };\n /** Message you would like to send, as Json and 200 response when\n * ```curl\n * GET /api\n * ```\n *\n * ```json\n * { \"message\": \"Welcome to YourAppName\" }\n * ```\n *\n * default message is: Welcome to our Rest API generated by Arkos, find more about Arkos at www.arkosjs.com.\n *\n *\n * */\n welcomeMessage?: string;\n /**\n * Port where the application will run, can be set in 3 ways:\n *\n * 1. default is 8000\n * 2. PORT under environment variables (Lower precedence)\n * 3. this config option (Higher precedence)\n */\n port?: number | undefined;\n /**\n * Allows to listen on a different host than localhost only\n */\n host?: string;\n /**\n * Defines authentication related configurations, by default is undefined.\n *\n * See [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for details.\n */\n authentication?: {\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /**\n * Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * See more at [www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field)\n *\n * By specifing here another field for username, for example passing \"email\", \"companyCode\" or something else your json will be like:\n *\n * **Example with email**\n *\n * ```json\n * {\n * \"email\": \"john.doe@example.com\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n */\n allowedUsernames?: string[];\n /** Defines wether to send the access token in response after login or only send as cookie, defeault is both.*/\n sendAccessTokenThrough?: \"cookie-only\" | \"response-only\" | \"both\";\n };\n /**\n * Specifies the regex pattern used by the authentication system to enforce password strength requirements.\n *\n * **Important**: If using validation libraries like Zod or class-validator, this will be completely overwritten.\n *\n * **Default**: ```/^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/``` - Ensures the password contains at least one uppercase letter, one lowercase letter, and one numeric digit.\n *\n * **message**: (Optional) A custom error message to display when the password does not meet the required strength criteria.\n */\n passwordValidation?: { regex: RegExp; message?: string };\n /**\n * Allows to specify the request rate limit for all authentication endpoints but `/api/users/me`.\n * \n * #### Default\n *{\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n *@see This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n requestRateLimitOptions?: RateLimitOptions;\n /**\n * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n * ⚠️ Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n */\n secure?: boolean;\n\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n */\n httpOnly?: boolean;\n\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n };\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * @See [www.arkosjs.com/docs/core-concepts/request-data-validation](https://www.arkosjs.com/docs/core-concepts/request-data-validation) for more details.\n */\n validation?:\n | {\n resolver?: \"class-validator\";\n /**\n * ValidatorOptions to used while validating request data.\n *\n * **Default**:\n * ```ts\n * {\n * whitelist: true\n * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver?: \"zod\";\n validationOptions?: Record<string, any>;\n };\n /**\n * Defines file upload configurations\n *\n * See [www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations](https://www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations)\n */\n fileUpload?: {\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n expressStaticOptions?: Parameters<typeof express.static>[1];\n /**\n * Defines upload restrictions for each file type: image, video, document or other.\n *\n * #### Important:\n * Passing an object without overriding everything will only cause it\n * to be deepmerged with the default options.\n *\n * See [www.arkosjs.com/docs/api-reference/default-supported-upload-files](https://www.arkosjs.com/docs/api-reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n restrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n files?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * Allows to specify the request rate limit for all endpoints.\n * \n * #### Default\n *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n ```\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n globalRequestRateLimitOptions?: Partial<RateLimitOptions>;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n jsonBodyParserOptions?: Parameters<typeof express.json>[0];\n /**\n * Allows to pass paremeters to cookieParser from npm package cookie-parser\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/cookie-parser](https://www.npmjs.com/package/cookie-parser) for further details.\n */\n cookieParserParameters?: Parameters<typeof cookieParser>;\n /**\n * Allows to define options for npm package compression\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/compression](https://www.npmjs.com/package/compression) for further details.\n */\n compressionOptions?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * #### for example:\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n * \n * #### Default:\n * \n * {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n }\n * \n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n * \n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParserOptions?: QueryParserOptions;\n /**\n * Configuration for CORS (Cross-Origin Resource Sharing).\n *\n * @property {string | string[] | \"all\"} [allowedOrigins] - List of allowed origins. If set to `\"all\"`, all origins are accepted.\n * @property {import('cors').CorsOptions} [options] - Additional CORS options passed directly to the `cors` middleware.\n * @property {import('cors').CorsOptionsDelegate} [customMiddleware] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customMiddleware` is provided, both `allowedOrigins` and `options` will be ignored in favor of the custom logic.\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?: {\n allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware\n *\n * see\n */\n customHandler?: cors.CorsOptionsDelegate;\n };\n /**\n * Defines express/arkos middlewares configurations\n */\n middlewares?: {\n /**\n * Allows to add an array of custom express middlewares into the default middleware stack.\n *\n * **Tip**: If you would like to acess the express app before everthing use `configureApp` and pass a function.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order](https://www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order)\n *\n * **Note**: If you want to use custom global error handler middleware use `middlewares.replace.globalErrorHandler`.\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.RequestHandler[];\n /**\n * An array containing a list of defaults middlewares to be disabled\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n disable?: (\n | \"compression\"\n | \"global-rate-limit\"\n | \"auth-rate-limit\"\n | \"cors\"\n | \"express-json\"\n | \"cookie-parser\"\n | \"query-parser\"\n | \"database-connection\"\n | \"request-logger\"\n | \"global-error-handler\"\n )[];\n /**\n * Allows you to replace each of the built-in middlewares with your own implementation\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default compression middleware\n */\n compression?: express.RequestHandler;\n /**\n * Replace the default global rate limit middleware\n */\n globalRateLimit?: express.RequestHandler;\n /**\n * Replace the default authentication rate limit middleware\n */\n authRateLimit?: express.RequestHandler;\n /**\n * Replace the default CORS middleware\n */\n cors?: express.RequestHandler;\n /**\n * Replace the default JSON body parser middleware\n */\n expressJson?: express.RequestHandler;\n /**\n * Replace the default cookie parser middleware\n */\n cookieParser?: express.RequestHandler;\n /**\n * Replace the default query parser middleware\n */\n queryParser?: express.RequestHandler;\n /**\n * Replace the default database connection check middleware\n */\n databaseConnection?: express.RequestHandler;\n /**\n * Replace the default request logger middleware\n */\n requestLogger?: express.RequestHandler;\n /**\n * Replace the default global error handler middleware\n */\n globalErrorHandler?: express.ErrorRequestHandler;\n };\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Allows to add an array of custom express routers into the default middleware/router stack.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/adding-custom-routers](https://www.arkosjs.com/docs/advanced-guide/adding-custom-routers)\n *\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.Router[];\n disable?: (\n | \"auth-router\"\n | \"prisma-models-router\"\n | \"file-uploader\"\n | \"welcome-endpoint\"\n )[];\n /**\n * Allows you to replace each of the built-in routers with your own implementation.\n *\n * **Note**: Doing this you will lose all default middleware chaining, auth control, handlers from the specific router.\n *\n * **Tip**: I you want to disable some prisma models specific endpoint\n * see [www.arkosjs.com/docs/guide/adding-custom-routers#disabling-auto-generated-endpoints](https://www.arkosjs.com/docs/guide/adding-custom-routers#disabling-auto-generated-endpoints)\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default authentication router\n * @param config The original Arkos configuration\n * @returns A router handling authentication endpoints\n */\n authRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default Prisma models router\n * @param config The original Arkos configuration\n * @returns A router handling Prisma model endpoints\n */\n prismaModelsRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default file uploader router\n * @param config The original Arkos configuration\n * @returns A router handling file upload endpoints\n */\n fileUploader?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default welcome endpoint handler\n * @param req Express request object\n * @param res Express response object\n * @param next Express next function\n */\n welcomeEndpoint?: express.RequestHandler;\n };\n };\n /**\n * Gives acess to the underlying express app so that you can add custom configurations beyong **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `app.listen` for you.\n *\n * If you want to call `app.listen` by yourself pass port as `undefined` and then use the return app from `arkos.init()`.\n *\n * See how to call `app.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app](https://www.arkosjs.com/docs/guide/accessing-the-express-app) for further details on the method configureApp.\n *\n * @param {express.Express} app\n * @returns {any}\n */\n configureApp?: (app: express.Express) => Promise<any> | any;\n /**\n * Gives access to the underlying HTTP server so that you can add custom configurations beyond **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `server.listen` for you.\n *\n * If you want to call `server.listen` by yourself pass port as `undefined` and then use the return server from `arkos.init()`.\n *\n * See how to call `server.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#creating-your-own-http-server](https://www.arkosjs.com/docs/guide/accessing-the-express-app#creating-your-own-http-server)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app#accessing-the-http-server](https://www.arkosjs.com/docs/guide/accessing-the-express-app#accessing-the-http-server) for further details on the method configureServer.\n *\n * @param {http.Server} server - The HTTP server instance\n * @returns {any}\n */\n configureServer?: (server: http.Server) => Promise<any> | any;\n /**\n * Allows to configure email configurations for sending emails through `emailService`\n *\n * See [www.arkosjs.com/docs/core-concepts/sending-emails](https://www.arkosjs.com/docs/core-concepts/sending-emails)\n */\n email?: {\n /**\n * Your email provider url\n */\n host: string;\n /**\n * Email provider SMTP port, Default is `465`\n */\n port?: number;\n /**\n * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n };\n};\n"]}
|
|
1
|
+
{"version":3,"file":"arkos-config.js","sourceRoot":"","sources":["../../../src/types/arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import http from \"http\";\nimport cors from \"cors\";\nimport express from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for passing prisma query options.\n *\n * See more\n */\n allowDangerousPrismaQueryOptions?: boolean;\n };\n };\n /** Message you would like to send, as Json and 200 response when\n * ```curl\n * GET /api\n * ```\n *\n * ```json\n * { \"message\": \"Welcome to YourAppName\" }\n * ```\n *\n * default message is: Welcome to our Rest API generated by Arkos, find more about Arkos at www.arkosjs.com.\n *\n *\n * */\n welcomeMessage?: string;\n /**\n * Port where the application will run, can be set in 3 ways:\n *\n * 1. default is 8000\n * 2. PORT under environment variables (Lower precedence)\n * 3. this config option (Higher precedence)\n */\n port?: number | undefined;\n /**\n * Allows to listen on a different host than localhost only\n */\n host?: string;\n /**\n * Defines authentication related configurations, by default is undefined.\n *\n * See [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for details.\n */\n authentication?: {\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /**\n * Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * See more at [www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/guide/authentication-system/sending-authentication-requests#example-changing-the-username-field)\n *\n * By specifing here another field for username, for example passing \"email\", \"companyCode\" or something else your json will be like:\n *\n * **Example with email**\n *\n * ```json\n * {\n * \"email\": \"john.doe@example.com\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n */\n allowedUsernames?: string[];\n /** Defines wether to send the access token in response after login or only send as cookie, defeault is both.*/\n sendAccessTokenThrough?: \"cookie-only\" | \"response-only\" | \"both\";\n };\n /**\n * Specifies the regex pattern used by the authentication system to enforce password strength requirements.\n *\n * **Important**: If using validation libraries like Zod or class-validator, this will be completely overwritten.\n *\n * **Default**: ```/^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/``` - Ensures the password contains at least one uppercase letter, one lowercase letter, and one numeric digit.\n *\n * **message**: (Optional) A custom error message to display when the password does not meet the required strength criteria.\n */\n passwordValidation?: { regex: RegExp; message?: string };\n /**\n * Allows to specify the request rate limit for all authentication endpoints but `/api/users/me`.\n * \n * #### Default\n *{\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n *@see This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n requestRateLimitOptions?: RateLimitOptions;\n /**\n * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n * ⚠️ Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n */\n secure?: boolean;\n\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n */\n httpOnly?: boolean;\n\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n };\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * @See [www.arkosjs.com/docs/core-concepts/request-data-validation](https://www.arkosjs.com/docs/core-concepts/request-data-validation) for more details.\n */\n validation?:\n | {\n resolver?: \"class-validator\";\n /**\n * ValidatorOptions to used while validating request data.\n *\n * **Default**:\n * ```ts\n * {\n * whitelist: true\n * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver?: \"zod\";\n validationOptions?: Record<string, any>;\n };\n /**\n * Defines file upload configurations\n *\n * See [www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations](https://www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations)\n */\n fileUpload?: {\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n expressStaticOptions?: Parameters<typeof express.static>[1];\n /**\n * Defines upload restrictions for each file type: image, video, document or other.\n *\n * #### Important:\n * Passing an object without overriding everything will only cause it\n * to be deepmerged with the default options.\n *\n * See [www.arkosjs.com/docs/api-reference/default-supported-upload-files](https://www.arkosjs.com/docs/api-reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n restrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n files?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * Allows to specify the request rate limit for all endpoints.\n * \n * #### Default\n *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n ```\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n globalRequestRateLimitOptions?: Partial<RateLimitOptions>;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n jsonBodyParserOptions?: Parameters<typeof express.json>[0];\n /**\n * Allows to pass paremeters to cookieParser from npm package cookie-parser\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/cookie-parser](https://www.npmjs.com/package/cookie-parser) for further details.\n */\n cookieParserParameters?: Parameters<typeof cookieParser>;\n /**\n * Allows to define options for npm package compression\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/compression](https://www.npmjs.com/package/compression) for further details.\n */\n compressionOptions?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * #### for example:\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n * \n * #### Default:\n * \n * {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n }\n * \n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n * \n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParserOptions?: QueryParserOptions;\n /**\n * Configuration for CORS (Cross-Origin Resource Sharing).\n *\n * @property {string | string[] | \"all\"} [allowedOrigins] - List of allowed origins. If set to `\"all\"`, all origins are accepted.\n * @property {import('cors').CorsOptions} [options] - Additional CORS options passed directly to the `cors` middleware.\n * @property {import('cors').CorsOptionsDelegate} [customMiddleware] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customMiddleware` is provided, both `allowedOrigins` and `options` will be ignored in favor of the custom logic.\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?: {\n /**\n * Defines allowed origins to acess the API.\n */\n allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware\n *\n * see\n */\n customHandler?: cors.CorsOptionsDelegate;\n };\n /**\n * Defines express/arkos middlewares configurations\n */\n middlewares?: {\n /**\n * Allows to add an array of custom express middlewares into the default middleware stack.\n *\n * **Tip**: If you would like to acess the express app before everthing use `configureApp` and pass a function.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order](https://www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order)\n *\n * **Note**: If you want to use custom global error handler middleware use `middlewares.replace.globalErrorHandler`.\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.RequestHandler[];\n /**\n * An array containing a list of defaults middlewares to be disabled\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n disable?: (\n | \"compression\"\n | \"global-rate-limit\"\n | \"auth-rate-limit\"\n | \"cors\"\n | \"express-json\"\n | \"cookie-parser\"\n | \"query-parser\"\n | \"database-connection\"\n | \"request-logger\"\n | \"global-error-handler\"\n )[];\n /**\n * Allows you to replace each of the built-in middlewares with your own implementation\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default compression middleware\n */\n compression?: express.RequestHandler;\n /**\n * Replace the default global rate limit middleware\n */\n globalRateLimit?: express.RequestHandler;\n /**\n * Replace the default authentication rate limit middleware\n */\n authRateLimit?: express.RequestHandler;\n /**\n * Replace the default CORS middleware\n */\n cors?: express.RequestHandler;\n /**\n * Replace the default JSON body parser middleware\n */\n expressJson?: express.RequestHandler;\n /**\n * Replace the default cookie parser middleware\n */\n cookieParser?: express.RequestHandler;\n /**\n * Replace the default query parser middleware\n */\n queryParser?: express.RequestHandler;\n /**\n * Replace the default database connection check middleware\n */\n databaseConnection?: express.RequestHandler;\n /**\n * Replace the default request logger middleware\n */\n requestLogger?: express.RequestHandler;\n /**\n * Replace the default global error handler middleware\n */\n globalErrorHandler?: express.ErrorRequestHandler;\n };\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Allows to add an array of custom express routers into the default middleware/router stack.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/adding-custom-routers](https://www.arkosjs.com/docs/advanced-guide/adding-custom-routers)\n *\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.Router[];\n disable?: (\n | \"auth-router\"\n | \"prisma-models-router\"\n | \"file-uploader\"\n | \"welcome-endpoint\"\n )[];\n /**\n * Allows you to replace each of the built-in routers with your own implementation.\n *\n * **Note**: Doing this you will lose all default middleware chaining, auth control, handlers from the specific router.\n *\n * **Tip**: I you want to disable some prisma models specific endpoint\n * see [www.arkosjs.com/docs/guide/adding-custom-routers#disabling-auto-generated-endpoints](https://www.arkosjs.com/docs/guide/adding-custom-routers#disabling-auto-generated-endpoints)\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default authentication router\n * @param config The original Arkos configuration\n * @returns A router handling authentication endpoints\n */\n authRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default Prisma models router\n * @param config The original Arkos configuration\n * @returns A router handling Prisma model endpoints\n */\n prismaModelsRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default file uploader router\n * @param config The original Arkos configuration\n * @returns A router handling file upload endpoints\n */\n fileUploader?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default welcome endpoint handler\n * @param req Express request object\n * @param res Express response object\n * @param next Express next function\n */\n welcomeEndpoint?: express.RequestHandler;\n };\n };\n /**\n * Gives acess to the underlying express app so that you can add custom configurations beyong **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `app.listen` for you.\n *\n * If you want to call `app.listen` by yourself pass port as `undefined` and then use the return app from `arkos.init()`.\n *\n * See how to call `app.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app](https://www.arkosjs.com/docs/guide/accessing-the-express-app) for further details on the method configureApp.\n *\n * @param {express.Express} app\n * @returns {any}\n */\n configureApp?: (app: express.Express) => Promise<any> | any;\n /**\n * Gives access to the underlying HTTP server so that you can add custom configurations beyond **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `server.listen` for you.\n *\n * If you want to call `server.listen` by yourself pass port as `undefined` and then use the return server from `arkos.init()`.\n *\n * See how to call `server.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#creating-your-own-http-server](https://www.arkosjs.com/docs/guide/accessing-the-express-app#creating-your-own-http-server)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app#accessing-the-http-server](https://www.arkosjs.com/docs/guide/accessing-the-express-app#accessing-the-http-server) for further details on the method configureServer.\n *\n * @param {http.Server} server - The HTTP server instance\n * @returns {any}\n */\n configureServer?: (server: http.Server) => Promise<any> | any;\n /**\n * Allows to configure email configurations for sending emails through `emailService`\n *\n * See [www.arkosjs.com/docs/core-concepts/sending-emails](https://www.arkosjs.com/docs/core-concepts/sending-emails)\n */\n email?: {\n /**\n * Your email provider url\n */\n host: string;\n /**\n * Email provider SMTP port, Default is `465`\n */\n port?: number;\n /**\n * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n };\n /**\n * Defines Swagger and OpenApi specifications for auto generating swagger documentation UI using whether it is Prisma Schemas, Class-validator DTOs, Zod Schemas or JSON-Schemas\n *\n * **Usage**\n *\n * ```ts\n * // src/app.ts\n *\n * import arkos from \"arkos\"\n *\n * arkos.init({\n * // other configs\n * swagger: {\n * mode: \"zod\",\n * options: {\n * openapi: \"3.0.0\",\n * title: \"API Generated By Arkos.js\",\n * description: \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n * }\n * }\n * })\n * ```\n *\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/swagger-api-documentation}\n */\n swagger?: {\n /**\n * Endpoint where the Swagger UI will be available.\n *\n * @default \"/api/docs\"\n */\n endpoint?: string;\n /**\n * Determines how your API schemas should be generated.\n *\n * - \"prisma\": Generates schemas based on Prisma models\n * - \"class-validator\": Uses class-validator and class-transformer DTO classes\n * - \"zod`\": Uses OpenAPI-compliant schemas directly\n * - \"json-schema\": Uses OpenAPI-compliant schemas directly\n */\n mode: \"prisma\" | \"class-validator\" | \"zod\" | \"json-schema\";\n /**\n *\n */\n options: {\n /**\n * Swagger definition according to OpenAPI Specification.\n */\n definition: {\n /**\n * OpenAPI version.\n *\n * @default \"3.0.0\"\n */\n openapi?: string;\n\n /**\n * Information about your API.\n */\n info?: {\n /**\n * Title of the API documentation.\n *\n *\n * @example \"My API\"\n *\n * @default \"API Generated By Arkos.js\"\n */\n title?: string;\n\n /**\n * Version of the API.\n *\n * @example \"1.0.0\"\n */\n version?: string;\n\n /**\n * Description of the API.\n *\n * @default \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n */\n description?: string;\n };\n\n /**\n * Server configurations for the API.\n *\n * @default [{ url: \"http://localhost:8000\", description: \"Local server\" }]\n *\n * This can be overridden automatically by Arkos based on CLI, .env, or `arkos.init()`.\n */\n servers?: {\n /**\n * Base URL of the server.\n *\n * @example \"http://localhost:8000\"\n */\n url: string;\n\n /**\n * Human-readable description of the server.\n *\n * @example \"Development Server\"\n */\n description: string;\n }[];\n\n /**\n * (Optional) Additional metadata such as terms of service, contact, or license.\n *\n * See: https://swagger.io/specification/#infoObject\n */\n termsOfService?: string;\n contact?: {\n name?: string;\n url?: string;\n email?: string;\n };\n license?: {\n name: string;\n url?: string;\n };\n\n /**\n * Tags to group and describe endpoints.\n */\n tags?: {\n name: string;\n description?: string;\n }[];\n\n /**\n * Security definitions (e.g., Bearer Auth).\n */\n components?: {\n securitySchemes?: Record<string, any>;\n schemas?: Record<string, any>;\n };\n\n /**\n * Global security requirements.\n */\n security?: Array<Record<string, string[]>>;\n };\n\n /**\n * Glob patterns defining where Swagger should look for API route definitions and comments.\n *\n * @default \n * ```ts\n * [\"./src/routers/*.router.{ts,js}\", \"./src/modules/**\\/*.router.{ts,js}\"]\n ```\n *\n * Adjust depending on TypeScript or JavaScript usage.\n */\n apis?: string[];\n\n /**\n * Custom Swagger UI options.\n *\n * See: https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/configuration.md\n */\n swaggerUiOptions?: Record<string, any>;\n\n /**\n * Enables deep linking in the Swagger UI.\n *\n * @default true\n */\n deepLinking?: boolean;\n\n /**\n * Enable/disable the \"Try it out\" button globally.\n *\n * @default true\n */\n tryItOutEnabled?: boolean;\n\n /**\n * Whether to persist authorization data across page reloads.\n *\n * @default false\n */\n persistAuthorization?: boolean;\n };\n };\n};\n"]}
|
|
@@ -119,4 +119,46 @@ export type ArkosConfig = {
|
|
|
119
119
|
};
|
|
120
120
|
name?: string;
|
|
121
121
|
};
|
|
122
|
+
swagger?: {
|
|
123
|
+
endpoint?: string;
|
|
124
|
+
mode: "prisma" | "class-validator" | "zod" | "json-schema";
|
|
125
|
+
options: {
|
|
126
|
+
definition: {
|
|
127
|
+
openapi?: string;
|
|
128
|
+
info?: {
|
|
129
|
+
title?: string;
|
|
130
|
+
version?: string;
|
|
131
|
+
description?: string;
|
|
132
|
+
};
|
|
133
|
+
servers?: {
|
|
134
|
+
url: string;
|
|
135
|
+
description: string;
|
|
136
|
+
}[];
|
|
137
|
+
termsOfService?: string;
|
|
138
|
+
contact?: {
|
|
139
|
+
name?: string;
|
|
140
|
+
url?: string;
|
|
141
|
+
email?: string;
|
|
142
|
+
};
|
|
143
|
+
license?: {
|
|
144
|
+
name: string;
|
|
145
|
+
url?: string;
|
|
146
|
+
};
|
|
147
|
+
tags?: {
|
|
148
|
+
name: string;
|
|
149
|
+
description?: string;
|
|
150
|
+
}[];
|
|
151
|
+
components?: {
|
|
152
|
+
securitySchemes?: Record<string, any>;
|
|
153
|
+
schemas?: Record<string, any>;
|
|
154
|
+
};
|
|
155
|
+
security?: Array<Record<string, string[]>>;
|
|
156
|
+
};
|
|
157
|
+
apis?: string[];
|
|
158
|
+
swaggerUiOptions?: Record<string, any>;
|
|
159
|
+
deepLinking?: boolean;
|
|
160
|
+
tryItOutEnabled?: boolean;
|
|
161
|
+
persistAuthorization?: boolean;
|
|
162
|
+
};
|
|
163
|
+
};
|
|
122
164
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "arkos",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.62-test",
|
|
4
4
|
"description": "The Express & Prisma Framework For RESTful API",
|
|
5
5
|
"main": "dist/cjs/exports/index.js",
|
|
6
6
|
"module": "dist/es2020/exports/index.js",
|
|
@@ -92,7 +92,7 @@
|
|
|
92
92
|
"build:types": "tsc -p tsconfig.types.json",
|
|
93
93
|
"build:cjs": "tsc -p tsconfig.cjs.json",
|
|
94
94
|
"postbuilda": "echo {\\\"type\":\"commonjs\\\"} > dist/cjs/package.json",
|
|
95
|
-
"build": "
|
|
95
|
+
"build": "npx rimraf dist && pnpm run build:cjs && pnpm run build:es2020 && pnpm run build:types && pnpm run minify",
|
|
96
96
|
"minify": "esbuild dist/**/*.js --minify --outdir=dist --allow-overwrite --log-limit=0 --define:process.env.NODE_ENV=process.env.NODE_ENV",
|
|
97
97
|
"clean": "rm -r dist",
|
|
98
98
|
"dev": "ts-node --watch",
|
|
@@ -153,6 +153,8 @@
|
|
|
153
153
|
"@types/node": "^22.13.13",
|
|
154
154
|
"@types/nodemailer": "^6.4.17",
|
|
155
155
|
"@types/pluralize": "^0.0.33",
|
|
156
|
+
"@types/swagger-jsdoc": "^6.0.4",
|
|
157
|
+
"@types/swagger-ui-express": "^4.1.8",
|
|
156
158
|
"@typescript-eslint/eslint-plugin": "^6.0.0",
|
|
157
159
|
"@typescript-eslint/parser": "^6.0.0",
|
|
158
160
|
"bcrypt": "^5.1.1",
|
|
@@ -166,7 +168,9 @@
|
|
|
166
168
|
},
|
|
167
169
|
"dependencies": {
|
|
168
170
|
"commander": "^13.1.0",
|
|
169
|
-
"pluralize": "^8.0.0"
|
|
171
|
+
"pluralize": "^8.0.0",
|
|
172
|
+
"swagger-jsdoc": "^6.2.8",
|
|
173
|
+
"swagger-ui-express": "^5.0.1"
|
|
170
174
|
},
|
|
171
175
|
"peerDependencies": {
|
|
172
176
|
"@prisma/client": "^6.4.1",
|