arkos 1.2.18-test → 1.2.19-test

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/cjs/modules/auth/auth.service.js.map +1 -1
  2. package/dist/cjs/utils/cli/utils/template-generator/templates/generate-middlewares.js +33 -66
  3. package/dist/cjs/utils/cli/utils/template-generator/templates/generate-middlewares.js.map +1 -1
  4. package/dist/cjs/utils/cli/utils/template-generator/templates/generate-prisma-query-options.js +16 -10
  5. package/dist/cjs/utils/cli/utils/template-generator/templates/generate-prisma-query-options.js.map +1 -1
  6. package/dist/cjs/utils/cli/utils/template-generator/templates/generate-router-template.js +5 -0
  7. package/dist/cjs/utils/cli/utils/template-generator/templates/generate-router-template.js.map +1 -1
  8. package/dist/esm/app.js +1 -1
  9. package/dist/esm/exports/auth/index.js +1 -1
  10. package/dist/esm/exports/controllers/index.js +2 -2
  11. package/dist/esm/exports/error-handler/index.js +2 -2
  12. package/dist/esm/exports/index.js +2 -2
  13. package/dist/esm/exports/middlewares/index.js +1 -1
  14. package/dist/esm/exports/prisma/index.js +1 -1
  15. package/dist/esm/exports/services/index.js +4 -4
  16. package/dist/esm/exports/utils/index.js +2 -2
  17. package/dist/esm/exports/validation/index.js +2 -2
  18. package/dist/esm/modules/auth/auth.controller.js +7 -7
  19. package/dist/esm/modules/auth/auth.router.js +6 -6
  20. package/dist/esm/modules/auth/auth.service.js +6 -6
  21. package/dist/esm/modules/auth/auth.service.js.map +1 -1
  22. package/dist/esm/modules/auth/utils/helpers/auth.controller.helpers.js +2 -2
  23. package/dist/esm/modules/base/base.controller.js +7 -7
  24. package/dist/esm/modules/base/base.middlewares.js +6 -6
  25. package/dist/esm/modules/base/base.router.js +4 -4
  26. package/dist/esm/modules/base/base.service.js +6 -6
  27. package/dist/esm/modules/base/utils/helpers/base.controller.helpers.js +1 -1
  28. package/dist/esm/modules/base/utils/helpers/base.middlewares.helpers.js +1 -1
  29. package/dist/esm/modules/base/utils/helpers/base.router.helpers.js +6 -6
  30. package/dist/esm/modules/base/utils/helpers/base.service.helpers.js +1 -1
  31. package/dist/esm/modules/email/email.service.js +2 -2
  32. package/dist/esm/modules/error-handler/error-handler.controller.js +3 -3
  33. package/dist/esm/modules/error-handler/utils/error-handler.helpers.js +1 -1
  34. package/dist/esm/modules/file-upload/file-upload.controller.js +7 -7
  35. package/dist/esm/modules/file-upload/file-upload.router.js +5 -5
  36. package/dist/esm/modules/file-upload/file-upload.service.js +5 -5
  37. package/dist/esm/modules/file-upload/utils/helpers/file-upload.helpers.js +2 -2
  38. package/dist/esm/modules/swagger/swagger.router.js +2 -2
  39. package/dist/esm/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js +2 -2
  40. package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/generate-class-validator-json-schemas.js +3 -3
  41. package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/generate-prisma-json-schemas.js +2 -2
  42. package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/generate-zod-json-schema.js +2 -2
  43. package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-main-routes.js +2 -2
  44. package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-parent-routes.js +3 -3
  45. package/dist/esm/modules/swagger/utils/helpers/swagger.router.helpers.js +9 -9
  46. package/dist/esm/server.js +1 -1
  47. package/dist/esm/utils/cli/build.js +4 -4
  48. package/dist/esm/utils/cli/dev.js +5 -5
  49. package/dist/esm/utils/cli/generate.js +4 -4
  50. package/dist/esm/utils/cli/index.js +5 -5
  51. package/dist/esm/utils/cli/start.js +4 -4
  52. package/dist/esm/utils/cli/utils/cli.helpers.js +2 -2
  53. package/dist/esm/utils/cli/utils/template-generator/templates/generate-auth-configs-template.js +1 -1
  54. package/dist/esm/utils/cli/utils/template-generator/templates/generate-middlewares.js +34 -67
  55. package/dist/esm/utils/cli/utils/template-generator/templates/generate-middlewares.js.map +1 -1
  56. package/dist/esm/utils/cli/utils/template-generator/templates/generate-prisma-query-options.js +18 -12
  57. package/dist/esm/utils/cli/utils/template-generator/templates/generate-prisma-query-options.js.map +1 -1
  58. package/dist/esm/utils/cli/utils/template-generator/templates/generate-router-template.js +6 -1
  59. package/dist/esm/utils/cli/utils/template-generator/templates/generate-router-template.js.map +1 -1
  60. package/dist/esm/utils/cli/utils/template-generator/templates/generate-service-template.js +2 -2
  61. package/dist/esm/utils/cli/utils/template-generators.js +6 -6
  62. package/dist/esm/utils/features/api.features.js +4 -4
  63. package/dist/esm/utils/features/change-case.features.js +1 -1
  64. package/dist/esm/utils/helpers/models.helpers.js +4 -4
  65. package/dist/esm/utils/helpers/prisma.helpers.js +4 -4
  66. package/dist/esm/utils/validate-dto.js +1 -1
  67. package/dist/esm/utils/validate-schema.js +1 -1
  68. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"auth.service.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.service.ts"],"names":[],"mappings":";;;;;;AAAA,gEAAgD;AAChD,wDAA8B;AAE9B,qFAA4D;AAC5D,iFAAwD;AACxD,+DAAoD;AACpD,yCAA8C;AAC9C,sEAA6C;AAC7C,uEAAuE;AAkBvE,MAAa,WAAW;IAAxB;QAuVE,iBAAY,GAAG,IAAA,qBAAU,EACvB,KAAK,EAAE,GAAiB,EAAE,GAAkB,EAAE,IAAuB,EAAE,EAAE;YACvE,MAAM,WAAW,GAAG,IAAA,uBAAc,GAAE,CAAC;YACrC,IAAI,CAAC,WAAW,EAAE,cAAc,EAAE,CAAC;gBACjC,IAAI,EAAE,CAAC;gBACP,OAAO;YACT,CAAC;YAED,GAAG,CAAC,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,oBAAoB,CAAC,GAAG,CAAC,CAAS,CAAC;YAC1D,IAAI,EAAE,CAAC;QACT,CAAC,CACF,CAAC;IAoBJ,CAAC;IA7WC,YAAY,CACV,EAAmB,EACnB,SAA+B,EAC/B,MAAe;QAE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BAAE,OAAO,IAAI,CAAC,YAAY,CAAC;QAC5E,CAAC;;YAAM,OAAO,IAAI,CAAC,YAAY,CAAC;QAEhC,OAAO,IAAI,CAAC,YAAY,CAAC;IAC3B,CAAC;CACF;AAtXD,kCAsXC;AAKD,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;AAEtC,kBAAe,WAAW,CAAC","sourcesContent":["import jwt, { SignOptions } from \"jsonwebtoken\";\nimport bcrypt from \"bcryptjs\";\nimport { User } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { callNext } from \"../base/base.middlewares\";\nimport { getArkosConfig } from \"../../server\";\nimport arkosEnv from \"../../utils/arkos-env\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport {\n ArkosRequest,\n ArkosResponse,\n ArkosNextFunction,\n ArkosRequestHandler,\n} from \"../../types\";\nimport {\n AuthJwtPayload,\n AccessAction,\n AccessControlConfig,\n AuthenticationControlConfig,\n} from \"../../types/auth\";\nimport { MsDuration } from \"./utils/helpers/auth.controller.helpers\";\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nexport class AuthService {\n /**\n * Signs a JWT token for the user.\n *\n * @param {number | string} id - The unique identifier of the user to generate the token for.\n * @param {string | number} [expiresIn] - The expiration time for the token. Defaults to environment variable `JWT_EXPIRES_IN`.\n * @param {string} [secret] - The secret key used to sign the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {string} The signed JWT token.\n */\n signJwtToken(\n id: number | string,\n expiresIn?: MsDuration | number,\n secret?: string\n ): string {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.NODE_ENV === \"production\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret on production!\",\n 500,\n {},\n \"MissingJWTOnProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n expiresIn = (expiresIn ||\n configs?.jwt?.expiresIn ||\n process.env.JWT_EXPIRES_IN ||\n arkosEnv.JWT_EXPIRES_IN) as keyof SignOptions[\"expiresIn\"];\n\n return jwt.sign({ id }, secret, {\n expiresIn: expiresIn as MsDuration,\n });\n }\n\n /**\n * Is used by default internally by Arkos under `BaseService` class to check if the password is already hashed.\n *\n * This was just added to prevent unwanted errors when someone just forgets that the `BaseService` class will automatically hash the password field using `authService.hashPassword` by default.\n *\n * So now before `BaseService` hashes it will test it.\n *\n *\n * @param password The password to be tested if is hashed\n * @returns\n */\n isPasswordHashed(password: string) {\n return !Number.isNaN(bcrypt.getRounds(password) * 1);\n }\n\n /**\n * Compares a candidate password with the stored user password to check if they match.\n *\n * @param {string} candidatePassword - The password provided by the user during login.\n * @param {string} userPassword - The password stored in the database.\n * @returns {Promise<boolean>} Returns true if the passwords match, otherwise false.\n */\n async isCorrectPassword(\n candidatePassword: string,\n userPassword: string\n ): Promise<boolean> {\n return await bcrypt.compare(candidatePassword, userPassword);\n }\n\n /**\n * Hashes a plain text password using bcrypt.\n *\n * @param {string} password - The password to be hashed.\n * @returns {Promise<string>} Returns the hashed password.\n */\n async hashPassword(password: string): Promise<string> {\n return await bcrypt.hash(password, 12);\n }\n\n /**\n * Checks if a password is strong, requiring uppercase, lowercase, and numeric characters as the default.\n *\n * **NB**: You must pay attention when using custom validation with zod or class-validator, try to use the same regex always.\n *\n * **Note**: You can define it when calling arkos.init()\n * ```ts\n * arkos.init({\n * authentication: {\n * passwordValidation:{ regex: /your-desired-regex/, message: 'password must contain...'}\n * }\n * })\n * ```\n *\n * @param {string} password - The password to check.\n * @returns {boolean} Returns true if the password meets the strength criteria, otherwise false.\n */\n public isPasswordStrong(password: string): boolean {\n const initAuthConfigs = getArkosConfig()?.authentication;\n\n const strongPasswordRegex =\n initAuthConfigs?.passwordValidation?.regex ||\n /^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/;\n return strongPasswordRegex.test(password);\n }\n\n /**\n * Checks if a user has changed their password after the JWT was issued.\n *\n * @param {User} user - The user object containing the passwordChangedAt field.\n * @param {number} JWTTimestamp - The timestamp when the JWT was issued.\n * @returns {boolean} Returns true if the user changed their password after the JWT was issued, otherwise false.\n */\n userChangedPasswordAfter(user: User, JWTTimestamp: number): boolean {\n if (user.passwordChangedAt) {\n const convertedTimestamp = parseInt(\n String(user.passwordChangedAt.getTime() / 1000),\n 10\n );\n\n return JWTTimestamp < convertedTimestamp;\n }\n return false;\n }\n\n /**\n * Verifies the authenticity of a JWT token.\n *\n * @param {string} token - The JWT token to verify.\n * @param {string} [secret] - The secret key used to verify the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {Promise<AuthJwtPayload>} Returns the decoded JWT payload if the token is valid.\n * @throws {Error} Throws an error if the token is invalid or expired.\n */\n async verifyJwtToken(\n token: string,\n secret?: string\n ): Promise<AuthJwtPayload> {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.NODE_ENV === \"production\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\"Missing JWT secret!\", 500);\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n return new Promise((resolve, reject) => {\n jwt.verify(token, secret, (err, decoded) => {\n if (err) reject(err);\n else resolve(decoded as AuthJwtPayload);\n });\n });\n }\n\n /**\n * Middleware function to handle access control based on user roles and permissions.\n *\n * @param {AccessAction} action - The action being performed (e.g., create, update, delete, view).\n * @param {string} resourceName - The resource name that the action is being performed on (e.g., \"User\", \"Post\").\n * @param {AccessControlConfig} accessControl - The access control configuration.\n * @returns {ArkosRequestHandler} The middleware function that checks if the user has permission to perform the action.\n */\n handleAccessControl(\n action: AccessAction,\n resourceName: string,\n accessControl?: AccessControlConfig\n ): ArkosRequestHandler {\n return catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n if (req.user) {\n const user = req.user as any;\n const prisma = getPrismaInstance();\n const configs = getArkosConfig();\n\n if (user.isSuperUser) {\n next();\n return;\n }\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const matchingRole = await prisma.userRole.findFirst({\n where: {\n userId: req.user.id,\n role: {\n permissions: {\n some: {\n resource: resourceName,\n action: action,\n },\n },\n },\n },\n select: { id: true },\n });\n\n if (!matchingRole)\n return next(\n new AppError(\n \"You do not have permission to perfom this action\",\n 403\n )\n );\n } else if (configs?.authentication?.mode === \"static\") {\n let authorizedRoles: string[] = [];\n\n if (!accessControl)\n return next(\n new AppError(\n \"You do not have permission to perform this action\",\n 403\n )\n );\n\n if (Array.isArray(accessControl)) authorizedRoles = accessControl;\n else if (accessControl[action])\n authorizedRoles = accessControl[action] || [];\n\n const userRoles = Array.isArray(user?.roles)\n ? user.roles\n : [user.role];\n const hasPermission = userRoles.some((role: string) =>\n authorizedRoles.includes(role)\n );\n\n if (!hasPermission) {\n return next(\n new AppError(\n \"You do not have permission to perform this action\",\n 403\n )\n );\n }\n }\n }\n\n next();\n }\n );\n }\n\n /**\n * Processes the cookies or authoriation token and returns the user.\n * @param req\n * @returns {Promise<User | null>} - if authentication is turned off in arkosConfig it returns null\n * @throws {AppError} Throws an error if the token is invalid or the user is not logged in.\n */\n async getAuthenticatedUser(req: ArkosRequest): Promise<User | null> {\n const arkosConfig = getArkosConfig();\n if (!arkosConfig?.authentication) return null;\n\n const prisma = getPrismaInstance();\n\n let token: string | undefined;\n\n if (\n req?.headers?.authorization &&\n req?.headers?.authorization.startsWith(\"Bearer\")\n ) {\n token = req?.headers?.authorization.split(\" \")[1];\n } else if (req?.cookies?.arkos_access_token !== \"no-token\" && req.cookies) {\n token = req?.cookies?.arkos_access_token;\n }\n\n if (!token)\n throw new AppError(\n \"You are not logged in! please log in to get access\",\n 401,\n {},\n \"LoginRequired\"\n );\n\n let decoded: AuthJwtPayload | undefined;\n try {\n decoded = await this.verifyJwtToken(token);\n } catch (err) {\n throw new AppError(\n \"Your auth token is invalid, please login again.\",\n 401,\n {},\n \"InvalidAuthToken\"\n );\n }\n\n if (!decoded?.id)\n throw new AppError(\n \"Your auth token is invalid, please login again.\",\n 401,\n {},\n \"InvalidAuthToken\"\n );\n\n const user: any | null = await (prisma as any).user.findUnique({\n where: { id: String(decoded.id) },\n // select: {\n // id: true,\n // passwordChangedAt: true,\n // isActive: true,\n // deletedSelfAccountAt: true,\n // isSuperUser: true,\n // },\n });\n\n if (!user)\n throw new AppError(\n \"The user belonging to this token does no longer exists\",\n 401\n );\n\n if (\n this.userChangedPasswordAfter(user, decoded.iat!) &&\n !req.path?.includes?.(\"logout\")\n )\n throw new AppError(\n \"User recently changed password! Please log in again.\",\n 401,\n {},\n \"PasswordChanged\"\n );\n\n return user;\n }\n\n /**\n * Middleware function to authenticate the user based on the JWT token.\n *\n * @param {ArkosRequest} req - The request object.\n * @param {ArkosResponse} res - The response object.\n * @param {ArkosNextFunction} next - The next middleware function to be called.\n * @returns {void}\n */\n authenticate = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const arkosConfig = getArkosConfig();\n if (!arkosConfig?.authentication) {\n next();\n return;\n }\n\n req.user = (await this.getAuthenticatedUser(req)) as User;\n next();\n }\n );\n\n /**\n * Handles authentication control by checking the `authenticationControl` configuration in the `authConfigs`.\n *\n * @param {ControllerActions} action - The action being performed (e.g., create, update, delete, view).\n * @param {AuthenticationControlConfig} authenticationControl - The authentication configuration object.\n * @returns {ArkosRequestHandler} The middleware function that checks if authentication is required.\n */\n handleAuthenticationControl(\n action: AccessAction,\n authenticationControl?: AuthenticationControlConfig | undefined\n ): ArkosRequestHandler {\n if (authenticationControl && typeof authenticationControl === \"object\") {\n if (authenticationControl[action] === false) return callNext;\n else if (authenticationControl[action] === true) return this.authenticate;\n } else return this.authenticate;\n\n return this.authenticate;\n }\n}\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nconst authService = new AuthService();\n\nexport default authService;\n"]}
