arkos 1.0.18-beta → 1.0.20-beta

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.
Files changed (144) hide show
  1. package/dist/cjs/app.js +1 -1
  2. package/dist/cjs/app.js.map +1 -1
  3. package/dist/cjs/exports/middlewares/index.js +7 -0
  4. package/dist/cjs/exports/middlewares/index.js.map +1 -0
  5. package/dist/cjs/exports/utils/index.js.map +1 -1
  6. package/dist/cjs/modules/auth/auth.controller.js +38 -37
  7. package/dist/cjs/modules/auth/auth.controller.js.map +1 -1
  8. package/dist/cjs/modules/auth/auth.router.js +4 -5
  9. package/dist/cjs/modules/auth/auth.router.js.map +1 -1
  10. package/dist/cjs/modules/auth/auth.service.js +27 -24
  11. package/dist/cjs/modules/auth/auth.service.js.map +1 -1
  12. package/dist/cjs/modules/auth/utils/helpers/auth.controller.helpers.js +8 -12
  13. package/dist/cjs/modules/auth/utils/helpers/auth.controller.helpers.js.map +1 -1
  14. package/dist/cjs/modules/auth/utils/helpers/auth.helpers.js +19 -0
  15. package/dist/cjs/modules/auth/utils/helpers/auth.helpers.js.map +1 -0
  16. package/dist/cjs/modules/base/base.controller.js +2 -29
  17. package/dist/cjs/modules/base/base.controller.js.map +1 -1
  18. package/dist/cjs/modules/base/base.middlewares.js +42 -1
  19. package/dist/cjs/modules/base/base.middlewares.js.map +1 -1
  20. package/dist/cjs/modules/base/base.router.js +2 -2
  21. package/dist/cjs/modules/base/base.router.js.map +1 -1
  22. package/dist/cjs/modules/base/utils/helpers/base.helpers.js +183 -0
  23. package/dist/cjs/modules/base/utils/helpers/base.helpers.js.map +1 -0
  24. package/dist/cjs/modules/base/utils/helpers/base.router.helpers.js +2 -3
  25. package/dist/cjs/modules/base/utils/helpers/base.router.helpers.js.map +1 -1
  26. package/dist/cjs/modules/base/utils/helpers/base.service.helpers.js +9 -11
  27. package/dist/cjs/modules/base/utils/helpers/base.service.helpers.js.map +1 -1
  28. package/dist/cjs/modules/error-handler/error-handler.controller.js +2 -0
  29. package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
  30. package/dist/cjs/modules/error-handler/utils/catch-async.js +1 -1
  31. package/dist/cjs/modules/error-handler/utils/catch-async.js.map +1 -1
  32. package/dist/cjs/modules/file-uploader/file-uploader.service.js +4 -4
  33. package/dist/cjs/modules/file-uploader/file-uploader.service.js.map +1 -1
  34. package/dist/cjs/modules/file-uploader/utils/helpers/file-uploader.helpers.js +7 -5
  35. package/dist/cjs/modules/file-uploader/utils/helpers/file-uploader.helpers.js.map +1 -1
  36. package/dist/cjs/server.js +1 -1
  37. package/dist/cjs/server.js.map +1 -1
  38. package/dist/cjs/types/arkos-config.js.map +1 -1
  39. package/dist/cjs/types/auth.js.map +1 -1
  40. package/dist/cjs/types/index.js.map +1 -1
  41. package/dist/cjs/types/prisma-model-router-config.js +3 -0
  42. package/dist/cjs/types/prisma-model-router-config.js.map +1 -0
  43. package/dist/cjs/utils/features/api.features.js +3 -2
  44. package/dist/cjs/utils/features/api.features.js.map +1 -1
  45. package/dist/cjs/utils/helpers/api.features.helpers.js +4 -3
  46. package/dist/cjs/utils/helpers/api.features.helpers.js.map +1 -1
  47. package/dist/cjs/utils/helpers/base.controller.helpers.js +77 -35
  48. package/dist/cjs/utils/helpers/base.controller.helpers.js.map +1 -1
  49. package/dist/cjs/utils/helpers/change-case.helpers.js +3 -3
  50. package/dist/cjs/utils/helpers/change-case.helpers.js.map +1 -1
  51. package/dist/cjs/utils/helpers/fs.helpers.js +14 -45
  52. package/dist/cjs/utils/helpers/fs.helpers.js.map +1 -1
  53. package/dist/cjs/utils/helpers/models.helpers.js +35 -30
  54. package/dist/cjs/utils/helpers/models.helpers.js.map +1 -1
  55. package/dist/cjs/utils/helpers/prisma.helpers.js +5 -3
  56. package/dist/cjs/utils/helpers/prisma.helpers.js.map +1 -1
  57. package/dist/cjs/utils/scripts/export-prisma-types.js +3 -3
  58. package/dist/cjs/utils/scripts/export-prisma-types.js.map +1 -1
  59. package/dist/cjs/utils/scripts/generate-insomnia-collection.js +228 -0
  60. package/dist/cjs/utils/scripts/generate-insomnia-collection.js.map +1 -0
  61. package/dist/cjs/utils/scripts/generate-zod-schemas.js +4 -3
  62. package/dist/cjs/utils/scripts/generate-zod-schemas.js.map +1 -1
  63. package/dist/cjs/utils/scripts/index.js +12 -0
  64. package/dist/cjs/utils/scripts/index.js.map +1 -0
  65. package/dist/es2020/app.js +1 -1
  66. package/dist/es2020/app.js.map +1 -1
  67. package/dist/es2020/exports/middlewares/index.js +2 -0
  68. package/dist/es2020/exports/middlewares/index.js.map +1 -0
  69. package/dist/es2020/exports/utils/index.js.map +1 -1
  70. package/dist/es2020/modules/auth/auth.controller.js +39 -38
  71. package/dist/es2020/modules/auth/auth.controller.js.map +1 -1
  72. package/dist/es2020/modules/auth/auth.router.js +1 -2
  73. package/dist/es2020/modules/auth/auth.router.js.map +1 -1
  74. package/dist/es2020/modules/auth/auth.service.js +27 -24
  75. package/dist/es2020/modules/auth/auth.service.js.map +1 -1
  76. package/dist/es2020/modules/auth/utils/helpers/auth.controller.helpers.js +8 -12
  77. package/dist/es2020/modules/auth/utils/helpers/auth.controller.helpers.js.map +1 -1
  78. package/dist/es2020/modules/auth/utils/helpers/auth.helpers.js +12 -0
  79. package/dist/es2020/modules/auth/utils/helpers/auth.helpers.js.map +1 -0
  80. package/dist/es2020/modules/base/base.controller.js +2 -29
  81. package/dist/es2020/modules/base/base.controller.js.map +1 -1
  82. package/dist/es2020/modules/base/base.middlewares.js +38 -1
  83. package/dist/es2020/modules/base/base.middlewares.js.map +1 -1
  84. package/dist/es2020/modules/base/base.router.js +2 -2
  85. package/dist/es2020/modules/base/base.router.js.map +1 -1
  86. package/dist/es2020/modules/base/utils/helpers/base.helpers.js +177 -0
  87. package/dist/es2020/modules/base/utils/helpers/base.helpers.js.map +1 -0
  88. package/dist/es2020/modules/base/utils/helpers/base.router.helpers.js +1 -2
  89. package/dist/es2020/modules/base/utils/helpers/base.router.helpers.js.map +1 -1
  90. package/dist/es2020/modules/base/utils/helpers/base.service.helpers.js +9 -11
  91. package/dist/es2020/modules/base/utils/helpers/base.service.helpers.js.map +1 -1
  92. package/dist/es2020/modules/error-handler/error-handler.controller.js +2 -0
  93. package/dist/es2020/modules/error-handler/error-handler.controller.js.map +1 -1
  94. package/dist/es2020/modules/error-handler/utils/catch-async.js +1 -1
  95. package/dist/es2020/modules/error-handler/utils/catch-async.js.map +1 -1
  96. package/dist/es2020/modules/file-uploader/file-uploader.service.js +4 -4
  97. package/dist/es2020/modules/file-uploader/file-uploader.service.js.map +1 -1
  98. package/dist/es2020/modules/file-uploader/utils/helpers/file-uploader.helpers.js +7 -5
  99. package/dist/es2020/modules/file-uploader/utils/helpers/file-uploader.helpers.js.map +1 -1
  100. package/dist/es2020/server.js +1 -1
  101. package/dist/es2020/server.js.map +1 -1
  102. package/dist/es2020/types/arkos-config.js.map +1 -1
  103. package/dist/es2020/types/auth.js.map +1 -1
  104. package/dist/es2020/types/index.js.map +1 -1
  105. package/dist/es2020/types/prisma-model-router-config.js +2 -0
  106. package/dist/es2020/types/prisma-model-router-config.js.map +1 -0
  107. package/dist/es2020/utils/features/api.features.js +3 -2
  108. package/dist/es2020/utils/features/api.features.js.map +1 -1
  109. package/dist/es2020/utils/helpers/api.features.helpers.js +4 -3
  110. package/dist/es2020/utils/helpers/api.features.helpers.js.map +1 -1
  111. package/dist/es2020/utils/helpers/base.controller.helpers.js +75 -31
  112. package/dist/es2020/utils/helpers/base.controller.helpers.js.map +1 -1
  113. package/dist/es2020/utils/helpers/change-case.helpers.js +3 -3
  114. package/dist/es2020/utils/helpers/change-case.helpers.js.map +1 -1
  115. package/dist/es2020/utils/helpers/fs.helpers.js +13 -44
  116. package/dist/es2020/utils/helpers/fs.helpers.js.map +1 -1
  117. package/dist/es2020/utils/helpers/models.helpers.js +36 -31
  118. package/dist/es2020/utils/helpers/models.helpers.js.map +1 -1
  119. package/dist/es2020/utils/helpers/prisma.helpers.js +6 -4
  120. package/dist/es2020/utils/helpers/prisma.helpers.js.map +1 -1
  121. package/dist/es2020/utils/scripts/export-prisma-types.js +3 -3
  122. package/dist/es2020/utils/scripts/export-prisma-types.js.map +1 -1
  123. package/dist/es2020/utils/scripts/generate-insomnia-collection.js +189 -0
  124. package/dist/es2020/utils/scripts/generate-insomnia-collection.js.map +1 -0
  125. package/dist/es2020/utils/scripts/generate-zod-schemas.js +4 -3
  126. package/dist/es2020/utils/scripts/generate-zod-schemas.js.map +1 -1
  127. package/dist/es2020/utils/scripts/index.js +10 -0
  128. package/dist/es2020/utils/scripts/index.js.map +1 -0
  129. package/dist/types/exports/middlewares/index.d.ts +1 -0
  130. package/dist/types/exports/utils/index.d.ts +1 -0
  131. package/dist/types/modules/auth/auth.service.d.ts +3 -3
  132. package/dist/types/modules/auth/utils/helpers/auth.helpers.d.ts +2 -0
  133. package/dist/types/modules/base/base.middlewares.d.ts +6 -1
  134. package/dist/types/modules/base/utils/helpers/base.helpers.d.ts +5 -0
  135. package/dist/types/modules/base/utils/helpers/base.service.helpers.d.ts +1 -1
  136. package/dist/types/types/arkos-config.d.ts +5 -0
  137. package/dist/types/types/auth.d.ts +9 -8
  138. package/dist/types/types/index.d.ts +2 -1
  139. package/dist/types/types/prisma-model-router-config.d.ts +18 -0
  140. package/dist/types/utils/helpers/base.controller.helpers.d.ts +4 -6
  141. package/dist/types/utils/helpers/fs.helpers.d.ts +2 -2
  142. package/dist/types/utils/scripts/generate-insomnia-collection.d.ts +1 -0
  143. package/dist/types/utils/scripts/index.d.ts +2 -0
  144. package/package.json +55 -34
