arkos 1.3.6-canary.1 → 1.3.6-canary.2

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.
@@ -1 +1 @@
1
- {"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,8BAmLC;AA5MD,mDAAwD;AACxD,gDAAwB;AACxB,kEAAyC;AACzC,4DAA2D;AAC3D,4DAGoC;AACpC,gHAA4E;AAC5E,2DAA+C;AAC/C,8DAAsC;AACtC,sEAAoE;AACpE,mEAAkE;AAClE,iFAA+E;AAE/E,+EAAmE;AACnE,wFAAyD;AACzD,qEAAoE;AACpE,2DAAiE;AACjE,2DAAmD;AACnD,2FAAkE;AAErD,QAAA,GAAG,GAAoB,IAAA,iBAAO,GAAE,CAAC;AAC9C,MAAM,iBAAiB,GAAG,IAAA,gBAAM,GAAE,CAAC;AAE5B,KAAK,UAAU,SAAS,CAC7B,WAAwB;IAExB,MAAM,OAAO,CAAC,GAAG,CAAC;QAChB,IAAA,iCAAgB,GAAE;QAClB,IAAA,wCAAuB,EAAC,WAAW,CAAC;QACpC,WAAW,EAAE,YAAY,IAAI,CAAC,MAAM,WAAW,EAAE,YAAY,CAAC,WAAG,CAAC,CAAC;KACpE,CAAC,CAAC;IAEH,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;IAE7D,WAAG,CAAC,GAAG,CAAC,0BAAe,CAAC,oBAAoB,CAAC,CAAC;IAE9C,IAAI,CAAC,mBAAmB,EAAE,QAAQ,EAAE,CAAC,aAAa,CAAC;QACjD,WAAG,CAAC,GAAG,CACL,mBAAmB,CAAC,WAAW;YAC7B,IAAA,qBAAW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ACJ,CAAC,CAAC,CAAC;IAEH,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, { NextFunction, Router } 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 { loadPrismaModule } from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploadRouter } from \"./modules/file-upload/file-upload.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\";\nimport { loadAllModuleComponents } from \"./utils/dynamic-loader\";\nimport { AppError } from \"./exports/error-handler\";\nimport debuggerService from \"./modules/debugger/debugger.service\";\n\nexport const app: express.Express = express();\nconst knowModulesRouter = Router();\n\nexport async function bootstrap(\n arkosConfig: ArkosConfig\n): Promise<express.Express> {\n await Promise.all([\n loadPrismaModule(),\n loadAllModuleComponents(arkosConfig),\n arkosConfig?.configureApp && (await arkosConfig?.configureApp(app)),\n ]);\n\n const middlewaresConfig = arkosConfig?.middlewares;\n const disabledMiddlewares = middlewaresConfig?.disable || [];\n const replacedMiddlewares = middlewaresConfig?.replace || {};\n\n app.use(debuggerService.logLevel2RequestInfo);\n\n if (!disabledMiddlewares?.includes?.(\"compression\"))\n app.use(\n replacedMiddlewares.compression ||\n compression(arkosConfig?.compressionOptions)\n );\n\n if (!disabledMiddlewares?.includes?.(\"global-rate-limit\"))\n app.use(\n replacedMiddlewares.globalRateLimit ||\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 500,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n handler: (_, res) => {\n res.status(429).json({\n message: \"Too many requests, please try again later\",\n });\n },\n },\n arkosConfig?.globalRequestRateLimitOptions || {}\n )\n )\n );\n\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 if (!disabledMiddlewares?.includes?.(\"express-json\"))\n app.use(\n replacedMiddlewares.expressJson ||\n express.json(arkosConfig?.jsonBodyParserOptions)\n );\n\n if (!disabledMiddlewares?.includes?.(\"cookie-parser\"))\n app.use(\n replacedMiddlewares.cookieParser ||\n cookieParser(...[...(arkosConfig?.cookieParserParameters || [])])\n );\n\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 if (!disabledMiddlewares?.includes?.(\"request-logger\"))\n app.use(replacedMiddlewares.requestLogger || handleRequestLogs);\n\n if (arkosConfig?.middlewares?.additional)\n arkosConfig.middlewares.additional.forEach((middleware) => {\n app.use(middleware);\n });\n\n const routersConfig = arkosConfig?.routers;\n const disabledRouters = routersConfig?.disable || [];\n const replacedRouters = routersConfig?.replace || {};\n\n if (!disabledRouters?.includes?.(\"welcome-endpoint\"))\n app.get(\n \"/api\",\n replacedRouters.welcomeEndpoint ||\n ((_, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n })\n );\n\n if (!disabledRouters?.includes?.(\"file-upload\")) {\n const fileUploadRouter = replacedRouters.fileUpload\n ? await replacedRouters.fileUpload(arkosConfig)\n : await getFileUploadRouter(arkosConfig);\n knowModulesRouter.use(fileUploadRouter);\n }\n\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 knowModulesRouter.use(\"/api\", authRouter);\n }\n\n if (!disabledRouters?.includes?.(\"prisma-models-router\")) {\n const modelsRouter = replacedRouters.prismaModelsRouter\n ? await replacedRouters.prismaModelsRouter(arkosConfig)\n : await getPrismaModelsRouter(arkosConfig);\n knowModulesRouter.use(\"/api\", modelsRouter);\n }\n\n app.use(knowModulesRouter);\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n if (\n arkosConfig.swagger &&\n (process.env.ARKOS_BUILD !== \"true\" ||\n arkosConfig.swagger.enableAfterBuild === true)\n )\n app.use(\"/api\", await getSwaggerRouter(arkosConfig));\n\n if (routersConfig?.additional)\n routersConfig.additional.forEach((router) => {\n app.use(router);\n });\n\n app.use(\"*\", (req) => {\n throw new AppError(\n \"Route not found\",\n 404,\n { route: req.route },\n \"RouteNotFound\"\n );\n });\n\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":["../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;IAElE,OAAO,WAAG,CAAC;AACb,CAAC","sourcesContent":["import express, { Router } 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 { loadPrismaModule } from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploadRouter } from \"./modules/file-upload/file-upload.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\";\nimport { loadAllModuleComponents } from \"./utils/dynamic-loader\";\nimport { AppError } from \"./exports/error-handler\";\nimport debuggerService from \"./modules/debugger/debugger.service\";\n\nexport const app: express.Express = express();\nconst knowModulesRouter = Router();\n\nexport async function bootstrap(\n arkosConfig: ArkosConfig\n): Promise<express.Express> {\n await Promise.all([\n loadPrismaModule(),\n loadAllModuleComponents(arkosConfig),\n arkosConfig?.configureApp && (await arkosConfig?.configureApp(app)),\n ]);\n\n const middlewaresConfig = arkosConfig?.middlewares;\n const disabledMiddlewares = middlewaresConfig?.disable || [];\n const replacedMiddlewares = middlewaresConfig?.replace || {};\n\n app.use(debuggerService.logLevel2RequestInfo);\n\n if (!disabledMiddlewares?.includes?.(\"compression\"))\n app.use(\n replacedMiddlewares.compression ||\n compression(arkosConfig?.compressionOptions)\n );\n\n if (!disabledMiddlewares?.includes?.(\"global-rate-limit\"))\n app.use(\n replacedMiddlewares.globalRateLimit ||\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 500,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n handler: (_, res) => {\n res.status(429).json({\n message: \"Too many requests, please try again later\",\n });\n },\n },\n arkosConfig?.globalRequestRateLimitOptions || {}\n )\n )\n );\n\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 if (!disabledMiddlewares?.includes?.(\"express-json\"))\n app.use(\n replacedMiddlewares.expressJson ||\n express.json(arkosConfig?.jsonBodyParserOptions)\n );\n\n if (!disabledMiddlewares?.includes?.(\"cookie-parser\"))\n app.use(\n replacedMiddlewares.cookieParser ||\n cookieParser(...[...(arkosConfig?.cookieParserParameters || [])])\n );\n\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 if (!disabledMiddlewares?.includes?.(\"request-logger\"))\n app.use(replacedMiddlewares.requestLogger || handleRequestLogs);\n\n if (arkosConfig?.middlewares?.additional)\n arkosConfig.middlewares.additional.forEach((middleware) => {\n app.use(middleware);\n });\n\n const routersConfig = arkosConfig?.routers;\n const disabledRouters = routersConfig?.disable || [];\n const replacedRouters = routersConfig?.replace || {};\n\n if (!disabledRouters?.includes?.(\"welcome-endpoint\"))\n app.get(\n \"/api\",\n replacedRouters.welcomeEndpoint ||\n ((_, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n })\n );\n\n if (!disabledRouters?.includes?.(\"file-upload\")) {\n const fileUploadRouter = replacedRouters.fileUpload\n ? await replacedRouters.fileUpload(arkosConfig)\n : await getFileUploadRouter(arkosConfig);\n knowModulesRouter.use(fileUploadRouter);\n }\n\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 knowModulesRouter.use(\"/api\", authRouter);\n }\n\n if (!disabledRouters?.includes?.(\"prisma-models-router\")) {\n const modelsRouter = replacedRouters.prismaModelsRouter\n ? await replacedRouters.prismaModelsRouter(arkosConfig)\n : await getPrismaModelsRouter(arkosConfig);\n knowModulesRouter.use(\"/api\", modelsRouter);\n }\n\n app.use(knowModulesRouter);\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n if (\n arkosConfig.swagger &&\n (process.env.ARKOS_BUILD !== \"true\" ||\n arkosConfig.swagger.enableAfterBuild === true)\n )\n app.use(\"/api\", await getSwaggerRouter(arkosConfig));\n\n if (routersConfig?.additional)\n routersConfig.additional.forEach((router) => {\n app.use(router);\n });\n\n app.use(\"*\", (req) => {\n throw new AppError(\n \"Route not found\",\n 404,\n { route: req.route },\n \"RouteNotFound\"\n );\n });\n\n if (!disabledMiddlewares?.includes?.(\"global-error-handler\"))\n app.use(replacedMiddlewares.globalErrorHandler || errorHandler);\n\n return app;\n}\n"]}
@@ -89,7 +89,8 @@ function processAuthenticationMiddlewares(action, modelName, authConfigs) {
89
89
  const authenticationControl = authConfigs?.authenticationControl;
90
90
  if ((authenticationControl &&
91
91
  typeof authenticationControl === "object" &&
92
- authenticationControl[action] === true) ||
92
+ (authenticationControl[action] === true ||
93
+ authenticationControl[action] !== false)) ||
93
94
  authenticationControl === true ||
94
95
  (!authenticationControl && authenticationControl !== false))
95
96
  return [
@@ -1 +1 @@
1
- {"version":3,"file":"base.router.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.router.helpers.ts"],"names":[],"mappings":";;;;;AAyBA,oCA6PC;AAED,4EAwBC;AAED,gDAYC;AAED,0DAWC;AA1UD,0DAAkC;AAElC,qDAAsD;AAOtD,qEAAuE;AACvE,8EAAqD;AACrD,2DAAuD;AACvD,6DAIgC;AAChC,+EAA8E;AAC9E,2EAAkD;AAClD,qEAA4E;AAC5E,yGAA+E;AAC/E,0FAAiE;AAG1D,KAAK,UAAU,YAAY,CAAC,MAAc,EAAE,YAAyB;IAC1E,OAAO,8BAAkB,CAAC,yBAAyB,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QACxE,MAAM,gBAAgB,GAAG,IAAA,iBAAS,EAAC,KAAK,CAAC,CAAC;QAC1C,MAAM,YAAY,GAAG,IAAA,oCAAmB,EAAC,gBAAgB,CAAC,IAAI,EAAE,CAAC;QAEjE,MAAM,EACJ,YAAY,EACZ,WAAW,EACX,kBAAkB,EAClB,MAAM,EAAE,kBAAkB,EAC1B,IAAI,EACJ,OAAO,GACR,GAAG,YAAY,CAAC;QAEjB,MAAM,SAAS,GAAG,mBAAS,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC;QACrD,MAAM,UAAU,GAAG,IAAI,gCAAc,CAAC,KAAK,CAAC,CAAC;QAE7C,MAAM,YAAY,GAAsB,kBAAkB,EAAE,MAAM,IAAI,EAAE,CAAC;QAEzE,MAAM,YAAY,GAAG,kBAAkB,EAAE,OAAiB,CAAC;QAC3D,MAAM,uBAAuB,GAAG,CAAC,IAAY,EAAE,MAAc,EAAE,EAAE;YAC/D,OAAO,YAAY,EAAE,KAAK,EAAE,IAAI,CAC9B,CAAC,KAAK,EAAE,EAAE,CACR,CAAC,KAAK,CAAC,IAAI,KAAK,QAAQ,IAAI,EAAE;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,CAAC;AACd,CAAC","sourcesContent":["import { Router } from \"express\";\nimport pluralize from \"pluralize\";\nimport { ArkosConfig, RouterConfig } from \"../../../../exports\";\nimport { kebabCase } from \"../../../../exports/utils\";\nimport { PrismaQueryOptions } from \"../../../../types\";\nimport {\n AuthRouterEndpoint,\n FileUploadRouterEndpoint,\n RouterEndpoint,\n} from \"../../../../types/router-config\";\nimport { getModuleComponents } from \"../../../../utils/dynamic-loader\";\nimport authService from \"../../../auth/auth.service\";\nimport { BaseController } from \"../../base.controller\";\nimport {\n addPrismaQueryOptionsToRequest,\n handleRequestBodyValidationAndTransformation,\n sendResponse,\n} from \"../../base.middlewares\";\nimport { processMiddleware } from \"../../../../utils/helpers/routers.helpers\";\nimport routerValidator from \"../router-validator\";\nimport { getUserFileExtension } from \"../../../../utils/helpers/fs.helpers\";\nimport prismaSchemaParser from \"../../../../utils/prisma/prisma-schema-parser\";\nimport debuggerService from \"../../../debugger/debugger.service\";\nimport { AccessAction, AuthConfigs } from \"../../../../types/auth\";\n\nexport async function setupRouters(router: Router, arkosConfigs: ArkosConfig) {\n return prismaSchemaParser.getModelsAsArrayOfStrings().map(async (model) => {\n const modelNameInKebab = kebabCase(model);\n const modelModules = getModuleComponents(modelNameInKebab) || {};\n\n const {\n interceptors,\n authConfigs,\n prismaQueryOptions,\n router: customRouterModule,\n dtos,\n schemas,\n } = modelModules;\n\n const routeName = pluralize.plural(modelNameInKebab);\n const controller = new BaseController(model);\n\n const routerConfig: RouterConfig<any> = customRouterModule?.config || {};\n\n const customRouter = customRouterModule?.default as Router;\n const hasCustomImplementation = (path: string, method: string) => {\n return customRouter?.stack?.some(\n (layer) =>\n (layer.path === `/api/${path}` ||\n layer.path === `api/${path}` ||\n layer.path === `api/${path}/` ||\n layer.path === `/api/${path}/`) &&\n layer.method.toLowerCase() === method.toLowerCase()\n );\n };\n\n const getValidationSchemaOrDto = (key: \"create\" | \"update\") => {\n const validationConfigs = arkosConfigs?.validation;\n if (validationConfigs?.resolver === \"class-validator\") {\n return dtos?.[key];\n } else if (validationConfigs?.resolver === \"zod\") {\n return schemas?.[key];\n }\n return undefined;\n };\n\n if (customRouter && customRouterModule) {\n if (routerValidator.isExpressRouter(customRouter))\n router.use(`/${routeName}`, customRouter);\n else\n throw Error(\n `ValidationError: The exported router from ${modelNameInKebab}.router.${getUserFileExtension()} is not a valid express Router.`\n );\n }\n\n if (\n !isEndpointDisabled(routerConfig, \"createOne\") &&\n !hasCustomImplementation(`/${routeName}`, \"post\")\n ) {\n router.post(\n `/${routeName}`,\n ...processAuthenticationMiddlewares(\n \"Create\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"create\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createOne\"\n ),\n ...processMiddleware(interceptors?.beforeCreateOne),\n controller.createOne,\n ...processMiddleware(interceptors?.afterCreateOne),\n sendResponse,\n ...processMiddleware(interceptors?.onCreateOneError, { type: \"error\" })\n );\n }\n\n // GET /{routeName} - Find Many\n if (\n !isEndpointDisabled(routerConfig, \"findMany\") &&\n !hasCustomImplementation(`/${routeName}`, \"get\")\n ) {\n router.get(\n `/${routeName}`,\n ...processAuthenticationMiddlewares(\n \"View\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findMany\"\n ),\n\n ...processMiddleware(interceptors?.beforeFindMany),\n controller.findMany,\n ...processMiddleware(interceptors?.afterFindMany),\n sendResponse,\n ...processMiddleware(interceptors?.onFindManyError, { type: \"error\" })\n );\n }\n\n // POST /{routeName}/many - Create Many\n if (\n !isEndpointDisabled(routerConfig, \"createMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"post\")\n ) {\n router.post(\n `/${routeName}/many`,\n ...processAuthenticationMiddlewares(\n \"Create\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"create\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createMany\"\n ),\n\n ...processMiddleware(interceptors?.beforeCreateMany),\n controller.createMany,\n ...processMiddleware(interceptors?.afterCreateMany),\n sendResponse,\n ...processMiddleware(interceptors?.onCreateManyError, { type: \"error\" })\n );\n }\n\n // PATCH /{routeName}/many - Update Many\n if (\n !isEndpointDisabled(routerConfig, \"updateMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/many`,\n ...processAuthenticationMiddlewares(\n \"Update\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateMany\"\n ),\n ...processMiddleware(interceptors?.beforeUpdateMany),\n controller.updateMany,\n ...processMiddleware(interceptors?.afterUpdateMany),\n sendResponse,\n ...processMiddleware(interceptors?.onUpdateManyError, { type: \"error\" })\n );\n }\n\n // DELETE /{routeName}/many - Delete Many\n if (\n !isEndpointDisabled(routerConfig, \"deleteMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/many`,\n ...processAuthenticationMiddlewares(\n \"Delete\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteMany\"\n ),\n ...processMiddleware(interceptors?.beforeDeleteMany),\n controller.deleteMany,\n ...processMiddleware(interceptors?.afterDeleteMany),\n sendResponse,\n ...processMiddleware(interceptors?.onDeleteManyError, { type: \"error\" })\n );\n }\n\n if (\n !isEndpointDisabled(routerConfig, \"findOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"get\")\n ) {\n router.get(\n `/${routeName}/:id`,\n ...processAuthenticationMiddlewares(\n \"View\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findOne\"\n ),\n ...processMiddleware(interceptors?.beforeFindOne),\n controller.findOne,\n ...processMiddleware(interceptors?.afterFindOne),\n sendResponse,\n ...processMiddleware(interceptors?.onFindOneError, { type: \"error\" })\n );\n }\n\n // PATCH /{routeName}/:id - Update One\n if (\n !isEndpointDisabled(routerConfig, \"updateOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/:id`,\n ...processAuthenticationMiddlewares(\n \"Update\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"update\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateOne\"\n ),\n ...processMiddleware(interceptors?.beforeUpdateOne),\n controller.updateOne,\n ...processMiddleware(interceptors?.afterUpdateOne),\n sendResponse,\n ...processMiddleware(interceptors?.onUpdateOneError, { type: \"error\" })\n );\n }\n\n // DELETE /{routeName}/:id - Delete One\n if (\n !isEndpointDisabled(routerConfig, \"deleteOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/:id`,\n ...processAuthenticationMiddlewares(\n \"Delete\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteOne\"\n ),\n ...processMiddleware(interceptors?.beforeDeleteOne),\n controller.deleteOne,\n ...processMiddleware(interceptors?.afterDeleteOne),\n sendResponse,\n ...processMiddleware(interceptors?.onDeleteOneError, { type: \"error\" })\n );\n }\n\n debuggerService.logModuleFinalRouter(modelNameInKebab, router);\n });\n}\n\nexport function processAuthenticationMiddlewares(\n action: AccessAction,\n modelName: string,\n authConfigs?: AuthConfigs\n) {\n const authenticationControl = authConfigs?.authenticationControl;\n\n if (\n (authenticationControl &&\n typeof authenticationControl === \"object\" &&\n authenticationControl[action] === true) ||\n authenticationControl === true ||\n (!authenticationControl && authenticationControl !== false)\n )\n return [\n authService.authenticate,\n authService.handleAccessControl(\n action,\n kebabCase(pluralize.singular(modelName)),\n authConfigs?.accessControl\n ),\n ];\n\n return [];\n}\n\nexport function isEndpointDisabled(\n routerConfig: RouterConfig<any>,\n endpoint: RouterEndpoint | AuthRouterEndpoint | FileUploadRouterEndpoint\n): boolean {\n if (!routerConfig?.disable) return false;\n\n if (routerConfig.disable === true) return true;\n\n if (typeof routerConfig.disable === \"object\")\n return routerConfig.disable[endpoint as never] === true;\n\n return false;\n}\n\nexport function isParentEndpointAllowed(\n routerConfig: any,\n endpoint: string\n): boolean {\n if (!routerConfig?.parent) return false;\n\n const parentEndpoints = routerConfig.parent.endpoints;\n if (parentEndpoints === \"*\") return true;\n if (Array.isArray(parentEndpoints)) return parentEndpoints.includes(endpoint);\n\n return true;\n}\n"]}
1
+ {"version":3,"file":"base.router.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.router.helpers.ts"],"names":[],"mappings":";;;;;AAyBA,oCA6PC;AAED,4EAyBC;AAED,gDAYC;AAED,0DAWC;AA3UD,0DAAkC;AAElC,qDAAsD;AAOtD,qEAAuE;AACvE,8EAAqD;AACrD,2DAAuD;AACvD,6DAIgC;AAChC,+EAA8E;AAC9E,2EAAkD;AAClD,qEAA4E;AAC5E,yGAA+E;AAC/E,0FAAiE;AAG1D,KAAK,UAAU,YAAY,CAAC,MAAc,EAAE,YAAyB;IAC1E,OAAO,8BAAkB,CAAC,yBAAyB,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QACxE,MAAM,gBAAgB,GAAG,IAAA,iBAAS,EAAC,KAAK,CAAC,CAAC;QA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,EAAE,CAAC;AACZ,CAAC;AAED,SAAgB,kBAAkB,CAChC,YAA+B,EAC/B,QAAwE;IAExE,IAAI,CAAC,YAAY,EAAE,OAAO;QAAE,OAAO,KAAK,CAAC;IAEzC,IAAI,YAAY,CAAC,OAAO,KAAK,IAAI;QAAE,OAAO,IAAI,CAAC;IAE/C,IAAI,OAAO,YAAY,CAAC,OAAO,KAAK,QAAQ;QAC1C,OAAO,YAAY,CAAC,OAAO,CAAC,QAAiB,CAAC,KAAK,IAAI,CAAC;IAE1D,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAgB,uBAAuB,CACrC,YAAiB,EACjB,QAAgB;IAEhB,IAAI,CAAC,YAAY,EAAE,MAAM;QAAE,OAAO,KAAK,CAAC;IAExC,MAAM,eAAe,GAAG,YAAY,CAAC,MAAM,CAAC,SAAS,CAAC;IACtD,IAAI,eAAe,KAAK,GAAG;QAAE,OAAO,IAAI,CAAC;IACzC,IAAI,KAAK,CAAC,OAAO,CAAC,eAAe,CAAC;QAAE,OAAO,eAAe,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;IAE9E,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { Router } from \"express\";\nimport pluralize from \"pluralize\";\nimport { ArkosConfig, RouterConfig } from \"../../../../exports\";\nimport { kebabCase } from \"../../../../exports/utils\";\nimport { PrismaQueryOptions } from \"../../../../types\";\nimport {\n AuthRouterEndpoint,\n FileUploadRouterEndpoint,\n RouterEndpoint,\n} from \"../../../../types/router-config\";\nimport { getModuleComponents } from \"../../../../utils/dynamic-loader\";\nimport authService from \"../../../auth/auth.service\";\nimport { BaseController } from \"../../base.controller\";\nimport {\n addPrismaQueryOptionsToRequest,\n handleRequestBodyValidationAndTransformation,\n sendResponse,\n} from \"../../base.middlewares\";\nimport { processMiddleware } from \"../../../../utils/helpers/routers.helpers\";\nimport routerValidator from \"../router-validator\";\nimport { getUserFileExtension } from \"../../../../utils/helpers/fs.helpers\";\nimport prismaSchemaParser from \"../../../../utils/prisma/prisma-schema-parser\";\nimport debuggerService from \"../../../debugger/debugger.service\";\nimport { AccessAction, AuthConfigs } from \"../../../../types/auth\";\n\nexport async function setupRouters(router: Router, arkosConfigs: ArkosConfig) {\n return prismaSchemaParser.getModelsAsArrayOfStrings().map(async (model) => {\n const modelNameInKebab = kebabCase(model);\n const modelModules = getModuleComponents(modelNameInKebab) || {};\n\n const {\n interceptors,\n authConfigs,\n prismaQueryOptions,\n router: customRouterModule,\n dtos,\n schemas,\n } = modelModules;\n\n const routeName = pluralize.plural(modelNameInKebab);\n const controller = new BaseController(model);\n\n const routerConfig: RouterConfig<any> = customRouterModule?.config || {};\n\n const customRouter = customRouterModule?.default as Router;\n const hasCustomImplementation = (path: string, method: string) => {\n return customRouter?.stack?.some(\n (layer) =>\n (layer.path === `/api/${path}` ||\n layer.path === `api/${path}` ||\n layer.path === `api/${path}/` ||\n layer.path === `/api/${path}/`) &&\n layer.method.toLowerCase() === method.toLowerCase()\n );\n };\n\n const getValidationSchemaOrDto = (key: \"create\" | \"update\") => {\n const validationConfigs = arkosConfigs?.validation;\n if (validationConfigs?.resolver === \"class-validator\") {\n return dtos?.[key];\n } else if (validationConfigs?.resolver === \"zod\") {\n return schemas?.[key];\n }\n return undefined;\n };\n\n if (customRouter && customRouterModule) {\n if (routerValidator.isExpressRouter(customRouter))\n router.use(`/${routeName}`, customRouter);\n else\n throw Error(\n `ValidationError: The exported router from ${modelNameInKebab}.router.${getUserFileExtension()} is not a valid express Router.`\n );\n }\n\n if (\n !isEndpointDisabled(routerConfig, \"createOne\") &&\n !hasCustomImplementation(`/${routeName}`, \"post\")\n ) {\n router.post(\n `/${routeName}`,\n ...processAuthenticationMiddlewares(\n \"Create\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"create\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createOne\"\n ),\n ...processMiddleware(interceptors?.beforeCreateOne),\n controller.createOne,\n ...processMiddleware(interceptors?.afterCreateOne),\n sendResponse,\n ...processMiddleware(interceptors?.onCreateOneError, { type: \"error\" })\n );\n }\n\n // GET /{routeName} - Find Many\n if (\n !isEndpointDisabled(routerConfig, \"findMany\") &&\n !hasCustomImplementation(`/${routeName}`, \"get\")\n ) {\n router.get(\n `/${routeName}`,\n ...processAuthenticationMiddlewares(\n \"View\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findMany\"\n ),\n\n ...processMiddleware(interceptors?.beforeFindMany),\n controller.findMany,\n ...processMiddleware(interceptors?.afterFindMany),\n sendResponse,\n ...processMiddleware(interceptors?.onFindManyError, { type: \"error\" })\n );\n }\n\n // POST /{routeName}/many - Create Many\n if (\n !isEndpointDisabled(routerConfig, \"createMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"post\")\n ) {\n router.post(\n `/${routeName}/many`,\n ...processAuthenticationMiddlewares(\n \"Create\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"create\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createMany\"\n ),\n\n ...processMiddleware(interceptors?.beforeCreateMany),\n controller.createMany,\n ...processMiddleware(interceptors?.afterCreateMany),\n sendResponse,\n ...processMiddleware(interceptors?.onCreateManyError, { type: \"error\" })\n );\n }\n\n // PATCH /{routeName}/many - Update Many\n if (\n !isEndpointDisabled(routerConfig, \"updateMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/many`,\n ...processAuthenticationMiddlewares(\n \"Update\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateMany\"\n ),\n ...processMiddleware(interceptors?.beforeUpdateMany),\n controller.updateMany,\n ...processMiddleware(interceptors?.afterUpdateMany),\n sendResponse,\n ...processMiddleware(interceptors?.onUpdateManyError, { type: \"error\" })\n );\n }\n\n // DELETE /{routeName}/many - Delete Many\n if (\n !isEndpointDisabled(routerConfig, \"deleteMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/many`,\n ...processAuthenticationMiddlewares(\n \"Delete\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteMany\"\n ),\n ...processMiddleware(interceptors?.beforeDeleteMany),\n controller.deleteMany,\n ...processMiddleware(interceptors?.afterDeleteMany),\n sendResponse,\n ...processMiddleware(interceptors?.onDeleteManyError, { type: \"error\" })\n );\n }\n\n if (\n !isEndpointDisabled(routerConfig, \"findOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"get\")\n ) {\n router.get(\n `/${routeName}/:id`,\n ...processAuthenticationMiddlewares(\n \"View\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findOne\"\n ),\n ...processMiddleware(interceptors?.beforeFindOne),\n controller.findOne,\n ...processMiddleware(interceptors?.afterFindOne),\n sendResponse,\n ...processMiddleware(interceptors?.onFindOneError, { type: \"error\" })\n );\n }\n\n // PATCH /{routeName}/:id - Update One\n if (\n !isEndpointDisabled(routerConfig, \"updateOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/:id`,\n ...processAuthenticationMiddlewares(\n \"Update\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"update\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateOne\"\n ),\n ...processMiddleware(interceptors?.beforeUpdateOne),\n controller.updateOne,\n ...processMiddleware(interceptors?.afterUpdateOne),\n sendResponse,\n ...processMiddleware(interceptors?.onUpdateOneError, { type: \"error\" })\n );\n }\n\n // DELETE /{routeName}/:id - Delete One\n if (\n !isEndpointDisabled(routerConfig, \"deleteOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/:id`,\n ...processAuthenticationMiddlewares(\n \"Delete\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteOne\"\n ),\n ...processMiddleware(interceptors?.beforeDeleteOne),\n controller.deleteOne,\n ...processMiddleware(interceptors?.afterDeleteOne),\n sendResponse,\n ...processMiddleware(interceptors?.onDeleteOneError, { type: \"error\" })\n );\n }\n\n debuggerService.logModuleFinalRouter(modelNameInKebab, router);\n });\n}\n\nexport function processAuthenticationMiddlewares(\n action: AccessAction,\n modelName: string,\n authConfigs?: AuthConfigs\n) {\n const authenticationControl = authConfigs?.authenticationControl;\n\n if (\n (authenticationControl &&\n typeof authenticationControl === \"object\" &&\n (authenticationControl[action] === true ||\n authenticationControl[action] !== false)) ||\n authenticationControl === true ||\n (!authenticationControl && authenticationControl !== false)\n )\n return [\n authService.authenticate,\n authService.handleAccessControl(\n action,\n kebabCase(pluralize.singular(modelName)),\n authConfigs?.accessControl\n ),\n ];\n\n return [];\n}\n\nexport function isEndpointDisabled(\n routerConfig: RouterConfig<any>,\n endpoint: RouterEndpoint | AuthRouterEndpoint | FileUploadRouterEndpoint\n): boolean {\n if (!routerConfig?.disable) return false;\n\n if (routerConfig.disable === true) return true;\n\n if (typeof routerConfig.disable === \"object\")\n return routerConfig.disable[endpoint as never] === true;\n\n return false;\n}\n\nexport function isParentEndpointAllowed(\n routerConfig: any,\n endpoint: string\n): boolean {\n if (!routerConfig?.parent) return false;\n\n const parentEndpoints = routerConfig.parent.endpoints;\n if (parentEndpoints === \"*\") return true;\n if (Array.isArray(parentEndpoints)) return parentEndpoints.includes(endpoint);\n\n return true;\n}\n"]}
@@ -40,9 +40,13 @@ function errorHandler(err, req, res, _) {
40
40
  console.error("[\x1b[31mError\x1b[0m]:", err);
41
41
  err.statusCode = err.statusCode || 500;
42
42
  err.status = err.status || "error";
43
- let error = err;
44
- if (process.env.NODE_ENV === "production")
45
- error = { ...err, message: err.message };
43
+ let error = {
44
+ ...err,
45
+ message: err.message,
46
+ stack: err?.stack || undefined,
47
+ };
48
+ if (process.env.NODE_ENV == "production")
49
+ delete error?.stack;
46
50
  if (err.name === "JsonWebTokenError")
47
51
  error = errorControllerHelper.handleJWTError();
48
52
  if (err.name === "TokenExpiredError")
@@ -82,7 +86,7 @@ function errorHandler(err, req, res, _) {
82
86
  if (err.name === "NetworkError")
83
87
  error = errorControllerHelper.handleNetworkError(err);
84
88
  if (process.env.NODE_ENV !== "production")
85
- return sendDevelopmentError(error, req, res);
89
+ return sendDevelopmentError({ ...error, originalError: err }, req, res);
86
90
  sendProductionError(error, req, res);
87
91
  }
88
92
  function sendDevelopmentError(err, req, res) {
@@ -110,7 +114,9 @@ function sendProductionError(err, req, res) {
110
114
  else
111
115
  res.status(500).json({
112
116
  status: "error",
113
- message: "Internal server error",
117
+ message: "Internal server error, please try again later.",
118
+ code: "Unknown",
119
+ meta: {},
114
120
  });
115
121
  return;
116
122
  }
@@ -118,12 +124,13 @@ function sendProductionError(err, req, res) {
118
124
  res.status(err.statusCode).json({
119
125
  title: "Internal server error",
120
126
  message: err.message,
127
+ code: "Unknown",
121
128
  });
122
129
  return;
123
130
  }
124
131
  res.status(err.statusCode).json({
125
132
  title: "Internal server error",
126
- message: "Please try again later.",
133
+ message: "Internal server error, please try again later.",
127
134
  });
128
135
  }
129
136
  process.on("SIGTERM", () => {
@@ -1 +1 @@
1
- {"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,+BA6DC;AA/ED,qFAAuE;AACvE,yCAAsC;AAiBtC,SAAwB,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,CAAe;IAEf,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;IAE9C,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,IAAI,GAAG,CAAC;IACvC,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,OAAO,CAAC;IAEnC,IAAI,KAAK,GAAG,GAAG,CAAC;IAEhB,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY;QACvC,KAAK,GAAG,EAAE,GAAG,GAAG,EAAE,OAAO,EAAE,GAAG,CAAC,OAAO,EAAE,CAAC;IAE3C,IAAI,GAAG,CAAC,IAAI,KAAK,mBAAmB;QAClC,KAAK,GAAG,qBAAqB,CAAC,cAAc,EAAE,CAAC;IACjD,IAAI,GAAG,CAAC,IAAI,KAAK,mBAAmB;QAClC,KAAK,GAAG,qBAAqB,CAAC,gBAAgB,EAAE,CAAC;IAEnD,IAAI,GAAG,CAAC,IAAI,KAAK,6BAA6B;QAC5C,KAAK,GAAG,qBAAqB,CAAC,iCAAiC,CAAC,GAAG,CAAC,CAAC;IACvE,IAAI,GAAG,CAAC,IAAI,KAAK,iCAAiC;QAChD,KAAK,GAAG,qBAAqB,CAAC,qCAAqC,CAAC,GAAG,CAAC,CAAC;IAC3E,IAAI,GAAG,CAAC,IAAI,KAAK,OAAO;QACtB,KAAK,GAAG,qBAAqB,CAAC,yBAAyB,CAAC,GAAG,CAAC,CAAC;IAC/D,IAAI,GAAG,CAAC,IAAI,KAAK,OAAO;QACtB,KAAK,GAAG,qBA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"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} _ - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n _: NextFunction\n): void {\n console.error(\"[\\x1b[31mError\\x1b[0m]:\", err);\n\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n let error = err;\n\n if (process.env.NODE_ENV === \"production\")\n error = { ...err, message: err.message };\n\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n if (err.name === \"PrismaClientInitializationError\")\n error = errorControllerHelper.handlePrismaClientInitializationError(err);\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"P2025\")\n error = errorControllerHelper.handleNonExistingRecord(err);\n if (err.code === \"P3000\")\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n if (err.code === \"P3001\")\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n if (err.code === \"P3002\")\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n if (err.code === \"P3003\")\n error = errorControllerHelper.handleVersionMismatchError(err);\n\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n\n if (process.env.NODE_ENV !== \"production\")\n return sendDevelopmentError(error, req, res);\n\n sendProductionError(error, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(\n err: AppError,\n req: Request,\n res: Response\n): void {\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n ...err,\n message: err.message.split(\"\\n\")[err.message.split(\"\\n\").length - 1],\n stack: err.stack?.split(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"Unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Internal server error\",\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: \"Please try again later.\",\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (\n process.env.NODE_ENV !== \"production\" &&\n process.env.NODE_ENV !== \"staging\"\n ) {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
1
+ {"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,+BAgEC;AAlFD,qFAAuE;AACvE,yCAAsC;AAiBtC,SAAwB,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,CAAe;IAEf,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;IAE9C,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,IAAI,GAAG,CAAC;IACvC,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,OAAO,CAAC;IAEnC,IAAI,KAAK,GAAQ;QACf,GAAG,GAAG;QACN,OAAO,EAAE,GAAG,CAAC,OAAO;QACpB,KAAK,EAAE,GAAG,EAAE,KAAK,IAAI,SAAS;KAC/B,CAAC;IAEF,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,IAAI,YAAY;QAAE,OAAO,KAAK,EAAE,KAAK,CAAC;IAE9D,IAAI,GAAG,CAAC,IAAI,KAAK,mBAAmB;QAClC,KAAK,GAAG,qBAAqB,CAAC,cAAc,EAAE,CAAC;IACjD,IAAI,GAAG,CAAC,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AAC;QAC9B,KAAK,EAAE,uBAAuB;QAC9B,OAAO,EAAE,gDAAgD;KAC1D,CAAC,CAAC;AACL,CAAC;AAWD,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;IACzB,IACE,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY;QACrC,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,SAAS,EAClC,CAAC;QACD,OAAO,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,KAAK,CAAC,2DAA2D,CAAC,CAAC;QAE3E,eAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;YACvC,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} _ - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n _: NextFunction\n): void {\n console.error(\"[\\x1b[31mError\\x1b[0m]:\", err);\n\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n let error: any = {\n ...err,\n message: err.message,\n stack: err?.stack || undefined,\n };\n\n if (process.env.NODE_ENV == \"production\") delete error?.stack;\n\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n if (err.name === \"PrismaClientInitializationError\")\n error = errorControllerHelper.handlePrismaClientInitializationError(err);\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"P2025\")\n error = errorControllerHelper.handleNonExistingRecord(err);\n if (err.code === \"P3000\")\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n if (err.code === \"P3001\")\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n if (err.code === \"P3002\")\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n if (err.code === \"P3003\")\n error = errorControllerHelper.handleVersionMismatchError(err);\n\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n\n if (process.env.NODE_ENV !== \"production\")\n return sendDevelopmentError({ ...error, originalError: err }, req, res);\n\n sendProductionError(error, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(err: any, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n ...err,\n message: err.message.split(\"\\n\")[err.message.split(\"\\n\").length - 1],\n stack: err.stack?.split(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"Unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Internal server error, please try again later.\",\n code: \"Unknown\",\n meta: {},\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n code: \"Unknown\",\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: \"Internal server error, please try again later.\",\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (\n process.env.NODE_ENV !== \"production\" &&\n process.env.NODE_ENV !== \"staging\"\n ) {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
@@ -19,6 +19,6 @@ function killServerChildProcess() {
19
19
  (0, start_1.killProductionServerChildProcess)();
20
20
  }
21
21
  function getVersion() {
22
- return "1.3.6-canary.1";
22
+ return "1.3.6-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aAAa,EAAE,UAAU;QAC3B,aAAa,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;YAC1C,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAClB,CAAC,CAAC,CAAC;IAEL,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,EAAE;QACnB,MAAM,IAAI,QAAQ,CAChB,iBAAiB,EACjB,GAAG,EACH,EAAE,KAAK,EAAE,GAAG,CAAC,KAAK,EAAE,EACpB,eAAe,CAChB,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,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, { NextFunction, Router } 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 { loadPrismaModule } from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploadRouter } from \"./modules/file-upload/file-upload.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\";\nimport { loadAllModuleComponents } from \"./utils/dynamic-loader\";\nimport { AppError } from \"./exports/error-handler\";\nimport debuggerService from \"./modules/debugger/debugger.service\";\n\nexport const app: express.Express = express();\nconst knowModulesRouter = Router();\n\nexport async function bootstrap(\n arkosConfig: ArkosConfig\n): Promise<express.Express> {\n await Promise.all([\n loadPrismaModule(),\n loadAllModuleComponents(arkosConfig),\n arkosConfig?.configureApp && (await arkosConfig?.configureApp(app)),\n ]);\n\n const middlewaresConfig = arkosConfig?.middlewares;\n const disabledMiddlewares = middlewaresConfig?.disable || [];\n const replacedMiddlewares = middlewaresConfig?.replace || {};\n\n app.use(debuggerService.logLevel2RequestInfo);\n\n if (!disabledMiddlewares?.includes?.(\"compression\"))\n app.use(\n replacedMiddlewares.compression ||\n compression(arkosConfig?.compressionOptions)\n );\n\n if (!disabledMiddlewares?.includes?.(\"global-rate-limit\"))\n app.use(\n replacedMiddlewares.globalRateLimit ||\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 500,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n handler: (_, res) => {\n res.status(429).json({\n message: \"Too many requests, please try again later\",\n });\n },\n },\n arkosConfig?.globalRequestRateLimitOptions || {}\n )\n )\n );\n\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 if (!disabledMiddlewares?.includes?.(\"express-json\"))\n app.use(\n replacedMiddlewares.expressJson ||\n express.json(arkosConfig?.jsonBodyParserOptions)\n );\n\n if (!disabledMiddlewares?.includes?.(\"cookie-parser\"))\n app.use(\n replacedMiddlewares.cookieParser ||\n cookieParser(...[...(arkosConfig?.cookieParserParameters || [])])\n );\n\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 if (!disabledMiddlewares?.includes?.(\"request-logger\"))\n app.use(replacedMiddlewares.requestLogger || handleRequestLogs);\n\n if (arkosConfig?.middlewares?.additional)\n arkosConfig.middlewares.additional.forEach((middleware) => {\n app.use(middleware);\n });\n\n const routersConfig = arkosConfig?.routers;\n const disabledRouters = routersConfig?.disable || [];\n const replacedRouters = routersConfig?.replace || {};\n\n if (!disabledRouters?.includes?.(\"welcome-endpoint\"))\n app.get(\n \"/api\",\n replacedRouters.welcomeEndpoint ||\n ((_, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n })\n );\n\n if (!disabledRouters?.includes?.(\"file-upload\")) {\n const fileUploadRouter = replacedRouters.fileUpload\n ? await replacedRouters.fileUpload(arkosConfig)\n : await getFileUploadRouter(arkosConfig);\n knowModulesRouter.use(fileUploadRouter);\n }\n\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 knowModulesRouter.use(\"/api\", authRouter);\n }\n\n if (!disabledRouters?.includes?.(\"prisma-models-router\")) {\n const modelsRouter = replacedRouters.prismaModelsRouter\n ? await replacedRouters.prismaModelsRouter(arkosConfig)\n : await getPrismaModelsRouter(arkosConfig);\n knowModulesRouter.use(\"/api\", modelsRouter);\n }\n\n app.use(knowModulesRouter);\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n if (\n arkosConfig.swagger &&\n (process.env.ARKOS_BUILD !== \"true\" ||\n arkosConfig.swagger.enableAfterBuild === true)\n )\n app.use(\"/api\", await getSwaggerRouter(arkosConfig));\n\n if (routersConfig?.additional)\n routersConfig.additional.forEach((router) => {\n app.use(router);\n });\n\n app.use(\"*\", (req) => {\n throw new AppError(\n \"Route not found\",\n 404,\n { route: req.route },\n \"RouteNotFound\"\n );\n });\n\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,EAAE,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAC1C,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,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAClE,OAAO,EAAE,mBAAmB,EAAE,MAAM,0CAA0C,CAAC;AAE/E,OAAO,EAAE,WAAW,EAAE,MAAM,sCAAsC,CAAC;AACnE,OAAO,SAAS,MAAM,kCAAkC,CAAC;AACzD,OAAO,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AACpE,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AACnD,OAAO,eAAe,MAAM,qCAAqC,CAAC;AAElE,MAAM,CAAC,MAAM,GAAG,GAAoB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,CAAC;IAExD,IACE,WAAW,CAAC,OAAO;QACnB,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM;YACjC,WAAW,CAAC,OAAO,CAAC,gBAAgB,KAAK,IAAI,CAAC;QAEhD,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,gBAAgB,CAAC,WAAW,CAAC,CAAC,CAAC;IAEvD,IAAI,aAAa,EAAE,UAAU;QAC3B,aAAa,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;YAC1C,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAClB,CAAC,CAAC,CAAC;IAEL,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,EAAE;QACnB,MAAM,IAAI,QAAQ,CAChB,iBAAiB,EACjB,GAAG,EACH,EAAE,KAAK,EAAE,GAAG,CAAC,KAAK,EAAE,EACpB,eAAe,CAChB,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,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, { Router } 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 { loadPrismaModule } from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploadRouter } from \"./modules/file-upload/file-upload.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\";\nimport { loadAllModuleComponents } from \"./utils/dynamic-loader\";\nimport { AppError } from \"./exports/error-handler\";\nimport debuggerService from \"./modules/debugger/debugger.service\";\n\nexport const app: express.Express = express();\nconst knowModulesRouter = Router();\n\nexport async function bootstrap(\n arkosConfig: ArkosConfig\n): Promise<express.Express> {\n await Promise.all([\n loadPrismaModule(),\n loadAllModuleComponents(arkosConfig),\n arkosConfig?.configureApp && (await arkosConfig?.configureApp(app)),\n ]);\n\n const middlewaresConfig = arkosConfig?.middlewares;\n const disabledMiddlewares = middlewaresConfig?.disable || [];\n const replacedMiddlewares = middlewaresConfig?.replace || {};\n\n app.use(debuggerService.logLevel2RequestInfo);\n\n if (!disabledMiddlewares?.includes?.(\"compression\"))\n app.use(\n replacedMiddlewares.compression ||\n compression(arkosConfig?.compressionOptions)\n );\n\n if (!disabledMiddlewares?.includes?.(\"global-rate-limit\"))\n app.use(\n replacedMiddlewares.globalRateLimit ||\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 500,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n handler: (_, res) => {\n res.status(429).json({\n message: \"Too many requests, please try again later\",\n });\n },\n },\n arkosConfig?.globalRequestRateLimitOptions || {}\n )\n )\n );\n\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 if (!disabledMiddlewares?.includes?.(\"express-json\"))\n app.use(\n replacedMiddlewares.expressJson ||\n express.json(arkosConfig?.jsonBodyParserOptions)\n );\n\n if (!disabledMiddlewares?.includes?.(\"cookie-parser\"))\n app.use(\n replacedMiddlewares.cookieParser ||\n cookieParser(...[...(arkosConfig?.cookieParserParameters || [])])\n );\n\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 if (!disabledMiddlewares?.includes?.(\"request-logger\"))\n app.use(replacedMiddlewares.requestLogger || handleRequestLogs);\n\n if (arkosConfig?.middlewares?.additional)\n arkosConfig.middlewares.additional.forEach((middleware) => {\n app.use(middleware);\n });\n\n const routersConfig = arkosConfig?.routers;\n const disabledRouters = routersConfig?.disable || [];\n const replacedRouters = routersConfig?.replace || {};\n\n if (!disabledRouters?.includes?.(\"welcome-endpoint\"))\n app.get(\n \"/api\",\n replacedRouters.welcomeEndpoint ||\n ((_, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n })\n );\n\n if (!disabledRouters?.includes?.(\"file-upload\")) {\n const fileUploadRouter = replacedRouters.fileUpload\n ? await replacedRouters.fileUpload(arkosConfig)\n : await getFileUploadRouter(arkosConfig);\n knowModulesRouter.use(fileUploadRouter);\n }\n\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 knowModulesRouter.use(\"/api\", authRouter);\n }\n\n if (!disabledRouters?.includes?.(\"prisma-models-router\")) {\n const modelsRouter = replacedRouters.prismaModelsRouter\n ? await replacedRouters.prismaModelsRouter(arkosConfig)\n : await getPrismaModelsRouter(arkosConfig);\n knowModulesRouter.use(\"/api\", modelsRouter);\n }\n\n app.use(knowModulesRouter);\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n if (\n arkosConfig.swagger &&\n (process.env.ARKOS_BUILD !== \"true\" ||\n arkosConfig.swagger.enableAfterBuild === true)\n )\n app.use(\"/api\", await getSwaggerRouter(arkosConfig));\n\n if (routersConfig?.additional)\n routersConfig.additional.forEach((router) => {\n app.use(router);\n });\n\n app.use(\"*\", (req) => {\n throw new AppError(\n \"Route not found\",\n 404,\n { route: req.route },\n \"RouteNotFound\"\n );\n });\n\n if (!disabledMiddlewares?.includes?.(\"global-error-handler\"))\n app.use(replacedMiddlewares.globalErrorHandler || errorHandler);\n\n return app;\n}\n"]}
@@ -80,7 +80,8 @@ export function processAuthenticationMiddlewares(action, modelName, authConfigs)
80
80
  const authenticationControl = authConfigs?.authenticationControl;
81
81
  if ((authenticationControl &&
82
82
  typeof authenticationControl === "object" &&
83
- authenticationControl[action] === true) ||
83
+ (authenticationControl[action] === true ||
84
+ authenticationControl[action] !== false)) ||
84
85
  authenticationControl === true ||
85
86
  (!authenticationControl && authenticationControl !== false))
86
87
  return [
@@ -1 +1 @@
1
- {"version":3,"file":"base.router.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.router.helpers.ts"],"names":[],"mappings":"AACA,OAAO,SAAS,MAAM,WAAW,CAAC;AAElC,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAOtD,OAAO,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AACvE,OAAO,WAAW,MAAM,4BAA4B,CAAC;AACrD,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EACL,8BAA8B,EAC9B,4CAA4C,EAC5C,YAAY,GACb,MAAM,wBAAwB,CAAC;AA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S,CAAC,CAAC,EACxC,WAAW,EAAE,aAAa,CAC3B;SACF,CAAC;IAEJ,OAAO,EAAE,CAAC;AACZ,CAAC;AAED,MAAM,UAAU,kBAAkB,CAChC,YAA+B,EAC/B,QAAwE;IAExE,IAAI,CAAC,YAAY,EAAE,OAAO;QAAE,OAAO,KAAK,CAAC;IAEzC,IAAI,YAAY,CAAC,OAAO,KAAK,IAAI;QAAE,OAAO,IAAI,CAAC;IAE/C,IAAI,OAAO,YAAY,CAAC,OAAO,KAAK,QAAQ;QAC1C,OAAO,YAAY,CAAC,OAAO,CAAC,QAAiB,CAAC,KAAK,IAAI,CAAC;IAE1D,OAAO,KAAK,CAAC;AACf,CAAC;AAED,MAAM,UAAU,uBAAuB,CACrC,YAAiB,EACjB,QAAgB;IAEhB,IAAI,CAAC,YAAY,EAAE,MAAM;QAAE,OAAO,KAAK,CAAC;IAExC,MAAM,eAAe,GAAG,YAAY,CAAC,MAAM,CAAC,SAAS,CAAC;IACtD,IAAI,eAAe,KAAK,GAAG;QAAE,OAAO,IAAI,CAAC;IACzC,IAAI,KAAK,CAAC,OAAO,CAAC,eAAe,CAAC;QAAE,OAAO,eAAe,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;IAE9E,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { Router } from \"express\";\nimport pluralize from \"pluralize\";\nimport { ArkosConfig, RouterConfig } from \"../../../../exports\";\nimport { kebabCase } from \"../../../../exports/utils\";\nimport { PrismaQueryOptions } from \"../../../../types\";\nimport {\n AuthRouterEndpoint,\n FileUploadRouterEndpoint,\n RouterEndpoint,\n} from \"../../../../types/router-config\";\nimport { getModuleComponents } from \"../../../../utils/dynamic-loader\";\nimport authService from \"../../../auth/auth.service\";\nimport { BaseController } from \"../../base.controller\";\nimport {\n addPrismaQueryOptionsToRequest,\n handleRequestBodyValidationAndTransformation,\n sendResponse,\n} from \"../../base.middlewares\";\nimport { processMiddleware } from \"../../../../utils/helpers/routers.helpers\";\nimport routerValidator from \"../router-validator\";\nimport { getUserFileExtension } from \"../../../../utils/helpers/fs.helpers\";\nimport prismaSchemaParser from \"../../../../utils/prisma/prisma-schema-parser\";\nimport debuggerService from \"../../../debugger/debugger.service\";\nimport { AccessAction, AuthConfigs } from \"../../../../types/auth\";\n\nexport async function setupRouters(router: Router, arkosConfigs: ArkosConfig) {\n return prismaSchemaParser.getModelsAsArrayOfStrings().map(async (model) => {\n const modelNameInKebab = kebabCase(model);\n const modelModules = getModuleComponents(modelNameInKebab) || {};\n\n const {\n interceptors,\n authConfigs,\n prismaQueryOptions,\n router: customRouterModule,\n dtos,\n schemas,\n } = modelModules;\n\n const routeName = pluralize.plural(modelNameInKebab);\n const controller = new BaseController(model);\n\n const routerConfig: RouterConfig<any> = customRouterModule?.config || {};\n\n const customRouter = customRouterModule?.default as Router;\n const hasCustomImplementation = (path: string, method: string) => {\n return customRouter?.stack?.some(\n (layer) =>\n (layer.path === `/api/${path}` ||\n layer.path === `api/${path}` ||\n layer.path === `api/${path}/` ||\n layer.path === `/api/${path}/`) &&\n layer.method.toLowerCase() === method.toLowerCase()\n );\n };\n\n const getValidationSchemaOrDto = (key: \"create\" | \"update\") => {\n const validationConfigs = arkosConfigs?.validation;\n if (validationConfigs?.resolver === \"class-validator\") {\n return dtos?.[key];\n } else if (validationConfigs?.resolver === \"zod\") {\n return schemas?.[key];\n }\n return undefined;\n };\n\n if (customRouter && customRouterModule) {\n if (routerValidator.isExpressRouter(customRouter))\n router.use(`/${routeName}`, customRouter);\n else\n throw Error(\n `ValidationError: The exported router from ${modelNameInKebab}.router.${getUserFileExtension()} is not a valid express Router.`\n );\n }\n\n if (\n !isEndpointDisabled(routerConfig, \"createOne\") &&\n !hasCustomImplementation(`/${routeName}`, \"post\")\n ) {\n router.post(\n `/${routeName}`,\n ...processAuthenticationMiddlewares(\n \"Create\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"create\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createOne\"\n ),\n ...processMiddleware(interceptors?.beforeCreateOne),\n controller.createOne,\n ...processMiddleware(interceptors?.afterCreateOne),\n sendResponse,\n ...processMiddleware(interceptors?.onCreateOneError, { type: \"error\" })\n );\n }\n\n // GET /{routeName} - Find Many\n if (\n !isEndpointDisabled(routerConfig, \"findMany\") &&\n !hasCustomImplementation(`/${routeName}`, \"get\")\n ) {\n router.get(\n `/${routeName}`,\n ...processAuthenticationMiddlewares(\n \"View\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findMany\"\n ),\n\n ...processMiddleware(interceptors?.beforeFindMany),\n controller.findMany,\n ...processMiddleware(interceptors?.afterFindMany),\n sendResponse,\n ...processMiddleware(interceptors?.onFindManyError, { type: \"error\" })\n );\n }\n\n // POST /{routeName}/many - Create Many\n if (\n !isEndpointDisabled(routerConfig, \"createMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"post\")\n ) {\n router.post(\n `/${routeName}/many`,\n ...processAuthenticationMiddlewares(\n \"Create\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"create\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createMany\"\n ),\n\n ...processMiddleware(interceptors?.beforeCreateMany),\n controller.createMany,\n ...processMiddleware(interceptors?.afterCreateMany),\n sendResponse,\n ...processMiddleware(interceptors?.onCreateManyError, { type: \"error\" })\n );\n }\n\n // PATCH /{routeName}/many - Update Many\n if (\n !isEndpointDisabled(routerConfig, \"updateMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/many`,\n ...processAuthenticationMiddlewares(\n \"Update\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateMany\"\n ),\n ...processMiddleware(interceptors?.beforeUpdateMany),\n controller.updateMany,\n ...processMiddleware(interceptors?.afterUpdateMany),\n sendResponse,\n ...processMiddleware(interceptors?.onUpdateManyError, { type: \"error\" })\n );\n }\n\n // DELETE /{routeName}/many - Delete Many\n if (\n !isEndpointDisabled(routerConfig, \"deleteMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/many`,\n ...processAuthenticationMiddlewares(\n \"Delete\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteMany\"\n ),\n ...processMiddleware(interceptors?.beforeDeleteMany),\n controller.deleteMany,\n ...processMiddleware(interceptors?.afterDeleteMany),\n sendResponse,\n ...processMiddleware(interceptors?.onDeleteManyError, { type: \"error\" })\n );\n }\n\n if (\n !isEndpointDisabled(routerConfig, \"findOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"get\")\n ) {\n router.get(\n `/${routeName}/:id`,\n ...processAuthenticationMiddlewares(\n \"View\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findOne\"\n ),\n ...processMiddleware(interceptors?.beforeFindOne),\n controller.findOne,\n ...processMiddleware(interceptors?.afterFindOne),\n sendResponse,\n ...processMiddleware(interceptors?.onFindOneError, { type: \"error\" })\n );\n }\n\n // PATCH /{routeName}/:id - Update One\n if (\n !isEndpointDisabled(routerConfig, \"updateOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/:id`,\n ...processAuthenticationMiddlewares(\n \"Update\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"update\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateOne\"\n ),\n ...processMiddleware(interceptors?.beforeUpdateOne),\n controller.updateOne,\n ...processMiddleware(interceptors?.afterUpdateOne),\n sendResponse,\n ...processMiddleware(interceptors?.onUpdateOneError, { type: \"error\" })\n );\n }\n\n // DELETE /{routeName}/:id - Delete One\n if (\n !isEndpointDisabled(routerConfig, \"deleteOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/:id`,\n ...processAuthenticationMiddlewares(\n \"Delete\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteOne\"\n ),\n ...processMiddleware(interceptors?.beforeDeleteOne),\n controller.deleteOne,\n ...processMiddleware(interceptors?.afterDeleteOne),\n sendResponse,\n ...processMiddleware(interceptors?.onDeleteOneError, { type: \"error\" })\n );\n }\n\n debuggerService.logModuleFinalRouter(modelNameInKebab, router);\n });\n}\n\nexport function processAuthenticationMiddlewares(\n action: AccessAction,\n modelName: string,\n authConfigs?: AuthConfigs\n) {\n const authenticationControl = authConfigs?.authenticationControl;\n\n if (\n (authenticationControl &&\n typeof authenticationControl === \"object\" &&\n authenticationControl[action] === true) ||\n authenticationControl === true ||\n (!authenticationControl && authenticationControl !== false)\n )\n return [\n authService.authenticate,\n authService.handleAccessControl(\n action,\n kebabCase(pluralize.singular(modelName)),\n authConfigs?.accessControl\n ),\n ];\n\n return [];\n}\n\nexport function isEndpointDisabled(\n routerConfig: RouterConfig<any>,\n endpoint: RouterEndpoint | AuthRouterEndpoint | FileUploadRouterEndpoint\n): boolean {\n if (!routerConfig?.disable) return false;\n\n if (routerConfig.disable === true) return true;\n\n if (typeof routerConfig.disable === \"object\")\n return routerConfig.disable[endpoint as never] === true;\n\n return false;\n}\n\nexport function isParentEndpointAllowed(\n routerConfig: any,\n endpoint: string\n): boolean {\n if (!routerConfig?.parent) return false;\n\n const parentEndpoints = routerConfig.parent.endpoints;\n if (parentEndpoints === \"*\") return true;\n if (Array.isArray(parentEndpoints)) return parentEndpoints.includes(endpoint);\n\n return true;\n}\n"]}
1
+ {"version":3,"file":"base.router.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/base/utils/helpers/base.router.helpers.ts"],"names":[],"mappings":"AACA,OAAO,SAAS,MAAM,WAAW,CAAC;AAElC,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAOtD,OAAO,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AACvE,OAAO,WAAW,MAAM,4BAA4B,CAAC;AACrD,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EACL,8BAA8B,EAC9B,4CAA4C,EAC5C,YAAY,GACb,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,iBAAiB,EAAE,MAAM,2CAA2C,CAAC;AAC9E,OAAO,eAAe,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,oBAAoB,EAAE,MAAM,sCAAsC,CAAC;AAC5E,OAAO,kBAAkB,MAAM,+CAA+C,CAAC;AAC/E,OAAO,eAAe,MAAM,oCAAoC,CAAC;AAGjE,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,MAAc,EAAE,YAAyB;IAC1E,OAAO,kBAAkB,CAAC,yBAAyB,EAAE,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QACxE,MAAM,gBAAgB,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC;QAC1C,MAAM,YAAY,GAAG,mBAAmB,CAAC,gBAAgB,CAAC,IAAI,EAAE,CAAC;QAEjE,MAAM,EACJ,YAAY,EACZ,WAAW,EACX,kBAAkB,EAClB,MAAM,EA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AAM;QAAE,OAAO,KAAK,CAAC;IAExC,MAAM,eAAe,GAAG,YAAY,CAAC,MAAM,CAAC,SAAS,CAAC;IACtD,IAAI,eAAe,KAAK,GAAG;QAAE,OAAO,IAAI,CAAC;IACzC,IAAI,KAAK,CAAC,OAAO,CAAC,eAAe,CAAC;QAAE,OAAO,eAAe,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;IAE9E,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { Router } from \"express\";\nimport pluralize from \"pluralize\";\nimport { ArkosConfig, RouterConfig } from \"../../../../exports\";\nimport { kebabCase } from \"../../../../exports/utils\";\nimport { PrismaQueryOptions } from \"../../../../types\";\nimport {\n AuthRouterEndpoint,\n FileUploadRouterEndpoint,\n RouterEndpoint,\n} from \"../../../../types/router-config\";\nimport { getModuleComponents } from \"../../../../utils/dynamic-loader\";\nimport authService from \"../../../auth/auth.service\";\nimport { BaseController } from \"../../base.controller\";\nimport {\n addPrismaQueryOptionsToRequest,\n handleRequestBodyValidationAndTransformation,\n sendResponse,\n} from \"../../base.middlewares\";\nimport { processMiddleware } from \"../../../../utils/helpers/routers.helpers\";\nimport routerValidator from \"../router-validator\";\nimport { getUserFileExtension } from \"../../../../utils/helpers/fs.helpers\";\nimport prismaSchemaParser from \"../../../../utils/prisma/prisma-schema-parser\";\nimport debuggerService from \"../../../debugger/debugger.service\";\nimport { AccessAction, AuthConfigs } from \"../../../../types/auth\";\n\nexport async function setupRouters(router: Router, arkosConfigs: ArkosConfig) {\n return prismaSchemaParser.getModelsAsArrayOfStrings().map(async (model) => {\n const modelNameInKebab = kebabCase(model);\n const modelModules = getModuleComponents(modelNameInKebab) || {};\n\n const {\n interceptors,\n authConfigs,\n prismaQueryOptions,\n router: customRouterModule,\n dtos,\n schemas,\n } = modelModules;\n\n const routeName = pluralize.plural(modelNameInKebab);\n const controller = new BaseController(model);\n\n const routerConfig: RouterConfig<any> = customRouterModule?.config || {};\n\n const customRouter = customRouterModule?.default as Router;\n const hasCustomImplementation = (path: string, method: string) => {\n return customRouter?.stack?.some(\n (layer) =>\n (layer.path === `/api/${path}` ||\n layer.path === `api/${path}` ||\n layer.path === `api/${path}/` ||\n layer.path === `/api/${path}/`) &&\n layer.method.toLowerCase() === method.toLowerCase()\n );\n };\n\n const getValidationSchemaOrDto = (key: \"create\" | \"update\") => {\n const validationConfigs = arkosConfigs?.validation;\n if (validationConfigs?.resolver === \"class-validator\") {\n return dtos?.[key];\n } else if (validationConfigs?.resolver === \"zod\") {\n return schemas?.[key];\n }\n return undefined;\n };\n\n if (customRouter && customRouterModule) {\n if (routerValidator.isExpressRouter(customRouter))\n router.use(`/${routeName}`, customRouter);\n else\n throw Error(\n `ValidationError: The exported router from ${modelNameInKebab}.router.${getUserFileExtension()} is not a valid express Router.`\n );\n }\n\n if (\n !isEndpointDisabled(routerConfig, \"createOne\") &&\n !hasCustomImplementation(`/${routeName}`, \"post\")\n ) {\n router.post(\n `/${routeName}`,\n ...processAuthenticationMiddlewares(\n \"Create\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"create\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createOne\"\n ),\n ...processMiddleware(interceptors?.beforeCreateOne),\n controller.createOne,\n ...processMiddleware(interceptors?.afterCreateOne),\n sendResponse,\n ...processMiddleware(interceptors?.onCreateOneError, { type: \"error\" })\n );\n }\n\n // GET /{routeName} - Find Many\n if (\n !isEndpointDisabled(routerConfig, \"findMany\") &&\n !hasCustomImplementation(`/${routeName}`, \"get\")\n ) {\n router.get(\n `/${routeName}`,\n ...processAuthenticationMiddlewares(\n \"View\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findMany\"\n ),\n\n ...processMiddleware(interceptors?.beforeFindMany),\n controller.findMany,\n ...processMiddleware(interceptors?.afterFindMany),\n sendResponse,\n ...processMiddleware(interceptors?.onFindManyError, { type: \"error\" })\n );\n }\n\n // POST /{routeName}/many - Create Many\n if (\n !isEndpointDisabled(routerConfig, \"createMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"post\")\n ) {\n router.post(\n `/${routeName}/many`,\n ...processAuthenticationMiddlewares(\n \"Create\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"create\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"createMany\"\n ),\n\n ...processMiddleware(interceptors?.beforeCreateMany),\n controller.createMany,\n ...processMiddleware(interceptors?.afterCreateMany),\n sendResponse,\n ...processMiddleware(interceptors?.onCreateManyError, { type: \"error\" })\n );\n }\n\n // PATCH /{routeName}/many - Update Many\n if (\n !isEndpointDisabled(routerConfig, \"updateMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/many`,\n ...processAuthenticationMiddlewares(\n \"Update\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateMany\"\n ),\n ...processMiddleware(interceptors?.beforeUpdateMany),\n controller.updateMany,\n ...processMiddleware(interceptors?.afterUpdateMany),\n sendResponse,\n ...processMiddleware(interceptors?.onUpdateManyError, { type: \"error\" })\n );\n }\n\n // DELETE /{routeName}/many - Delete Many\n if (\n !isEndpointDisabled(routerConfig, \"deleteMany\") &&\n !hasCustomImplementation(`/${routeName}/many`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/many`,\n ...processAuthenticationMiddlewares(\n \"Delete\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteMany\"\n ),\n ...processMiddleware(interceptors?.beforeDeleteMany),\n controller.deleteMany,\n ...processMiddleware(interceptors?.afterDeleteMany),\n sendResponse,\n ...processMiddleware(interceptors?.onDeleteManyError, { type: \"error\" })\n );\n }\n\n if (\n !isEndpointDisabled(routerConfig, \"findOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"get\")\n ) {\n router.get(\n `/${routeName}/:id`,\n ...processAuthenticationMiddlewares(\n \"View\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"findOne\"\n ),\n ...processMiddleware(interceptors?.beforeFindOne),\n controller.findOne,\n ...processMiddleware(interceptors?.afterFindOne),\n sendResponse,\n ...processMiddleware(interceptors?.onFindOneError, { type: \"error\" })\n );\n }\n\n // PATCH /{routeName}/:id - Update One\n if (\n !isEndpointDisabled(routerConfig, \"updateOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"patch\")\n ) {\n router.patch(\n `/${routeName}/:id`,\n ...processAuthenticationMiddlewares(\n \"Update\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n handleRequestBodyValidationAndTransformation(\n getValidationSchemaOrDto(\"update\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"updateOne\"\n ),\n ...processMiddleware(interceptors?.beforeUpdateOne),\n controller.updateOne,\n ...processMiddleware(interceptors?.afterUpdateOne),\n sendResponse,\n ...processMiddleware(interceptors?.onUpdateOneError, { type: \"error\" })\n );\n }\n\n // DELETE /{routeName}/:id - Delete One\n if (\n !isEndpointDisabled(routerConfig, \"deleteOne\") &&\n !hasCustomImplementation(`/${routeName}/:id`, \"delete\")\n ) {\n router.delete(\n `/${routeName}/:id`,\n ...processAuthenticationMiddlewares(\n \"Delete\",\n kebabCase(pluralize.singular(modelNameInKebab)),\n authConfigs\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as PrismaQueryOptions<any>,\n \"deleteOne\"\n ),\n ...processMiddleware(interceptors?.beforeDeleteOne),\n controller.deleteOne,\n ...processMiddleware(interceptors?.afterDeleteOne),\n sendResponse,\n ...processMiddleware(interceptors?.onDeleteOneError, { type: \"error\" })\n );\n }\n\n debuggerService.logModuleFinalRouter(modelNameInKebab, router);\n });\n}\n\nexport function processAuthenticationMiddlewares(\n action: AccessAction,\n modelName: string,\n authConfigs?: AuthConfigs\n) {\n const authenticationControl = authConfigs?.authenticationControl;\n\n if (\n (authenticationControl &&\n typeof authenticationControl === \"object\" &&\n (authenticationControl[action] === true ||\n authenticationControl[action] !== false)) ||\n authenticationControl === true ||\n (!authenticationControl && authenticationControl !== false)\n )\n return [\n authService.authenticate,\n authService.handleAccessControl(\n action,\n kebabCase(pluralize.singular(modelName)),\n authConfigs?.accessControl\n ),\n ];\n\n return [];\n}\n\nexport function isEndpointDisabled(\n routerConfig: RouterConfig<any>,\n endpoint: RouterEndpoint | AuthRouterEndpoint | FileUploadRouterEndpoint\n): boolean {\n if (!routerConfig?.disable) return false;\n\n if (routerConfig.disable === true) return true;\n\n if (typeof routerConfig.disable === \"object\")\n return routerConfig.disable[endpoint as never] === true;\n\n return false;\n}\n\nexport function isParentEndpointAllowed(\n routerConfig: any,\n endpoint: string\n): boolean {\n if (!routerConfig?.parent) return false;\n\n const parentEndpoints = routerConfig.parent.endpoints;\n if (parentEndpoints === \"*\") return true;\n if (Array.isArray(parentEndpoints)) return parentEndpoints.includes(endpoint);\n\n return true;\n}\n"]}
@@ -4,9 +4,13 @@ export default function errorHandler(err, req, res, _) {
4
4
  console.error("[\x1b[31mError\x1b[0m]:", err);
5
5
  err.statusCode = err.statusCode || 500;
6
6
  err.status = err.status || "error";
7
- let error = err;
8
- if (process.env.NODE_ENV === "production")
9
- error = { ...err, message: err.message };
7
+ let error = {
8
+ ...err,
9
+ message: err.message,
10
+ stack: err?.stack || undefined,
11
+ };
12
+ if (process.env.NODE_ENV == "production")
13
+ delete error?.stack;
10
14
  if (err.name === "JsonWebTokenError")
11
15
  error = errorControllerHelper.handleJWTError();
12
16
  if (err.name === "TokenExpiredError")
@@ -46,7 +50,7 @@ export default function errorHandler(err, req, res, _) {
46
50
  if (err.name === "NetworkError")
47
51
  error = errorControllerHelper.handleNetworkError(err);
48
52
  if (process.env.NODE_ENV !== "production")
49
- return sendDevelopmentError(error, req, res);
53
+ return sendDevelopmentError({ ...error, originalError: err }, req, res);
50
54
  sendProductionError(error, req, res);
51
55
  }
52
56
  function sendDevelopmentError(err, req, res) {
@@ -74,7 +78,9 @@ function sendProductionError(err, req, res) {
74
78
  else
75
79
  res.status(500).json({
76
80
  status: "error",
77
- message: "Internal server error",
81
+ message: "Internal server error, please try again later.",
82
+ code: "Unknown",
83
+ meta: {},
78
84
  });
79
85
  return;
80
86
  }
@@ -82,12 +88,13 @@ function sendProductionError(err, req, res) {
82
88
  res.status(err.statusCode).json({
83
89
  title: "Internal server error",
84
90
  message: err.message,
91
+ code: "Unknown",
85
92
  });
86
93
  return;
87
94
  }
88
95
  res.status(err.statusCode).json({
89
96
  title: "Internal server error",
90
- message: "Please try again later.",
97
+ message: "Internal server error, please try again later.",
91
98
  });
92
99
  }
93
100
  process.on("SIGTERM", () => {
@@ -1 +1 @@
1
- {"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,qBAAqB,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAiBtC,MAAM,CAAC,OAAO,UAAU,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,CAAe;IAEf,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;IAE9C,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,IAAI,GAAG,CAAC;IACvC,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QACtB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;YAC9B,KAAK,EAAE,uBAAuB;YAC9B,OAAO,EAAE,GAAG,CAAC,OAAO;SACrB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;QAC9B,KAAK,EAAE,uBAAuB;QAC9B,OAAO,EAAE,yBAAyB;KACnC,CAAC,CAAC;AACL,CAAC;AAWD,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;IACzB,IACE,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY;QACrC,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,SAAS,EAClC,CAAC;QACD,OAAO,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,KAAK,CAAC,2DAA2D,CAAC,CAAC;QAE3E,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;YACvC,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} _ - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n _: NextFunction\n): void {\n console.error(\"[\\x1b[31mError\\x1b[0m]:\", err);\n\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n let error = err;\n\n if (process.env.NODE_ENV === \"production\")\n error = { ...err, message: err.message };\n\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n if (err.name === \"PrismaClientInitializationError\")\n error = errorControllerHelper.handlePrismaClientInitializationError(err);\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"P2025\")\n error = errorControllerHelper.handleNonExistingRecord(err);\n if (err.code === \"P3000\")\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n if (err.code === \"P3001\")\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n if (err.code === \"P3002\")\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n if (err.code === \"P3003\")\n error = errorControllerHelper.handleVersionMismatchError(err);\n\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n\n if (process.env.NODE_ENV !== \"production\")\n return sendDevelopmentError(error, req, res);\n\n sendProductionError(error, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(\n err: AppError,\n req: Request,\n res: Response\n): void {\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n ...err,\n message: err.message.split(\"\\n\")[err.message.split(\"\\n\").length - 1],\n stack: err.stack?.split(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"Unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Internal server error\",\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: \"Please try again later.\",\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (\n process.env.NODE_ENV !== \"production\" &&\n process.env.NODE_ENV !== \"staging\"\n ) {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
1
+ {"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,qBAAqB,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAiBtC,MAAM,CAAC,OAAO,UAAU,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,CAAe;IAEf,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;IAE9C,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,IAAI,GAAG,CAAC;IACvC,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,OAAO,CAAC;IAEnC,IAAI,KAAK,GAAQ;QACf,GAAG,GAAG;QACN,OAAO,EAAE,GAAG,CAAC,OAAO;QACpB,KAAK,EAAE,GAAG,EAAE,KAAK,IAAI,SAAS;KAC/B,CAAC;IAEF,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,IAAI,YAAY;QAAE,OAAO,KAAK,EAAE,KAAK,CAAC;IAE9D,IAAI,GAAG,CAAC,IAAI,KAAK,mBAAmB;QAClC,KAAK,GAAG,qBAAqB,CAAC,cAAc,EAAE,CAAC;IACjD,IAAI,GAAG,CAAC,IAAI,KAAK,mBAAmB;QAClC,KAAK,GAAG,qBAAqB,CAAC,gBAAgB,EAAE,CAAC;IAEnD,IAAI,GAAG,CAAC,IAAI,KAAK,6BAA6B;QAC5C,KAAK,GAAG,qBAAqB,CAAC,iCAAiC,CAAC,GAAG,CAAC,CAAC;IACvE,IAAI,GAAG,CAAC,IAAI,KAAK,iCAAiC;QAChD,KAAK,GAAG,qBAAqB,CAAC,qCAAqC,CAAC,GAAG,CAAC,CAAC;IAC3E,IAAI,GAAG,CAAC,IAAI,KAAK,OAAO;QACtB,KAAK,GAAG,qBAAqB,CAAC,yBAAyB,C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,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;YACvC,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} _ - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n _: NextFunction\n): void {\n console.error(\"[\\x1b[31mError\\x1b[0m]:\", err);\n\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n let error: any = {\n ...err,\n message: err.message,\n stack: err?.stack || undefined,\n };\n\n if (process.env.NODE_ENV == \"production\") delete error?.stack;\n\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n if (err.name === \"PrismaClientInitializationError\")\n error = errorControllerHelper.handlePrismaClientInitializationError(err);\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"P2025\")\n error = errorControllerHelper.handleNonExistingRecord(err);\n if (err.code === \"P3000\")\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n if (err.code === \"P3001\")\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n if (err.code === \"P3002\")\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n if (err.code === \"P3003\")\n error = errorControllerHelper.handleVersionMismatchError(err);\n\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n\n if (process.env.NODE_ENV !== \"production\")\n return sendDevelopmentError({ ...error, originalError: err }, req, res);\n\n sendProductionError(error, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(err: any, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n ...err,\n message: err.message.split(\"\\n\")[err.message.split(\"\\n\").length - 1],\n stack: err.stack?.split(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"Unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Internal server error, please try again later.\",\n code: \"Unknown\",\n meta: {},\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n code: \"Unknown\",\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: \"Internal server error, please try again later.\",\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (\n process.env.NODE_ENV !== \"production\" &&\n process.env.NODE_ENV !== \"staging\"\n ) {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
@@ -11,6 +11,6 @@ export function killServerChildProcess() {
11
11
  killProductionServerChildProcess();
12
12
  }
13
13
  export function getVersion() {
14
- return "1.3.6-canary.1";
14
+ return "1.3.6-canary.2";
15
15
  }
16
16
  //# sourceMappingURL=cli.helpers.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "arkos",
3
- "version": "1.3.6-canary.1",
3
+ "version": "1.3.6-canary.2",
4
4
  "description": "The Express & Prisma RESTful Framework",
5
5
  "main": "dist/cjs/exports/index.js",
6
6
  "module": "dist/esm/exports/index.js",