1
+ {"version":3,"file":"auth.service.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.service.ts"],"names":[],"mappings":";;;;;;AAAA,gEAAgD;AAChD,wDAA8B;AAE9B,qFAA4D;AAC5D,iFAAwD;AACxD,+DAAoD;AACpD,yCAA8C;AAC9C,sEAA6C;AAC7C,uEAAuE;AAkBvE,MAAa,WAAW;IAAxB;QAgVE,iBAAY,GAAG,IAAA,qBAAU,EACvB,KAAK,EAAE,GAAiB,EAAE,GAAkB,EAAE,IAAuB,EAAE,EAAE;YACvE,MAAM,WAAW,GAAG,IAAA,uBAAc,GAAE,CAAC;YACrC,IAAI,CAAC,WAAW,EAAE,cAAc,EAAE,CAAC;gBACjC,IAAI,EAAE,CAAC;gBACP,OAAO;YACT,CAAC;YAED,GAAG,CAAC,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,oBAAoB,CAAC,GAAG,CAAC,CAAS,CAAC;YAC1D,IAAI,EAAE,CAAC;QACT,CAAC,CACF,CAAC;IAoBJ,CAAC;IAtWC,YAAY,CACV,EAAmB,EACnB,SAA+B,EAC/B,MAAe;QAEf,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,GAAG,IAAA,uBAAc,GAAE,CAAC;QAErD,IACE,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY;YACrC,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU;YACvB,CAAC,OAAO,EAAE,GAAG,EAAE,MAAM;YAErB,MAAM,IAAI,mBAAQ,CAChB,mCAAmC,EACnC,GAAG,EACH,EAAE,EACF,wBAAwB,CACzB,CAAC;QAEJ,MAAM;YACJ,MAAM;gBACN,OAAO,EAAE,GAAG,EAAE,MAAM;gBACpB,OAAO,CAAC,GAAG,CAAC,UAAU;gBACtB,mBAAQ,CAAC,UAAU,CAAC;QAEtB,SAAS,GAAG,CAAC,SAAS;YACpB,OAAO,EAAE,GAAG,EAAE,SAAS;YACvB,OAAO,CAAC,GAAG,C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UAAU,CAAC;YAC7D,KAAK,EAAE,EAAE,EAAE,EAAE,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE;SAClC,CAAC,CAAC;QAEH,IAAI,CAAC,IAAI;YACP,MAAM,IAAI,mBAAQ,CAChB,wDAAwD,EACxD,GAAG,CACJ,CAAC;QAEJ,IACE,IAAI,CAAC,wBAAwB,CAAC,IAAI,EAAE,OAAO,CAAC,GAAI,CAAC;YACjD,CAAC,GAAG,CAAC,IAAI,EAAE,QAAQ,EAAE,CAAC,QAAQ,CAAC;YAE/B,MAAM,IAAI,mBAAQ,CAChB,sDAAsD,EACtD,GAAG,EACH,EAAE,EACF,iBAAiB,CAClB,CAAC;QAEJ,OAAO,IAAI,CAAC;IACd,CAAC;IA8BD,2BAA2B,CACzB,MAAoB,EACpB,qBAA+D;QAE/D,IAAI,qBAAqB,IAAI,OAAO,qBAAqB,KAAK,QAAQ,EAAE,CAAC;YACvE,IAAI,qBAAqB,CAAC,MAAM,CAAC,KAAK,KAAK;gBAAE,OAAO,2BAAQ,CAAC;iBACxD,IAAI,qBAAqB,CAAC,MAAM,CAAC,KAAK,IAAI;gBAAE,OAAO,IAAI,CAAC,YAAY,CAAC;QAC5E,CAAC;;YAAM,OAAO,IAAI,CAAC,YAAY,CAAC;QAEhC,OAAO,IAAI,CAAC,YAAY,CAAC;IAC3B,CAAC;CACF;AA/WD,kCA+WC;AAKD,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;AAEtC,kBAAe,WAAW,CAAC","sourcesContent":["import jwt, { SignOptions } from \"jsonwebtoken\";\nimport bcrypt from \"bcryptjs\";\nimport { User } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { callNext } from \"../base/base.middlewares\";\nimport { getArkosConfig } from \"../../server\";\nimport arkosEnv from \"../../utils/arkos-env\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport {\n ArkosRequest,\n ArkosResponse,\n ArkosNextFunction,\n ArkosRequestHandler,\n} from \"../../types\";\nimport {\n AuthJwtPayload,\n AccessAction,\n AccessControlConfig,\n AuthenticationControlConfig,\n} from \"../../types/auth\";\nimport { MsDuration } from \"./utils/helpers/auth.controller.helpers\";\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nexport class AuthService {\n /**\n * Signs a JWT token for the user.\n *\n * @param {number | string} id - The unique identifier of the user to generate the token for.\n * @param {string | number} [expiresIn] - The expiration time for the token. Defaults to environment variable `JWT_EXPIRES_IN`.\n * @param {string} [secret] - The secret key used to sign the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {string} The signed JWT token.\n */\n signJwtToken(\n id: number | string,\n expiresIn?: MsDuration | number,\n secret?: string\n ): string {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.NODE_ENV === \"production\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret on production!\",\n 500,\n {},\n \"MissingJWTOnProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n expiresIn = (expiresIn ||\n configs?.jwt?.expiresIn ||\n process.env.JWT_EXPIRES_IN ||\n arkosEnv.JWT_EXPIRES_IN) as keyof SignOptions[\"expiresIn\"];\n\n return jwt.sign({ id }, secret, {\n expiresIn: expiresIn as MsDuration,\n });\n }\n\n /**\n * Is used by default internally by Arkos under `BaseService` class to check if the password is already hashed.\n *\n * This was just added to prevent unwanted errors when someone just forgets that the `BaseService` class will automatically hash the password field using `authService.hashPassword` by default.\n *\n * So now before `BaseService` hashes it will test it.\n *\n *\n * @param password The password to be tested if is hashed\n * @returns\n */\n isPasswordHashed(password: string) {\n return !Number.isNaN(bcrypt.getRounds(password) * 1);\n }\n\n /**\n * Compares a candidate password with the stored user password to check if they match.\n *\n * @param {string} candidatePassword - The password provided by the user during login.\n * @param {string} userPassword - The password stored in the database.\n * @returns {Promise<boolean>} Returns true if the passwords match, otherwise false.\n */\n async isCorrectPassword(\n candidatePassword: string,\n userPassword: string\n ): Promise<boolean> {\n return await bcrypt.compare(candidatePassword, userPassword);\n }\n\n /**\n * Hashes a plain text password using bcrypt.\n *\n * @param {string} password - The password to be hashed.\n * @returns {Promise<string>} Returns the hashed password.\n */\n async hashPassword(password: string): Promise<string> {\n return await bcrypt.hash(password, 12);\n }\n\n /**\n * Checks if a password is strong, requiring uppercase, lowercase, and numeric characters as the default.\n *\n * **NB**: You must pay attention when using custom validation with zod or class-validator, try to use the same regex always.\n *\n * **Note**: You can define it when calling arkos.init()\n * ```ts\n * arkos.init({\n * authentication: {\n * passwordValidation:{ regex: /your-desired-regex/, message: 'password must contain...'}\n * }\n * })\n * ```\n *\n * @param {string} password - The password to check.\n * @returns {boolean} Returns true if the password meets the strength criteria, otherwise false.\n */\n public isPasswordStrong(password: string): boolean {\n const initAuthConfigs = getArkosConfig()?.authentication;\n\n const strongPasswordRegex =\n initAuthConfigs?.passwordValidation?.regex ||\n /^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/;\n return strongPasswordRegex.test(password);\n }\n\n /**\n * Checks if a user has changed their password after the JWT was issued.\n *\n * @param {User} user - The user object containing the passwordChangedAt field.\n * @param {number} JWTTimestamp - The timestamp when the JWT was issued.\n * @returns {boolean} Returns true if the user changed their password after the JWT was issued, otherwise false.\n */\n userChangedPasswordAfter(user: User, JWTTimestamp: number): boolean {\n if (user.passwordChangedAt) {\n const convertedTimestamp = parseInt(\n String(user.passwordChangedAt.getTime() / 1000),\n 10\n );\n\n return JWTTimestamp < convertedTimestamp;\n }\n return false;\n }\n\n /**\n * Verifies the authenticity of a JWT token.\n *\n * @param {string} token - The JWT token to verify.\n * @param {string} [secret] - The secret key used to verify the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {Promise<AuthJwtPayload>} Returns the decoded JWT payload if the token is valid.\n * @throws {Error} Throws an error if the token is invalid or expired.\n */\n async verifyJwtToken(\n token: string,\n secret?: string\n ): Promise<AuthJwtPayload> {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.NODE_ENV === \"production\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\"Missing JWT secret!\", 500);\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n return new Promise((resolve, reject) => {\n jwt.verify(token, secret, (err, decoded) => {\n if (err) reject(err);\n else resolve(decoded as AuthJwtPayload);\n });\n });\n }\n\n /**\n * Middleware function to handle access control based on user roles and permissions.\n *\n * @param {AccessAction} action - The action being performed (e.g., create, update, delete, view).\n * @param {string} resourceName - The resource name that the action is being performed on (e.g., \"User\", \"Post\").\n * @param {AccessControlConfig} accessControl - The access control configuration.\n * @returns {ArkosRequestHandler} The middleware function that checks if the user has permission to perform the action.\n */\n handleAccessControl(\n action: AccessAction,\n resourceName: string,\n accessControl?: AccessControlConfig\n ): ArkosRequestHandler {\n return catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n if (req.user) {\n const user = req.user as any;\n const prisma = getPrismaInstance();\n const configs = getArkosConfig();\n\n if (user.isSuperUser) {\n next();\n return;\n }\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const matchingRole = await prisma.userRole.findFirst({\n where: {\n userId: req.user.id,\n role: {\n permissions: {\n some: {\n resource: resourceName,\n action: action,\n },\n },\n },\n },\n select: { id: true },\n });\n\n if (!matchingRole)\n return next(\n new AppError(\n \"You do not have permission to perfom this action\",\n 403\n )\n );\n } else if (configs?.authentication?.mode === \"static\") {\n let authorizedRoles: string[] = [];\n\n if (!accessControl)\n return next(\n new AppError(\n \"You do not have permission to perform this action\",\n 403\n )\n );\n\n if (Array.isArray(accessControl)) authorizedRoles = accessControl;\n else if (accessControl[action])\n authorizedRoles = accessControl[action] || [];\n\n const userRoles = Array.isArray(user?.roles)\n ? user.roles\n : [user.role];\n const hasPermission = userRoles.some((role: string) =>\n authorizedRoles.includes(role)\n );\n\n if (!hasPermission) {\n return next(\n new AppError(\n \"You do not have permission to perform this action\",\n 403\n )\n );\n }\n }\n }\n\n next();\n }\n );\n }\n\n /**\n * Processes the cookies or authoriation token and returns the user.\n * @param req\n * @returns {Promise<User | null>} - if authentication is turned off in arkosConfig it returns null\n * @throws {AppError} Throws an error if the token is invalid or the user is not logged in.\n */\n async getAuthenticatedUser(req: ArkosRequest): Promise<User | null> {\n const arkosConfig = getArkosConfig();\n if (!arkosConfig?.authentication) return null;\n\n const prisma = getPrismaInstance();\n\n let token: string | undefined;\n\n if (\n req?.headers?.authorization &&\n req?.headers?.authorization.startsWith(\"Bearer\")\n ) {\n token = req?.headers?.authorization.split(\" \")[1];\n } else if (req?.cookies?.arkos_access_token !== \"no-token\" && req.cookies) {\n token = req?.cookies?.arkos_access_token;\n }\n\n if (!token)\n throw new AppError(\n \"You are not logged in! please log in to get access\",\n 401,\n {},\n \"LoginRequired\"\n );\n\n let decoded: AuthJwtPayload | undefined;\n try {\n decoded = await this.verifyJwtToken(token);\n } catch (err) {\n throw new AppError(\n \"Your auth token is invalid, please login again.\",\n 401,\n {},\n \"InvalidAuthToken\"\n );\n }\n\n if (!decoded?.id)\n throw new AppError(\n \"Your auth token is invalid, please login again.\",\n 401,\n {},\n \"InvalidAuthToken\"\n );\n\n const user: any | null = await (prisma as any).user.findUnique({\n where: { id: String(decoded.id) },\n });\n\n if (!user)\n throw new AppError(\n \"The user belonging to this token does no longer exists\",\n 401\n );\n\n if (\n this.userChangedPasswordAfter(user, decoded.iat!) &&\n !req.path?.includes?.(\"logout\")\n )\n throw new AppError(\n \"User recently changed password! Please log in again.\",\n 401,\n {},\n \"PasswordChanged\"\n );\n\n return user;\n }\n\n /**\n * Middleware function to authenticate the user based on the JWT token.\n *\n * @param {ArkosRequest} req - The request object.\n * @param {ArkosResponse} res - The response object.\n * @param {ArkosNextFunction} next - The next middleware function to be called.\n * @returns {void}\n */\n authenticate = catchAsync(\n async (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => {\n const arkosConfig = getArkosConfig();\n if (!arkosConfig?.authentication) {\n next();\n return;\n }\n\n req.user = (await this.getAuthenticatedUser(req)) as User;\n next();\n }\n );\n\n /**\n * Handles authentication control by checking the `authenticationControl` configuration in the `authConfigs`.\n *\n * @param {ControllerActions} action - The action being performed (e.g., create, update, delete, view).\n * @param {AuthenticationControlConfig} authenticationControl - The authentication configuration object.\n * @returns {ArkosRequestHandler} The middleware function that checks if authentication is required.\n */\n handleAuthenticationControl(\n action: AccessAction,\n authenticationControl?: AuthenticationControlConfig | undefined\n ): ArkosRequestHandler {\n if (authenticationControl && typeof authenticationControl === \"object\") {\n if (authenticationControl[action] === false) return callNext;\n else if (authenticationControl[action] === true) return this.authenticate;\n } else return this.authenticate;\n\n return this.authenticate;\n }\n}\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nconst authService = new AuthService();\n\nexport default authService;\n"]}
@@ -23,246 +23,213 @@ import { catchAsync } from "arkos/error-handler";`
23
23
  if (isAuth) {
24
24
  return `${baseImports}