@@ -1 +1 @@
1
- {"version":3,"file":"file-uploader.service.js","sourceRoot":"","sources":["../../../../src/modules/file-uploader/file-uploader.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,oDAA+C;AAC/C,gDAAwB;AACxB,4CAAoB;AAEpB,iFAAwD;AACxD,+BAAiC;AACjC,yCAA8C;AAC9C,4FAA6D;AAE7D,iFAG+C;AAC/C,mE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;IAKF,MAAM,oBAAoB,GAAG,IAAI,mBAAmB,CAClD,GAAG,aAAa,SAAS,EACzB,YAAY,CAAC,MAAM,CAAC,OAAO,EAC3B,YAAY,CAAC,MAAM,CAAC,mBAAmB,EACvC,YAAY,CAAC,MAAM,CAAC,QAAQ,CAC7B,CAAC;IAKF,MAAM,uBAAuB,GAAG,IAAI,mBAAmB,CACrD,GAAG,aAAa,YAAY,EAC5B,YAAY,CAAC,SAAS,CAAC,OAAO,EAC9B,YAAY,CAAC,SAAS,CAAC,mBAAmB,EAC1C,YAAY,CAAC,SAAS,CAAC,QAAQ,CAChC,CAAC;IAKF,MAAM,mBAAmB,GAAG,IAAI,mBAAmB,CACjD,GAAG,aAAa,QAAQ,EACxB,YAAY,CAAC,KAAK,CAAC,OAAO,EAC1B,YAAY,CAAC,KAAK,CAAC,mBAAmB,EACtC,YAAY,CAAC,KAAK,CAAC,QAAQ,CAC5B,CAAC;IAEF,OAAO;QACL,oBAAoB;QACpB,oBAAoB;QACpB,uBAAuB;QACvB,mBAAmB;KACpB,CAAC;AACJ,CAAC,CAAC;AA7FW,QAAA,uBAAuB,2BA6FlC","sourcesContent":["import multer, { StorageEngine } from \"multer\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport { NextFunction } from \"express\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { promisify } from \"util\";\nimport { getArkosConfig } from \"../../server\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { ArkosRequest, ArkosResponse } from \"../../types\";\nimport {\n processFile,\n processImage,\n} from \"./utils/helpers/file-uploader.helpers\";\nimport { removeBothSlashes } from \"../../utils/helpers/text.helpers\";\n\n/**\n * Service to handle file uploads, including single and multiple file uploads,\n * file validation (type, size), and file deletion.\n */\nexport class FileUploaderService {\n public readonly uploadDir: string;\n private fileSizeLimit: number;\n private allowedFileTypes: RegExp;\n private storage: StorageEngine;\n private maxCount: number;\n\n /**\n * Constructor to initialize the file uploader service.\n * @param {string} uploadDir - The directory where files will be uploaded.\n * @param {number} fileSizeLimit - The maximum allowed file size.\n * @param {RegExp} allowedFileTypes - The regular expression for allowed file types.\n */\n constructor(\n uploadDir: string,\n fileSizeLimit: number = 1024 * 1024 * 5,\n allowedFileTypes: RegExp = /.*/,\n maxCount: number = 30\n ) {\n uploadDir = uploadDir.startsWith(\"/\") ? uploadDir.substring(1) : uploadDir;\n uploadDir = uploadDir.endsWith(\"/\") ? uploadDir.slice(0, -1) : uploadDir;\n\n this.uploadDir = path.resolve(process.cwd(), `${uploadDir}/`);\n this.fileSizeLimit = fileSizeLimit;\n this.allowedFileTypes = allowedFileTypes;\n this.maxCount = maxCount;\n\n if (!fs.existsSync(this.uploadDir)) {\n fs.mkdirSync(this.uploadDir, { recursive: true });\n }\n\n this.storage = multer.diskStorage({\n destination: (req, file, cb) => {\n cb(null, this.uploadDir);\n },\n filename: (req, file, cb) => {\n const uniqueSuffix = Date.now() + \"-\" + Math.round(Math.random() * 1e9);\n cb(null, `${uniqueSuffix}${path.extname(file.originalname)}`);\n },\n });\n }\n\n /**\n * Validates the file's type and MIME type.\n * @param {Request} req - The Express request object.\n * @param {Express.Multer.File} file - The uploaded file.\n * @param {Function} cb - The callback function to indicate if file is valid.\n */\n private fileFilter = (req: any, file: any, cb: any) => {\n const extName = this.allowedFileTypes.test(\n path.extname(file.originalname).toLowerCase()\n );\n const mimeType = this.allowedFileTypes.test(file.mimetype);\n\n if (mimeType && extName) {\n cb(null, true);\n } else {\n cb(new AppError(\"Invalid file type\", 400));\n }\n };\n\n /**\n * Returns the multer upload configuration.\n * @returns {multer.Instance} The multer instance configured for file uploads.\n */\n public getUploader() {\n return multer({\n storage: this.storage,\n fileFilter: this.fileFilter,\n limits: { fileSize: this.fileSizeLimit },\n });\n }\n\n /**\n * Middleware to handle single file upload.\n * @param {string} [oldFilePath] - The path to the file to delete before uploading.\n * @returns {Function} Middleware function for handling file upload.\n */\n public handleSingleUpload(oldFilePath?: string) {\n return (req: ArkosRequest, res: ArkosResponse, next: NextFunction) => {\n const upload = this.getUploader().single(this.getFieldName());\n upload(req, res, async (err) => {\n if (err instanceof multer.MulterError) {\n return next(err);\n } else if (err) {\n return next(err);\n }\n\n if (oldFilePath) {\n const { fileUpload: configs } = getArkosConfig();\n\n const filePath = path.resolve(\n process.cwd(),\n removeBothSlashes(configs?.baseUploadDir!),\n removeBothSlashes(oldFilePath)\n );\n try {\n const stats = await promisify(fs.stat)(filePath);\n if (stats) await promisify(fs.unlink)(filePath);\n } catch (err) {\n console.error(err);\n }\n }\n\n next();\n });\n };\n }\n\n /**\n * Middleware to handle multiple file uploads.\n * @param {number} maxCount - The maximum number of files allowed for upload.\n * @returns {Function} Middleware function for handling multiple file uploads.\n */\n public handleMultipleUpload() {\n return (req: ArkosRequest, res: ArkosResponse, next: NextFunction) => {\n const upload = this.getUploader().array(\n this.getFieldName(),\n this.maxCount\n );\n upload(req, res, (err) => {\n if (err instanceof multer.MulterError) return next(err);\n else if (err) return next(err);\n next();\n });\n };\n }\n\n /**\n * Middleware to handle deletion of a single file from the filesystem.\n * @param {string} oldFilePath - The path to the file to be deleted.\n * @returns {Function} Middleware function for handling file deletion.\n */\n public handleDeleteSingleFile(oldFilePath: string) {\n return async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: NextFunction\n ) => {\n const filePath = path.join(oldFilePath);\n try {\n const stats = await promisify(fs.stat)(filePath);\n if (stats) {\n await promisify(fs.unlink)(filePath);\n }\n } catch (err) {\n console.error(err);\n }\n\n next();\n };\n }\n\n /**\n * Deletes a file based on its URL by identifying the appropriate uploader service\n * @param {string} fileUrl - The URL of the file to delete\n * @returns {Promise<boolean>} - True if deletion successful, false otherwise\n */\n public async deleteFileByUrl(fileUrl: string): Promise<boolean> {\n try {\n // Get configuration values\n const { fileUpload } = getArkosConfig();\n const baseRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n // Parse the URL to get the path\n let urlPath: string;\n if (fileUrl.startsWith(\"http\")) {\n const url = new URL(fileUrl);\n urlPath = url.pathname;\n } else {\n urlPath = fileUrl;\n }\n\n // Extract the path after the base route\n const baseRouteIndex = urlPath.indexOf(baseRoute);\n if (baseRouteIndex === -1) {\n throw new AppError(\"Invalid file URL: base route not found\", 400);\n }\n\n const pathAfterBaseRoute = urlPath.substring(\n baseRouteIndex + baseRoute.length\n );\n const cleanPath = pathAfterBaseRoute.startsWith(\"/\")\n ? pathAfterBaseRoute.substring(1)\n : pathAfterBaseRoute;\n\n // Determine file type and file name\n const fileTypes = [\"images\", \"videos\", \"documents\", \"files\"];\n let fileType: string | null = null;\n let fileName: string | null = null;\n\n for (const type of fileTypes) {\n const typeIndex = cleanPath.indexOf(type + \"/\");\n if (typeIndex !== -1) {\n fileType = type;\n fileName = cleanPath.substring(typeIndex + type.length + 1);\n break;\n }\n }\n\n if (!fileType || !fileName) {\n throw new AppError(\n \"Unable to determine file type or file name from URL\",\n 400\n );\n }\n\n // Get the appropriate uploader service based on file type\n const {\n documentUploaderService,\n fileUploaderService,\n imageUploaderService,\n videoUploaderService,\n } = getFileUploaderServices();\n\n let filePath: string;\n switch (fileType) {\n case \"images\":\n filePath = path.join(imageUploaderService.uploadDir, fileName);\n break;\n case \"videos\":\n filePath = path.join(videoUploaderService.uploadDir, fileName);\n break;\n case \"documents\":\n filePath = path.join(documentUploaderService.uploadDir, fileName);\n break;\n case \"files\":\n filePath = path.join(fileUploaderService.uploadDir, fileName);\n break;\n default:\n throw new AppError(`Unsupported file type: ${fileType}`, 400);\n }\n\n // Delete the file\n\n await promisify(fs.stat)(filePath);\n await promisify(fs.unlink)(filePath);\n\n return true;\n } catch (error: any) {\n if (error instanceof AppError) {\n throw error;\n }\n\n if (error.code === \"ENOENT\") {\n throw new AppError(\"File not found\", 404);\n }\n\n throw new AppError(`Failed to delete file: ${error.message}`, 500);\n }\n }\n\n private getFieldName() {\n let fieldName = \"files\";\n if (this.uploadDir.endsWith(\"images\") || this.uploadDir.endsWith(\"images/\"))\n fieldName = \"images\";\n if (this.uploadDir.endsWith(\"videos\") || this.uploadDir.endsWith(\"videos/\"))\n fieldName = \"videos\";\n if (\n this.uploadDir.endsWith(\"documents\") ||\n this.uploadDir.endsWith(\"documents/\")\n )\n fieldName = \"documents\";\n if (this.uploadDir.endsWith(\"files\") || this.uploadDir.endsWith(\"files/\"))\n fieldName = \"files\";\n return fieldName;\n }\n\n /**\n * Handles the upload process and returns the full URLs of uploaded files\n * @param {ArkosRequest} req - Arkos request object containing the files\n * @param {ArkosResponse} res - Arkos response object\n * @param {object} options - Optional parameters for image processing\n * @returns {Promise<string|string[]>} URL or array of URLs to the uploaded files\n */\n public async upload(\n req: ArkosRequest,\n res: ArkosResponse,\n options: {\n format?: string;\n width?: number;\n height?: number;\n resizeTo?: number;\n } = {}\n ): Promise<string | string[] | null> {\n const { fileUpload } = getArkosConfig();\n const baseRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n return new Promise((resolve, reject) => {\n // Determine if it's a single or multiple file upload\n const isMultiple = Array.isArray(req.query.multiple)\n ? req.query.multiple[0] == \"true\"\n : req.query.multiple == \"true\";\n\n // Use appropriate upload handler\n const uploadHandler = isMultiple\n ? this.getUploader().array(this.getFieldName(), this.maxCount)\n : this.getUploader().single(this.getFieldName());\n\n uploadHandler(req, res, async (err) => {\n if (err) return reject(err);\n\n try {\n // Determine the base URL for file access\n const protocol = req.get(\"host\")?.includes(\"localhost\")\n ? \"http\"\n : \"https\";\n const baseURL = `${protocol}://${req.get(\"host\")}`;\n\n // Get file type from uploadDir path\n const dirParts = this.uploadDir.split(\"/\");\n const fileType =\n (this.uploadDir.endsWith(\"/\")\n ? dirParts[dirParts.length - 2]\n : dirParts[dirParts.length - 1]) || \"files\";\n\n // Process all uploaded files\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n // Process multiple files\n const isImageUploader = this.uploadDir.includes(\"/images\");\n if (isImageUploader) {\n data = await Promise.all(\n req.files.map((file) => processImage(req, file.path, options))\n );\n } else {\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n // Filter out any null values from failed processing\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n // Process a single file\n const isImageUploader = this.uploadDir.includes(\"/images\");\n if (isImageUploader) {\n data = await processImage(req, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n } else {\n return reject(new AppError(\"No file uploaded\", 400));\n }\n\n resolve(data);\n } catch (error) {\n reject(error);\n }\n });\n });\n }\n}\n\n/**\n * Creates and returns all file uploader services based on config\n * @returns Object containing all specialized file uploader services\n */\nexport const getFileUploaderServices = () => {\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n // Default regex patterns for each file type\n const defaultRegexPatterns = {\n images:\n /jpeg|jpg|png|gif|webp|svg|bmp|tiff|heif|heic|ico|jfif|raw|cr2|nef|orf|sr2|arw|dng|pef|raf|rw2|psd|ai|eps|xcf|jxr|wdp|hdp|jp2|j2k|jpf|jpx|jpm|mj2|avif/,\n videos:\n /mp4|avi|mov|mkv|flv|wmv|webm|mpg|mpeg|3gp|m4v|ts|rm|rmvb|vob|ogv|dv|qt|asf|m2ts|mts|divx|f4v|swf|mxf|roq|nsv|mvb|svi|mpe|m2v|mp2|mpv|h264|h265|hevc/,\n documents:\n /pdf|doc|docx|xls|xlsx|ppt|pptx|odt|ods|odg|odp|txt|rtf|csv|epub|md|tex|pages|numbers|key|xml|json|yaml|yml|ini|cfg|conf|log|html|htm|xhtml|djvu|mobi|azw|azw3|fb2|lit|ps|wpd|wps|dot|dotx|xlt|xltx|pot|potx|oft|one|onetoc2|opf|oxps|hwp/,\n files: /.*/,\n };\n\n // Default upload restrictions\n const defaultRestrictions = {\n images: {\n maxCount: 30,\n maxSize: 1024 * 1024 * 15, // 15 MB\n supportedFilesRegex:\n /jpeg|jpg|png|gif|webp|svg|bmp|tiff|heif|heic|ico|jfif|raw|cr2|nef|orf|sr2|arw|dng|pef|raf|rw2|psd|ai|eps|xcf|jxr|wdp|hdp|jp2|j2k|jpf|jpx|jpm|mj2|avif/,\n },\n videos: {\n maxCount: 10,\n maxSize: 1024 * 1024 * 5096, // 5 GB\n supportedFilesRegex:\n /mp4|avi|mov|mkv|flv|wmv|webm|mpg|mpeg|3gp|m4v|ts|rm|rmvb|vob|ogv|dv|qt|asf|m2ts|mts|divx|f4v|swf|mxf|roq|nsv|mvb|svi|mpe|m2v|mp2|mpv|h264|h265|hevc/,\n },\n documents: {\n maxCount: 30,\n maxSize: 1024 * 1024 * 50, // 50 MB\n supportedFilesRegex:\n /pdf|doc|docx|xls|xlsx|ppt|pptx|odt|ods|odg|odp|txt|rtf|csv|epub|md|tex|pages|numbers|key|xml|json|yaml|yml|ini|cfg|conf|log|html|htm|xhtml|djvu|mobi|azw|azw3|fb2|lit|ps|wpd|wps|dot|dotx|xlt|xltx|pot|potx|oft|one|onetoc2|opf|oxps|hwp/,\n },\n files: {\n maxCount: 10,\n maxSize: 1024 * 1024 * 5096, // 5 GB\n supportedFilesRegex: /.*/,\n },\n };\n\n // Merge with user configuration (if any)\n const restrictions = fileUpload?.restrictions\n ? deepmerge(defaultRestrictions, fileUpload.restrictions)\n : defaultRestrictions;\n\n /**\n * Specialized file uploader service for handling image uploads.\n */\n const imageUploaderService = new FileUploaderService(\n `${baseUploadDir}/images`,\n restrictions.images.maxSize,\n restrictions.images.supportedFilesRegex,\n restrictions.images.maxCount\n );\n\n /**\n * Specialized file uploader service for handling video uploads.\n */\n const videoUploaderService = new FileUploaderService(\n `${baseUploadDir}/videos`,\n restrictions.videos.maxSize,\n restrictions.videos.supportedFilesRegex,\n restrictions.videos.maxCount\n );\n\n /**\n * Specialized file uploader service for handling document uploads.\n */\n const documentUploaderService = new FileUploaderService(\n `${baseUploadDir}/documents`,\n restrictions.documents.maxSize,\n restrictions.documents.supportedFilesRegex,\n restrictions.documents.maxCount\n );\n\n /**\n * Generic file uploader service for handling all file uploads.\n */\n const fileUploaderService = new FileUploaderService(\n `${baseUploadDir}/files`,\n restrictions.files.maxSize,\n restrictions.files.supportedFilesRegex,\n restrictions.files.maxCount\n );\n\n return {\n imageUploaderService,\n videoUploaderService,\n documentUploaderService,\n fileUploaderService,\n };\n};\n"]}
1
+ {"version":3,"file":"file-uploader.service.js","sourceRoot":"","sources":["../../../../src/modules/file-uploader/file-uploader.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,oDAA+C;AAC/C,gDAAwB;AACxB,4CAAoB;AAEpB,iFAAwD;AACxD,+BAAiC;AACjC,yCAA8C;AAC9C,4FAA6D;AAE7D,iFAG+C;AAC/C,mEAAqE;AAMrE,MAAa,mBAAmB;IAa9B,YACE,SAAiB,EACjB,gBAAwB,IAAI,GAAG,IAAI,GAAG,CAAC,EACvC,mBAA2B,IAAI,EAC/B,WAAmB,EAAE;QA+Bf,eAAU,GAAG,CAAC,GAAQ,EAAE,IAAS,EAAE,EAAO,EAAE,EAAE;YACpD,MAAM,OAAO,GAAG,IAAI,CAAC,gBAAgB,CAAC,IAAI,CACxC,cAAI,CAAC,OAAO,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,WAAW,EAAE,CAC9C,CAAC;YACF,MAAM,QAAQ,GAAG,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;YAE3D,IAAI,QAAQ,IAAI,OAAO,EAAE,CAAC;gBACxB,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;YACjB,CAAC;iBAAM,CAAC;gBACN,EAAE,CAAC,IAAI,mBAAQ,CAAC,mBAAmB,EAAE,GAAG,CAAC,CAAC,CAAC;YAC7C,CAAC;QACH,CAAC,CAAC;QAxCA,SAAS,GAAG,SAAS,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAC3E,SAAS,GAAG,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CA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,CAAC;IAGF,MAAM,YAAY,GAAG,CAAA,UAAU,aAAV,UAAU,uBAAV,UAAU,CAAE,YAAY;QAC3C,CAAC,CAAC,IAAA,0BAAS,EAAC,mBAAmB,EAAE,UAAU,CAAC,YAAY,CAAC;QACzD,CAAC,CAAC,mBAAmB,CAAC;IAKxB,MAAM,oBAAoB,GAAG,IAAI,mBAAmB,CAClD,GAAG,aAAa,SAAS,EACzB,YAAY,CAAC,MAAM,CAAC,OAAO,EAC3B,YAAY,CAAC,MAAM,CAAC,mBAAmB,EACvC,YAAY,CAAC,MAAM,CAAC,QAAQ,CAC7B,CAAC;IAKF,MAAM,oBAAoB,GAAG,IAAI,mBAAmB,CAClD,GAAG,aAAa,SAAS,EACzB,YAAY,CAAC,MAAM,CAAC,OAAO,EAC3B,YAAY,CAAC,MAAM,CAAC,mBAAmB,EACvC,YAAY,CAAC,MAAM,CAAC,QAAQ,CAC7B,CAAC;IAKF,MAAM,uBAAuB,GAAG,IAAI,mBAAmB,CACrD,GAAG,aAAa,YAAY,EAC5B,YAAY,CAAC,SAAS,CAAC,OAAO,EAC9B,YAAY,CAAC,SAAS,CAAC,mBAAmB,EAC1C,YAAY,CAAC,SAAS,CAAC,QAAQ,CAChC,CAAC;IAKF,MAAM,mBAAmB,GAAG,IAAI,mBAAmB,CACjD,GAAG,aAAa,QAAQ,EACxB,YAAY,CAAC,KAAK,CAAC,OAAO,EAC1B,YAAY,CAAC,KAAK,CAAC,mBAAmB,EACtC,YAAY,CAAC,KAAK,CAAC,QAAQ,CAC5B,CAAC;IAEF,OAAO;QACL,oBAAoB;QACpB,oBAAoB;QACpB,uBAAuB;QACvB,mBAAmB;KACpB,CAAC;AACJ,CAAC,CAAC;AA7FW,QAAA,uBAAuB,2BA6FlC","sourcesContent":["import multer, { StorageEngine } from \"multer\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport { NextFunction } from \"express\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { promisify } from \"util\";\nimport { getArkosConfig } from \"../../server\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { ArkosRequest, ArkosResponse } from \"../../types\";\nimport {\n processFile,\n processImage,\n} from \"./utils/helpers/file-uploader.helpers\";\nimport { removeBothSlashes } from \"../../utils/helpers/text.helpers\";\n\n/**\n * Service to handle file uploads, including single and multiple file uploads,\n * file validation (type, size), and file deletion.\n */\nexport class FileUploaderService {\n public readonly uploadDir: string;\n private fileSizeLimit: number;\n private allowedFileTypes: RegExp;\n private storage: StorageEngine;\n private maxCount: number;\n\n /**\n * Constructor to initialize the file uploader service.\n * @param {string} uploadDir - The directory where files will be uploaded.\n * @param {number} fileSizeLimit - The maximum allowed file size.\n * @param {RegExp} allowedFileTypes - The regular expression for allowed file types.\n */\n constructor(\n uploadDir: string,\n fileSizeLimit: number = 1024 * 1024 * 5,\n allowedFileTypes: RegExp = /.*/,\n maxCount: number = 30\n ) {\n uploadDir = uploadDir.startsWith(\"/\") ? uploadDir.substring(1) : uploadDir;\n uploadDir = uploadDir.endsWith(\"/\") ? uploadDir.slice(0, -1) : uploadDir;\n\n this.uploadDir = path.resolve(process.cwd(), `${uploadDir}/`);\n this.fileSizeLimit = fileSizeLimit;\n this.allowedFileTypes = allowedFileTypes;\n this.maxCount = maxCount;\n\n if (!fs.existsSync(this.uploadDir)) {\n fs.mkdirSync(this.uploadDir, { recursive: true });\n }\n\n this.storage = multer.diskStorage({\n destination: (req, file, cb) => {\n cb(null, this.uploadDir);\n },\n filename: (req, file, cb) => {\n const uniqueSuffix = Date.now() + \"-\" + Math.round(Math.random() * 1e9);\n cb(null, `${uniqueSuffix}${path.extname(file.originalname)}`);\n },\n });\n }\n\n /**\n * Validates the file's type and MIME type.\n * @param {Request} req - The Express request object.\n * @param {Express.Multer.File} file - The uploaded file.\n * @param {Function} cb - The callback function to indicate if file is valid.\n */\n private fileFilter = (req: any, file: any, cb: any) => {\n const extName = this.allowedFileTypes.test(\n path.extname(file.originalname).toLowerCase()\n );\n const mimeType = this.allowedFileTypes.test(file.mimetype);\n\n if (mimeType && extName) {\n cb(null, true);\n } else {\n cb(new AppError(\"Invalid file type\", 400));\n }\n };\n\n /**\n * Returns the multer upload configuration.\n * @returns {multer.Instance} The multer instance configured for file uploads.\n */\n public getUploader() {\n return multer({\n storage: this.storage,\n fileFilter: this.fileFilter,\n limits: { fileSize: this.fileSizeLimit },\n });\n }\n\n /**\n * Middleware to handle single file upload.\n * @param {string} [oldFilePath] - The path to the file to delete before uploading.\n * @returns {Function} Middleware function for handling file upload.\n */\n public handleSingleUpload(oldFilePath?: string) {\n return (req: ArkosRequest, res: ArkosResponse, next: NextFunction) => {\n const upload = this.getUploader().single(this.getFieldName());\n upload(req, res, async (err) => {\n if (err instanceof multer.MulterError) {\n return next(err);\n } else if (err) {\n return next(err);\n }\n\n if (oldFilePath) {\n const { fileUpload: configs } = getArkosConfig();\n\n const filePath = path.resolve(\n process.cwd(),\n removeBothSlashes(configs?.baseUploadDir!),\n removeBothSlashes(oldFilePath)\n );\n try {\n const stats = await promisify(fs.stat)(filePath);\n if (stats) await promisify(fs.unlink)(filePath);\n } catch (err) {\n console.error(err);\n }\n }\n\n next();\n });\n };\n }\n\n /**\n * Middleware to handle multiple file uploads.\n * @param {number} maxCount - The maximum number of files allowed for upload.\n * @returns {Function} Middleware function for handling multiple file uploads.\n */\n public handleMultipleUpload() {\n return (req: ArkosRequest, res: ArkosResponse, next: NextFunction) => {\n const upload = this.getUploader().array(\n this.getFieldName(),\n this.maxCount\n );\n upload(req, res, (err) => {\n if (err instanceof multer.MulterError) return next(err);\n else if (err) return next(err);\n next();\n });\n };\n }\n\n /**\n * Middleware to handle deletion of a single file from the filesystem.\n * @param {string} oldFilePath - The path to the file to be deleted.\n * @returns {Function} Middleware function for handling file deletion.\n */\n public handleDeleteSingleFile(oldFilePath: string) {\n return async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: NextFunction\n ) => {\n const filePath = path.join(oldFilePath);\n try {\n const stats = await promisify(fs.stat)(filePath);\n if (stats) {\n await promisify(fs.unlink)(filePath);\n }\n } catch (err) {\n console.error(err);\n }\n\n next();\n };\n }\n\n /**\n * Deletes a file based on its URL by identifying the appropriate uploader service\n * @param {string} fileUrl - The URL of the file to delete\n * @returns {Promise<boolean>} - True if deletion successful, false otherwise\n */\n public async deleteFileByUrl(fileUrl: string): Promise<boolean> {\n try {\n // Get configuration values\n const { fileUpload } = getArkosConfig();\n const baseRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n // Parse the URL to get the path\n let urlPath: string;\n if (fileUrl.startsWith(\"http\")) {\n const url = new URL(fileUrl);\n urlPath = url.pathname;\n } else {\n urlPath = fileUrl;\n }\n\n // Extract the path after the base route\n const baseRouteIndex = urlPath.indexOf(baseRoute);\n if (baseRouteIndex === -1) {\n throw new AppError(\"Invalid file URL: base route not found\", 400);\n }\n\n const pathAfterBaseRoute = urlPath.substring(\n baseRouteIndex + baseRoute.length\n );\n const cleanPath = pathAfterBaseRoute.startsWith(\"/\")\n ? pathAfterBaseRoute.substring(1)\n : pathAfterBaseRoute;\n\n // Determine file type and file name\n const fileTypes = [\"images\", \"videos\", \"documents\", \"files\"];\n let fileType: string | null = null;\n let fileName: string | null = null;\n\n for (const type of fileTypes) {\n const typeIndex = cleanPath.indexOf(type + \"/\");\n if (typeIndex !== -1) {\n fileType = type;\n fileName = cleanPath.substring(typeIndex + type.length + 1);\n break;\n }\n }\n\n if (!fileType || !fileName) {\n throw new AppError(\n \"Unable to determine file type or file name from URL\",\n 400\n );\n }\n\n // Get the appropriate uploader service based on file type\n const {\n documentUploaderService,\n fileUploaderService,\n imageUploaderService,\n videoUploaderService,\n } = getFileUploaderServices();\n\n let filePath: string;\n switch (fileType) {\n case \"images\":\n filePath = path.join(imageUploaderService.uploadDir, fileName);\n break;\n case \"videos\":\n filePath = path.join(videoUploaderService.uploadDir, fileName);\n break;\n case \"documents\":\n filePath = path.join(documentUploaderService.uploadDir, fileName);\n break;\n case \"files\":\n filePath = path.join(fileUploaderService.uploadDir, fileName);\n break;\n default:\n throw new AppError(`Unsupported file type: ${fileType}`, 400);\n }\n\n // Delete the file\n\n await promisify(fs.stat)(filePath);\n await promisify(fs.unlink)(filePath);\n\n return true;\n } catch (error: any) {\n if (error instanceof AppError) {\n throw error;\n }\n\n if (error.code === \"ENOENT\") {\n throw new AppError(\"File not found\", 404);\n }\n\n throw new AppError(`Failed to delete file: ${error.message}`, 500);\n }\n }\n\n private getFieldName() {\n let fieldName = \"files\";\n if (this.uploadDir.endsWith(\"images\") || this.uploadDir.endsWith(\"images/\"))\n fieldName = \"images\";\n if (this.uploadDir.endsWith(\"videos\") || this.uploadDir.endsWith(\"videos/\"))\n fieldName = \"videos\";\n if (\n this.uploadDir.endsWith(\"documents\") ||\n this.uploadDir.endsWith(\"documents/\")\n )\n fieldName = \"documents\";\n if (this.uploadDir.endsWith(\"files\") || this.uploadDir.endsWith(\"files/\"))\n fieldName = \"files\";\n return fieldName;\n }\n\n /**\n * Handles the upload process and returns the full URLs of uploaded files\n * @param {ArkosRequest} req - Arkos request object containing the files\n * @param {ArkosResponse} res - Arkos response object\n * @param {object} options - Optional parameters for image processing\n * @returns {Promise<string|string[]>} URL or array of URLs to the uploaded files\n */\n public async upload(\n req: ArkosRequest,\n res: ArkosResponse,\n options: {\n format?: string;\n width?: number;\n height?: number;\n resizeTo?: number;\n } = {}\n ): Promise<string | string[] | null> {\n const { fileUpload } = getArkosConfig();\n const baseRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n return new Promise((resolve, reject) => {\n // Determine if it's a single or multiple file upload\n const isMultiple = Array.isArray(req.query.multiple)\n ? req.query.multiple[0] == \"true\"\n : req.query.multiple == \"true\";\n\n // Use appropriate upload handler\n const uploadHandler = isMultiple\n ? this.getUploader().array(this.getFieldName(), this.maxCount)\n : this.getUploader().single(this.getFieldName());\n\n uploadHandler(req, res, async (err) => {\n if (err) return reject(err);\n\n try {\n // Determine the base URL for file access\n const protocol = req.get(\"host\")?.includes?.(\"localhost\")\n ? \"http\"\n : \"https\";\n const baseURL = `${protocol}://${req.get(\"host\")}`;\n\n // Get file type from uploadDir path\n const dirParts = this.uploadDir.split(\"/\");\n const fileType =\n (this.uploadDir.endsWith(\"/\")\n ? dirParts[dirParts.length - 2]\n : dirParts[dirParts.length - 1]) || \"files\";\n\n // Process all uploaded files\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n // Process multiple files\n const isImageUploader = this.uploadDir?.includes?.(\"/images\");\n if (isImageUploader) {\n data = await Promise.all(\n req.files.map((file) => processImage(req, file.path, options))\n );\n } else {\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n // Filter out any null values from failed processing\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n // Process a single file\n const isImageUploader = this.uploadDir?.includes?.(\"/images\");\n if (isImageUploader) {\n data = await processImage(req, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n } else {\n return reject(new AppError(\"No file uploaded\", 400));\n }\n\n resolve(data);\n } catch (error) {\n reject(error);\n }\n });\n });\n }\n}\n\n/**\n * Creates and returns all file uploader services based on config\n * @returns Object containing all specialized file uploader services\n */\nexport const getFileUploaderServices = () => {\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n // Default regex patterns for each file type\n const defaultRegexPatterns = {\n images:\n /jpeg|jpg|png|gif|webp|svg|bmp|tiff|heif|heic|ico|jfif|raw|cr2|nef|orf|sr2|arw|dng|pef|raf|rw2|psd|ai|eps|xcf|jxr|wdp|hdp|jp2|j2k|jpf|jpx|jpm|mj2|avif/,\n videos:\n /mp4|avi|mov|mkv|flv|wmv|webm|mpg|mpeg|3gp|m4v|ts|rm|rmvb|vob|ogv|dv|qt|asf|m2ts|mts|divx|f4v|swf|mxf|roq|nsv|mvb|svi|mpe|m2v|mp2|mpv|h264|h265|hevc/,\n documents:\n /pdf|doc|docx|xls|xlsx|ppt|pptx|odt|ods|odg|odp|txt|rtf|csv|epub|md|tex|pages|numbers|key|xml|json|yaml|yml|ini|cfg|conf|log|html|htm|xhtml|djvu|mobi|azw|azw3|fb2|lit|ps|wpd|wps|dot|dotx|xlt|xltx|pot|potx|oft|one|onetoc2|opf|oxps|hwp/,\n files: /.*/,\n };\n\n // Default upload restrictions\n const defaultRestrictions = {\n images: {\n maxCount: 30,\n maxSize: 1024 * 1024 * 15, // 15 MB\n supportedFilesRegex:\n /jpeg|jpg|png|gif|webp|svg|bmp|tiff|heif|heic|ico|jfif|raw|cr2|nef|orf|sr2|arw|dng|pef|raf|rw2|psd|ai|eps|xcf|jxr|wdp|hdp|jp2|j2k|jpf|jpx|jpm|mj2|avif/,\n },\n videos: {\n maxCount: 10,\n maxSize: 1024 * 1024 * 5096, // 5 GB\n supportedFilesRegex:\n /mp4|avi|mov|mkv|flv|wmv|webm|mpg|mpeg|3gp|m4v|ts|rm|rmvb|vob|ogv|dv|qt|asf|m2ts|mts|divx|f4v|swf|mxf|roq|nsv|mvb|svi|mpe|m2v|mp2|mpv|h264|h265|hevc/,\n },\n documents: {\n maxCount: 30,\n maxSize: 1024 * 1024 * 50, // 50 MB\n supportedFilesRegex:\n /pdf|doc|docx|xls|xlsx|ppt|pptx|odt|ods|odg|odp|txt|rtf|csv|epub|md|tex|pages|numbers|key|xml|json|yaml|yml|ini|cfg|conf|log|html|htm|xhtml|djvu|mobi|azw|azw3|fb2|lit|ps|wpd|wps|dot|dotx|xlt|xltx|pot|potx|oft|one|onetoc2|opf|oxps|hwp/,\n },\n files: {\n maxCount: 10,\n maxSize: 1024 * 1024 * 5096, // 5 GB\n supportedFilesRegex: /.*/,\n },\n };\n\n // Merge with user configuration (if any)\n const restrictions = fileUpload?.restrictions\n ? deepmerge(defaultRestrictions, fileUpload.restrictions)\n : defaultRestrictions;\n\n /**\n * Specialized file uploader service for handling image uploads.\n */\n const imageUploaderService = new FileUploaderService(\n `${baseUploadDir}/images`,\n restrictions.images.maxSize,\n restrictions.images.supportedFilesRegex,\n restrictions.images.maxCount\n );\n\n /**\n * Specialized file uploader service for handling video uploads.\n */\n const videoUploaderService = new FileUploaderService(\n `${baseUploadDir}/videos`,\n restrictions.videos.maxSize,\n restrictions.videos.supportedFilesRegex,\n restrictions.videos.maxCount\n );\n\n /**\n * Specialized file uploader service for handling document uploads.\n */\n const documentUploaderService = new FileUploaderService(\n `${baseUploadDir}/documents`,\n restrictions.documents.maxSize,\n restrictions.documents.supportedFilesRegex,\n restrictions.documents.maxCount\n );\n\n /**\n * Generic file uploader service for handling all file uploads.\n */\n const fileUploaderService = new FileUploaderService(\n `${baseUploadDir}/files`,\n restrictions.files.maxSize,\n restrictions.files.supportedFilesRegex,\n restrictions.files.maxCount\n );\n\n return {\n imageUploaderService,\n videoUploaderService,\n documentUploaderService,\n fileUploaderService,\n };\n};\n"]}
@@ -21,10 +21,12 @@ const util_1 = require("util");
21
21
  const server_1 = require("../../../../server");
22
22
  const mimetype_1 = __importDefault(require("mimetype"));
23
23
  function extractRequestInfo(req) {
24
- var _a, _b, _c;
24
+ var _a, _b, _c, _d;
25
25
  const { fileUpload } = (0, server_1.getArkosConfig)();
26
- const protocol = ((_b = (_a = req.get) === null || _a === void 0 ? void 0 : _a.call(req, "host")) === null || _b === void 0 ? void 0 : _b.includes("localhost")) ? "http" : "https";
27
- const baseURL = `${protocol}://${(_c = req.get) === null || _c === void 0 ? void 0 : _c.call(req, "host")}`;
26
+ const protocol = ((_c = (_b = (_a = req.get) === null || _a === void 0 ? void 0 : _a.call(req, "host")) === null || _b === void 0 ? void 0 : _b.includes) === null || _c === void 0 ? void 0 : _c.call(_b, "localhost"))
27
+ ? "http"
28
+ : "https";
29
+ const baseURL = `${protocol}://${(_d = req.get) === null || _d === void 0 ? void 0 : _d.call(req, "host")}`;
28
30
  const baseRoute = (fileUpload === null || fileUpload === void 0 ? void 0 : fileUpload.baseRoute) || "/api/uploads";
29
31
  return { baseURL, baseRoute };
30
32
  }
@@ -47,12 +49,12 @@ const processFile = (req, filePath) => __awaiter(void 0, void 0, void 0, functio
47
49
  });
48
50
  exports.processFile = processFile;
49
51
  const processImage = (req, filePath, options) => __awaiter(void 0, void 0, void 0, function* () {
50
- var _a;
52
+ var _a, _b;
51
53
  const { baseURL, baseRoute } = extractRequestInfo(req);
52
54
  const ext = path_1.default.extname(filePath).toLowerCase();
53
55
  const originalFormat = ext.replace(".", "");
54
56
  const outputFormat = options.format || originalFormat;
55
- if (!((_a = mimetype_1.default.lookup(ext)) === null || _a === void 0 ? void 0 : _a.includes("image"))) {
57
+ if (!((_b = (_a = mimetype_1.default.lookup(ext)) === null || _a === void 0 ? void 0 : _a.includes) === null || _b === void 0 ? void 0 : _b.call(_a, "image"))) {
56
58
  const relativePath = generateRelativePath(filePath, req.params.fileType);
57
59
  return `${baseURL}${baseRoute}/${relativePath}`;
58
60
  }
@@ -1 +1 @@
1
- {"version":3,"file":"file-uploader.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/file-uploader/utils/helpers/file-uploader.helpers.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAQA,gDAQC;AAhBD,4CAAoB;AACpB,gDAAwB;AACxB,kDAA0B;AAC1B,+BAAiC;AACjC,+CAAoD;AACpD,wDAAgC;AAGhC,SAAgB,kBAAkB,CAAC,GAA0B;;IAC3D,MAAM,EAAE,UAAU,EAAE,GAAG,IAAA,uBAAc,GAAE,CAAC;IAGxC,MAAM,QAAQ,GAAG,CAAA,MAAA,MAAA,GAAG,CAAC,GAAG,oDAAG,MAAM,CAAC,0CAAE,QAAQ,CAAC,WAAW,CAAC,EAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC;IAC7E,MAAM,OAAO,GAAG,GAAG,QAAQ,MAAM,MAAA,GAAG,CAAC,GAAG,oDAAG,MAAM,CAAC,EAAE,CAAC;IACrD,MAAM,SAAS,GAAG,CAAA,UAAU,aAAV,UAAU,uBAAV,UAAU,CAAE,SAAS,KAAI,cAAc,CAAC;IAC1D,OAAO,EAAE,OAAO,EAAE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AO,GAAG,EAAE,CAAC;QAEf,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC,CAAA,CAAC;AArEW,QAAA,YAAY,gBAqEvB","sourcesContent":["import fs from \"fs\";\nimport path from \"path\";\nimport sharp from \"sharp\";\nimport { promisify } from \"util\";\nimport { getArkosConfig } from \"../../../../server\";\nimport mimetype from \"mimetype\";\nimport { ArkosRequest } from \"../../../../types\";\n\nexport function extractRequestInfo(req: Partial<ArkosRequest>) {\n const { fileUpload } = getArkosConfig();\n\n // Determine the base URL for file access\n const protocol = req.get?.(\"host\")?.includes(\"localhost\") ? \"http\" : \"https\";\n const baseURL = `${protocol}://${req.get?.(\"host\")}`;\n const baseRoute = fileUpload?.baseRoute || \"/api/uploads\";\n return { baseURL, baseRoute };\n}\n\n/**\n * Generates the correct relative path regardless of upload directory location\n */\nconst generateRelativePath = (filePath: string, fileType: string) => {\n const { fileUpload } = getArkosConfig();\n\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n if (baseUploadDir.startsWith(\"..\")) {\n // For paths outside project directory\n return path.join(fileType, path.basename(filePath));\n } else {\n // For paths within project\n return filePath\n .replace(`${baseUploadDir}/`, \"\")\n .replace(process.cwd() + \"/\", \"\");\n }\n};\n\n/**\n * Handles basic file processing for non-image files\n */\nexport const processFile = async (\n req: Partial<ArkosRequest>,\n filePath: string\n): Promise<string> => {\n const { baseURL, baseRoute } = extractRequestInfo(req);\n\n const relativePath = generateRelativePath(filePath, req.params!.fileType);\n return `${baseURL}${baseRoute === \"/\" ? \"\" : baseRoute}/${relativePath}`;\n};\n\n/**\n * Processes image files using Sharp for resizing and format conversion\n */\nexport const processImage = async (\n req: Partial<ArkosRequest>,\n filePath: string,\n options: Record<string, any>\n): Promise<string | null> => {\n const { baseURL, baseRoute } = extractRequestInfo(req);\n\n const ext = path.extname(filePath).toLowerCase();\n const originalFormat = ext.replace(\".\", \"\");\n const outputFormat = options.format || originalFormat;\n\n if (!mimetype.lookup(ext)?.includes(\"image\")) {\n const relativePath = generateRelativePath(filePath, req.params!.fileType);\n return `${baseURL}${baseRoute}/${relativePath}`;\n }\n\n // Create a temp filename with original name + random string\n const tempName = `${path.basename(filePath, ext)}_${Date.now()}${ext}`;\n const tempPath = path.join(path.dirname(filePath), tempName);\n\n try {\n let transformer = sharp(filePath);\n const metadata = await transformer.metadata();\n\n // Apply resize transformations if requested\n if (options.resizeTo && metadata.width && metadata.height) {\n const targetSize = options.resizeTo;\n const scaleFactor =\n targetSize / Math.min(metadata.width, metadata.height);\n const newWidth = Math.round(metadata.width * scaleFactor);\n const newHeight = Math.round(metadata.height * scaleFactor);\n transformer = transformer.resize(newWidth, newHeight);\n } else if (options.width || options.height) {\n transformer = transformer.resize(\n options.width || null,\n options.height || null,\n {\n fit: \"inside\",\n }\n );\n }\n\n // Apply format transformations if requested\n if (outputFormat === \"webp\") {\n transformer = transformer.toFormat(\"webp\");\n } else if (outputFormat === \"jpeg\" || outputFormat === \"jpg\") {\n transformer = transformer.toFormat(\"jpeg\");\n }\n\n // Save to temp file first\n await transformer.toFile(tempPath);\n\n // Rename temp file to original filename\n await promisify(fs.rename)(tempPath, filePath);\n\n // Return the public URL for the file\n const relativePath = generateRelativePath(filePath, req?.params!.fileType);\n\n return `${baseURL}${baseRoute}/${relativePath}`;\n } catch (error) {\n // Clean up temp file if it exists\n try {\n await promisify(fs.stat)(tempPath);\n await promisify(fs.unlink)(tempPath);\n } catch (err) {\n // If temp file doesn't exist, no need to clean up\n }\n throw error;\n }\n};\n"]}
1
+ {"version":3,"file":"file-uploader.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/file-uploader/utils/helpers/file-uploader.helpers.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAQA,gDAUC;AAlBD,4CAAoB;AACpB,gDAAwB;AACxB,kDAA0B;AAC1B,+BAAiC;AACjC,+CAAoD;AACpD,wDAAgC;AAGhC,SAAgB,kBAAkB,CAAC,GAA0B;;IAC3D,MAAM,EAAE,U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,QAAQ,CAAC,CAAC;QAG/C,MAAM,YAAY,GAAG,oBAAoB,CAAC,QAAQ,EAAE,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,MAAM,CAAE,QAAQ,CAAC,CAAC;QAE3E,OAAO,GAAG,OAAO,GAAG,SAAS,IAAI,YAAY,EAAE,CAAC;IAClD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAEf,IAAI,CAAC;YACH,MAAM,IAAA,gBAAS,EAAC,YAAE,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,CAAC;YACnC,MAAM,IAAA,gBAAS,EAAC,YAAE,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,CAAC;QACvC,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;QAEf,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC,CAAA,CAAC;AArEW,QAAA,YAAY,gBAqEvB","sourcesContent":["import fs from \"fs\";\nimport path from \"path\";\nimport sharp from \"sharp\";\nimport { promisify } from \"util\";\nimport { getArkosConfig } from \"../../../../server\";\nimport mimetype from \"mimetype\";\nimport { ArkosRequest } from \"../../../../types\";\n\nexport function extractRequestInfo(req: Partial<ArkosRequest>) {\n const { fileUpload } = getArkosConfig();\n\n // Determine the base URL for file access\n const protocol = req.get?.(\"host\")?.includes?.(\"localhost\")\n ? \"http\"\n : \"https\";\n const baseURL = `${protocol}://${req.get?.(\"host\")}`;\n const baseRoute = fileUpload?.baseRoute || \"/api/uploads\";\n return { baseURL, baseRoute };\n}\n\n/**\n * Generates the correct relative path regardless of upload directory location\n */\nconst generateRelativePath = (filePath: string, fileType: string) => {\n const { fileUpload } = getArkosConfig();\n\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n if (baseUploadDir.startsWith(\"..\")) {\n // For paths outside project directory\n return path.join(fileType, path.basename(filePath));\n } else {\n // For paths within project\n return filePath\n .replace(`${baseUploadDir}/`, \"\")\n .replace(process.cwd() + \"/\", \"\");\n }\n};\n\n/**\n * Handles basic file processing for non-image files\n */\nexport const processFile = async (\n req: Partial<ArkosRequest>,\n filePath: string\n): Promise<string> => {\n const { baseURL, baseRoute } = extractRequestInfo(req);\n\n const relativePath = generateRelativePath(filePath, req.params!.fileType);\n return `${baseURL}${baseRoute === \"/\" ? \"\" : baseRoute}/${relativePath}`;\n};\n\n/**\n * Processes image files using Sharp for resizing and format conversion\n */\nexport const processImage = async (\n req: Partial<ArkosRequest>,\n filePath: string,\n options: Record<string, any>\n): Promise<string | null> => {\n const { baseURL, baseRoute } = extractRequestInfo(req);\n\n const ext = path.extname(filePath).toLowerCase();\n const originalFormat = ext.replace(\".\", \"\");\n const outputFormat = options.format || originalFormat;\n\n if (!mimetype.lookup(ext)?.includes?.(\"image\")) {\n const relativePath = generateRelativePath(filePath, req.params!.fileType);\n return `${baseURL}${baseRoute}/${relativePath}`;\n }\n\n // Create a temp filename with original name + random string\n const tempName = `${path.basename(filePath, ext)}_${Date.now()}${ext}`;\n const tempPath = path.join(path.dirname(filePath), tempName);\n\n try {\n let transformer = sharp(filePath);\n const metadata = await transformer.metadata();\n\n // Apply resize transformations if requested\n if (options.resizeTo && metadata.width && metadata.height) {\n const targetSize = options.resizeTo;\n const scaleFactor =\n targetSize / Math.min(metadata.width, metadata.height);\n const newWidth = Math.round(metadata.width * scaleFactor);\n const newHeight = Math.round(metadata.height * scaleFactor);\n transformer = transformer.resize(newWidth, newHeight);\n } else if (options.width || options.height) {\n transformer = transformer.resize(\n options.width || null,\n options.height || null,\n {\n fit: \"inside\",\n }\n );\n }\n\n // Apply format transformations if requested\n if (outputFormat === \"webp\") {\n transformer = transformer.toFormat(\"webp\");\n } else if (outputFormat === \"jpeg\" || outputFormat === \"jpg\") {\n transformer = transformer.toFormat(\"jpeg\");\n }\n\n // Save to temp file first\n await transformer.toFile(tempPath);\n\n // Rename temp file to original filename\n await promisify(fs.rename)(tempPath, filePath);\n\n // Return the public URL for the file\n const relativePath = generateRelativePath(filePath, req?.params!.fileType);\n\n return `${baseURL}${baseRoute}/${relativePath}`;\n } catch (error) {\n // Clean up temp file if it exists\n try {\n await promisify(fs.stat)(tempPath);\n await promisify(fs.unlink)(tempPath);\n } catch (err) {\n // If temp file doesn't exist, no need to clean up\n }\n throw error;\n }\n};\n"]}
@@ -1 +1 @@
1
- "use strict";var __awaiter=this&&this.__awaiter||function(e,t,n,s){function u(r){return r instanceof n?r:new n(function(i){i(r)})}return new(n||(n=Promise))(function(r,i){function l(o){try{p(s.next(o))}catch(c){i(c)}}function a(o){try{p(s.throw(o))}catch(c){i(c)}}function p(o){o.done?r(o.value):u(o.value).then(l,a)}p((s=s.apply(e,t||[])).next())})},__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.server=void 0,exports.getArkosConfig=getArkosConfig,exports.getExpressApp=getExpressApp,exports.initApp=initApp;const app_1=require("./app"),deepmerge_helper_1=__importDefault(require("./utils/helpers/deepmerge.helper"));process.on("uncaughtException",e=>{console.error("UNCAUGHT EXCEPTION! SHUTTING DOWN..."),console.error(e.name,e.message),console.error(e),process.exit(1)});let server,_app,_arkosConfig={welcomeMessage:"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com",port:8e3,fileUpload:{baseUploadDir:"uploads",baseRoute:"/api/uploads"}};function initApp(){return __awaiter(this,arguments,void 0,function*(e={}){_arkosConfig=(0,deepmerge_helper_1.default)(_arkosConfig,e);const t=_arkosConfig.port;return _app=yield(0,app_1.bootstrap)(_arkosConfig),t&&(exports.server=server=_app.listen(e?.host?[t,e?.host]:t,()=>{const n=new Date().toTimeString().split(" ")[0];console.info(`[\x1B[32mREADY\x1B[0m] \x1B[90m${n}\x1B[0m App running on port \x1B[33m${t}\x1B[0m, server waiting on http://localhost:${t}`),process.env.NODE_ENV&&console.info(`${`Environment: ${process.env.NODE_ENV}`}`)})),_app})}process.on("unhandledRejection",e=>{console.error("UNHANDLED REJECTION! SHUTTING DOWN..."),console.error(e.name,e.message),server.close(()=>{process.exit(1)})});function getArkosConfig(){return _arkosConfig}function getExpressApp(){return _app}
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(e,t,n,s){function u(r){return r instanceof n?r:new n(function(i){i(r)})}return new(n||(n=Promise))(function(r,i){function l(o){try{p(s.next(o))}catch(c){i(c)}}function a(o){try{p(s.throw(o))}catch(c){i(c)}}function p(o){o.done?r(o.value):u(o.value).then(l,a)}p((s=s.apply(e,t||[])).next())})},__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.server=void 0,exports.getArkosConfig=getArkosConfig,exports.getExpressApp=getExpressApp,exports.initApp=initApp;const app_1=require("./app"),deepmerge_helper_1=__importDefault(require("./utils/helpers/deepmerge.helper"));process.on("uncaughtException",e=>{console.error("UNCAUGHT EXCEPTION! SHUTTING DOWN..."),console.error(e.name,e.message),console.error(e),process.exit(1)});let server,_app,_arkosConfig={welcomeMessage:"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com",port:8e3,fileUpload:{baseUploadDir:"uploads",baseRoute:"/api/uploads"}};function initApp(){return __awaiter(this,arguments,void 0,function*(e={}){_arkosConfig=(0,deepmerge_helper_1.default)(_arkosConfig,e);const t=_arkosConfig.port;return _app=yield(0,app_1.bootstrap)(_arkosConfig),t&&(exports.server=server=_app.listen(e?.host?[t,e?.host]:t,()=>{const n=new Date().toTimeString().split(" ")[0];console.info(`[\x1B[32mREADY\x1B[0m] \x1B[90m${n}\x1B[0m App running on port \x1B[33m${t}\x1B[0m, server waiting on http://localhost:${t}`),process.env.NODE_ENV&&console.info(`${`Environment: ${process.env.NODE_ENV}`}`)})),_app})}process.on("unhandledRejection",e=>{console.error("UNHANDLED REJECTION! SHUTTING DOWN..."),console.error(e.name,e.message),console.error(e),server.close(()=>{process.exit(1)})});function getArkosConfig(){return _arkosConfig}function getExpressApp(){return _app}
@@ -1 +1 @@
1
- {"version":3,"file":"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AAC,CAAC;gBACrD,OAAO,CAAC,IAAI,CACV,kCAAkC,IAAI,uCAAuC,IAAI,+CAA+C,IAAI,EAAE,CACvI,CAAC;gBAEF,IAAI,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ;oBACxB,OAAO,CAAC,IAAI,CAAC,GAAG,gBAAgB,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;YAC9D,CAAC,CACF,CAAC;QAEJ,OAAO,IAAI,CAAC;IACd,CAAC;CAAA;AAED,OAAO,CAAC,EAAE,CAAC,oBAAoB,EAAE,CAAC,GAAa,EAAE,EAAE;IACjD,OAAO,CAAC,KAAK,CAAC,uCAAuC,CAAC,CAAC;IACvD,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE;QAChB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,SAAgB,cAAc;IAC5B,OAAO,YAAY,CAAC;AACtB,CAAC;AAED,SAAgB,aAAa;IAC3B,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { IncomingMessage, Server, ServerResponse } from \"http\";\nimport AppError from \"./modules/error-handler/utils/app-error\";\nimport { Express } from \"express\";\nimport { bootstrap } from \"./app\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\n\nprocess.on(\"uncaughtException\", (err) => {\n console.error(\"UNCAUGHT EXCEPTION! SHUTTING DOWN...\");\n console.error(err.name, err.message);\n console.error(err);\n process.exit(1);\n});\n\nlet server: Server<typeof IncomingMessage, typeof ServerResponse>;\nlet _app: Express;\n\nlet _arkosConfig: ArkosConfig = {\n welcomeMessage:\n \"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com\",\n port: 8000,\n fileUpload: {\n baseUploadDir: \"uploads\",\n baseRoute: \"/api/uploads\",\n },\n};\n\n/**\n * Initializes the application server.\n *\n * This function starts the server by listening on a specified port.\n * The port is determined by the following order of precedence:\n * 1. The `port` argument passed to the function.\n * 2. Defaults to `8000` if neither is provided.\n *\n * @param {ArkosConfig} arkosConfig - initial configs for the api ( authentication, port).\n * @returns {Promise<Express>} This function returns the Express App after all middlewares configurations.\n * You can prevent it from listen py passing port as undefined\n *\n */\nasync function initApp(arkosConfig: ArkosConfig = {}): Promise<Express> {\n _arkosConfig = deepmerge(_arkosConfig, arkosConfig);\n\n const port = _arkosConfig.port;\n _app = await bootstrap(_arkosConfig);\n\n if (port)\n server = _app.listen(\n arkosConfig?.host ? [port, arkosConfig?.host!] : port,\n () => {\n const time = new Date().toTimeString().split(\" \")[0];\n console.info(\n `[\\x1b[32mREADY\\x1b[0m] \\x1b[90m${time}\\x1b[0m App running on port \\x1b[33m${port}\\x1b[0m, server waiting on http://localhost:${port}`\n );\n\n if (!!process.env.NODE_ENV)\n console.info(`${`Environment: ${process.env.NODE_ENV}`}`);\n }\n );\n\n return _app;\n}\n\nprocess.on(\"unhandledRejection\", (err: AppError) => {\n console.error(\"UNHANDLED REJECTION! SHUTTING DOWN...\");\n console.error(err.name, err.message);\n server.close(() => {\n process.exit(1);\n });\n});\n\nexport function getArkosConfig() {\n return _arkosConfig;\n}\n\nexport function getExpressApp() {\n return _app;\n}\n\nexport { server, initApp };\n"]}
1
+ {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAwEA,wCAEC;AAED,sCAEC;AAEgB,0BAAO;AA7ExB,+BAAkC;AAElC,wFAAyD;AAEzD,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,GAAG,EAAE,EAAE;IACtC,OAAO,CAAC,KAAK,CAAC,sCAAsC,CAAC,CAAC;IACtD,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAA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,CAAC;CAAA;AAED,OAAO,CAAC,EAAE,CAAC,oBAAoB,EAAE,CAAC,GAAa,EAAE,EAAE;IACjD,OAAO,CAAC,KAAK,CAAC,uCAAuC,CAAC,CAAC;IACvD,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE;QAChB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,SAAgB,cAAc;IAC5B,OAAO,YAAY,CAAC;AACtB,CAAC;AAED,SAAgB,aAAa;IAC3B,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { IncomingMessage, Server, ServerResponse } from \"http\";\nimport AppError from \"./modules/error-handler/utils/app-error\";\nimport { Express } from \"express\";\nimport { bootstrap } from \"./app\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\n\nprocess.on(\"uncaughtException\", (err) => {\n console.error(\"UNCAUGHT EXCEPTION! SHUTTING DOWN...\");\n console.error(err.name, err.message);\n console.error(err);\n process.exit(1);\n});\n\nlet server: Server<typeof IncomingMessage, typeof ServerResponse>;\nlet _app: Express;\n\nlet _arkosConfig: ArkosConfig = {\n welcomeMessage:\n \"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com\",\n port: 8000,\n fileUpload: {\n baseUploadDir: \"uploads\",\n baseRoute: \"/api/uploads\",\n },\n};\n\n/**\n * Initializes the application server.\n *\n * This function starts the server by listening on a specified port.\n * The port is determined by the following order of precedence:\n * 1. The `port` argument passed to the function.\n * 2. Defaults to `8000` if neither is provided.\n *\n * @param {ArkosConfig} arkosConfig - initial configs for the api ( authentication, port).\n * @returns {Promise<Express>} This function returns the Express App after all middlewares configurations.\n * You can prevent it from listen py passing port as undefined\n *\n */\nasync function initApp(arkosConfig: ArkosConfig = {}): Promise<Express> {\n _arkosConfig = deepmerge(_arkosConfig, arkosConfig);\n\n const port = _arkosConfig.port;\n _app = await bootstrap(_arkosConfig);\n\n if (port)\n server = _app.listen(\n arkosConfig?.host ? [port, arkosConfig?.host!] : port,\n () => {\n const time = new Date().toTimeString().split(\" \")[0];\n console.info(\n `[\\x1b[32mREADY\\x1b[0m] \\x1b[90m${time}\\x1b[0m App running on port \\x1b[33m${port}\\x1b[0m, server waiting on http://localhost:${port}`\n );\n\n if (!!process.env.NODE_ENV)\n console.info(`${`Environment: ${process.env.NODE_ENV}`}`);\n }\n );\n\n return _app;\n}\n\nprocess.on(\"unhandledRejection\", (err: AppError) => {\n console.error(\"UNHANDLED REJECTION! SHUTTING DOWN...\");\n console.error(err.name, err.message);\n console.error(err);\n server.close(() => {\n process.exit(1);\n });\n});\n\nexport function getArkosConfig() {\n return _arkosConfig;\n}\n\nexport function getExpressApp() {\n return _app;\n}\n\nexport { server, initApp };\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"arkos-config.js","sourceRoot":"","sources":["../../../src/types/arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import cors from \"cors\";\nimport express from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { SignOptions } from \"jsonwebtoken\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /** Message you would like to send, as Json and 200 response when\n * ```\n * GET /api\n * ```\n * ```json\n * { \"message\": \"Welcome to YourAppName\" }\n * ```\n *\n * default message is: Welcome to our Rest API generated by Arkos, find more about Arkos at www.arkosjs.com,\n *\n *\n * */\n welcomeMessage?: string;\n /**\n * Port where the application will run, can be set in 3 ways:\n *\n * 1. default is 8000\n * 2. PORT under environment variables (Lower precedence)\n * 3. this config option (Higher precedence)\n */\n port?: number | undefined;\n /**\n * Allows to listen on a different host than localhost only\n */\n host?: string;\n /**\n * Defines authentication related configurations, by default is undefined.\n *\n * See [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for details.\n */\n authentication?: {\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /**\n * Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * See more at [www.arkosjs.com/docs/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/authentication-system/sending-authentication-requests#example-changing-the-username-field)\n *\n * By specifing here another field for username, for example passing \"email\", \"companyCode\" or something else your json will be like:\n *\n * **Example with email**\n *\n * ```json\n * {\n * \"email\": \"john.doe@example.com\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n */\n allowedUsernames?: string[];\n /** Defines wether to send the access token in response after login or only send as cookie, defeault is both.*/\n sendAccessTokenThrough?: \"cookie-only\" | \"response-only\" | \"both\";\n };\n /**\n * @deprecated\n *\n * **Use this instead**:\n *\n * ```ts\n * arkos.init({\n * authentication: {\n * login: {\n * allowedUsernames: [\"email\", \"profile.nickname\"]\n * }\n * }\n * })\n * ```\n *\n * * See more at [www.arkosjs.com/docs/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/authentication-system/sending-authentication-requests#example-changing-the-username-field)\n *\n */\n usernameField?: string;\n /**\n * Specifies the regex pattern used by the authentication system to enforce password strength requirements.\n *\n * **Important**: If using validation libraries like Zod or class-validator, this will be completely overwritten.\n *\n * **Default**: ```/^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/``` - Ensures the password contains at least one uppercase letter, one lowercase letter, and one numeric digit.\n *\n * **message**: (Optional) A custom error message to display when the password does not meet the required strength criteria.\n */\n passwordValidation?: { regex: RegExp; message?: string };\n /**\n * Allows to specify the request rate limit for all authentication endpoints but `/api/users/me`.\n * \n * #### Default\n *{\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n requestRateLimitOptions?: RateLimitOptions;\n /**\n * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_EXPIRES_IN`: Defaults to 90 (used for calculating cookie expiration).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n * ⚠️ Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n */\n secure?: boolean;\n\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n */\n httpOnly?: boolean;\n\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n };\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * See [www.arkosjs.com/docs/core-concepts/request-data-validation](https://www.arkosjs.com/docs/core-concepts/request-data-validation) for more details.\n */\n validation?:\n | {\n resolver?: \"class-validator\";\n /**\n * ValidatorOptions to used while validating request data.\n *\n * **Default**:\n * ```ts\n * {\n * whitelist: true\n * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver?: \"zod\";\n validationOptions?: Record<string, any>;\n };\n /**\n * Defines file upload configurations\n *\n * See [www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations](https://www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations)\n */\n fileUpload?: {\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n expressStaticOptions?: Parameters<typeof express.static>[1];\n /**\n * Defines upload restrictions for each file type: image, video, document or other.\n *\n * #### Important:\n * Passing an object without overriding everything will only cause it\n * to be deepmerged with the default options.\n *\n * See [www.arkosjs.com/docs/api-reference/default-supported-upload-files](https://www.arkosjs.com/docs/api-reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n restrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n files?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * Allows to specify the request rate limit for all endpoints.\n * \n * #### Default\n *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n ```\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n globalRequestRateLimitOptions?: Partial<RateLimitOptions>;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n jsonBodyParserOptions?: Parameters<typeof express.json>[0];\n /**\n * Allows to pass paremeters to cookieParser from npm package cookie-parser\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/cookie-parser](https://www.npmjs.com/package/cookie-parser) for further details.\n */\n cookieParserParameters?: Parameters<typeof cookieParser>;\n /**\n * Allows to define options for npm package compression\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/compression](https://www.npmjs.com/package/compression) for further details.\n */\n compressionOptions?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * #### for example:\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n * \n * #### Default:\n * \n * {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n }\n * \n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n * \n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParserOptions?: QueryParserOptions;\n /**\n * Configuration for CORS (Cross-Origin Resource Sharing).\n *\n * @property {string | string[] | \"all\"} [allowedOrigins] - List of allowed origins. If set to `\"all\"`, all origins are accepted.\n * @property {import('cors').CorsOptions} [options] - Additional CORS options passed directly to the `cors` middleware.\n * @property {import('cors').CorsOptionsDelegate} [customMiddleware] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customMiddleware` is provided, both `allowedOrigins` and `options` will be ignored in favor of the custom logic.\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?: {\n allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware\n *\n * see\n */\n customHandler?: cors.CorsOptionsDelegate;\n };\n /**\n * Defines express/arkos middlewares configurations\n */\n middlewares?: {\n /**\n * Allows to add an array of custom express middlewares into the default middleware stack.\n *\n * **Tip**: If you would like to acess the express app before everthing use `configureApp` and pass a function.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order](https://www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order)\n *\n * **Note**: If you want to use custom global error handler middleware use `middlewares.replace.globalErrorHandler`.\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.RequestHandler[];\n /**\n * An array containing a list of defaults middlewares to be disabled\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n disable?: (\n | \"compression\"\n | \"global-rate-limit\"\n | \"auth-rate-limit\"\n | \"cors\"\n | \"express-json\"\n | \"cookie-parser\"\n | \"query-parser\"\n | \"database-connection\"\n | \"request-logger\"\n | \"global-error-handler\"\n )[];\n /**\n * Allows you to replace each of the built-in middlewares with your own implementation\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default compression middleware\n */\n compression?: express.RequestHandler;\n /**\n * Replace the default global rate limit middleware\n */\n globalRateLimit?: express.RequestHandler;\n /**\n * Replace the default authentication rate limit middleware\n */\n authRateLimit?: express.RequestHandler;\n /**\n * Replace the default CORS middleware\n */\n cors?: express.RequestHandler;\n /**\n * Replace the default JSON body parser middleware\n */\n expressJson?: express.RequestHandler;\n /**\n * Replace the default cookie parser middleware\n */\n cookieParser?: express.RequestHandler;\n /**\n * Replace the default query parser middleware\n */\n queryParser?: express.RequestHandler;\n /**\n * Replace the default database connection check middleware\n */\n databaseConnection?: express.RequestHandler;\n /**\n * Replace the default request logger middleware\n */\n requestLogger?: express.RequestHandler;\n /**\n * Replace the default global error handler middleware\n */\n globalErrorHandler?: express.ErrorRequestHandler;\n };\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Allows to add an array of custom express routers into the default middleware/router stack.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/adding-custom-routers](https://www.arkosjs.com/docs/advanced-guide/adding-custom-routers)\n *\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.Router[];\n disable?: (\n | \"auth-router\"\n | \"prisma-models-router\"\n | \"file-uploader\"\n | \"welcome-endpoint\"\n )[];\n /**\n * Allows you to replace each of the built-in routers with your own implementation.\n *\n * **Note**: Doing this you will lose all default middleware chaining, auth control, handlers from the specific router.\n *\n * **Tip**: I you want to disable some prisma models specific endpoint\n * see [www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers#disabling-endpoints](https://www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers#disabling-endpoints)\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default authentication router\n * @param config The original Arkos configuration\n * @returns A router handling authentication endpoints\n */\n authRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default Prisma models router\n * @param config The original Arkos configuration\n * @returns A router handling Prisma model endpoints\n */\n prismaModelsRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default file uploader router\n * @param config The original Arkos configuration\n * @returns A router handling file upload endpoints\n */\n fileUploader?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default welcome endpoint handler\n * @param req Express request object\n * @param res Express response object\n * @param next Express next function\n */\n welcomeEndpoint?: express.RequestHandler;\n };\n };\n /**\n * Gives acess to the underlying express app so that you can add custom configurations beyong **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `app.listen` for you.\n *\n * If you want to call `app.listen` by yourself pass port as `undefined` and then use the return app from `arkos.init()`.\n *\n * See how to call `app.listen` correctly [www.arkosjs.com/docs/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/accessing-the-express-app](https://www.arkosjs.com/docs/accessing-the-express-app) for further details on the method configureApp.\n *\n * @param {express.Express} app\n * @returns {any}\n */\n configureApp?: (app: express.Express) => Promise<any> | any;\n /**\n * Allows to configure email configurations for sending emails through `emailService`\n *\n * See [www.arkosjs.com/docs/core-concepts/sending-emails](https://www.arkosjs.com/docs/core-concepts/sending-emails)\n */\n email?: {\n /**\n * Your email provider url\n */\n host: string;\n /**\n * Email provider SMTP port, Default is `465`\n */\n port?: number;\n /**\n * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n };\n};\n"]}
1
+ {"version":3,"file":"arkos-config.js","sourceRoot":"","sources":["../../../src/types/arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import cors from \"cors\";\nimport express from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for pass prisma query options.\n *\n * See more\n */\n allowDangerousPrismaQueryOptions?: boolean;\n };\n };\n /** Message you would like to send, as Json and 200 response when\n * ```\n * GET /api\n * ```\n * ```json\n * { \"message\": \"Welcome to YourAppName\" }\n * ```\n *\n * default message is: Welcome to our Rest API generated by Arkos, find more about Arkos at www.arkosjs.com,\n *\n *\n * */\n welcomeMessage?: string;\n /**\n * Port where the application will run, can be set in 3 ways:\n *\n * 1. default is 8000\n * 2. PORT under environment variables (Lower precedence)\n * 3. this config option (Higher precedence)\n */\n port?: number | undefined;\n /**\n * Allows to listen on a different host than localhost only\n */\n host?: string;\n /**\n * Defines authentication related configurations, by default is undefined.\n *\n * See [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for details.\n */\n authentication?: {\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/built-in-authentication-system](https://www.arkosjs.com/docs/core-concepts/built-in-authentication-system) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /**\n * Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * See more at [www.arkosjs.com/docs/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/authentication-system/sending-authentication-requests#example-changing-the-username-field)\n *\n * By specifing here another field for username, for example passing \"email\", \"companyCode\" or something else your json will be like:\n *\n * **Example with email**\n *\n * ```json\n * {\n * \"email\": \"john.doe@example.com\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n */\n allowedUsernames?: string[];\n /** Defines wether to send the access token in response after login or only send as cookie, defeault is both.*/\n sendAccessTokenThrough?: \"cookie-only\" | \"response-only\" | \"both\";\n };\n /**\n * @deprecated\n *\n * **Use this instead**:\n *\n * ```ts\n * arkos.init({\n * authentication: {\n * login: {\n * allowedUsernames: [\"email\", \"profile.nickname\"]\n * }\n * }\n * })\n * ```\n *\n * * See more at [www.arkosjs.com/docs/authentication-system/sending-authentication-requests#example-changing-the-username-field](https://www.arkosjs.com/docs/authentication-system/sending-authentication-requests#example-changing-the-username-field)\n *\n */\n usernameField?: string;\n /**\n * Specifies the regex pattern used by the authentication system to enforce password strength requirements.\n *\n * **Important**: If using validation libraries like Zod or class-validator, this will be completely overwritten.\n *\n * **Default**: ```/^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/``` - Ensures the password contains at least one uppercase letter, one lowercase letter, and one numeric digit.\n *\n * **message**: (Optional) A custom error message to display when the password does not meet the required strength criteria.\n */\n passwordValidation?: { regex: RegExp; message?: string };\n /**\n * Allows to specify the request rate limit for all authentication endpoints but `/api/users/me`.\n * \n * #### Default\n *{\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n requestRateLimitOptions?: RateLimitOptions;\n /**\n * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n * ⚠️ Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n */\n secure?: boolean;\n\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n */\n httpOnly?: boolean;\n\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n };\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * See [www.arkosjs.com/docs/core-concepts/request-data-validation](https://www.arkosjs.com/docs/core-concepts/request-data-validation) for more details.\n */\n validation?:\n | {\n resolver?: \"class-validator\";\n /**\n * ValidatorOptions to used while validating request data.\n *\n * **Default**:\n * ```ts\n * {\n * whitelist: true\n * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver?: \"zod\";\n validationOptions?: Record<string, any>;\n };\n /**\n * Defines file upload configurations\n *\n * See [www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations](https://www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations)\n */\n fileUpload?: {\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n expressStaticOptions?: Parameters<typeof express.static>[1];\n /**\n * Defines upload restrictions for each file type: image, video, document or other.\n *\n * #### Important:\n * Passing an object without overriding everything will only cause it\n * to be deepmerged with the default options.\n *\n * See [www.arkosjs.com/docs/api-reference/default-supported-upload-files](https://www.arkosjs.com/docs/api-reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n restrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n files?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * Allows to specify the request rate limit for all endpoints.\n * \n * #### Default\n *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n ```\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n globalRequestRateLimitOptions?: Partial<RateLimitOptions>;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n jsonBodyParserOptions?: Parameters<typeof express.json>[0];\n /**\n * Allows to pass paremeters to cookieParser from npm package cookie-parser\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/cookie-parser](https://www.npmjs.com/package/cookie-parser) for further details.\n */\n cookieParserParameters?: Parameters<typeof cookieParser>;\n /**\n * Allows to define options for npm package compression\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/compression](https://www.npmjs.com/package/compression) for further details.\n */\n compressionOptions?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * #### for example:\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n * \n * #### Default:\n * \n * {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n }\n * \n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n * \n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParserOptions?: QueryParserOptions;\n /**\n * Configuration for CORS (Cross-Origin Resource Sharing).\n *\n * @property {string | string[] | \"all\"} [allowedOrigins] - List of allowed origins. If set to `\"all\"`, all origins are accepted.\n * @property {import('cors').CorsOptions} [options] - Additional CORS options passed directly to the `cors` middleware.\n * @property {import('cors').CorsOptionsDelegate} [customMiddleware] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customMiddleware` is provided, both `allowedOrigins` and `options` will be ignored in favor of the custom logic.\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?: {\n allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware\n *\n * see\n */\n customHandler?: cors.CorsOptionsDelegate;\n };\n /**\n * Defines express/arkos middlewares configurations\n */\n middlewares?: {\n /**\n * Allows to add an array of custom express middlewares into the default middleware stack.\n *\n * **Tip**: If you would like to acess the express app before everthing use `configureApp` and pass a function.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order](https://www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order)\n *\n * **Note**: If you want to use custom global error handler middleware use `middlewares.replace.globalErrorHandler`.\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.RequestHandler[];\n /**\n * An array containing a list of defaults middlewares to be disabled\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n disable?: (\n | \"compression\"\n | \"global-rate-limit\"\n | \"auth-rate-limit\"\n | \"cors\"\n | \"express-json\"\n | \"cookie-parser\"\n | \"query-parser\"\n | \"database-connection\"\n | \"request-logger\"\n | \"global-error-handler\"\n )[];\n /**\n * Allows you to replace each of the built-in middlewares with your own implementation\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default compression middleware\n */\n compression?: express.RequestHandler;\n /**\n * Replace the default global rate limit middleware\n */\n globalRateLimit?: express.RequestHandler;\n /**\n * Replace the default authentication rate limit middleware\n */\n authRateLimit?: express.RequestHandler;\n /**\n * Replace the default CORS middleware\n */\n cors?: express.RequestHandler;\n /**\n * Replace the default JSON body parser middleware\n */\n expressJson?: express.RequestHandler;\n /**\n * Replace the default cookie parser middleware\n */\n cookieParser?: express.RequestHandler;\n /**\n * Replace the default query parser middleware\n */\n queryParser?: express.RequestHandler;\n /**\n * Replace the default database connection check middleware\n */\n databaseConnection?: express.RequestHandler;\n /**\n * Replace the default request logger middleware\n */\n requestLogger?: express.RequestHandler;\n /**\n * Replace the default global error handler middleware\n */\n globalErrorHandler?: express.ErrorRequestHandler;\n };\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Allows to add an array of custom express routers into the default middleware/router stack.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/adding-custom-routers](https://www.arkosjs.com/docs/advanced-guide/adding-custom-routers)\n *\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n additional?: express.Router[];\n disable?: (\n | \"auth-router\"\n | \"prisma-models-router\"\n | \"file-uploader\"\n | \"welcome-endpoint\"\n )[];\n /**\n * Allows you to replace each of the built-in routers with your own implementation.\n *\n * **Note**: Doing this you will lose all default middleware chaining, auth control, handlers from the specific router.\n *\n * **Tip**: I you want to disable some prisma models specific endpoint\n * see [www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers#disabling-endpoints](https://www.arkosjs.com/docs/advanced-guide/customizing-prisma-models-routers#disabling-endpoints)\n *\n * **Caution**: Be careful with this because you may endup breaking your entire application.\n */\n replace?: {\n /**\n * Replace the default authentication router\n * @param config The original Arkos configuration\n * @returns A router handling authentication endpoints\n */\n authRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default Prisma models router\n * @param config The original Arkos configuration\n * @returns A router handling Prisma model endpoints\n */\n prismaModelsRouter?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default file uploader router\n * @param config The original Arkos configuration\n * @returns A router handling file upload endpoints\n */\n fileUploader?: (\n config: ArkosConfig\n ) => express.Router | Promise<express.Router>;\n /**\n * Replace the default welcome endpoint handler\n * @param req Express request object\n * @param res Express response object\n * @param next Express next function\n */\n welcomeEndpoint?: express.RequestHandler;\n };\n };\n /**\n * Gives acess to the underlying express app so that you can add custom configurations beyong **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `app.listen` for you.\n *\n * If you want to call `app.listen` by yourself pass port as `undefined` and then use the return app from `arkos.init()`.\n *\n * See how to call `app.listen` correctly [www.arkosjs.com/docs/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/accessing-the-express-app](https://www.arkosjs.com/docs/accessing-the-express-app) for further details on the method configureApp.\n *\n * @param {express.Express} app\n * @returns {any}\n */\n configureApp?: (app: express.Express) => Promise<any> | any;\n /**\n * Allows to configure email configurations for sending emails through `emailService`\n *\n * See [www.arkosjs.com/docs/core-concepts/sending-emails](https://www.arkosjs.com/docs/core-concepts/sending-emails)\n */\n email?: {\n /**\n * Your email provider url\n */\n host: string;\n /**\n * Email provider SMTP port, Default is `465`\n */\n port?: number;\n /**\n * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n };\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"auth.js","sourceRoot":"","sources":["../../../src/types/auth.ts"],"names":[],"mappings":"","sourcesContent":["import { JwtPayload } from \"jsonwebtoken\";\n\n/**\n * Possible actions that can be performed by a controller.\n */\nexport type ControllerActions = \"create\" | \"update\" | \"delete\" | \"view\";\n\n/**\n * Rules defining access control for different controller actions.\n *\n * @typeParam key - One of the `ControllerActions`.\n * @typeParam Role - A type representing a role or set of roles allowed to perform the action.\n */\nexport type AccessControlRules = {\n /**\n * Maps each `ControllerAction` to the roles allowed to perform it.\n */\n [key in ControllerActions]: any[];\n};\n\n/**\n * Rules defining access control for different controller actions.\n *\n * @typeParam key - One of the `ControllerActions`.\n * @typeParam Role - A type representing a role or set of roles allowed to perform the action.\n */\nexport type AuthenticationControlRules = {\n /**\n * Maps each `ControllerAction` to the actions that requires authentication to perform it.\n */\n [key in ControllerActions]: boolean;\n};\n\n/**\n * Configuration for authentication and access control.\n */\nexport type AuthConfigs = {\n /**\n * Defines access control rules for roles or actions.\n *\n * @type {Role | Role[] | AccessControlRules}\n */\n authenticationControl?: boolean | Partial<AuthenticationControlRules>;\n /**\n * List of user roles, or restricted by actions\n */\n accessControl?: any[] | Partial<AccessControlRules>;\n};\n\n/**\n * Payload structure for JWT-based authentication, extending the standard `JwtPayload`.\n */\nexport interface AuthJwtPayload extends JwtPayload {\n /**\n * The unique identifier of the authenticated user.\n *\n * @type {number | string}\n */\n id?: number | string;\n\n [x: string]: any;\n}\n"]}
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../../../src/types/auth.ts"],"names":[],"mappings":"","sourcesContent":["import { JwtPayload } from \"jsonwebtoken\";\n\n/**\n * Base set of controller actions available to all controllers.\n */\nexport type BaseControllerActions = \"create\" | \"update\" | \"delete\" | \"view\";\n\n/**\n * Extends the base controller actions with custom actions.\n *\n * @typeParam T - Additional action types that extend the base actions.\n */\nexport type ExtendedControllerActions<T extends string = never> =\n | BaseControllerActions\n | T;\n\n/**\n * Rules defining access control for different controller actions.\n *\n * @typeParam T - Additional action types that extend the base actions.\n * @typeParam Role - A type representing a role or set of roles allowed to perform the action.\n */\nexport type AccessControlRules<T extends string = never> = {\n /**\n * Maps each controller action to the roles allowed to perform it.\n */\n [key in ExtendedControllerActions<T>]: any[];\n};\n\n/**\n * Rules defining authentication requirements for different controller actions.\n *\n * @typeParam T - Additional action types that extend the base actions.\n */\nexport type AuthenticationControlRules<T extends string = never> = {\n /**\n * Maps each controller action to whether authentication is required to perform it.\n */\n [key in ExtendedControllerActions<T>]: boolean;\n};\n\n/**\n * Configuration for authentication and access control.\n *\n * @typeParam T - Additional action types that extend the base actions.\n */\nexport type AuthConfigs<T extends string = never> = {\n /**\n * Defines authentication requirements for actions.\n * - When boolean: applies to all actions\n * - When partial rules: applies to specified actions\n *\n * @type {boolean | Partial<AuthenticationControlRules<T>>}\n */\n authenticationControl?: boolean | Partial<AuthenticationControlRules<T>>;\n\n /**\n * Defines role-based access control.\n * - When array: list of roles allowed for all actions\n * - When partial rules: specific roles for each action\n *\n * @type {any[] | Partial<AccessControlRules<T>>}\n */\n accessControl?: any[] | Partial<AccessControlRules<T>>;\n};\n\n/**\n * Payload structure for JWT-based authentication, extending the standard `JwtPayload`.\n */\nexport interface AuthJwtPayload extends JwtPayload {\n /**\n * The unique identifier of the authenticated user.\n *\n * @type {number | string}\n */\n id?: number | string;\n\n /**\n * Additional properties can be added to the payload.\n */\n [x: string]: any;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/types/index.ts"],"names":[],"mappings":";;;AAuCA,IAAY,oBAKX;AALD,WAAY,oBAAoB;IAC9B,yCAAiB,CAAA;IACjB,qCAAa,CAAA;IACb,yCAAiB,CAAA;IACjB,yCAAiB,CAAA;AACnB,CAAC,EALW,oBAAoB,oCAApB,oBAAoB,QAK/B","sourcesContent":["import { Prisma } from \"@prisma/client\";\nimport { NextFunction, Request, RequestHandler, Response } from \"express\";\n\nexport type PrismaOperations = \"findMany\";\n\nexport type PrismaQueryOptions<T> = {\n queryOptions?: Omit<\n Prisma.Args<T, \"findMany\">,\n \"where\" | \"cursor\" | \"take\" | \"skip\" | \"orderBy\"\n >;\n findOne?: Partial<Partial<Prisma.Args<T, \"findUnique\">>>;\n findMany?: Partial<Prisma.Args<T, \"findMany\">>;\n deleteMany?: Partial<Prisma.Args<T, \"deleteMany\">>;\n updateMany?: Partial<Prisma.Args<T, \"updateMany\">>;\n createMany?: Partial<Prisma.Args<T, \"createMany\">>;\n createOne?: Partial<Prisma.Args<T, \"create\">>;\n updateOne?: Partial<Prisma.Args<T, \"update\">>;\n deleteOne?: Partial<Prisma.Args<T, \"delete\">>;\n};\n\nexport interface UserRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n roleId: string;\n role: AuthRole;\n user: User;\n userId: string;\n}\n\nexport interface AuthRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n name: string;\n permissions: AuthPermission[];\n userRoles: UserRole[];\n}\n\nexport enum AuthPermissionAction {\n create = \"create\",\n view = \"view\",\n update = \"update\",\n delete = \"delete\",\n}\n\nexport interface AuthPermission {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n resource: string;\n action: AuthPermissionAction;\n roleId: string;\n role: AuthRole;\n}\n\nexport interface User {\n id: string;\n isStaff: boolean;\n isSuperUser: boolean;\n password: string;\n passwordChangedAt?: Date;\n deletedSelfAccountAt: Date;\n isActive: boolean;\n roles?: UserRole[] | any[];\n role?: UserRole | any;\n}\n\nexport interface ArkosRequest extends Request {\n user?: User & Record<string, any>;\n relationFields?: Record<string, boolean>;\n include?: Record<string, any>;\n responseData?: Record<string, any> | null | undefined;\n additionalData?: Record<string, any> | null | undefined;\n responseStatus?: number | string | null | undefined;\n}\n\nexport interface ArkosResponse extends Response {}\nexport interface ArkosNextFunction extends NextFunction {}\nexport interface ArkosRequestHandler extends RequestHandler {}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/types/index.ts"],"names":[],"mappings":";;;AAuCA,IAAY,oBAKX;AALD,WAAY,oBAAoB;IAC9B,yCAAiB,CAAA;IACjB,qCAAa,CAAA;IACb,yCAAiB,CAAA;IACjB,yCAAiB,CAAA;AACnB,CAAC,EALW,oBAAoB,oCAApB,oBAAoB,QAK/B","sourcesContent":["import { Prisma } from \"@prisma/client\";\nimport { NextFunction, Request, RequestHandler, Response } from \"express\";\n\nexport type PrismaOperations = \"findMany\";\n\nexport type PrismaQueryOptions<T> = {\n queryOptions?: Omit<\n Prisma.Args<T, \"findMany\">,\n \"where\" | \"cursor\" | \"take\" | \"skip\" | \"orderBy\"\n >;\n findOne?: Partial<Partial<Prisma.Args<T, \"findUnique\">>>;\n findMany?: Partial<Prisma.Args<T, \"findMany\">>;\n deleteMany?: Partial<Prisma.Args<T, \"deleteMany\">>;\n updateMany?: Partial<Prisma.Args<T, \"updateMany\">>;\n createMany?: Partial<Prisma.Args<T, \"createMany\">>;\n createOne?: Partial<Prisma.Args<T, \"create\">>;\n updateOne?: Partial<Prisma.Args<T, \"update\">>;\n deleteOne?: Partial<Prisma.Args<T, \"delete\">>;\n};\n\nexport interface UserRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n roleId: string;\n role: AuthRole;\n user: User;\n userId: string;\n}\n\nexport interface AuthRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n name: string;\n permissions: AuthPermission[];\n userRoles: UserRole[];\n}\n\nexport enum AuthPermissionAction {\n create = \"create\",\n view = \"view\",\n update = \"update\",\n delete = \"delete\",\n}\n\nexport interface AuthPermission {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n resource: string;\n action: AuthPermissionAction;\n roleId: string;\n role: AuthRole;\n}\n\nexport interface User {\n id: string;\n isStaff: boolean;\n isSuperUser: boolean;\n password: string;\n passwordChangedAt?: Date;\n deletedSelfAccountAt: Date;\n isActive: boolean;\n roles?: UserRole[] | any[];\n role?: UserRole | any;\n}\n\nexport interface ArkosRequest<Body = any, Query = any> extends Request {\n user?: User & Record<string, any>;\n relationFields?: Record<string, boolean>;\n include?: Record<string, any>;\n responseData?: Record<string, any> | null | undefined;\n additionalData?: Record<string, any> | null | undefined;\n responseStatus?: number | string | null | undefined;\n body: Body;\n // query: Query extends Request['ParsedQs'];\n}\n\nexport interface ArkosResponse extends Response {}\nexport interface ArkosNextFunction extends NextFunction {}\nexport interface ArkosRequestHandler extends RequestHandler {}\n"]}
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=prisma-model-router-config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prisma-model-router-config.js","sourceRoot":"","sources":["../../../src/types/prisma-model-router-config.ts"],"names":[],"mappings":"","sourcesContent":["export type AvailableEndpoints =\n | \"createOne\"\n | \"findOne\"\n | \"updateOne\"\n | \"deleteOne\"\n | \"findMany\"\n | \"createMany\"\n | \"udpateMany\"\n | \"deleteMany\";\n\n/**\n * Allows to customize the generated routers\n *\n * See docs [www.arkosjs.com/docs/advanced-guide/customizing-generated-routers#generated-routers-configuration](https://www.arkosjs.com/docs/advanced-guide/customizing-generated-routers#generated-routers-configuration)\n */\nexport type PrismaModelRouterConfig = {\n /**\n * Allows to configure nested routes.\n *\n * **Example**\n *\n * ```curl\n * GET /api/authors/:id/posts\n * ```\n *\n * Returning only the fields belonging to the passed author id.\n *\n * See more at [www.arkosjs.com/docs/advanced-guide/customizing-generated-routers](https://www.arkosjs.com/docs/advanced-guide/customizing-generated-routers)\n */\n parent?: {\n /**\n * Your prisma model name in kebab-case and singular.\n */\n model?: string;\n /**\n * Defines the parentId field stores the Id relation. e.g authorId, categoryId, productId.\n *\n *\n *\n * **Note**: By default **Arkos** will look for modelNameId, modelName being the model specified in `parent.model`.\n *\n * **Example**\n * ```prisma\n * model Post {\n * // other fields\n * authorId String\n * author Author @relation(fields: [authorId], references: [id])\n * }\n * ```\n *\n * When passed `parent.model` to `author` **Arkos** will create an endpoint:\n * ```curl\n * GET /api/authors/:id/posts\n * GET /api/authors/:id/posts/:id\n * POST /api/authors/:id/posts\n * UPDATE /api/authors/:id/posts/:id\n * DELETE /api/authors/:id/posts/:id\n * POST /api/authors/:id/posts/many\n * UPDATE /api/authors/:id/posts/many\n * DELETE /api/authors/:id/posts/many\n * ```\n *\n * If you want to point to a different field pass it here.\n */\n referenceField?: string;\n /**\n * Customizes what endpoints to be created.\n *\n * Default is \"*\" to generate all endpoints\n */\n endpoints?: \"*\" | AvailableEndpoints | AvailableEndpoints[];\n };\n /**\n * Use to disable endpoints or the whole router\n *\n * If `true`, will disable:\n *\n * ```curl\n * POST /api/[mode-name]\n * GET /api/[mode-name]/:id\n * PATCH /api/[mode-name]:id\n * DELETE /api/[mode-name]:id\n * POST /api/[mode-name]/many\n * GET /api/[mode-name]\n * UPDATE /api/[mode-name]/many\n * DELETE /api/[mode-name]/many\n * ```\n */\n disable?:\n | boolean\n | {\n /**\n * If `true`, will disable:\n *\n * ```curl\n * POST /api/[mode-name]\n * ```\n */\n createOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * GET /api/[mode-name]/:id\n * ```\n */\n findOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * PATCH /api/[mode-name]:id\n * ```\n */\n updateOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * DELETE /api/[mode-name]:id\n * ```\n */\n deleteOne?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * POST /api/[mode-name]/many\n * ```\n */\n createMany?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * GET /api/[mode-name]\n * ```\n */\n findMany?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * UPDATE /api/[mode-name]/many\n * ```\n */\n updateMany?: boolean;\n /**\n * If `true`, will disable:\n *\n * ```curl\n * DELETE /api/[mode-name]/many\n * ```\n */\n deleteMany?: boolean;\n };\n};\n"]}
@@ -60,13 +60,14 @@ class APIFeatures {
60
60
  if (!!this.searchParams.search) {
61
61
  const prisma = (0, prisma_helpers_1.getPrismaInstance)();
62
62
  Object.keys(prisma[this.modelName].fields).forEach((key) => {
63
+ var _a, _b;
63
64
  const field = prisma[this.modelName].fields[key];
64
65
  if (field.typeName === "String" &&
65
66
  key !== "id" &&
66
67
  key !== "password" &&
67
68
  !field.isList &&
68
- !key.includes("Id") &&
69
- !key.includes("ID")) {
69
+ !((_a = key === null || key === void 0 ? void 0 : key.includes) === null || _a === void 0 ? void 0 : _a.call(key, "Id")) &&
70
+ !((_b = key === null || key === void 0 ? void 0 : key.includes) === null || _b === void 0 ? void 0 : _b.call(key, "ID"))) {
70
71
  searchableFields.push({
71
72
  [`${key}`]: {
72
73
  contains: this.searchParams.search,
@@ -1 +1 @@
1
- {"version":3,"file":"api.features.js","sourceRoot":"","sources":["../../../../src/utils/features/api.features.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AACA,mFAAoD;AACpD,0EAAgF;AAChF,4FAAmE;AACnE,8DAA8D;AAI9D,MAAqB,WAAW;IAsB9B,YACE,GAAY,EACZ,SAAoB,EACpB,cAAwC;QArB1C,YAAO,GAAQ,EAAE,CAAC;QAGlB,mBAAc,GAAG;YACf,MAAM;YACN,MAAM;YACN,OAAO;YACP,QAAQ;YACR,WAAW;YACX,cAAc;YACd,QAAQ;YACR,SAAS;YACT,YAAY;YACZ,OAAO;YACP,oBAAoB;YACpB,eAAe;SAChB,CAAC;QAOA,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;Q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O,EAAE,CAAC;gBACzB,OAAO,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;YAC9B,CAAC;QACH,CAAC;QAGD,IAAI,CAAA,MAAA,IAAI,CAAC,YAAY,0CAAE,SAAS,MAAI,MAAA,IAAI,CAAC,YAAY,0CAAE,YAAY,CAAA,EAAE,CAAC;YACpE,MAAM,IAAI,mBAAQ,CAChB,4GAA4G,EAC5G,GAAG,CACJ,CAAC;QACJ,CAAC;QAED,OAAO,IAAI,CAAC;IACd,CAAC;IAED,QAAQ;QACN,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC;QACvD,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,EAAE,CAAC;QAC1D,MAAM,IAAI,GAAG,CAAC,IAAI,GAAG,CAAC,CAAC,GAAG,KAAK,CAAC;QAEhC,IAAI,CAAC,OAAO,mCACP,IAAI,CAAC,OAAO,KACf,IAAI,EACJ,IAAI,EAAE,KAAK,GACZ,CAAC;QACF,OAAO,IAAI,CAAC;IACd,CAAC;IAEK,IAAI;;YACR,MAAM,MAAM,GAAG,IAAA,kCAAiB,GAAE,CAAC;YACnC,OAAO,MAAO,MAAc,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACtE,CAAC;KAAA;CACF;AA5RD,8BA4RC","sourcesContent":["import { Request } from \"express\";\nimport deepmerge from \"../helpers/deepmerge.helper\";\nimport { parseQueryParamsWithModifiers } from \"../helpers/api.features.helpers\";\nimport AppError from \"../../modules/error-handler/utils/app-error\";\nimport { getPrismaInstance } from \"../helpers/prisma.helpers\";\n\ntype ModelName = string;\n\nexport default class APIFeatures {\n req: Request;\n searchParams: any; // The query string parameters from the request\n searchParamsWithModifiers: any; // The query string parameters from the request\n filters: any = {};\n modelName: ModelName;\n relationFields: Record<string, boolean>;\n excludedFields = [\n \"page\",\n \"sort\",\n \"limit\",\n \"fields\",\n \"addFields\",\n \"removeFields\",\n \"search\",\n \"include\",\n \"filterMode\",\n \"where\",\n \"prismaQueryOptions\",\n \"ignoredFields\",\n ];\n\n constructor(\n req: Request,\n modelName: ModelName,\n relationFields?: Record<string, boolean>\n ) {\n this.req = req;\n this.modelName = modelName;\n this.searchParams = parseQueryParamsWithModifiers(req.query);\n this.filters = { ...this.filters };\n\n if (relationFields) this.filters.iclude = relationFields;\n this.relationFields = relationFields || {};\n }\n\n filter() {\n const searchableFields: Record<string, any>[] = [];\n\n const queryObj = { ...this.searchParams };\n\n this.excludedFields.forEach((el) => delete queryObj[el]);\n\n let queryStr = JSON.stringify(queryObj);\n queryStr = queryStr.replace(/\\b(gte|gt|lte|lt)\\b/g, (match) => `${match}`);\n\n const whereObj = { ...this.req.params, ...queryObj };\n const whereLogicalOperatorFilters = Object.keys(whereObj).map((key) => ({\n [key]: whereObj[key],\n }));\n\n let whereOptions =\n whereLogicalOperatorFilters.length > 0\n ? {\n [(this.req.query?.filterMode as string) ?? \"OR\"]:\n whereLogicalOperatorFilters,\n }\n : {};\n\n if (!!this.searchParams.search) {\n const prisma = getPrismaInstance();\n\n Object.keys((prisma as any)[this.modelName].fields).forEach((key) => {\n const field = ((prisma as any)[this.modelName].fields as any)[key];\n if (\n field.typeName === \"String\" &&\n key !== \"id\" &&\n key !== \"password\" &&\n !field.isList &&\n !key.includes(\"Id\") &&\n !key.includes(\"ID\")\n ) {\n searchableFields.push({\n [`${key}`]: {\n contains: this.searchParams.search,\n mode: \"insensitive\",\n },\n });\n }\n });\n\n whereOptions = deepmerge(whereOptions, {\n OR: searchableFields,\n });\n }\n\n const parsedQueryOptions =\n typeof this.req.query?.prismaQueryOptions === \"string\"\n ? JSON.parse(this.req.query?.prismaQueryOptions)\n : {};\n\n this.filters = deepmerge(\n {\n where: whereOptions,\n },\n parsedQueryOptions,\n this.filters\n );\n return this;\n }\n\n search() {\n if (this.searchParams?.search) {\n this.filters = deepmerge(this.filters, {\n where: {\n OR: [],\n },\n });\n }\n }\n\n sort() {\n if (this.searchParams.sort) {\n const sortBy = this.searchParams?.sort\n ?.split(\",\")\n ?.map((field: string) => ({\n [field.startsWith(\"-\") ? field.substring(1) : field]:\n field.startsWith(\"-\") ? \"desc\" : \"asc\",\n }));\n this.filters = deepmerge(this.filters, { orderBy: sortBy });\n }\n\n return this;\n }\n\n // limitFields() {\n // if (\n // this.searchParams?.fields &&\n // !this.searchParams?.addFields &&\n // !this.searchParams?.removeFields\n // ) {\n // const fieldsToSelect = this.searchParams.fields\n // .split(\",\")\n // .filter(\n // (field: string) => !field.startsWith(\"+\") && !field.startsWith(\"-\")\n // );\n\n // this.filters = {\n // ...this.filters,\n // select: fieldsToSelect.reduce((acc: any, field: string) => {\n // acc[field] = true;\n // return acc;\n // }, {}),\n // };\n // this.filters.select = { ...this.filters.select, ...this.filters.include };\n // delete this.filters.include;\n // } else if (\n // this.searchParams?.fields &&\n // (this.searchParams?.addFields || this.searchParams?.removeFields)\n // )\n // throw new AppError(\n // \"Cannot use fields in the same query with addFields or removeFields.\",\n // 400\n // );\n\n // if (this.searchParams?.addFields && !this.searchParams?.fields) {\n // const fieldsToAdd = this.searchParams.addFields\n // .split(\",\")\n // .filter((field: string) => field.startsWith(\"+\"));\n\n // this.filters = {\n // ...this.filters,\n // select: {\n // ...this.filters.include,\n // ...fieldsToAdd.reduce((acc: any, field: string) => {\n // acc[field.replace(\"+\", \"\")] = true;\n // return acc;\n // }, {}),\n // },\n // };\n // } else if (this.searchParams?.fields && this.searchParams?.addFields)\n // throw new AppError(\n // \"Cannot use addFields in the same query with fields.\",\n // 400\n // );\n\n // if (this.searchParams?.removeFields && !this.searchParams?.fields) {\n // const fieldsToRemove = this.searchParams.removeFields\n // .split(\",\")\n // .filter((field: string) => field.startsWith(\"-\"));\n\n // this.filters = {\n // ...this.filters,\n // select: {\n // ...this.filters.include,\n // ...fieldsToRemove.reduce((acc: any, field: string) => {\n // acc[field.replace(\"-\", \"\")] = false;\n // return acc;\n // }, {}),\n // },\n // };\n // } else if (this.searchParams?.removeFields && this.searchParams?.addFields)\n // throw new AppError(\n // \"Cannot use removeFields in the same query with fields.\",\n // 400\n // );\n\n // return this;\n // }\n\n limitFields() {\n if (this.searchParams?.fields) {\n const fields = this.searchParams.fields.split(\",\");\n\n // Separate fields into includes, excludes, and regular fields\n const regularFields = fields.filter(\n (field: string) => !field.startsWith(\"+\") && !field.startsWith(\"-\")\n );\n const includeFields = fields\n .filter((field: string) => field.startsWith(\"+\"))\n .map((field: string) => field.substring(1));\n const excludeFields = fields\n .filter((field: string) => field.startsWith(\"-\"))\n .map((field: string) => field.substring(1));\n\n // Create selection object based on field type\n let selection: Record<string, any> = {};\n\n // If regular fields exist, use them as the base selection\n if (regularFields.length > 0) {\n selection = regularFields.reduce(\n (acc: Record<string, any>, field: string) => {\n acc[field] = true;\n return acc;\n },\n {} as Record<string, any>\n );\n }\n // Otherwise, use include fields as additions to any existing included fields\n else {\n // Start with current include fields if they exist\n selection = this.filters.include || {};\n\n // Add any explicitly included fields\n includeFields.forEach((field: string) => {\n selection[field] = true;\n });\n\n // Add any explicitly excluded fields\n excludeFields.forEach((field: string) => {\n selection[field] = false;\n });\n }\n\n // Apply the selection to filters\n this.filters = {\n ...this.filters,\n select: selection,\n };\n\n // Remove the include filter as it's now part of select\n if (this.filters.include) {\n delete this.filters.include;\n }\n }\n\n // Remove any references to the now-unused parameters\n if (this.searchParams?.addFields || this.searchParams?.removeFields) {\n throw new AppError(\n \"The addFields and removeFields parameters are deprecated. Please use fields with + and - prefixes instead.\",\n 400\n );\n }\n\n return this;\n }\n\n paginate() {\n const page = parseInt(this.searchParams.page, 10) || 1;\n const limit = parseInt(this.searchParams.limit, 10) || 30;\n const skip = (page - 1) * limit;\n\n this.filters = {\n ...this.filters,\n skip,\n take: limit,\n };\n return this;\n }\n\n async exec() {\n const prisma = getPrismaInstance();\n return await (prisma as any)[this.modelName].findMany(this.filters);\n }\n}\n"]}
1
+ {"version":3,"file":"api.features.js","sourceRoot":"","sources":["../../../../src/utils/features/api.features.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AACA,mFAAoD;AACpD,0EAAgF;AAChF,4FAAmE;AACnE,8DAA8D;AAI9D,MAAqB,WAAW;IAsB9B,YACE,GAAY,EACZ,SAAoB,EACpB,cAAwC;QArB1C,YAAO,GAAQ,EAAE,CAAC;QAGlB,mBAAc,GAAG;YACf,MAAM;YACN,MAAM;YACN,OAAO;YACP,QAAQ;YACR,WAAW;YACX,cAAc;YACd,QAAQ;YACR,SAAS;YACT,YAAY;YACZ,OAAO;YACP,oBAAoB;YACpB,eAAe;SAChB,CAAC;QAOA,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,YAAY,GAAG,IAAA,oDAA6B,EAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAC7D,IAAI,CAAC,OAAO,qBAAQ,IAAI,CAAC,OAAO,CAAE,CAAC;QAEnC,IAAI,cAAc;YAAE,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,cAAc,CAAC;QACzD,IAAI,CAAC,cAAc,GAAG,cAAc,IAAI,EAAE,CAAC;IAC7C,CAAC;IAED,MAAM;;QACJ,MAAM,gBAAgB,GAA0B,EAAE,CAAC;QAEnD,MAAM,QAAQ,qBAAQ,IAAI,CAAC,YAAY,CAAE,CAAC;QAE1C,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,OAAO,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC;QAEzD,IAAI,QAAQ,GAAG,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;QACxC,QAAQ,GAAG,QAAQ,CAAC,OAAO,CAAC,sBAAsB,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,GAAG,KAAK,EA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KAAK,CAAC;QAEhC,IAAI,CAAC,OAAO,mCACP,IAAI,CAAC,OAAO,KACf,IAAI,EACJ,IAAI,EAAE,KAAK,GACZ,CAAC;QACF,OAAO,IAAI,CAAC;IACd,CAAC;IAEK,IAAI;;YACR,MAAM,MAAM,GAAG,IAAA,kCAAiB,GAAE,CAAC;YACnC,OAAO,MAAO,MAAc,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACtE,CAAC;KAAA;CACF;AA5RD,8BA4RC","sourcesContent":["import { Request } from \"express\";\nimport deepmerge from \"../helpers/deepmerge.helper\";\nimport { parseQueryParamsWithModifiers } from \"../helpers/api.features.helpers\";\nimport AppError from \"../../modules/error-handler/utils/app-error\";\nimport { getPrismaInstance } from \"../helpers/prisma.helpers\";\n\ntype ModelName = string;\n\nexport default class APIFeatures {\n req: Request;\n searchParams: any; // The query string parameters from the request\n searchParamsWithModifiers: any; // The query string parameters from the request\n filters: any = {};\n modelName: ModelName;\n relationFields: Record<string, boolean>;\n excludedFields = [\n \"page\",\n \"sort\",\n \"limit\",\n \"fields\",\n \"addFields\",\n \"removeFields\",\n \"search\",\n \"include\",\n \"filterMode\",\n \"where\",\n \"prismaQueryOptions\",\n \"ignoredFields\",\n ];\n\n constructor(\n req: Request,\n modelName: ModelName,\n relationFields?: Record<string, boolean>\n ) {\n this.req = req;\n this.modelName = modelName;\n this.searchParams = parseQueryParamsWithModifiers(req.query);\n this.filters = { ...this.filters };\n\n if (relationFields) this.filters.iclude = relationFields;\n this.relationFields = relationFields || {};\n }\n\n filter() {\n const searchableFields: Record<string, any>[] = [];\n\n const queryObj = { ...this.searchParams };\n\n this.excludedFields.forEach((el) => delete queryObj[el]);\n\n let queryStr = JSON.stringify(queryObj);\n queryStr = queryStr.replace(/\\b(gte|gt|lte|lt)\\b/g, (match) => `${match}`);\n\n const whereObj = { ...this.req.params, ...queryObj };\n const whereLogicalOperatorFilters = Object.keys(whereObj).map((key) => ({\n [key]: whereObj[key],\n }));\n\n let whereOptions =\n whereLogicalOperatorFilters.length > 0\n ? {\n [(this.req.query?.filterMode as string) ?? \"OR\"]:\n whereLogicalOperatorFilters,\n }\n : {};\n\n if (!!this.searchParams.search) {\n const prisma = getPrismaInstance();\n\n Object.keys((prisma as any)[this.modelName].fields).forEach((key) => {\n const field = ((prisma as any)[this.modelName].fields as any)[key];\n if (\n field.typeName === \"String\" &&\n key !== \"id\" &&\n key !== \"password\" &&\n !field.isList &&\n !key?.includes?.(\"Id\") &&\n !key?.includes?.(\"ID\")\n ) {\n searchableFields.push({\n [`${key}`]: {\n contains: this.searchParams.search,\n mode: \"insensitive\",\n },\n });\n }\n });\n\n whereOptions = deepmerge(whereOptions, {\n OR: searchableFields,\n });\n }\n\n const parsedQueryOptions =\n typeof this.req.query?.prismaQueryOptions === \"string\"\n ? JSON.parse(this.req.query?.prismaQueryOptions)\n : {};\n\n this.filters = deepmerge(\n {\n where: whereOptions,\n },\n parsedQueryOptions,\n this.filters\n );\n return this;\n }\n\n search() {\n if (this.searchParams?.search) {\n this.filters = deepmerge(this.filters, {\n where: {\n OR: [],\n },\n });\n }\n }\n\n sort() {\n if (this.searchParams.sort) {\n const sortBy = this.searchParams?.sort\n ?.split(\",\")\n ?.map((field: string) => ({\n [field.startsWith(\"-\") ? field.substring(1) : field]:\n field.startsWith(\"-\") ? \"desc\" : \"asc\",\n }));\n this.filters = deepmerge(this.filters, { orderBy: sortBy });\n }\n\n return this;\n }\n\n // limitFields() {\n // if (\n // this.searchParams?.fields &&\n // !this.searchParams?.addFields &&\n // !this.searchParams?.removeFields\n // ) {\n // const fieldsToSelect = this.searchParams.fields\n // .split(\",\")\n // .filter(\n // (field: string) => !field.startsWith(\"+\") && !field.startsWith(\"-\")\n // );\n\n // this.filters = {\n // ...this.filters,\n // select: fieldsToSelect.reduce((acc: any, field: string) => {\n // acc[field] = true;\n // return acc;\n // }, {}),\n // };\n // this.filters.select = { ...this.filters.select, ...this.filters.include };\n // delete this.filters.include;\n // } else if (\n // this.searchParams?.fields &&\n // (this.searchParams?.addFields || this.searchParams?.removeFields)\n // )\n // throw new AppError(\n // \"Cannot use fields in the same query with addFields or removeFields.\",\n // 400\n // );\n\n // if (this.searchParams?.addFields && !this.searchParams?.fields) {\n // const fieldsToAdd = this.searchParams.addFields\n // .split(\",\")\n // .filter((field: string) => field.startsWith(\"+\"));\n\n // this.filters = {\n // ...this.filters,\n // select: {\n // ...this.filters.include,\n // ...fieldsToAdd.reduce((acc: any, field: string) => {\n // acc[field.replace(\"+\", \"\")] = true;\n // return acc;\n // }, {}),\n // },\n // };\n // } else if (this.searchParams?.fields && this.searchParams?.addFields)\n // throw new AppError(\n // \"Cannot use addFields in the same query with fields.\",\n // 400\n // );\n\n // if (this.searchParams?.removeFields && !this.searchParams?.fields) {\n // const fieldsToRemove = this.searchParams.removeFields\n // .split(\",\")\n // .filter((field: string) => field.startsWith(\"-\"));\n\n // this.filters = {\n // ...this.filters,\n // select: {\n // ...this.filters.include,\n // ...fieldsToRemove.reduce((acc: any, field: string) => {\n // acc[field.replace(\"-\", \"\")] = false;\n // return acc;\n // }, {}),\n // },\n // };\n // } else if (this.searchParams?.removeFields && this.searchParams?.addFields)\n // throw new AppError(\n // \"Cannot use removeFields in the same query with fields.\",\n // 400\n // );\n\n // return this;\n // }\n\n limitFields() {\n if (this.searchParams?.fields) {\n const fields = this.searchParams.fields.split(\",\");\n\n // Separate fields into includes, excludes, and regular fields\n const regularFields = fields.filter(\n (field: string) => !field.startsWith(\"+\") && !field.startsWith(\"-\")\n );\n const includeFields = fields\n .filter((field: string) => field.startsWith(\"+\"))\n .map((field: string) => field.substring(1));\n const excludeFields = fields\n .filter((field: string) => field.startsWith(\"-\"))\n .map((field: string) => field.substring(1));\n\n // Create selection object based on field type\n let selection: Record<string, any> = {};\n\n // If regular fields exist, use them as the base selection\n if (regularFields.length > 0) {\n selection = regularFields.reduce(\n (acc: Record<string, any>, field: string) => {\n acc[field] = true;\n return acc;\n },\n {} as Record<string, any>\n );\n }\n // Otherwise, use include fields as additions to any existing included fields\n else {\n // Start with current include fields if they exist\n selection = this.filters.include || {};\n\n // Add any explicitly included fields\n includeFields.forEach((field: string) => {\n selection[field] = true;\n });\n\n // Add any explicitly excluded fields\n excludeFields.forEach((field: string) => {\n selection[field] = false;\n });\n }\n\n // Apply the selection to filters\n this.filters = {\n ...this.filters,\n select: selection,\n };\n\n // Remove the include filter as it's now part of select\n if (this.filters.include) {\n delete this.filters.include;\n }\n }\n\n // Remove any references to the now-unused parameters\n if (this.searchParams?.addFields || this.searchParams?.removeFields) {\n throw new AppError(\n \"The addFields and removeFields parameters are deprecated. Please use fields with + and - prefixes instead.\",\n 400\n );\n }\n\n return this;\n }\n\n paginate() {\n const page = parseInt(this.searchParams.page, 10) || 1;\n const limit = parseInt(this.searchParams.limit, 10) || 30;\n const skip = (page - 1) * limit;\n\n this.filters = {\n ...this.filters,\n skip,\n take: limit,\n };\n return this;\n }\n\n async exec() {\n const prisma = getPrismaInstance();\n return await (prisma as any)[this.modelName].findMany(this.filters);\n }\n}\n"]}
@@ -93,13 +93,14 @@ function parseQueryParamsWithModifiers(query, fieldConfig = DEFAULT_FIELD_CONFIG
93
93
  }, {});
94
94
  }
95
95
  function convertValue(value, fieldName, config) {
96
- if (config.dateFields.includes(fieldName) && value) {
96
+ var _a, _b, _c, _d, _e, _f;
97
+ if (((_b = (_a = config.dateFields) === null || _a === void 0 ? void 0 : _a.includes) === null || _b === void 0 ? void 0 : _b.call(_a, fieldName)) && value) {
97
98
  return new Date(value);
98
99
  }
99
- if (config.booleanFields.includes(fieldName) && value) {
100
+ if (((_d = (_c = config.booleanFields) === null || _c === void 0 ? void 0 : _c.includes) === null || _d === void 0 ? void 0 : _d.call(_c, fieldName)) && value) {
100
101
  return value.toLowerCase() === "true";
101
102
  }
102
- if (config.numericFields.includes(fieldName) && value) {
103
+ if (((_f = (_e = config.numericFields) === null || _e === void 0 ? void 0 : _e.includes) === null || _f === void 0 ? void 0 : _f.call(_e, fieldName)) && value) {
103
104
  return Number(value);
104
105
  }
105
106
  return value;
@@ -1 +1 @@
1
- {"version":3,"file":"api.features.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/api.features.helpers.ts"],"names":[],"mappings":";;AAiDA,sEAiHC;AA7ID,MAAM,oBAAoB,GAAgB;IACxC,UAAU,EAAE,CAAC,WAAW,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,CAAC;IAC3D,aAAa,EAAE,CAAC,UAAU,EAAE,WAAW,EAAE,aAAa,EAAE,YAAY,CAAC;IACrE,aAAa,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,QAAQ,CAAC;CAChE,CAAC;AAwBF,SAAgB,6BAA6B,CAC3C,KAA0B,EAE1B,cAA2B,oBAAoB;IAE/C,OAAO,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAC7D,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE;;QACpB,MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAC9B,IAAI,CAAC,KAAK,IAAI,KAAK,KAAK,KAAK,IAAI,KAAK,KAAK,OAAO,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC;YACpE,OAAO,GAAG,CAAC;QAGb,MAAM,WAAW,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAA,KAAK,CAAC,CAAC,CAAC,0CAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC;QAExE,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACrB,GAAG,CAAC,GAAG,CAAC;gBACN,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK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AC,WAAW,EAAE,KAAK,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS;iBAC9D,CAAC;gBACF,MAAM;YAER;gBACE,YAAY,CAAC,UAAU,CAAC,GAAG;oBACzB,CAAC,YAAY,CAAC,EAAE,YAAY,CAAC,WAAW,EAAE,SAAS,EAAE,WAAW,CAAC;iBAClE,CAAC;QACN,CAAC;QAED,OAAO,GAAG,CAAC;IACb,CAAC,EACD,EAAkB,CACnB,CAAC;AACJ,CAAC;AAqBD,SAAS,YAAY,CACnB,KAAa,EACb,SAAiB,EACjB,MAAmB;IAGnB,IAAI,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,SAAS,CAAC,IAAI,KAAK,EAAE,CAAC;QACnD,OAAO,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;IACzB,CAAC;IAGD,IAAI,MAAM,CAAC,aAAa,CAAC,QAAQ,CAAC,SAAS,CAAC,IAAI,KAAK,EAAE,CAAC;QACtD,OAAO,KAAK,CAAC,WAAW,EAAE,KAAK,MAAM,CAAC;IACxC,CAAC;IAGD,IAAI,MAAM,CAAC,aAAa,CAAC,QAAQ,CAAC,SAAS,CAAC,IAAI,KAAK,EAAE,CAAC;QACtD,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;IACvB,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["/**\n * Configuration types for field type mapping\n */\ninterface FieldConfig {\n dateFields: string[];\n booleanFields: string[];\n numericFields: string[];\n}\n\n/**\n * Type for the structured filter object returned by the parser\n */\ntype ParsedFilter = {\n [key: string]: any;\n orderBy?: Record<string, \"asc\" | \"desc\">;\n OR?: Record<string, any>[];\n};\n\n/**\n * Default configuration for field types\n */\nconst DEFAULT_FIELD_CONFIG: FieldConfig = {\n dateFields: [\"createdAt\", \"updatedAt\", \"deletedAt\", \"date\"],\n booleanFields: [\"isActive\", \"isDeleted\", \"isPublished\", \"isArchived\"],\n numericFields: [\"age\", \"price\", \"quantity\", \"amount\", \"rating\"],\n};\n\n/**\n * Parses query parameters into a structured filter object compatible with Prisma queries.\n * Supports various operators and data type conversions.\n *\n * @param query - Object containing query parameters\n * @param fieldConfig - Optional configuration for field type mapping\n * @returns Structured filter object for database queries\n *\n * @example\n * // Basic usage\n * parseQueryParamsWithModifiers({ name__contains: 'john' })\n * // => { name: { contains: 'john', mode: 'sensitive' } }\n *\n * @example\n * // Complex query\n * parseQueryParamsWithModifiers({\n * name__not__equals: 'john',\n * age__gt: '25',\n * tags__in: 'tag1,tag2',\n * orderBy__createdAt: 'desc'\n * })\n */\nexport function parseQueryParamsWithModifiers(\n query: Record<string, any>,\n // excludedFields: string[],\n fieldConfig: FieldConfig = DEFAULT_FIELD_CONFIG\n): ParsedFilter {\n return Object.entries(JSON.parse(JSON.stringify(query))).reduce(\n (acc, [key, value]) => {\n const parts = key.split(\"__\");\n if (!value && value !== false && value !== \"false\" && parts.length < 2)\n return acc;\n\n // Convert value to string if it's not already\n const stringValue = Array.isArray(value) ? value[0]?.toString() : value;\n\n if (parts.length < 2) {\n acc[key] =\n typeof value === \"string\" && !Number.isNaN(value)\n ? convertValue(stringValue, parts[0], fieldConfig)\n : value;\n return acc;\n }\n const fieldName = parts[0];\n\n // Handle ordering\n if (fieldName === \"orderBy\" && parts.length === 2) {\n if (!acc.orderBy) acc.orderBy = {};\n acc.orderBy[parts[1]] = stringValue as \"asc\" | \"desc\";\n return acc;\n }\n\n // Handle simple equals case\n if (parts.length === 1) {\n acc[fieldName] = {\n equals: convertValue(stringValue, fieldName, fieldConfig),\n };\n return acc;\n }\n\n let currentLevel = acc;\n let currentKey = fieldName;\n\n // Build nested structure\n for (let i = 1; i < parts.length - 1; i++) {\n if (!currentLevel[currentKey]) {\n currentLevel[currentKey] = {};\n }\n currentLevel = currentLevel[currentKey];\n currentKey = parts[i];\n }\n\n const lastOperator = parts[parts.length - 1];\n\n // Handle special operators\n switch (lastOperator) {\n case \"icontains\":\n currentLevel[currentKey] = {\n contains: stringValue,\n mode: \"insensitive\",\n };\n break;\n\n case \"contains\":\n currentLevel[currentKey] = {\n contains: stringValue,\n mode: \"sensitive\",\n };\n break;\n\n case \"in\":\n case \"notIn\":\n currentLevel[currentKey] = {\n [lastOperator]: stringValue\n .split(\",\")\n .map((v: string) =>\n convertValue(v.trim(), fieldName, fieldConfig)\n ),\n };\n break;\n\n case \"or\":\n const values: string[] = stringValue.split(\",\");\n if (!acc.OR) acc.OR = [];\n acc.OR.push(\n ...values.map((val) => ({\n [fieldName]: {\n equals: convertValue(val.trim(), fieldName, fieldConfig),\n },\n }))\n );\n break;\n\n case \"isNull\":\n currentLevel[currentKey] = {\n equals: stringValue.toLowerCase() === \"true\" ? null : undefined,\n };\n break;\n\n case \"isEmpty\":\n currentLevel[currentKey] = {\n equals: stringValue.toLowerCase() === \"true\" ? \"\" : undefined,\n };\n break;\n\n default:\n currentLevel[currentKey] = {\n [lastOperator]: convertValue(stringValue, fieldName, fieldConfig),\n };\n }\n\n return acc;\n },\n {} as ParsedFilter\n );\n}\n\n/**\n * Converts string values to appropriate types based on field configuration\n * \n * // Example usage:\n/*\n const query = {\n name__not__equals: 'uanela',\n email__contains: 'example.com',\n description__icontains: 'test',\n age__gt: '25',\n status: 'active',\n tags__in: 'tag1,tag2,tag3',\n createdAt__gt: '2024-01-01',\n isActive: 'true',\n orderBy__createdAt: 'desc'\n };\n \n const result = parseQueryParamsWithModifiers(query);\n */\nfunction convertValue(\n value: string,\n fieldName: string,\n config: FieldConfig\n): any {\n // Handle date fields\n if (config.dateFields.includes(fieldName) && value) {\n return new Date(value);\n }\n\n // Handle boolean fields\n if (config.booleanFields.includes(fieldName) && value) {\n return value.toLowerCase() === \"true\";\n }\n\n // Handle numeric fields\n if (config.numericFields.includes(fieldName) && value) {\n return Number(value);\n }\n\n return value;\n}\n"]}
1
+ {"version":3,"file":"api.features.helpers.js","sourceRoot":"","sources":["../../../../src/utils/helpers/api.features.helpers.ts"],"names":[],"mappings":";;AAiDA,sEAiH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,EAAE,SAAS,EAAE,WAAW,CAAC;iBAClE,CAAC;QACN,CAAC;QAED,OAAO,GAAG,CAAC;IACb,CAAC,EACD,EAAkB,CACnB,CAAC;AACJ,CAAC;AAqBD,SAAS,YAAY,CACnB,KAAa,EACb,SAAiB,EACjB,MAAmB;;IAGnB,IAAI,CAAA,MAAA,MAAA,MAAM,CAAC,UAAU,0CAAE,QAAQ,mDAAG,SAAS,CAAC,KAAI,KAAK,EAAE,CAAC;QACtD,OAAO,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;IACzB,CAAC;IAGD,IAAI,CAAA,MAAA,MAAA,MAAM,CAAC,aAAa,0CAAE,QAAQ,mDAAG,SAAS,CAAC,KAAI,KAAK,EAAE,CAAC;QACzD,OAAO,KAAK,CAAC,WAAW,EAAE,KAAK,MAAM,CAAC;IACxC,CAAC;IAGD,IAAI,CAAA,MAAA,MAAA,MAAM,CAAC,aAAa,0CAAE,QAAQ,mDAAG,SAAS,CAAC,KAAI,KAAK,EAAE,CAAC;QACzD,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;IACvB,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["/**\n * Configuration types for field type mapping\n */\ninterface FieldConfig {\n dateFields: string[];\n booleanFields: string[];\n numericFields: string[];\n}\n\n/**\n * Type for the structured filter object returned by the parser\n */\ntype ParsedFilter = {\n [key: string]: any;\n orderBy?: Record<string, \"asc\" | \"desc\">;\n OR?: Record<string, any>[];\n};\n\n/**\n * Default configuration for field types\n */\nconst DEFAULT_FIELD_CONFIG: FieldConfig = {\n dateFields: [\"createdAt\", \"updatedAt\", \"deletedAt\", \"date\"],\n booleanFields: [\"isActive\", \"isDeleted\", \"isPublished\", \"isArchived\"],\n numericFields: [\"age\", \"price\", \"quantity\", \"amount\", \"rating\"],\n};\n\n/**\n * Parses query parameters into a structured filter object compatible with Prisma queries.\n * Supports various operators and data type conversions.\n *\n * @param query - Object containing query parameters\n * @param fieldConfig - Optional configuration for field type mapping\n * @returns Structured filter object for database queries\n *\n * @example\n * // Basic usage\n * parseQueryParamsWithModifiers({ name__contains: 'john' })\n * // => { name: { contains: 'john', mode: 'sensitive' } }\n *\n * @example\n * // Complex query\n * parseQueryParamsWithModifiers({\n * name__not__equals: 'john',\n * age__gt: '25',\n * tags__in: 'tag1,tag2',\n * orderBy__createdAt: 'desc'\n * })\n */\nexport function parseQueryParamsWithModifiers(\n query: Record<string, any>,\n // excludedFields: string[],\n fieldConfig: FieldConfig = DEFAULT_FIELD_CONFIG\n): ParsedFilter {\n return Object.entries(JSON.parse(JSON.stringify(query))).reduce(\n (acc, [key, value]) => {\n const parts = key.split(\"__\");\n if (!value && value !== false && value !== \"false\" && parts.length < 2)\n return acc;\n\n // Convert value to string if it's not already\n const stringValue = Array.isArray(value) ? value[0]?.toString() : value;\n\n if (parts.length < 2) {\n acc[key] =\n typeof value === \"string\" && !Number.isNaN(value)\n ? convertValue(stringValue, parts[0], fieldConfig)\n : value;\n return acc;\n }\n const fieldName = parts[0];\n\n // Handle ordering\n if (fieldName === \"orderBy\" && parts.length === 2) {\n if (!acc.orderBy) acc.orderBy = {};\n acc.orderBy[parts[1]] = stringValue as \"asc\" | \"desc\";\n return acc;\n }\n\n // Handle simple equals case\n if (parts.length === 1) {\n acc[fieldName] = {\n equals: convertValue(stringValue, fieldName, fieldConfig),\n };\n return acc;\n }\n\n let currentLevel = acc;\n let currentKey = fieldName;\n\n // Build nested structure\n for (let i = 1; i < parts.length - 1; i++) {\n if (!currentLevel[currentKey]) {\n currentLevel[currentKey] = {};\n }\n currentLevel = currentLevel[currentKey];\n currentKey = parts[i];\n }\n\n const lastOperator = parts[parts.length - 1];\n\n // Handle special operators\n switch (lastOperator) {\n case \"icontains\":\n currentLevel[currentKey] = {\n contains: stringValue,\n mode: \"insensitive\",\n };\n break;\n\n case \"contains\":\n currentLevel[currentKey] = {\n contains: stringValue,\n mode: \"sensitive\",\n };\n break;\n\n case \"in\":\n case \"notIn\":\n currentLevel[currentKey] = {\n [lastOperator]: stringValue\n .split(\",\")\n .map((v: string) =>\n convertValue(v.trim(), fieldName, fieldConfig)\n ),\n };\n break;\n\n case \"or\":\n const values: string[] = stringValue.split(\",\");\n if (!acc.OR) acc.OR = [];\n acc.OR.push(\n ...values.map((val) => ({\n [fieldName]: {\n equals: convertValue(val.trim(), fieldName, fieldConfig),\n },\n }))\n );\n break;\n\n case \"isNull\":\n currentLevel[currentKey] = {\n equals: stringValue.toLowerCase() === \"true\" ? null : undefined,\n };\n break;\n\n case \"isEmpty\":\n currentLevel[currentKey] = {\n equals: stringValue.toLowerCase() === \"true\" ? \"\" : undefined,\n };\n break;\n\n default:\n currentLevel[currentKey] = {\n [lastOperator]: convertValue(stringValue, fieldName, fieldConfig),\n };\n }\n\n return acc;\n },\n {} as ParsedFilter\n );\n}\n\n/**\n * Converts string values to appropriate types based on field configuration\n * \n * // Example usage:\n/*\n const query = {\n name__not__equals: 'uanela',\n email__contains: 'example.com',\n description__icontains: 'test',\n age__gt: '25',\n status: 'active',\n tags__in: 'tag1,tag2,tag3',\n createdAt__gt: '2024-01-01',\n isActive: 'true',\n orderBy__createdAt: 'desc'\n };\n \n const result = parseQueryParamsWithModifiers(query);\n */\nfunction convertValue(\n value: string,\n fieldName: string,\n config: FieldConfig\n): any {\n // Handle date fields\n if (config.dateFields?.includes?.(fieldName) && value) {\n return new Date(value);\n }\n\n // Handle boolean fields\n if (config.booleanFields?.includes?.(fieldName) && value) {\n return value.toLowerCase() === \"true\";\n }\n\n // Handle numeric fields\n if (config.numericFields?.includes?.(fieldName) && value) {\n return Number(value);\n }\n\n return value;\n}\n"]}