25
25
 
26
- // export const beforeGetMe = catchAsync(
26
+ // export const beforeGetMe =
27
27
  // async (${functionParams}) => {
28
28
  // // Your logic here
29
29
  // next();
30
30
  // }
31
- // );
32
31
 
33
- // export const afterGetMe = catchAsync(
32
+ // export const afterGetMe =
34
33
  // async (${functionParams}) => {
35
34
  // // Your logic here
36
35
  // next();
37
36
  // }
38
- // );
39
37
 
40
- // export const beforeLogin = catchAsync(
38
+ // export const beforeLogin =
41
39
  // async (${functionParams}) => {
42
40
  // // Your logic here
43
41
  // next();
44
42
  // }
45
- // );
46
43
 
47
- // export const afterLogin = catchAsync(
44
+ // export const afterLogin =
48
45
  // async (${functionParams}) => {
49
46
  // // Your logic here
50
47
  // next();
51
48
  // }
52
- // );
53
49
 
54
- // export const beforeLogout = catchAsync(
50
+ // export const beforeLogout =
55
51
  // async (${functionParams}) => {
56
52
  // // Your logic here
57
53
  // next();
58
54
  // }
59
- // );
60
55
 
61
- // export const afterLogout = catchAsync(
56
+ // export const afterLogout =
62
57
  // async (${functionParams}) => {
63
58
  // // Your logic here
64
59
  // next();
65
60
  // }
66
- // );
67
61
 
68
- // export const beforeSignup = catchAsync(
62
+ // export const beforeSignup =
69
63
  // async (${functionParams}) => {
70
64
  // // Your logic here
71
65
  // next();
72
66
  // }
73
- // );
74
67
 
75
- // export const afterSignup = catchAsync(
68
+ // export const afterSignup =
76
69
  // async (${functionParams}) => {
77
70
  // // Your logic here
78
71
  // next();
79
72
  // }
80
- // );
81
73
 
82
- // export const beforeUpdatePassword = catchAsync(
74
+ // export const beforeUpdatePassword =
83
75
  // async (${functionParams}) => {
84
76
  // // Your logic here
85
77
  // next();
86
78
  // }
87
- // );
88
79
 
89
- // export const afterUpdatePassword = catchAsync(
80
+ // export const afterUpdatePassword =
90
81
  // async (${functionParams}) => {
91
82
  // // Your logic here
92
83
  // next();
93
84
  // }
94
- // );
95
85
  `;
96
86
  }
97
87
  if (isFileUpload) {
98
88
  return `${baseImports}
99
89
 
100
90
 
101
- // export const beforeFindFile = catchAsync(
91
+ // export const beforeFindFile =
102
92
  // async (${functionParams}) => {
103
93
  // // Your logic here
104
94
  // next();
105
95
  // }
106
- // );
107
96
 
108
97
  // There is not afterFindFile: because the main handler is handleded by express.static()
109
98
 
110
- // export const beforeUploadFile = catchAsync(
99
+ // export const beforeUploadFile =
111
100
  // async (${functionParams}) => {
112
101
  // // Your logic here
113
102
  // next();
114
103
  // }
115
- // );
116
104
 
117
- // export const afterUploadFile = catchAsync(
105
+ // export const afterUploadFile =
118
106
  // async (${functionParams}) => {
119
107
  // // Your logic here
120
108
  // next();
121
109
  // }
122
- // );
123
110
 
124
- // export const beforeUpdateFile = catchAsync(
111
+ // export const beforeUpdateFile =
125
112
  // async (${functionParams}) => {
126
113
  // // Your logic here
127
114
  // next();
128
115
  // }
129
- // );
130
116
 
131
- // export const afterUpdateFile = catchAsync(
117
+ // export const afterUpdateFile =
132
118
  // async (${functionParams}) => {
133
119
  // // Your logic here
134
120
  // next();
135
121
  // }
136
- // );
137
122
 
138
- // export const beforeDeleteFile = catchAsync(
123
+ // export const beforeDeleteFile =
139
124
  // async (${functionParams}) => {
140
125
  // // Your logic here
141
126
  // next();
142
127
  // }
143
- // );
144
128
 
145
- // export const afterDeleteFile = catchAsync(
129
+ // export const afterDeleteFile =
146
130
  // async (${functionParams}) => {
147
131
  // // Your logic here
148
132
  // next();
149
133
  // }
150
- // );
151
134
  `;
152
135
  }
153
136
  return `${baseImports}
154
137
 
155
- // export const beforeCreateOne = catchAsync(
138
+ // export const beforeCreateOne =
156
139
  // async (${functionParams}) => {
157
140
  // // Your logic here
158
141
  // next();
159
142
  // }
160
- // );
161
143
 
162
- // export const afterCreateOne = catchAsync(
144
+ // export const afterCreateOne =
163
145
  // async (${functionParams}) => {
164
146
  // // Your logic here
165
147
  // next();
166
148
  // }
167
- // );
168
149
 
169
- // export const beforeFindOne = catchAsync(
150
+ // export const beforeFindOne =
170
151
  // async (${functionParams}) => {
171
152
  // // Your logic here
172
153
  // next();
173
154
  // }
174
- // );
175
155
 
176
- // export const afterFindOne = catchAsync(
156
+ // export const afterFindOne =
177
157
  // async (${functionParams}) => {
178
158
  // // Your logic here
179
159
  // next();
180
160
  // }
181
- // );
182
161
 
183
- // export const beforeFindMany = catchAsync(
162
+ // export const beforeFindMany =
184
163
  // async (${functionParams}) => {
185
164
  // // Your logic here
186
165
  // next();
187
166
  // }
188
- // );
189
167
 
190
- // export const afterFindMany = catchAsync(
168
+ // export const afterFindMany =
191
169
  // async (${functionParams}) => {
192
170
  // // Your logic here
193
171
  // next();
194
172
  // }
195
- // );
196
173
 
197
- // export const beforeUpdateOne = catchAsync(
174
+ // export const beforeUpdateOne =
198
175
  // async (${functionParams}) => {
199
176
  // // Your logic here
200
177
  // next();
201
178
  // }
202
- // );
203
179
 
204
- // export const afterUpdateOne = catchAsync(
180
+ // export const afterUpdateOne =
205
181
  // async (${functionParams}) => {
206
182
  // // Your logic here
207
183
  // next();
208
184
  // }
209
- // );
210
185
 
211
- // export const beforeDeleteOne = catchAsync(
186
+ // export const beforeDeleteOne =
212
187
  // async (${functionParams}) => {
213
188
  // // Your logic here
214
189
  // next();
215
190
  // }
216
- // );
217
191
 
218
- // export const afterDeleteOne = catchAsync(
192
+ // export const afterDeleteOne =
219
193
  // async (${functionParams}) => {
220
194
  // // Your logic here
221
195
  // next();
222
196
  // }
223
- // );
224
197
 
225
- // export const beforeCreateMany = catchAsync(
198
+ // export const beforeCreateMany =
226
199
  // async (${functionParams}) => {
227
200
  // // Your logic here
228
201
  // next();
229
202
  // }
230
- // );
231
203
 
232
- // export const afterCreateMany = catchAsync(
204
+ // export const afterCreateMany =
233
205
  // async (${functionParams}) => {
234
206
  // // Your logic here
235
207
  // next();
236
208
  // }
237
- // );
238
209
 
239
- // export const beforeUpdateMany = catchAsync(
210
+ // export const beforeUpdateMany =
240
211
  // async (${functionParams}) => {
241
212
  // // Your logic here
242
213
  // next();
243
214
  // }
244
- // );
245
215
 
246
- // export const afterUpdateMany = catchAsync(
216
+ // export const afterUpdateMany =
247
217
  // async (${functionParams}) => {
248
218
  // // Your logic here
249
219
  // next();
250
220
  // }
251
- // );
252
221
 
253
- // export const beforeDeleteMany = catchAsync(
222
+ // export const beforeDeleteMany =
254
223
  // async (${functionParams}) => {
255
224
  // // Your logic here
256
225
  // next();
257
226
  // }
258
- // );
259
227
 
260
- // export const afterDeleteMany = catchAsync(
228
+ // export const afterDeleteMany =
261
229
  // async (${functionParams}) => {
262
230
  // // Your logic here
263
231
  // next();
264
232
  // }
265
- // );
266
233
  `;
267
234
  }
268
235
  //# sourceMappingURL=generate-middlewares.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate-middlewares.js","sourceRoot":"","sources":["../../../../../../../src/utils/cli/utils/template-generator/templates/generate-middlewares.ts"],"names":[],"mappings":";;AAG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AAG,WAAW;;;;cAIX,cAAc;;;;;;;;;cASd,cAAc;;;;;;;cAOd,cAAc;;;;;;;cAOd,cAAc;;;;;;;cAOd,cAAc;;;;;;;cAOd,cAAc;;;;;;;cAOd,cAAc;;;;;CAK3B,CAAC;IACA,CAAC;IAGD,OAAO,GAAG,WAAW;;;cAGT,cAAc;;;;;;;cAOd,cAAc;;;;;;;cAOd,cAAc;;;;;;;cAOd,cAAc;;;;;;;cAOd,cAAc;;;;;;;cAOd,cAAc;;;;;;;cAOd,cAAc;;;;;;;cAOd,cAAc;;;;;;;cAOd,cAAc;;;;;;;cAOd,cAAc;;;;;;;cAOd,cAAc;;;;;;;cAOd,cAAc;;;;;;;cAOd,cAAc;;;;;;;cAOd,cAAc;;;;;;;cAOd,cAAc;;;;;;;cAOd,cAAc;;;;;CAK3B,CAAC;AACF,CAAC","sourcesContent":["import { getUserFileExtension } from \"../../../../helpers/fs.helpers\";\nimport { TemplateOptions } from \"../../template-generators\";\n\nexport function generateMiddlewaresTemplate(options: TemplateOptions): string {\n const { modelName } = options;\n const ext = getUserFileExtension();\n const isTypeScript = ext === \"ts\";\n\n if (!modelName)\n throw new Error(\"Model name is required for middleware template\");\n\n const isAuth = modelName.camel === \"auth\";\n const isFileUpload =\n modelName.camel === \"fileUpload\" || modelName.camel === \"file-upload\";\n\n // Generate imports based on TypeScript/JavaScript\n const requestType = isTypeScript ? \"ArkosRequest\" : \"req\";\n const responseType = isTypeScript ? \"ArkosResponse\" : \"res\";\n const nextType = isTypeScript ? \"ArkosNextFunction\" : \"next\";\n\n const baseImports = isTypeScript\n ? `import { ArkosRequest, ArkosResponse, ArkosNextFunction } from \"arkos\";\nimport { catchAsync } from \"arkos/error-handler\";`\n : `import { catchAsync } from \"arkos/error-handler\";`;\n\n const functionParams = isTypeScript\n ? `req: ${requestType}, res: ${responseType}, next: ${nextType}`\n : `req, res, next`;\n\n if (isAuth) {\n return `${baseImports}\n\n// export const beforeGetMe = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const afterGetMe = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const beforeLogin = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const afterLogin = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const beforeLogout = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const afterLogout = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const beforeSignup = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const afterSignup = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const beforeUpdatePassword = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const afterUpdatePassword = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n`;\n }\n\n if (isFileUpload) {\n return `${baseImports}\n\n\n// export const beforeFindFile = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// There is not afterFindFile: because the main handler is handleded by express.static()\n\n// export const beforeUploadFile = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const afterUploadFile = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const beforeUpdateFile = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const afterUpdateFile = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const beforeDeleteFile = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const afterDeleteFile = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n`;\n }\n\n // Regular model middlewares\n return `${baseImports}\n\n// export const beforeCreateOne = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const afterCreateOne = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const beforeFindOne = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const afterFindOne = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const beforeFindMany = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const afterFindMany = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const beforeUpdateOne = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const afterUpdateOne = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const beforeDeleteOne = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const afterDeleteOne = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const beforeCreateMany = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const afterCreateMany = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const beforeUpdateMany = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const afterUpdateMany = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const beforeDeleteMany = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n\n// export const afterDeleteMany = catchAsync(\n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n// );\n`;\n}\n"]}
1
+ {"version":3,"file":"generate-middlewares.js","sourceRoot":"","sources":["../../../../../../../src/utils/cli/utils/template-generator/templates/generate-middlewares.ts"],"names":[],"m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AG,WAAW;;;;cAIX,cAAc;;;;;;;;cAQd,cAAc;;;;;;cAMd,cAAc;;;;;;cAMd,cAAc;;;;;;cAMd,cAAc;;;;;;cAMd,cAAc;;;;;;cAMd,cAAc;;;;CAI3B,CAAC;IACA,CAAC;IAGD,OAAO,GAAG,WAAW;;;cAGT,cAAc;;;;;;cAMd,cAAc;;;;;;cAMd,cAAc;;;;;;cAMd,cAAc;;;;;;cAMd,cAAc;;;;;;cAMd,cAAc;;;;;;cAMd,cAAc;;;;;;cAMd,cAAc;;;;;;cAMd,cAAc;;;;;;cAMd,cAAc;;;;;;cAMd,cAAc;;;;;;cAMd,cAAc;;;;;;cAMd,cAAc;;;;;;cAMd,cAAc;;;;;;cAMd,cAAc;;;;;;cAMd,cAAc;;;;CAI3B,CAAC;AACF,CAAC","sourcesContent":["import { getUserFileExtension } from \"../../../../helpers/fs.helpers\";\nimport { TemplateOptions } from \"../../template-generators\";\n\nexport function generateMiddlewaresTemplate(options: TemplateOptions): string {\n const { modelName } = options;\n const ext = getUserFileExtension();\n const isTypeScript = ext === \"ts\";\n\n if (!modelName)\n throw new Error(\"Model name is required for middleware template\");\n\n const isAuth = modelName.camel === \"auth\";\n const isFileUpload =\n modelName.camel === \"fileUpload\" || modelName.camel === \"file-upload\";\n\n // Generate imports based on TypeScript/JavaScript\n const requestType = isTypeScript ? \"ArkosRequest\" : \"req\";\n const responseType = isTypeScript ? \"ArkosResponse\" : \"res\";\n const nextType = isTypeScript ? \"ArkosNextFunction\" : \"next\";\n\n const baseImports = isTypeScript\n ? `import { ArkosRequest, ArkosResponse, ArkosNextFunction } from \"arkos\";\nimport { catchAsync } from \"arkos/error-handler\";`\n : `import { catchAsync } from \"arkos/error-handler\";`;\n\n const functionParams = isTypeScript\n ? `req: ${requestType}, res: ${responseType}, next: ${nextType}`\n : `req, res, next`;\n\n if (isAuth) {\n return `${baseImports}\n\n// export const beforeGetMe = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const afterGetMe = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const beforeLogin = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const afterLogin = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const beforeLogout = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const afterLogout = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const beforeSignup = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const afterSignup = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const beforeUpdatePassword = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const afterUpdatePassword = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n`;\n }\n\n if (isFileUpload) {\n return `${baseImports}\n\n\n// export const beforeFindFile = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// There is not afterFindFile: because the main handler is handleded by express.static()\n\n// export const beforeUploadFile = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const afterUploadFile = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const beforeUpdateFile = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const afterUpdateFile = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const beforeDeleteFile = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const afterDeleteFile = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n`;\n }\n\n // Regular model middlewares\n return `${baseImports}\n\n// export const beforeCreateOne = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const afterCreateOne = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const beforeFindOne = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const afterFindOne = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const beforeFindMany = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const afterFindMany = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const beforeUpdateOne = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const afterUpdateOne = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const beforeDeleteOne = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const afterDeleteOne = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const beforeCreateMany = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const afterCreateMany = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const beforeUpdateMany = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const afterUpdateMany = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const beforeDeleteMany = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n\n// export const afterDeleteMany = \n// async (${functionParams}) => {\n// // Your logic here\n// next();\n// }\n`;\n}\n"]}
@@ -39,16 +39,22 @@ export default ${modelName.camel}QueryOptions;
39
39
  return `${prismaImport}${imports};
40
40
 
41
41
  const ${modelName.camel}QueryOptions${typeAnnotation} = {
42
- // for all queries
43
- queryOptions: {},
44
- findOne: {},
45
- findMany: {},
46
- deleteMany: {},
47
- updateMany: {},
48
- createMany: {},
49
- createOne: {},
50
- updateOne: {},
51
- deleteOne: {},
42
+ global: {},
43
+ find: {},
44
+ findOne: {},
45
+ findMany: {},
46
+ udpate: {},
47
+ updateMany: {},
48
+ updateOne: {},
49
+ create: {},
50
+ createMany: {},
51
+ createOne: {},
52
+ save: {},
53
+ saveMany: {},
54
+ saveOne: {},
55
+ delete: {},
56
+ deleteMany: {},
57
+ deleteOne: {},
52
58
  }
53
59
 
54
60
  export default ${modelName.camel}QueryOptions;
@@ -1 +1 @@
1
- {"version":3,"file":"generate-prisma-query-options.js","sourceRoot":"","sources":["../../../../../../../src/utils/cli/utils/template-generator/templates/generate-prisma-query-options.ts"],"names":[],"mappings":";;AAGA,oEA6DC;AAhED,+DAAsE;AAGtE,SAAgB,4BAA4B,CAAC,OAAwB;IACnE,MAAM,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC;IAC9B,MAAM,MAAM,GAAG,SAAS,EAAE,KAAK,KAAK,MAAM,CAAC;IAC3C,MAAM,GAAG,GAAG,IAAA,iCAAoB,GAAE,CAAC;IACnC,MAAM,YAAY,GAAG,GAAG,KAAK,IAAI,CAAC;IAElC,IAAI,CAAC,SAAS;QACZ,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAC;IAGtE,MAAM,OAAO,GAAG,MAAM;QACpB,CAAC,CAAC,uDAAuD;QACzD,CAAC,CAAC,mDAAmD,CAAC;IAGxD,MAAM,cAAc,GAAG,YAAY;QACjC,CAAC,CAAC,MAAM;YACN,CAAC,CAAC,0CAA0C,SAAS,CAAC,KAAK,GAAG;YAC9D,CAAC,CAAC,sCAAsC,SAAS,CAAC,KAAK,GAAG;QAC5D,CAAC,CAAC,EAAE,CAAC;IAGP,MAAM,YAAY,GAAG,YAAY;QAC/B,CAAC,CAAC,gDAAgD;QAClD,CAAC,CAAC,EAAE,CAAC;IAEP,IAAI,MAAM,EAAE,CAAC;QAEX,OAAO,GAAG,YAAY,GAAG,OAAO;;QAE5B,SAAS,CAAC,KAAK,eAAe,cAAc;;;;;;;;;iBASnC,SAAS,CAAC,KAAK;CAC/B,CAAC;IACA,CAAC;SAAM,CAAC;QAEN,OAAO,GAAG,YAAY,GAAG,OAAO;;QAE5B,SAAS,CAAC,KAAK,eAAe,cAAc;;;;;;;;;;;;;iBAanC,SAAS,CAAC,KAAK;CAC/B,CAAC;IACA,CAAC;AACH,CAAC","sourcesContent":["import { getUserFileExtension } from \"../../../../helpers/fs.helpers\";\nimport { TemplateOptions } from \"../../template-generators\";\n\nexport function generateQueryOptionsTemplate(options: TemplateOptions): string {\n const { modelName } = options;\n const isAuth = modelName?.camel === \"auth\";\n const ext = getUserFileExtension();\n const isTypeScript = ext === \"ts\";\n\n if (!modelName)\n throw new Error(\"Model name is required for query config template\");\n\n // Generate imports\n const imports = isAuth\n ? `import { AuthPrismaQueryOptions } from 'arkos/prisma'`\n : `import { PrismaQueryOptions } from 'arkos/prisma'`;\n\n // Generate type annotation for TypeScript\n const typeAnnotation = isTypeScript\n ? isAuth\n ? `: AuthPrismaQueryOptions<typeof prisma.${modelName.camel}>`\n : `: PrismaQueryOptions<typeof prisma.${modelName.camel}>`\n : \"\";\n\n // Generate prisma import if TypeScript\n const prismaImport = isTypeScript\n ? `import { prisma } from \"../../utils/prisma\";\\n`\n : \"\";\n\n if (isAuth) {\n // Auth template\n return `${prismaImport}${imports};\n\nconst ${modelName.camel}QueryOptions${typeAnnotation} = {\n getMe: {},\n updateMe: {},\n deleteMe: {},\n login: {},\n signup: {},\n updatePassword: {},\n}\n\nexport default ${modelName.camel}QueryOptions;\n`;\n } else {\n // Regular template\n return `${prismaImport}${imports};\n\nconst ${modelName.camel}QueryOptions${typeAnnotation} = {\n // for all queries\n queryOptions: {},\n findOne: {},\n findMany: {},\n deleteMany: {},\n updateMany: {},\n createMany: {},\n createOne: {},\n updateOne: {},\n deleteOne: {},\n}\n\nexport default ${modelName.camel}QueryOptions;\n`;\n }\n}\n"]}
1
+ {"version":3,"file":"generate-prisma-query-options.js","sourceRoot":"","sources":["../../../../../../../src/utils/cli/utils/template-generator/templates/generate-prisma-query-options.ts"],"names":[],"mappings":";;AAGA,oEAmEC;AAtED,+DAAsE;AAGtE,SAAgB,4BAA4B,CAAC,OAAwB;IACnE,MAAM,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC;IAC9B,MAAM,MAAM,GAAG,SAAS,EAAE,KAAK,KAAK,MAAM,CAAC;IAC3C,MAAM,GAAG,GAAG,IAAA,iCAAoB,GAAE,CAAC;IACnC,MAAM,YAAY,GAAG,GAAG,KAAK,IAAI,CAAC;IAElC,IAAI,CAAC,SAAS;QACZ,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAC;IAGtE,MAAM,OAAO,GAAG,MAAM;QACpB,CAAC,CAAC,uDAAuD;QACzD,CAAC,CAAC,mDAAmD,CAAC;IAGxD,MAAM,cAAc,GAAG,YAAY;QACjC,CAAC,CAAC,MAAM;YACN,CAAC,CAAC,0CAA0C,SAAS,CAAC,KAAK,GAAG;YAC9D,CAAC,CAAC,sCAAsC,SAAS,CAAC,KAAK,GAAG;QAC5D,CAAC,CAAC,EAAE,CAAC;IAGP,MAAM,YAAY,GAAG,YAAY;QAC/B,CAAC,CAAC,gDAAgD;QAClD,CAAC,CAAC,EAAE,CAAC;IAEP,IAAI,MAAM,EAAE,CAAC;QAEX,OAAO,GAAG,YAAY,GAAG,OAAO;;QAE5B,SAAS,CAAC,KAAK,eAAe,cAAc;;;;;;;;;iBASnC,SAAS,CAAC,KAAK;CAC/B,CAAC;IACA,CAAC;SAAM,CAAC;QAEN,OAAO,GAAG,YAAY,GAAG,OAAO;;QAE5B,SAAS,CAAC,KAAK,eAAe,cAAc;;;;;;;;;;;;;;;;;;;iBAmBnC,SAAS,CAAC,KAAK;CAC/B,CAAC;IACA,CAAC;AACH,CAAC","sourcesContent":["import { getUserFileExtension } from \"../../../../helpers/fs.helpers\";\nimport { TemplateOptions } from \"../../template-generators\";\n\nexport function generateQueryOptionsTemplate(options: TemplateOptions): string {\n const { modelName } = options;\n const isAuth = modelName?.camel === \"auth\";\n const ext = getUserFileExtension();\n const isTypeScript = ext === \"ts\";\n\n if (!modelName)\n throw new Error(\"Model name is required for query config template\");\n\n // Generate imports\n const imports = isAuth\n ? `import { AuthPrismaQueryOptions } from 'arkos/prisma'`\n : `import { PrismaQueryOptions } from 'arkos/prisma'`;\n\n // Generate type annotation for TypeScript\n const typeAnnotation = isTypeScript\n ? isAuth\n ? `: AuthPrismaQueryOptions<typeof prisma.${modelName.camel}>`\n : `: PrismaQueryOptions<typeof prisma.${modelName.camel}>`\n : \"\";\n\n // Generate prisma import if TypeScript\n const prismaImport = isTypeScript\n ? `import { prisma } from \"../../utils/prisma\";\\n`\n : \"\";\n\n if (isAuth) {\n // Auth template\n return `${prismaImport}${imports};\n\nconst ${modelName.camel}QueryOptions${typeAnnotation} = {\n getMe: {},\n updateMe: {},\n deleteMe: {},\n login: {},\n signup: {},\n updatePassword: {},\n}\n\nexport default ${modelName.camel}QueryOptions;\n`;\n } else {\n // Regular template\n return `${prismaImport}${imports};\n\nconst ${modelName.camel}QueryOptions${typeAnnotation} = {\n global: {},\n find: {},\n findOne: {},\n findMany: {},\n udpate: {},\n updateMany: {},\n updateOne: {},\n create: {},\n createMany: {},\n createOne: {},\n save: {},\n saveMany: {},\n saveOne: {},\n delete: {},\n deleteMany: {},\n deleteOne: {},\n}\n\nexport default ${modelName.camel}QueryOptions;\n`;\n }\n}\n"]}
@@ -12,6 +12,8 @@ function generateRouterTemplate(options) {
12
12
  throw new Error("Model name is required for router template");
13
13
  const ext = (0, fs_helpers_1.getUserFileExtension)();
14
14
  const controllerPath = imports?.controller || `./${modelName.kebab}.controller.${ext}`;
15
+ const routerConfigTsType = ext === "ts" ? ": RouterConfig" : "";
16
+ const routerConfigTsTypeImport = ext === "ts" ? "import { RouterConfig } from 'arkos'" : "";
15
17
  const controllerExists = (0, fs_helpers_1.checkFileExists)(controllerPath);
16
18
  const controllerImportLine = controllerExists
17
19
  ? `import ${modelName.camel}Controller from "${imports?.controller || `./${modelName.kebab}.controller`}"`
@@ -22,6 +24,9 @@ function generateRouterTemplate(options) {
22
24
  return `import { Router } from 'express'
23
25
  import { authService } from 'arkos/services'
24
26
  ${controllerImportLine}
27
+ ${routerConfigTsTypeImport}
28
+
29
+ export const config${routerConfigTsType} = { }
25
30
 
26
31
  const ${modelName.camel}Router = Router()
27
32
 
@@ -1 +1 @@
1
- {"version":3,"file":"generate-router-template.js","sourceRoot":"","sources":["../../../../../../../src/utils/cli/utils/template-generator/templates/generate-router-template.ts"],"names":[],"mappings":";;;;;AAOA,wDAyCC;AAhDD,0DAAkC;AAClC,+DAGwC;AAGxC,SAAgB,sBAAsB,CAAC,OAAwB;IAC7D,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;IAEvC,IAAI,CAAC,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;IAG9E,MAAM,GAAG,GAAG,IAAA,iCAAoB,GAAE,CAAC;IACnC,MAAM,cAAc,GAClB,OAAO,EAAE,UAAU,IAAI,KAAK,SAAS,CAAC,KAAK,eAAe,GAAG,EAAE,CAAC;IAElE,MAAM,gBAAgB,GAAG,IAAA,4BAAe,EAAC,cAAc,CAAC,CAAC;IAEzD,MAAM,oBAAoB,GAAG,gBAAgB;QAC3C,CAAC,CAAC,UAAU,SAAS,CAAC,KAAK,oBACvB,OAAO,EAAE,UAAU,IAAI,KAAK,SAAS,CAAC,KAAK,aAC7C,GAAG;QACL,CAAC,CAAC,aAAa,SAAS,CAAC,KAAK,oBAC1B,OAAO,EAAE,UAAU,IAAI,KAAK,SAAS,CAAC,KAAK,aAC7C,GAAG,CAAC;IAER,MAAM,qBAAqB,GAAG,gBAAgB;QAC5C,CAAC,CAAC,KAAK,SAAS,CAAC,KAAK,wBAAwB;QAC9C,CAAC,CAAC,QAAQ,SAAS,CAAC,KAAK,wBAAwB,CAAC;IAEpD,OAAO;;EAEP,oBAAoB;;QAEd,SAAS,CAAC,KAAK;;EAErB,SAAS,CAAC,KAAK;4CAC2B,IAAA,mBAAS,EACjD,SAAS,CAAC,KAAK,CAChB;;qDAEkD,SAAS,CAAC,KAAK;EAClE,qBAAqB;;;iBAGN,SAAS,CAAC,KAAK;CAC/B,CAAC;AACF,CAAC","sourcesContent":["import pluralize from \"pluralize\";\nimport {\n checkFileExists,\n getUserFileExtension,\n} from \"../../../../helpers/fs.helpers\";\nimport { TemplateOptions } from \"../../template-generators\";\n\nexport function generateRouterTemplate(options: TemplateOptions): string {\n const { modelName, imports } = options;\n\n if (!modelName) throw new Error(\"Model name is required for router template\");\n\n // Check if controller file exists\n const ext = getUserFileExtension();\n const controllerPath =\n imports?.controller || `./${modelName.kebab}.controller.${ext}`;\n\n const controllerExists = checkFileExists(controllerPath);\n\n const controllerImportLine = controllerExists\n ? `import ${modelName.camel}Controller from \"${\n imports?.controller || `./${modelName.kebab}.controller`\n }\"`\n : `// import ${modelName.camel}Controller from \"${\n imports?.controller || `./${modelName.kebab}.controller`\n }\"`;\n\n const controllerHandlerLine = controllerExists\n ? ` ${modelName.camel}Controller.someHandler`\n : ` // ${modelName.camel}Controller.someHandler`;\n\n return `import { Router } from 'express'\nimport { authService } from 'arkos/services'\n${controllerImportLine}\n\nconst ${modelName.camel}Router = Router()\n\n${modelName.camel}Router.post(\n '/custom-endpoint', // resolves to /api/${pluralize(\n modelName.kebab\n )}/custom-endpoint\n authService.authenticate,\n authService.handleAccessControl('CustomAction', '${modelName.kebab}'),\n${controllerHandlerLine}\n)\n\nexport default ${modelName.camel}Router\n`;\n}\n"]}
1
+ {"version":3,"file":"generate-router-template.js","sourceRoot":"","sources":["../../../../../../../src/utils/cli/utils/template-generator/templates/generate-router-template.ts"],"names":[],"mappings":";;;;;AAOA,wDAgDC;AAvDD,0DAAkC;AAClC,+DAGwC;AAGxC,SAAgB,sBAAsB,CAAC,OAAwB;IAC7D,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;IAEvC,IAAI,CAAC,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;IAG9E,MAAM,GAAG,GAAG,IAAA,iCAAoB,GAAE,CAAC;IACnC,MAAM,cAAc,GAClB,OAAO,EAAE,UAAU,IAAI,KAAK,SAAS,CAAC,KAAK,eAAe,GAAG,EAAE,CAAC;IAElE,MAAM,kBAAkB,GAAG,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC,EAAE,CAAC;IAChE,MAAM,wBAAwB,GAC5B,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,sCAAsC,CAAC,CAAC,CAAC,EAAE,CAAC;IAE7D,MAAM,gBAAgB,GAAG,IAAA,4BAAe,EAAC,cAAc,CAAC,CAAC;IAEzD,MAAM,oBAAoB,GAAG,gBAAgB;QAC3C,CAAC,CAAC,UAAU,SAAS,CAAC,KAAK,oBACvB,OAAO,EAAE,UAAU,IAAI,KAAK,SAAS,CAAC,KAAK,aAC7C,GAAG;QACL,CAAC,CAAC,aAAa,SAAS,CAAC,KAAK,oBAC1B,OAAO,EAAE,UAAU,IAAI,KAAK,SAAS,CAAC,KAAK,aAC7C,GAAG,CAAC;IAER,MAAM,qBAAqB,GAAG,gBAAgB;QAC5C,CAAC,CAAC,KAAK,SAAS,CAAC,KAAK,wBAAwB;QAC9C,CAAC,CAAC,QAAQ,SAAS,CAAC,KAAK,wBAAwB,CAAC;IAEpD,OAAO;;EAEP,oBAAoB;EACpB,wBAAwB;;qBAEL,kBAAkB;;QAE/B,SAAS,CAAC,KAAK;;EAErB,SAAS,CAAC,KAAK;4CAC2B,IAAA,mBAAS,EACjD,SAAS,CAAC,KAAK,CAChB;;qDAEkD,SAAS,CAAC,KAAK;EAClE,qBAAqB;;;iBAGN,SAAS,CAAC,KAAK;CAC/B,CAAC;AACF,CAAC","sourcesContent":["import pluralize from \"pluralize\";\nimport {\n checkFileExists,\n getUserFileExtension,\n} from \"../../../../helpers/fs.helpers\";\nimport { TemplateOptions } from \"../../template-generators\";\n\nexport function generateRouterTemplate(options: TemplateOptions): string {\n const { modelName, imports } = options;\n\n if (!modelName) throw new Error(\"Model name is required for router template\");\n\n // Check if controller file exists\n const ext = getUserFileExtension();\n const controllerPath =\n imports?.controller || `./${modelName.kebab}.controller.${ext}`;\n\n const routerConfigTsType = ext === \"ts\" ? \": RouterConfig\" : \"\";\n const routerConfigTsTypeImport =\n ext === \"ts\" ? \"import { RouterConfig } from 'arkos'\" : \"\";\n\n const controllerExists = checkFileExists(controllerPath);\n\n const controllerImportLine = controllerExists\n ? `import ${modelName.camel}Controller from \"${\n imports?.controller || `./${modelName.kebab}.controller`\n }\"`\n : `// import ${modelName.camel}Controller from \"${\n imports?.controller || `./${modelName.kebab}.controller`\n }\"`;\n\n const controllerHandlerLine = controllerExists\n ? ` ${modelName.camel}Controller.someHandler`\n : ` // ${modelName.camel}Controller.someHandler`;\n\n return `import { Router } from 'express'\nimport { authService } from 'arkos/services'\n${controllerImportLine}\n${routerConfigTsTypeImport}\n\nexport const config${routerConfigTsType} = { }\n\nconst ${modelName.camel}Router = Router()\n\n${modelName.camel}Router.post(\n '/custom-endpoint', // resolves to /api/${pluralize(\n modelName.kebab\n )}/custom-endpoint\n authService.authenticate,\n authService.handleAccessControl('CustomAction', '${modelName.kebab}'),\n${controllerHandlerLine}\n)\n\nexport default ${modelName.camel}Router\n`;\n}\n"]}
package/dist/esm/app.js CHANGED
@@ -1 +1 @@
1
- "use strict";import c from"express";import p from"cors";import m from"cookie-parser";import{getAuthRouter as f}from"./modules/auth/auth.router.js";import{getPrismaModelsRouter as w,getAvailableResourcesAndRoutesRouter as R}from"./modules/base/base.router.js";import h from"./modules/error-handler/error-handler.controller.js";import{rateLimit as P}from"express-rate-limit";import y from"compression";import{handleRequestLogs as b}from"./modules/base/base.middlewares.js";import{checkDatabaseConnection as q,loadPrismaModule as A}from"./utils/helpers/prisma.helpers.js";import{getFileUploadRouter as O}from"./modules/file-upload/file-upload.router.js";import{queryParser as g}from"./utils/helpers/query-parser.helpers.js";import d from"./utils/helpers/deepmerge.helper.js";import{getSwaggerRouter as E}from"./modules/swagger/swagger.router.js";export const app=c();export async function bootstrap(e){await A(),e?.configureApp&&await e.configureApp(app);const n=e?.middlewares,t=n?.disable||[],a=n?.replace||{};t?.includes?.("compression")||app.use(a.compression||y(e?.compressionOptions)),t?.includes?.("global-rate-limit")||app.use(a.globalRateLimit||P(d({windowMs:60*1e3,limit:500,standardHeaders:"draft-7",legacyHeaders:!1,handler:(r,s)=>{s.status(429).json({message:"Too many requests, please try again later"})}},e?.globalRequestRateLimitOptions||{}))),t?.includes?.("cors")||app.use(a.cors||p(e?.cors?.customHandler?e.cors.customHandler:d({origin:(r,s)=>{const i=e?.cors?.allowedOrigins;i==="*"?s(null,!0):Array.isArray(i)?s(null,!r||i?.includes?.(r)):typeof i=="string"?s(null,!r||i===r):s(null,!1)},methods:["GET","POST","PUT","DELETE","PATCH","OPTIONS"],allowedHeaders:["Content-Type","Authorization","Connection"],credentials:!0},e?.cors?.options||{}))),t?.includes?.("express-json")||app.use(a.expressJson||c.json(e?.jsonBodyParserOptions)),t?.includes?.("cookie-parser")||app.use(a.cookieParser||m(...e?.cookieParserParameters||[])),t?.includes?.("query-parser")||app.use(a.queryParser||g(d({parseNull:!0,parseUndefined:!0,parseBoolean:!0},e?.queryParserOptions||{}))),t?.includes?.("database-connection")||app.use(a.databaseConnection||q),t?.includes?.("request-logger")||app.use(a.requestLogger||b),e?.middlewares?.additional&&e.middlewares.additional.forEach(r=>{app.use(r)});const l=e?.routers,u=l?.disable||[],o=l?.replace||{};if(u?.includes?.("welcome-endpoint")||app.get("/api",o.welcomeEndpoint||((r,s)=>{s.status(200).json({message:e.welcomeMessage})})),!u?.includes?.("file-upload")){const r=o.fileUpload?await o.fileUpload(e):await O(e);app.use(r)}if(!u?.includes?.("auth-router")&&e.authentication){const r=o.authRouter?await o.authRouter(e):await f(e);app.use("/api",r)}if(!u?.includes?.("prisma-models-router")){const r=o.prismaModelsRouter?await o.prismaModelsRouter(e):await w(e);app.use("/api",r)}return app.use("/api",R()),e.swagger&&(process.env.ARKOS_BUILD!=="true"||e.swagger.enableAfterBuild===!0)&&app.use("/api",await E(e)),l?.additional&&l.additional.forEach(r=>{app.use(r)}),t?.includes?.("global-error-handler")||app.use(a.globalErrorHandler||h),app.use("*",(r,s)=>{s.status(404).json({message:"Route not found!"})}),app}
1
+ "use strict";import c from"express";import p from"cors";import m from"cookie-parser";import{getAuthRouter as f}from"./modules/auth/auth.router";import{getPrismaModelsRouter as w,getAvailableResourcesAndRoutesRouter as R}from"./modules/base/base.router";import h from"./modules/error-handler/error-handler.controller";import{rateLimit as P}from"express-rate-limit";import y from"compression";import{handleRequestLogs as b}from"./modules/base/base.middlewares";import{checkDatabaseConnection as q,loadPrismaModule as A}from"./utils/helpers/prisma.helpers";import{getFileUploadRouter as O}from"./modules/file-upload/file-upload.router";import{queryParser as g}from"./utils/helpers/query-parser.helpers";import d from"./utils/helpers/deepmerge.helper";import{getSwaggerRouter as E}from"./modules/swagger/swagger.router";export const app=c();export async function bootstrap(e){await A(),e?.configureApp&&await e.configureApp(app);const n=e?.middlewares,t=n?.disable||[],a=n?.replace||{};t?.includes?.("compression")||app.use(a.compression||y(e?.compressionOptions)),t?.includes?.("global-rate-limit")||app.use(a.globalRateLimit||P(d({windowMs:60*1e3,limit:500,standardHeaders:"draft-7",legacyHeaders:!1,handler:(r,s)=>{s.status(429).json({message:"Too many requests, please try again later"})}},e?.globalRequestRateLimitOptions||{}))),t?.includes?.("cors")||app.use(a.cors||p(e?.cors?.customHandler?e.cors.customHandler:d({origin:(r,s)=>{const i=e?.cors?.allowedOrigins;i==="*"?s(null,!0):Array.isArray(i)?s(null,!r||i?.includes?.(r)):typeof i=="string"?s(null,!r||i===r):s(null,!1)},methods:["GET","POST","PUT","DELETE","PATCH","OPTIONS"],allowedHeaders:["Content-Type","Authorization","Connection"],credentials:!0},e?.cors?.options||{}))),t?.includes?.("express-json")||app.use(a.expressJson||c.json(e?.jsonBodyParserOptions)),t?.includes?.("cookie-parser")||app.use(a.cookieParser||m(...e?.cookieParserParameters||[])),t?.includes?.("query-parser")||app.use(a.queryParser||g(d({parseNull:!0,parseUndefined:!0,parseBoolean:!0},e?.queryParserOptions||{}))),t?.includes?.("database-connection")||app.use(a.databaseConnection||q),t?.includes?.("request-logger")||app.use(a.requestLogger||b),e?.middlewares?.additional&&e.middlewares.additional.forEach(r=>{app.use(r)});const l=e?.routers,u=l?.disable||[],o=l?.replace||{};if(u?.includes?.("welcome-endpoint")||app.get("/api",o.welcomeEndpoint||((r,s)=>{s.status(200).json({message:e.welcomeMessage})})),!u?.includes?.("file-upload")){const r=o.fileUpload?await o.fileUpload(e):await O(e);app.use(r)}if(!u?.includes?.("auth-router")&&e.authentication){const r=o.authRouter?await o.authRouter(e):await f(e);app.use("/api",r)}if(!u?.includes?.("prisma-models-router")){const r=o.prismaModelsRouter?await o.prismaModelsRouter(e):await w(e);app.use("/api",r)}return app.use("/api",R()),e.swagger&&(process.env.ARKOS_BUILD!=="true"||e.swagger.enableAfterBuild===!0)&&app.use("/api",await E(e)),l?.additional&&l.additional.forEach(r=>{app.use(r)}),t?.includes?.("global-error-handler")||app.use(a.globalErrorHandler||h),app.use("*",(r,s)=>{s.status(404).json({message:"Route not found!"})}),app}
@@ -1,2 +1,2 @@
1
- export { defaultExcludedUserFields } from "./../../modules/auth/auth.controller.js";
1
+ export { defaultExcludedUserFields } from "./../../modules/auth/auth.controller";
2
2
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,4 @@
1
- import { BaseController } from "./../../modules/base/base.controller.js";
2
- import fileUploadController from "../../modules/file-upload/file-upload.controller.js";
1
+ import { BaseController } from "./../../modules/base/base.controller";
2
+ import fileUploadController from "../../modules/file-upload/file-upload.controller";
3
3
  export { fileUploadController, BaseController };
4
4
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,4 @@
1
- import catchAsync from "../../modules/error-handler/utils/catch-async.js";
2
- import AppError from "../../modules/error-handler/utils/app-error.js";
1
+ import catchAsync from "../../modules/error-handler/utils/catch-async";
2
+ import AppError from "../../modules/error-handler/utils/app-error";
3
3
  export { catchAsync, AppError };
4
4
  //# sourceMappingURL=index.js.map
@@ -1,5 +1,5 @@
1
- import { BaseController } from "./../modules/base/base.controller.js";
2
- import { initApp, getArkosConfig } from "../server.js";
1
+ import { BaseController } from "./../modules/base/base.controller";
2
+ import { initApp, getArkosConfig } from "../server";
3
3
  const arkos = {
4
4
  init: initApp,
5
5
  };
@@ -1,2 +1,2 @@
1
- export { addPrismaQueryOptionsToRequest, handleRequestBodyValidationAndTransformation, } from "../../modules/base/base.middlewares.js";
1
+ export { addPrismaQueryOptionsToRequest, handleRequestBodyValidationAndTransformation, } from "../../modules/base/base.middlewares";
2
2
  //# sourceMappingURL=index.js.map
@@ -1,3 +1,3 @@
1
- import { getModels } from "../../utils/helpers/models.helpers.js";
1
+ import { getModels } from "../../utils/helpers/models.helpers";
2
2
  export { getModels as getPrismaModels, };
3
3
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
- import { getFileUploadServices, FileUploadService, } from "../../modules/file-upload/file-upload.service.js";
2
- import authService, { AuthService } from "../../modules/auth/auth.service.js";
3
- import emailService, { EmailService } from "../../modules/email/email.service.js";
4
- import { BaseService, getBaseServices } from "../../modules/base/base.service.js";
1
+ import { getFileUploadServices, FileUploadService, } from "../../modules/file-upload/file-upload.service";
2
+ import authService, { AuthService } from "../../modules/auth/auth.service";
3
+ import emailService, { EmailService } from "../../modules/email/email.service";
4
+ import { BaseService, getBaseServices } from "../../modules/base/base.service";
5
5
  export { authService, AuthService };
6
6
  export { BaseService, getBaseServices };
7
7
  export { emailService, EmailService };
@@ -1,4 +1,4 @@
1
- export * from "../../utils/helpers/change-case.helpers.js";
2
- import APIFeatures, { apiFeatures } from "../../utils/features/api.features.js";
1
+ export * from "../../utils/helpers/change-case.helpers";
2
+ import APIFeatures, { apiFeatures } from "../../utils/features/api.features";
3
3
  export { APIFeatures, apiFeatures };
4
4
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,4 @@
1
- import validateDto from "../../utils/validate-dto.js";
2
- import validateSchema from "../../utils/validate-schema.js";
1
+ import validateDto from "../../utils/validate-dto";
2
+ import validateSchema from "../../utils/validate-schema";
3
3
  export { validateDto, validateSchema };
4
4
  //# sourceMappingURL=index.js.map
@@ -1,10 +1,10 @@
1
- import catchAsync from "../error-handler/utils/catch-async.js";
2
- import AppError from "../error-handler/utils/app-error.js";
3
- import authService from "./auth.service.js";
4
- import { getBaseServices } from "../base/base.service.js";
5
- import arkosEnv from "../../utils/arkos-env.js";
6
- import { getArkosConfig } from "../../server.js";
7
- import { createPrismaWhereClause, determineUsernameField, getNestedValue, toMs, } from "./utils/helpers/auth.controller.helpers.js";
1
+ import catchAsync from "../error-handler/utils/catch-async";
2
+ import AppError from "../error-handler/utils/app-error";
3
+ import authService from "./auth.service";
4
+ import { getBaseServices } from "../base/base.service";
5
+ import arkosEnv from "../../utils/arkos-env";
6
+ import { getArkosConfig } from "../../server";
7
+ import { createPrismaWhereClause, determineUsernameField, getNestedValue, toMs, } from "./utils/helpers/auth.controller.helpers";
8
8
  export const defaultExcludedUserFields = {
9
9
  password: false,
10
10
  };