arkos 1.3.8-canary.9 → 1.3.9-canary.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (24) hide show
  1. package/cli.js +2 -5
  2. package/dist/cjs/modules/auth/auth.controller.js +7 -7
  3. package/dist/cjs/modules/auth/auth.controller.js.map +1 -1
  4. package/dist/cjs/modules/error-handler/error-handler.controller.js +1 -2
  5. package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
  6. package/dist/cjs/modules/swagger/swagger.router.js.map +1 -1
  7. package/dist/cjs/modules/swagger/utils/helpers/missing-json-schemas-generator.js +2 -4
  8. package/dist/cjs/modules/swagger/utils/helpers/missing-json-schemas-generator.js.map +1 -1
  9. package/dist/cjs/modules/swagger/utils/helpers/swagger.router.helpers.js.map +1 -1
  10. package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
  11. package/dist/cjs/utils/prisma/prisma-json-schema-generator.js +1 -12
  12. package/dist/cjs/utils/prisma/prisma-json-schema-generator.js.map +1 -1
  13. package/dist/esm/modules/auth/auth.controller.js +7 -7
  14. package/dist/esm/modules/auth/auth.controller.js.map +1 -1
  15. package/dist/esm/modules/error-handler/error-handler.controller.js +1 -2
  16. package/dist/esm/modules/error-handler/error-handler.controller.js.map +1 -1
  17. package/dist/esm/modules/swagger/swagger.router.js.map +1 -1
  18. package/dist/esm/modules/swagger/utils/helpers/missing-json-schemas-generator.js +2 -4
  19. package/dist/esm/modules/swagger/utils/helpers/missing-json-schemas-generator.js.map +1 -1
  20. package/dist/esm/modules/swagger/utils/helpers/swagger.router.helpers.js.map +1 -1
  21. package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
  22. package/dist/esm/utils/prisma/prisma-json-schema-generator.js +1 -12
  23. package/dist/esm/utils/prisma/prisma-json-schema-generator.js.map +1 -1
  24. package/package.json +1 -1
package/cli.js CHANGED
@@ -16,11 +16,8 @@
16
16
  console.error("Error checking package.json:", err);
17
17
  }
18
18
 
19
- if (useEsm) {
20
- await import("./dist/esm/utils/cli/index.js");
21
- } else {
22
- await import("./dist/cjs/utils/cli/index.js");
23
- }
19
+ if (useEsm) await import("./dist/esm/utils/cli/index.js");
20
+ else await import("./dist/cjs/utils/cli/index.js");
24
21
  } catch (err) {
25
22
  console.error("Failed to load CLI:", err);
26
23
  process.exit(1);
@@ -76,7 +76,7 @@ const authControllerFactory = async (interceptors = {}) => {
76
76
  const usernameValue = req.body[lastField];
77
77
  const { password } = req.body;
78
78
  if (!usernameValue || !password)
79
- return next(new app_error_1.default(`Please provide both ${lastField} and password`, 400));
79
+ return next(new app_error_1.default(`Please provide both ${lastField} and password`, 400, `MissingCredentialFields`));
80
80
  let whereClause;
81
81
  if (usernameField?.includes?.(".")) {
82
82
  const valueToFind = (0, auth_controller_helpers_1.getNestedValue)(req.body, usernameField);
@@ -91,7 +91,7 @@ const authControllerFactory = async (interceptors = {}) => {
91
91
  const user = (await userService.findOne(whereClause, req.prismaQueryOptions || {}));
92
92
  if (!user ||
93
93
  !(await auth_service_1.default.isCorrectPassword(password, user.password))) {
94
- return next(new app_error_1.default(`Incorrect ${lastField} or password`, 401));
94
+ return next(new app_error_1.default(`Incorrect ${lastField} or password`, 401, `IncorrectCredentials`));
95
95
  }
96
96
  const token = auth_service_1.default.signJwtToken(user.id);
97
97
  const cookieOptions = auth_service_1.default.getJwtCookieOptions(req);
@@ -165,7 +165,7 @@ const authControllerFactory = async (interceptors = {}) => {
165
165
  updatePassword: (0, catch_async_1.default)(async (req, res, next) => {
166
166
  const { currentPassword, newPassword } = req.body;
167
167
  if (!currentPassword || !newPassword)
168
- return next(new app_error_1.default("currentPassword and newPassword are required", 400));
168
+ return next(new app_error_1.default("currentPassword and newPassword are required", 400, "SameCurrentAndNewPassword"));
169
169
  const user = req.user;
170
170
  if (!user || user?.isActive === false || user?.deletedSelfAccountAt)
171
171
  return next(new app_error_1.default("User not found!", 404));
@@ -173,11 +173,11 @@ const authControllerFactory = async (interceptors = {}) => {
173
173
  const configs = (0, server_1.getArkosConfig)();
174
174
  const initAuthConfigs = configs?.authentication;
175
175
  if (!isPasswordCorrect)
176
- return next(new app_error_1.default("Current password is incorrect.", 400));
176
+ return next(new app_error_1.default("Current password is incorrect", 400, "IncorrentCurrentPassword"));
177
177
  if (!auth_service_1.default.isPasswordStrong(String(newPassword)) &&
178
178
  !configs?.validation) {
179
179
  return next(new app_error_1.default(initAuthConfigs?.passwordValidation?.message ||
180
- "The new password must contain at least one uppercase letter, one lowercase letter, and one number", 400));
180
+ "The new password must contain at least one uppercase letter, one lowercase letter, and one number", 400, "PasswordDoesNotMeetRequirements"));
181
181
  }
182
182
  await userService.updateOne({ id: user.id }, {
183
183
  password: await auth_service_1.default.hashPassword(newPassword),
@@ -216,7 +216,7 @@ const authControllerFactory = async (interceptors = {}) => {
216
216
  const arkosConfig = (0, server_1.getArkosConfig)();
217
217
  const resourceName = req.params?.resourceName;
218
218
  if (!resourceName)
219
- throw new app_error_1.default(`Please provide a resoureName`, 400);
219
+ throw new app_error_1.default(`Please provide a resoureName`, 400, "MissiongResourseName");
220
220
  const authActions = auth_action_service_1.default
221
221
  .getByResource(req.params?.resourceName)
222
222
  ?.map((authAction) => {
@@ -225,7 +225,7 @@ const authControllerFactory = async (interceptors = {}) => {
225
225
  return authAction;
226
226
  });
227
227
  if (!authActions)
228
- throw new app_error_1.default(`No auth action with resource name ${resourceName}`, 404);
228
+ throw new app_error_1.default(`No auth action with resource name ${resourceName}`, 404, "AuthActionNotFound");
229
229
  res.json({
230
230
  total: authActions.length,
231
231
  results: authActions.length,
@@ -1 +1 @@
1
- {"version":3,"file":"auth.controller.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.controller.ts"],"names":[],"mappings":";;;;;;AAAA,qFAA4D;AAC5D,iFAAwD;AAExD,kEAAyC;AACzC,uDAAmD;AAEnD,yCAA8C;AAC9C,qFAIiD;AACjD,+FAAqE;AAKxD,QAAA,yBAAyB,GAAG;IACvC,QAAQ,EAAE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CAAC,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC;gBACxC,EAAE,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE;gBACnB,IAAI,WAAW,EAAE,cAAc,EAAE,IAAI,KAAK,SAAS;oBACjD,OAAQ,UAAkB,EAAE,KAAK,CAAC;gBACpC,OAAO,UAAU,CAAC;YACpB,CAAC,CAAC,CAAC;YAEL,IAAI,CAAC,WAAW;gBACd,MAAM,IAAI,mBAAQ,CAChB,qCAAqC,YAAY,EAAE,EACnD,GAAG,CACJ,CAAC;YAEJ,GAAG,CAAC,IAAI,CAAC;gBACP,KAAK,EAAE,WAAW,CAAC,MAAM;gBACzB,OAAO,EAAE,WAAW,CAAC,MAAM;gBAC3B,IAAI,EAAE,WAAW;aAClB,CAAC,CAAC;QACL,CAAC,CACF;KACF,CAAC;AACJ,CAAC,CAAC;AA9YW,QAAA,qBAAqB,yBA8YhC","sourcesContent":["import catchAsync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { ArkosRequest, ArkosResponse, ArkosNextFunction } from \"../../types\";\nimport authService from \"./auth.service\";\nimport { BaseService } from \"../base/base.service\";\nimport { User } from \"../../types\";\nimport { getArkosConfig } from \"../../server\";\nimport {\n createPrismaWhereClause,\n determineUsernameField,\n getNestedValue,\n} from \"./utils/helpers/auth.controller.helpers\";\nimport authActionService from \"./utils/services/auth-action.service\";\n\n/**\n * Default fields to exclude from user object when returning to client\n */\nexport const defaultExcludedUserFields = {\n password: false,\n};\n\n/**\n * Factory function to create authentication controller with configurable interceptors\n *\n * @param interceptors - Optional middleware functions to execute after controller actions\n * @returns An object containing all authentication controller methods\n */\nexport const authControllerFactory = async (interceptors: any = {}) => {\n const userService = new BaseService(\"user\");\n\n return {\n /**\n * Retrieves the current authenticated user's information\n */\n getMe: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const user = (await userService.findOne(\n { id: req.user!.id },\n req.prismaQueryOptions || {}\n )) as Record<string, any>;\n\n Object.keys(defaultExcludedUserFields).forEach((key) => {\n if (user) delete user[key as keyof User];\n });\n\n if (interceptors?.afterGetMe) {\n (res as any).originalData = { data: user };\n req.responseData = { data: user };\n res.locals.data = { data: user };\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json({ data: user });\n }\n ),\n\n /**\n * Updates the current authenticated user's information\n */\n updateMe: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n if (\"password\" in req.body)\n throw new AppError(\n \"In order to update password use the update-password endpoint.\",\n 400,\n {},\n \"InvalidFieldPassword\"\n );\n\n const user = (await userService.updateOne(\n { id: req.user!.id },\n req.body,\n req.prismaQueryOptions || {}\n )) as Record<string, any>;\n\n Object.keys(defaultExcludedUserFields).forEach((key) => {\n if (user) delete user[key as keyof User];\n });\n\n if (interceptors?.afterUpdateMe) {\n (res as any).originalData = { data: user };\n req.responseData = { data: user };\n res.locals.data = { data: user };\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json({ data: user });\n }\n ),\n\n /**\n * Logs out the current user by invalidating their access token cookie\n */\n logout: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n res.cookie(\"arkos_access_token\", \"no-token\", {\n expires: new Date(Date.now() + 10 * 1000),\n httpOnly: true,\n });\n\n if (interceptors?.afterLogout) {\n (res as any).originalData = null;\n req.responseData = null;\n res.locals.data = null;\n (res as any).originalStatus = 204;\n req.responseStatus = 204;\n res.locals.status = 204;\n return next();\n }\n\n res.status(204).json();\n }\n ),\n\n /**\n * Authenticates a user using configurable username field and password\n * Username field can be specified in query parameter or config\n *\n * Supports nested fields and array queries (e.g., \"profile.nickname\", \"phones.some.number\")\n */\n login: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const authConfigs = getArkosConfig()?.authentication;\n\n const usernameField = determineUsernameField(req);\n\n // For the error message, we only care about the top-level field name\n const lastField =\n usernameField.split(\".\")[usernameField.split(\".\").length - 1];\n\n const usernameValue = req.body[lastField];\n\n const { password } = req.body;\n\n if (!usernameValue || !password)\n return next(\n new AppError(`Please provide both ${lastField} and password`, 400)\n );\n\n let whereClause: Record<string, any>;\n\n if (usernameField?.includes?.(\".\")) {\n const valueToFind = getNestedValue(req.body, usernameField);\n if (valueToFind === undefined) {\n return next(new AppError(`Invalid ${usernameField} provided`, 400));\n }\n whereClause = createPrismaWhereClause(usernameField, valueToFind);\n } else {\n whereClause = { [usernameField]: usernameValue };\n }\n\n const user = (await userService.findOne(\n whereClause,\n req.prismaQueryOptions || {}\n )) as Record<string, any>;\n\n if (\n !user ||\n !(await authService.isCorrectPassword(password, user.password))\n ) {\n return next(new AppError(`Incorrect ${lastField} or password`, 401));\n }\n\n const token = authService.signJwtToken(user.id!);\n\n const cookieOptions = authService.getJwtCookieOptions(req);\n\n if (\n authConfigs?.login?.sendAccessTokenThrough === \"response-only\" ||\n authConfigs?.login?.sendAccessTokenThrough === \"both\" ||\n !authConfigs?.login?.sendAccessTokenThrough\n ) {\n req.responseData = { accessToken: token };\n res.locals.data = { accessToken: token };\n }\n\n if (\n authConfigs?.login?.sendAccessTokenThrough === \"cookie-only\" ||\n authConfigs?.login?.sendAccessTokenThrough === \"both\" ||\n !authConfigs?.login?.sendAccessTokenThrough\n )\n res.cookie(\"arkos_access_token\", token, cookieOptions);\n\n req.accessToken = token;\n\n if (interceptors?.afterLogin) {\n (res as any).originalData = req.responseData;\n req.additionalData = { user };\n res.locals.additional = { user };\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n if (\n authConfigs?.login?.sendAccessTokenThrough === \"response-only\" ||\n authConfigs?.login?.sendAccessTokenThrough === \"both\" ||\n !authConfigs?.login?.sendAccessTokenThrough\n ) {\n res.status(200).json(req.responseData);\n } else if (\n authConfigs?.login?.sendAccessTokenThrough === \"cookie-only\" ||\n authConfigs?.login?.sendAccessTokenThrough === \"both\" ||\n !authConfigs?.login?.sendAccessTokenThrough\n )\n res.status(200).send();\n }\n ),\n\n /**\n * Creates a new user account using the userService\n */\n signup: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const user = (await userService.createOne(\n req.body,\n req.prismaQueryOptions || {}\n )) as Record<string, any>;\n\n if (interceptors?.afterSignup) {\n (res as any).originalData = { data: user };\n req.responseData = { data: user };\n res.locals.data = { data: user };\n (res as any).originalStatus = 201;\n req.responseStatus = 201;\n res.locals.status = 201;\n return next();\n }\n\n Object.keys(defaultExcludedUserFields).forEach((key) => {\n delete user[key as keyof User];\n });\n\n res.status(201).json({ data: user });\n }\n ),\n /**\n * Marks user account as self-deleted by setting deletedSelfAccountAt timestamp\n */\n deleteMe: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const userId = req.user!.id;\n\n const updatedUser = (await userService.updateOne(\n { id: userId },\n {\n deletedSelfAccountAt: new Date().toISOString(),\n },\n req.prismaQueryOptions || {}\n )) as Record<string, any>;\n\n if (interceptors?.afterDeleteMe) {\n (res as any).originalData = { data: updatedUser };\n req.responseData = { data: updatedUser };\n res.locals.data = { data: updatedUser };\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n Object.keys(defaultExcludedUserFields).forEach((key) => {\n delete updatedUser[key as keyof User];\n });\n\n res.status(200).json({\n message: \"Account deleted successfully\",\n });\n }\n ),\n\n /**\n * Updates the password of the authenticated user\n */\n updatePassword: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const { currentPassword, newPassword } = req.body;\n\n if (!currentPassword || !newPassword)\n return next(\n new AppError(\"currentPassword and newPassword are required\", 400)\n );\n\n const user = req.user;\n\n if (!user || user?.isActive === false || user?.deletedSelfAccountAt)\n return next(new AppError(\"User not found!\", 404));\n\n // Check if the current password is correct\n const isPasswordCorrect = await authService.isCorrectPassword(\n String(currentPassword),\n String(user.password)\n );\n\n const configs = getArkosConfig();\n const initAuthConfigs = configs?.authentication;\n\n if (!isPasswordCorrect)\n return next(new AppError(\"Current password is incorrect.\", 400));\n\n // Check password strength (optional but recommended)\n if (\n !authService.isPasswordStrong(String(newPassword)) &&\n !configs?.validation\n ) {\n return next(\n new AppError(\n initAuthConfigs?.passwordValidation?.message ||\n \"The new password must contain at least one uppercase letter, one lowercase letter, and one number\",\n 400\n )\n );\n }\n\n // Update the password\n await userService.updateOne(\n { id: user.id },\n {\n password: await authService.hashPassword(newPassword),\n passwordChangedAt: new Date(Date.now()),\n }\n );\n\n const responseData = {\n status: \"success\",\n message: \"Password updated successfully!\",\n };\n\n if (interceptors?.afterUpdatePassword) {\n (res as any).originalData = responseData;\n req.additionalData = { user };\n req.responseData = responseData;\n res.locals.data = responseData;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(responseData);\n }\n ),\n\n findManyAuthAction: catchAsync(\n async (_: ArkosRequest, res: ArkosResponse) => {\n const arkosConfig = getArkosConfig();\n const authActions = authActionService.getAll()?.map((authAction) => {\n if (arkosConfig?.authentication?.mode === \"dynamic\")\n delete (authAction as any)?.roles;\n return authAction;\n });\n\n res.json({\n total: authActions.length,\n results: authActions.length,\n data: authActions,\n });\n }\n ),\n\n findOneAuthAction: catchAsync(\n async (req: ArkosRequest, res: ArkosResponse) => {\n const arkosConfig = getArkosConfig();\n const resourceName = req.params?.resourceName;\n\n if (!resourceName)\n throw new AppError(`Please provide a resoureName`, 400);\n\n const authActions = authActionService\n .getByResource(req.params?.resourceName)\n ?.map((authAction) => {\n if (arkosConfig?.authentication?.mode === \"dynamic\")\n delete (authAction as any)?.roles;\n return authAction;\n });\n\n if (!authActions)\n throw new AppError(\n `No auth action with resource name ${resourceName}`,\n 404\n );\n\n res.json({\n total: authActions.length,\n results: authActions.length,\n data: authActions,\n });\n }\n ),\n };\n};\n"]}
1
+ {"version":3,"file":"auth.controller.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.controller.ts"],"names":[],"mappings":";;;;;;AAAA,qFAA4D;AAC5D,iFAAwD;AAExD,kEAAyC;AACzC,uDAAmD;AAEnD,yCAA8C;AAC9C,qFAIiD;AACjD,+FAAqE;AAKxD,QAAA,yBAAyB,GAAG;IACvC,QAAQ,EAAE,KAAK;CAChB,CAAC;AAQK,MAAM,qBAAqB,GAAG,KAAK,EAAE,eAAoB,EAAE,EAAE,EAAE;IACpE,MAAM,WAAW,GAAG,IAAI,0BAAW,CAAC,MAAM,CAAC,CAAC;IAE5C,OAAO;QAIL,KAAK,EAAE,IAAA,qBAAU,EACf,KAAK,EACH,GAAiB,EACjB,GAAkB,EAClB,IAAuB,EACvB,EAAE;YACF,MAAM,IAAI,GAAG,CAAC,MAAM,WAAW,CAAC,OAAO,CACrC,EAAE,EAAE,EAAE,GAAG,CAAC,IAAK,CAAC,EAAE,EAAE,EACpB,GAAG,CAAC,kBAAkB,IAAI,EAAE,CAC7B,CAAwB,CAAC;YAE1B,MAAM,CAAC,IAAI,CAAC,iCAAyB,CAAC,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE;gBACrD,IAAI,IAAI;oBAAE,OAAO,IAAI,CAAC,GAAiB,CAAC,CAAC;YAC3C,CAAC,CAAC,CAAC;YAEH,IAAI,YAAY,EAAE,UAAU,EAAE,CAAC;gBAC5B,GAAW,CAAC,YAAY,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;gBAC3C,GAAG,CAAC,YAAY,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;gBAClC,GAAG,CAAC,MAAM,CAAC,IAAI,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;gBAChC,GAAW,CAAC,cAAc,GAAG,GAAG,CAAC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gBAC3B,IAAI,EAAE,WAAW;aAClB,CAAC,CAAC;QACL,CAAC,CACF;QAED,iBAAiB,EAAE,IAAA,qBAAU,EAC3B,KAAK,EAAE,GAAiB,EAAE,GAAkB,EAAE,EAAE;YAC9C,MAAM,WAAW,GAAG,IAAA,uBAAc,GAAE,CAAC;YACrC,MAAM,YAAY,GAAG,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC;YAE9C,IAAI,CAAC,YAAY;gBACf,MAAM,IAAI,mBAAQ,CAChB,8BAA8B,EAC9B,GAAG,EACH,sBAAsB,CACvB,CAAC;YAEJ,MAAM,WAAW,GAAG,6BAAiB;iBAClC,aAAa,CAAC,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC;gBACxC,EAAE,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE;gBACnB,IAAI,WAAW,EAAE,cAAc,EAAE,IAAI,KAAK,SAAS;oBACjD,OAAQ,UAAkB,EAAE,KAAK,CAAC;gBACpC,OAAO,UAAU,CAAC;YACpB,CAAC,CAAC,CAAC;YAEL,IAAI,CAAC,WAAW;gBACd,MAAM,IAAI,mBAAQ,CAChB,qCAAqC,YAAY,EAAE,EACnD,GAAG,EACH,oBAAoB,CACrB,CAAC;YAEJ,GAAG,CAAC,IAAI,CAAC;gBACP,KAAK,EAAE,WAAW,CAAC,MAAM;gBACzB,OAAO,EAAE,WAAW,CAAC,MAAM;gBAC3B,IAAI,EAAE,WAAW;aAClB,CAAC,CAAC;QACL,CAAC,CACF;KACF,CAAC;AACJ,CAAC,CAAC;AAraW,QAAA,qBAAqB,yBAqahC","sourcesContent":["import catchAsync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { ArkosRequest, ArkosResponse, ArkosNextFunction } from \"../../types\";\nimport authService from \"./auth.service\";\nimport { BaseService } from \"../base/base.service\";\nimport { User } from \"../../types\";\nimport { getArkosConfig } from \"../../server\";\nimport {\n createPrismaWhereClause,\n determineUsernameField,\n getNestedValue,\n} from \"./utils/helpers/auth.controller.helpers\";\nimport authActionService from \"./utils/services/auth-action.service\";\n\n/**\n * Default fields to exclude from user object when returning to client\n */\nexport const defaultExcludedUserFields = {\n password: false,\n};\n\n/**\n * Factory function to create authentication controller with configurable interceptors\n *\n * @param interceptors - Optional middleware functions to execute after controller actions\n * @returns An object containing all authentication controller methods\n */\nexport const authControllerFactory = async (interceptors: any = {}) => {\n const userService = new BaseService(\"user\");\n\n return {\n /**\n * Retrieves the current authenticated user's information\n */\n getMe: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const user = (await userService.findOne(\n { id: req.user!.id },\n req.prismaQueryOptions || {}\n )) as Record<string, any>;\n\n Object.keys(defaultExcludedUserFields).forEach((key) => {\n if (user) delete user[key as keyof User];\n });\n\n if (interceptors?.afterGetMe) {\n (res as any).originalData = { data: user };\n req.responseData = { data: user };\n res.locals.data = { data: user };\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json({ data: user });\n }\n ),\n\n /**\n * Updates the current authenticated user's information\n */\n updateMe: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n if (\"password\" in req.body)\n throw new AppError(\n \"In order to update password use the update-password endpoint.\",\n 400,\n {},\n \"InvalidFieldPassword\"\n );\n\n const user = (await userService.updateOne(\n { id: req.user!.id },\n req.body,\n req.prismaQueryOptions || {}\n )) as Record<string, any>;\n\n Object.keys(defaultExcludedUserFields).forEach((key) => {\n if (user) delete user[key as keyof User];\n });\n\n if (interceptors?.afterUpdateMe) {\n (res as any).originalData = { data: user };\n req.responseData = { data: user };\n res.locals.data = { data: user };\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json({ data: user });\n }\n ),\n\n /**\n * Logs out the current user by invalidating their access token cookie\n */\n logout: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n res.cookie(\"arkos_access_token\", \"no-token\", {\n expires: new Date(Date.now() + 10 * 1000),\n httpOnly: true,\n });\n\n if (interceptors?.afterLogout) {\n (res as any).originalData = null;\n req.responseData = null;\n res.locals.data = null;\n (res as any).originalStatus = 204;\n req.responseStatus = 204;\n res.locals.status = 204;\n return next();\n }\n\n res.status(204).json();\n }\n ),\n\n /**\n * Authenticates a user using configurable username field and password\n * Username field can be specified in query parameter or config\n *\n * Supports nested fields and array queries (e.g., \"profile.nickname\", \"phones.some.number\")\n */\n login: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const authConfigs = getArkosConfig()?.authentication;\n\n const usernameField = determineUsernameField(req);\n\n // For the error message, we only care about the top-level field name\n const lastField =\n usernameField.split(\".\")[usernameField.split(\".\").length - 1];\n\n const usernameValue = req.body[lastField];\n\n const { password } = req.body;\n\n if (!usernameValue || !password)\n return next(\n new AppError(\n `Please provide both ${lastField} and password`,\n 400,\n `MissingCredentialFields`\n )\n );\n\n let whereClause: Record<string, any>;\n\n if (usernameField?.includes?.(\".\")) {\n const valueToFind = getNestedValue(req.body, usernameField);\n if (valueToFind === undefined) {\n return next(new AppError(`Invalid ${usernameField} provided`, 400));\n }\n whereClause = createPrismaWhereClause(usernameField, valueToFind);\n } else {\n whereClause = { [usernameField]: usernameValue };\n }\n\n const user = (await userService.findOne(\n whereClause,\n req.prismaQueryOptions || {}\n )) as Record<string, any>;\n\n if (\n !user ||\n !(await authService.isCorrectPassword(password, user.password))\n ) {\n return next(\n new AppError(\n `Incorrect ${lastField} or password`,\n 401,\n `IncorrectCredentials`\n )\n );\n }\n\n const token = authService.signJwtToken(user.id!);\n\n const cookieOptions = authService.getJwtCookieOptions(req);\n\n if (\n authConfigs?.login?.sendAccessTokenThrough === \"response-only\" ||\n authConfigs?.login?.sendAccessTokenThrough === \"both\" ||\n !authConfigs?.login?.sendAccessTokenThrough\n ) {\n req.responseData = { accessToken: token };\n res.locals.data = { accessToken: token };\n }\n\n if (\n authConfigs?.login?.sendAccessTokenThrough === \"cookie-only\" ||\n authConfigs?.login?.sendAccessTokenThrough === \"both\" ||\n !authConfigs?.login?.sendAccessTokenThrough\n )\n res.cookie(\"arkos_access_token\", token, cookieOptions);\n\n req.accessToken = token;\n\n if (interceptors?.afterLogin) {\n (res as any).originalData = req.responseData;\n req.additionalData = { user };\n res.locals.additional = { user };\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n if (\n authConfigs?.login?.sendAccessTokenThrough === \"response-only\" ||\n authConfigs?.login?.sendAccessTokenThrough === \"both\" ||\n !authConfigs?.login?.sendAccessTokenThrough\n ) {\n res.status(200).json(req.responseData);\n } else if (\n authConfigs?.login?.sendAccessTokenThrough === \"cookie-only\" ||\n authConfigs?.login?.sendAccessTokenThrough === \"both\" ||\n !authConfigs?.login?.sendAccessTokenThrough\n )\n res.status(200).send();\n }\n ),\n\n /**\n * Creates a new user account using the userService\n */\n signup: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const user = (await userService.createOne(\n req.body,\n req.prismaQueryOptions || {}\n )) as Record<string, any>;\n\n if (interceptors?.afterSignup) {\n (res as any).originalData = { data: user };\n req.responseData = { data: user };\n res.locals.data = { data: user };\n (res as any).originalStatus = 201;\n req.responseStatus = 201;\n res.locals.status = 201;\n return next();\n }\n\n Object.keys(defaultExcludedUserFields).forEach((key) => {\n delete user[key as keyof User];\n });\n\n res.status(201).json({ data: user });\n }\n ),\n /**\n * Marks user account as self-deleted by setting deletedSelfAccountAt timestamp\n */\n deleteMe: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const userId = req.user!.id;\n\n const updatedUser = (await userService.updateOne(\n { id: userId },\n {\n deletedSelfAccountAt: new Date().toISOString(),\n },\n req.prismaQueryOptions || {}\n )) as Record<string, any>;\n\n if (interceptors?.afterDeleteMe) {\n (res as any).originalData = { data: updatedUser };\n req.responseData = { data: updatedUser };\n res.locals.data = { data: updatedUser };\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n Object.keys(defaultExcludedUserFields).forEach((key) => {\n delete updatedUser[key as keyof User];\n });\n\n res.status(200).json({\n message: \"Account deleted successfully\",\n });\n }\n ),\n\n /**\n * Updates the password of the authenticated user\n */\n updatePassword: catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n const { currentPassword, newPassword } = req.body;\n\n if (!currentPassword || !newPassword)\n return next(\n new AppError(\n \"currentPassword and newPassword are required\",\n 400,\n \"SameCurrentAndNewPassword\"\n )\n );\n\n const user = req.user;\n\n if (!user || user?.isActive === false || user?.deletedSelfAccountAt)\n return next(new AppError(\"User not found!\", 404));\n\n const isPasswordCorrect = await authService.isCorrectPassword(\n String(currentPassword),\n String(user.password)\n );\n\n const configs = getArkosConfig();\n const initAuthConfigs = configs?.authentication;\n\n if (!isPasswordCorrect)\n return next(\n new AppError(\n \"Current password is incorrect\",\n 400,\n \"IncorrentCurrentPassword\"\n )\n );\n\n if (\n !authService.isPasswordStrong(String(newPassword)) &&\n !configs?.validation\n ) {\n return next(\n new AppError(\n initAuthConfigs?.passwordValidation?.message ||\n \"The new password must contain at least one uppercase letter, one lowercase letter, and one number\",\n 400,\n \"PasswordDoesNotMeetRequirements\"\n )\n );\n }\n\n await userService.updateOne(\n { id: user.id },\n {\n password: await authService.hashPassword(newPassword),\n passwordChangedAt: new Date(Date.now()),\n }\n );\n\n const responseData = {\n status: \"success\",\n message: \"Password updated successfully!\",\n };\n\n if (interceptors?.afterUpdatePassword) {\n (res as any).originalData = responseData;\n req.additionalData = { user };\n req.responseData = responseData;\n res.locals.data = responseData;\n (res as any).originalStatus = 200;\n req.responseStatus = 200;\n res.locals.status = 200;\n return next();\n }\n\n res.status(200).json(responseData);\n }\n ),\n\n findManyAuthAction: catchAsync(\n async (_: ArkosRequest, res: ArkosResponse) => {\n const arkosConfig = getArkosConfig();\n const authActions = authActionService.getAll()?.map((authAction) => {\n if (arkosConfig?.authentication?.mode === \"dynamic\")\n delete (authAction as any)?.roles;\n return authAction;\n });\n\n res.json({\n total: authActions.length,\n results: authActions.length,\n data: authActions,\n });\n }\n ),\n\n findOneAuthAction: catchAsync(\n async (req: ArkosRequest, res: ArkosResponse) => {\n const arkosConfig = getArkosConfig();\n const resourceName = req.params?.resourceName;\n\n if (!resourceName)\n throw new AppError(\n `Please provide a resoureName`,\n 400,\n \"MissiongResourseName\"\n );\n\n const authActions = authActionService\n .getByResource(req.params?.resourceName)\n ?.map((authAction) => {\n if (arkosConfig?.authentication?.mode === \"dynamic\")\n delete (authAction as any)?.roles;\n return authAction;\n });\n\n if (!authActions)\n throw new AppError(\n `No auth action with resource name ${resourceName}`,\n 404,\n \"AuthActionNotFound\"\n );\n\n res.json({\n total: authActions.length,\n results: authActions.length,\n data: authActions,\n });\n }\n ),\n };\n};\n"]}
@@ -139,8 +139,7 @@ function sendProductionError(err, req, res) {
139
139
  });
140
140
  }
141
141
  process.on("SIGTERM", () => {
142
- if (process.env.NODE_ENV !== "production" &&
143
- process.env.NODE_ENV !== "staging") {
142
+ if (process.env.ARKOS_BUILD !== "true") {
144
143
  process.exit();
145
144
  }
146
145
  else {
@@ -1 +1 @@
1
- {"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,+BAyEC;AA3FD,qFAAuE;AACvE,yCAAsC;AAiBtC,SAAwB,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,CAAe;IAEf,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;IAE9C,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,IAA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G,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;gBACnB,MAAM,EAAE,OAAO;gBACf,OAAO,EAAE,gDAAgD;gBACzD,IAAI,EAAE,SAAS;gBACf,IAAI,EAAE,EAAE;aACT,CAAC,CAAC;QAEL,OAAO;IACT,CAAC;IAED,IAAI,GAAG,CAAC,aAAa,EAAE,CAAC;QACtB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;YAC9B,KAAK,EAAE,uBAAuB;YAC9B,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,IAAI,EAAE,SAAS;SAChB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;QAC9B,KAAK,EAAE,uBAAuB;QAC9B,OAAO,EAAE,gDAAgD;KAC1D,CAAC,CAAC;AACL,CAAC;AAWD,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;IACzB,IACE,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY;QACrC,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,SAAS,EAClC,CAAC;QACD,OAAO,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,KAAK,CAAC,2DAA2D,CAAC,CAAC;QAE3E,eAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;YACvC,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} _ - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n _: NextFunction\n): void {\n console.error(\"[\\x1b[31mError\\x1b[0m]:\", err);\n\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n let error: any = {\n ...err,\n message: err.message,\n stack: err?.stack || undefined,\n };\n\n if (process.env.NODE_ENV == \"production\") delete error?.stack;\n\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n if (err.name === \"PrismaClientInitializationError\")\n error = errorControllerHelper.handlePrismaClientInitializationError(err);\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"P2025\")\n error = errorControllerHelper.handleNonExistingRecord(err);\n if (err.code === \"P3000\")\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n if (err.code === \"P3001\")\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n if (err.code === \"P3002\")\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n if (err.code === \"P3003\")\n error = errorControllerHelper.handleVersionMismatchError(err);\n\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n\n if (process.env.NODE_ENV !== \"production\")\n return sendDevelopmentError(\n {\n ...error,\n message: error.message,\n stack: err.stack,\n originalError: err,\n },\n req,\n res\n );\n\n sendProductionError(error, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(err: any, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n ...err,\n message: err.message.split(\"\\n\")[err.message.split(\"\\n\").length - 1],\n stack: err.stack?.split(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"Unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Internal server error, please try again later.\",\n code: \"Unknown\",\n meta: {},\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n code: \"Unknown\",\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: \"Internal server error, please try again later.\",\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (\n process.env.NODE_ENV !== \"production\" &&\n process.env.NODE_ENV !== \"staging\"\n ) {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
1
+ {"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,+BAyEC;AA3FD,qFAAuE;AACvE,yCAAsC;AAiBtC,SAAwB,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,CAAe;IAEf,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;IAE9C,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,IAAI,GAAG,CAAC;IACvC,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,OAAO,CAAC;IAEnC,IAAI,KAAK,GAAQ;QACf,GAAG,GAAG;QACN,OAAO,EAAE,GAAG,CAAC,OAAO;QACpB,KAAK,EAAE,GAAG,EAAE,KAAK,IAAI,SAAS;KAC/B,CAAC;IAEF,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,IAAI,YAAY;QAAE,OAAO,KAAK,EAAE,KAAK,CAAC;IAE9D,IAAI,GAAG,CAAC,IAAI,KAAK,mBAAmB;QAClC,KAAK,GAAG,qBAAqB,CAAC,cAAc,EAAE,CAAC;IACjD,IAAI,GAAG,CAAC,IAAI,KAAK,mBAAmB;QAClC,K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C,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;QAC9B,KAAK,EAAE,uBAAuB;QAC9B,OAAO,EAAE,gDAAgD;KAC1D,CAAC,CAAC;AACL,CAAC;AAWD,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;IACzB,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM,EAAE,CAAC;QACvC,OAAO,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,KAAK,CAAC,2DAA2D,CAAC,CAAC;QAE3E,eAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;YACvC,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} _ - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n _: NextFunction\n): void {\n console.error(\"[\\x1b[31mError\\x1b[0m]:\", err);\n\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n let error: any = {\n ...err,\n message: err.message,\n stack: err?.stack || undefined,\n };\n\n if (process.env.NODE_ENV == \"production\") delete error?.stack;\n\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n if (err.name === \"PrismaClientInitializationError\")\n error = errorControllerHelper.handlePrismaClientInitializationError(err);\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"P2025\")\n error = errorControllerHelper.handleNonExistingRecord(err);\n if (err.code === \"P3000\")\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n if (err.code === \"P3001\")\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n if (err.code === \"P3002\")\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n if (err.code === \"P3003\")\n error = errorControllerHelper.handleVersionMismatchError(err);\n\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n\n if (process.env.NODE_ENV !== \"production\")\n return sendDevelopmentError(\n {\n ...error,\n message: error.message,\n stack: err.stack,\n originalError: err,\n },\n req,\n res\n );\n\n sendProductionError(error, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(err: any, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n ...err,\n message: err.message.split(\"\\n\")[err.message.split(\"\\n\").length - 1],\n stack: err.stack?.split(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"Unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Internal server error, please try again later.\",\n code: \"Unknown\",\n meta: {},\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n code: \"Unknown\",\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: \"Internal server error, please try again later.\",\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (process.env.ARKOS_BUILD !== \"true\") {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"swagger.router.js","sourceRoot":"","sources":["../../../../src/modules/swagger/swagger.router.ts"],"names":[],"mappings":";;;;;AAgBA,4CAkDC;AAlED,qC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AG,cAAc,EAAE,+BAA+B;KACnD,CAAC,CACH,CAAC;IAEF,OAAO,aAAa,CAAC;AACvB,CAAC","sourcesContent":["import { Router } from \"express\";\nimport swaggerJsdoc from \"swagger-jsdoc\";\nimport { ArkosConfig } from \"../../types/arkos-config\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport {\n generatePathsForModels,\n getOpenAPIJsonSchemasByConfigMode,\n} from \"./utils/helpers/swagger.router.helpers\";\nimport missingJsonSchemaGenerator from \"./utils/helpers/missing-json-schemas-generator\";\nimport getSwaggerDefaultConfig from \"./utils/helpers/get-swagger-default-configs\";\nimport { importEsmPreventingTsTransformation } from \"../../utils/helpers/global.helpers\";\nimport generateSystemJsonSchemas from \"./utils/helpers/json-schema-generators/generate-system-json-schemas\";\nimport getFileUploadJsonSchemaPaths from \"./utils/helpers/get-file-upload-json-schema-paths\";\n\nconst swaggerRouter = Router();\n\nexport async function getSwaggerRouter(\n arkosConfig: ArkosConfig\n): Promise<Router> {\n let defaultJsonSchemas = await getOpenAPIJsonSchemasByConfigMode(arkosConfig);\n const defaultModelsPaths = await generatePathsForModels(arkosConfig);\n const fileUploadDefaultPaths = getFileUploadJsonSchemaPaths(arkosConfig);\n const missingJsonSchemas =\n await missingJsonSchemaGenerator.generateMissingJsonSchemas(\n defaultModelsPaths,\n defaultJsonSchemas,\n arkosConfig\n );\n\n defaultJsonSchemas = {\n ...defaultJsonSchemas,\n ...missingJsonSchemas,\n ...generateSystemJsonSchemas(arkosConfig),\n };\n\n const swaggerConfigs = deepmerge(\n (await getSwaggerDefaultConfig(\n {\n ...defaultModelsPaths,\n ...fileUploadDefaultPaths,\n },\n defaultJsonSchemas\n )) || {},\n arkosConfig.swagger || {}\n ) as ArkosConfig[\"swagger\"];\n\n const { definition, ...options } = swaggerConfigs?.options!;\n\n const swaggerSpecification = swaggerJsdoc({\n definition: definition as swaggerJsdoc.SwaggerDefinition,\n ...options,\n });\n\n const scalar = await importEsmPreventingTsTransformation(\n \"@scalar/express-api-reference\"\n );\n\n swaggerRouter.use(\n swaggerConfigs!.endpoint!,\n scalar.apiReference({\n content: swaggerSpecification,\n ...swaggerConfigs?.scalarApiReferenceConfiguration,\n })\n );\n\n return swaggerRouter;\n}\n"]}
1
+ {"version":3,"file":"swagger.router.js","sourceRoot":"","sources":["../../../../src/modules/swagger/swagger.router.ts"],"names":[],"mappings":";;;;;AAgBA,4CAmDC;AAnED,qCAAiC;AACjC,kEAAyC;AAEzC,4FAA6D;AAC7D,mFAGgD;AAChD,oHAAwF;AACxF,8GAAkF;AAClF,uEAAyF;AACzF,uIAA4G;AAC5G,0HAA6F;AAE7F,MAAM,aAAa,GAAG,IAAA,gBAAM,GAAE,CAAC;AAExB,KAAK,UAAU,gBAAgB,CACpC,WAAwB;IAExB,IAAI,kBAAkB,GAAG,MAAM,IAAA,0DAAiC,EAAC,WAAW,CAAC,CAAC;IAC9E,MAAM,kBAAkB,GAAG,MAAM,IAAA,+CAAsB,EAAC,WAAW,CAAC,CAAC;IACrE,MAAM,sBAAsB,GAAG,IAAA,2CAA4B,EAAC,WAAW,CAAC,CAAC;IAEzE,MAAM,kBAAkB,GACtB,MAAM,wCAA0B,CAAC,0BAA0B,CACzD,kBAAkB,EAClB,kBAAkB,EAClB,WAAW,CACZ,CAAC;IAEJ,kBAAkB,GAAG;QACnB,GAAG,kBAAkB;QACrB,GAAG,kBAAkB;QACrB,GAAG,IAAA,sCAAyB,EAAC,WAAW,CAAC;KAC1C,CAAC;IAEF,MAAM,cAAc,GAAG,IAAA,0BAAS,EAC9B,CAAC,MAAM,IAAA,qCAAuB,EAC5B;QACE,GAAG,kBAAkB;QACrB,GAAG,sBAAsB;KAC1B,EACD,kBAAkB,CACnB,CAAC,IAAI,EAAE,EACR,WAAW,CAAC,OAAO,IAAI,EAAE,CACA,CAAC;IAE5B,MAAM,EAAE,UAAU,EAAE,GAAG,OAAO,EAAE,GAAG,cAAc,EAAE,OAAQ,CAAC;IAE5D,MAAM,oBAAoB,GAAG,IAAA,uBAAY,EAAC;QACxC,UAAU,EAAE,UAA4C;QACxD,GAAG,OAAO;KACX,CAAC,CAAC;IAEH,MAAM,MAAM,GAAG,MAAM,IAAA,oDAAmC,EACtD,+BAA+B,CAChC,CAAC;IAEF,aAAa,CAAC,GAAG,CACf,cAAe,CAAC,QAAS,EACzB,MAAM,CAAC,YAAY,CAAC;QAClB,OAAO,EAAE,oBAAoB;QAC7B,GAAG,cAAc,EAAE,+BAA+B;KACnD,CAAC,CACH,CAAC;IAEF,OAAO,aAAa,CAAC;AACvB,CAAC","sourcesContent":["import { Router } from \"express\";\nimport swaggerJsdoc from \"swagger-jsdoc\";\nimport { ArkosConfig } from \"../../types/arkos-config\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport {\n generatePathsForModels,\n getOpenAPIJsonSchemasByConfigMode,\n} from \"./utils/helpers/swagger.router.helpers\";\nimport missingJsonSchemaGenerator from \"./utils/helpers/missing-json-schemas-generator\";\nimport getSwaggerDefaultConfig from \"./utils/helpers/get-swagger-default-configs\";\nimport { importEsmPreventingTsTransformation } from \"../../utils/helpers/global.helpers\";\nimport generateSystemJsonSchemas from \"./utils/helpers/json-schema-generators/generate-system-json-schemas\";\nimport getFileUploadJsonSchemaPaths from \"./utils/helpers/get-file-upload-json-schema-paths\";\n\nconst swaggerRouter = Router();\n\nexport async function getSwaggerRouter(\n arkosConfig: ArkosConfig\n): Promise<Router> {\n let defaultJsonSchemas = await getOpenAPIJsonSchemasByConfigMode(arkosConfig);\n const defaultModelsPaths = await generatePathsForModels(arkosConfig);\n const fileUploadDefaultPaths = getFileUploadJsonSchemaPaths(arkosConfig);\n\n const missingJsonSchemas =\n await missingJsonSchemaGenerator.generateMissingJsonSchemas(\n defaultModelsPaths,\n defaultJsonSchemas,\n arkosConfig\n );\n\n defaultJsonSchemas = {\n ...defaultJsonSchemas,\n ...missingJsonSchemas,\n ...generateSystemJsonSchemas(arkosConfig),\n };\n\n const swaggerConfigs = deepmerge(\n (await getSwaggerDefaultConfig(\n {\n ...defaultModelsPaths,\n ...fileUploadDefaultPaths,\n },\n defaultJsonSchemas\n )) || {},\n arkosConfig.swagger || {}\n ) as ArkosConfig[\"swagger\"];\n\n const { definition, ...options } = swaggerConfigs?.options!;\n\n const swaggerSpecification = swaggerJsdoc({\n definition: definition as swaggerJsdoc.SwaggerDefinition,\n ...options,\n });\n\n const scalar = await importEsmPreventingTsTransformation(\n \"@scalar/express-api-reference\"\n );\n\n swaggerRouter.use(\n swaggerConfigs!.endpoint!,\n scalar.apiReference({\n content: swaggerSpecification,\n ...swaggerConfigs?.scalarApiReferenceConfiguration,\n })\n );\n\n return swaggerRouter;\n}\n"]}
@@ -168,12 +168,10 @@ class MissingJsonSchemasGenerator {
168
168
  mappedKey = "UpdatePasswordSchema";
169
169
  }
170
170
  else {
171
- if (key.includes("ModelSchema")) {
171
+ if (key.includes("ModelSchema"))
172
172
  mappedKey = key;
173
- }
174
- else {
173
+ else
175
174
  mappedKey = `${key}ModelSchema`;
176
- }
177
175
  }
178
176
  missingSchemas[mappedKey] = schema;
179
177
  });
@@ -1 +1 @@
1
- {"version":3,"file":"missing-json-schemas-generator.js","sourceRoot":"","sources":["../../../../../../src/modules/swagger/utils/helpers/missing-json-schemas-generator.ts"],"names":[],"mappings":";;;;;AAEA,yHAA8F;AAC9F,yCAAqC;AAKrC,MAAM,2BAA2B;IAOvB,6BAA6B,CAAC,SAAiB;QACrD,MAAM,KAAK,GAAG,SAAS,CAAC,KAAK,CAC3B,+GAA+G,CAChH,CAAC;QACF,IAAI,KAAK,EAAE,CAAC;YACV,IAAI,SAAS,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;YAEzB,IACE,SAAS,CAAC,WAAW,EAAE,KAAK,MAAM;gBAClC,SAAS,CAAC,WAAW,EAAE,KAAK,OAAO;gBACnC,SAAS,CAAC,WAAW,EAAE,KAAK,QAAQ;gBACpC,SAAS,CAAC,WAAW,EAAE,KAAK,OAAO;gBACnC,SAAS,CA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AAS,GAAkB,IAAI,CAAC;gBACpC,IAAI,MAAM,GAAkB,IAAI,CAAC;gBAGjC,IAAI,OAAO,CAAC,WAAW,EAAE,CAAC;oBACxB,SAAS,GAAG,IAAI,CAAC,+BAA+B,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;oBACtE,MAAM,GAAG,IAAI,CAAC,4BAA4B,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;gBAClE,CAAC;gBAGD,IAAI,CAAC,SAAS,IAAI,CAAC,MAAM,EAAE,CAAC;oBAC1B,SAAS,GAAG,SAAS,IAAI,IAAI,CAAC,6BAA6B,CAAC,GAAG,CAAC,CAAC;oBACjE,MAAM,GAAG,MAAM,IAAI,IAAI,CAAC,0BAA0B,CAAC,GAAG,CAAC,CAAC;gBAC1D,CAAC;gBAED,IAAI,SAAS,IAAI,MAAM,EAAE,CAAC;oBACxB,YAAY,CAAC,IAAI,CAAC;wBAChB,KAAK,EAAE,SAAS;wBAChB,MAAM;wBACN,GAAG;wBACH,WAAW,EAAE,OAAO,CAAC,WAAW;qBACjC,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;QACH,CAAC;QAED,OAAO;YACL,OAAO;YACP,WAAW;YACX,YAAY;YACZ,YAAY;SACb,CAAC;IACJ,CAAC;CACF;AAED,MAAM,0BAA0B,GAAG,IAAI,2BAA2B,EAAE,CAAC;AAErE,kBAAe,0BAA0B,CAAC","sourcesContent":["import { OpenAPIV3 } from \"openapi-types\";\nimport { ArkosConfig } from \"../../../../exports\";\nimport PrismaJsonSchemaGenerator from \"../../../../utils/prisma/prisma-json-schema-generator\";\nimport { singular } from \"pluralize\";\n\n/**\n * Used to backfill missing json schema contained in paths in situation such as when using a `arkosConfig.swagger.mode` different from prisma and `strict` to false, in this situation the jsonSchemas paths are filled with $ref pointing to non existent jsonSchema components.\n */\nclass MissingJsonSchemasGenerator {\n /**\n * Extract model name from schema reference\n * @example\n * \"#/components/schemas/CreateUserModelSchema\" -> \"User\"\n * \"#/components/schemas/FindManyPostModelSchema\" -> \"Post\"\n */\n private extractModelNameFromSchemaRef(schemaRef: string): string | null {\n const match = schemaRef.match(\n /#\\/components\\/schemas\\/(?:Create|Update|UpdateMany|FindOne|FindMany|CreateMany)?(.+?)(?:ModelSchema|Schema)$/\n );\n if (match) {\n let modelName = match[1];\n // Handle special auth cases\n if (\n modelName.toLowerCase() === \"auth\" ||\n modelName.toLowerCase() === \"login\" ||\n modelName.toLowerCase() === \"signup\" ||\n modelName.toLowerCase() === \"getme\" ||\n modelName.toLowerCase() === \"updateme\" ||\n modelName.toLowerCase() === \"updatepassword\"\n ) {\n return \"Auth\";\n }\n return modelName;\n }\n return null;\n }\n\n /**\n * Extract action type from operationId\n * @example\n * \"createManyUser\" -> \"createMany\"\n * \"findUsers\" -> \"findMany\"\n * \"updateUser\" -> \"updateOne\"\n */\n private extractActionFromOperationId(operationId: string): string | null {\n if (!operationId) return null;\n // Handle bulk operations first (more specific patterns)\n if (operationId.includes(\"createMany\")) return \"createMany\";\n if (operationId.includes(\"updateMany\")) return \"updateMany\";\n if (operationId.includes(\"deleteMany\")) return \"deleteMany\";\n if (operationId.includes(\"updateMe\")) return \"updateMe\";\n if (operationId.includes(\"updatePassword\")) return \"updatePassword\";\n\n // Handle single operations\n if (operationId.startsWith(\"create\")) return \"createOne\";\n if (operationId.startsWith(\"update\")) return \"updateOne\";\n if (operationId.startsWith(\"delete\")) return \"deleteOne\";\n if (\n operationId.startsWith(\"find\") &&\n (operationId.includes(\"ById\") || operationId.includes(\"One\"))\n )\n return \"findOne\";\n if (operationId.startsWith(\"find\")) return \"findMany\";\n\n // Handle auth operations\n if (operationId.includes(\"login\") || operationId === \"login\")\n return \"login\";\n if (operationId.includes(\"signup\") || operationId === \"signup\")\n return \"signup\";\n if (operationId.includes(\"getMe\") || operationId === \"getMe\")\n return \"getMe\";\n if (operationId.includes(\"updateMe\") || operationId === \"updateMe\")\n return \"updateMe\";\n if (\n operationId.includes(\"updatePassword\") ||\n operationId === \"updatePassword\"\n )\n return \"updatePassword\";\n\n return null;\n }\n\n /**\n * Extract model name from operationId\n * @example\n * \"createManyUser\" -> \"User\"\n * \"findUsers\" -> \"User\"\n * \"updateUser\" -> \"User\"\n */\n private extractModelNameFromOperationId(operationId: string): string | null {\n if (!operationId) return null;\n // Remove common prefixes and suffixes to isolate model name\n let modelName = operationId\n .replace(/^(create|update|delete|find)Many/i, \"\")\n .replace(/^(create|update|delete|find)/i, \"\")\n .replace(/ById$/i, \"\");\n\n // Handle auth operations\n if (\n operationId.toLowerCase().includes(\"login\") ||\n operationId.toLowerCase().includes(\"signup\") ||\n operationId.toLowerCase().includes(\"getme\") ||\n operationId.toLowerCase().includes(\"updateme\") ||\n operationId.toLowerCase().includes(\"updatepassword\")\n ) {\n return \"Auth\";\n }\n\n return singular(modelName) || null;\n }\n\n /**\n * Recursively extract all $ref values from an object along with their context\n */\n private extractSchemaRefsWithContext(\n obj: any,\n refs: Map<\n string,\n { operationId?: string; method?: string; path?: string }\n > = new Map(),\n context: { operationId?: string; method?: string; path?: string } = {}\n ): Map<string, { operationId?: string; method?: string; path?: string }> {\n if (typeof obj !== \"object\" || obj === null) {\n return refs;\n }\n\n if (Array.isArray(obj)) {\n obj.forEach((item) =>\n this.extractSchemaRefsWithContext(item, refs, context)\n );\n return refs;\n }\n\n // Update context when we find operationId\n if (obj.operationId && typeof obj.operationId === \"string\") {\n context = { ...context, operationId: obj.operationId };\n }\n\n if (obj.$ref && typeof obj.$ref === \"string\") {\n refs.set(obj.$ref, { ...context });\n }\n\n Object.values(obj).forEach((value) => {\n this.extractSchemaRefsWithContext(value, refs, context);\n });\n\n return refs;\n }\n\n /**\n * Extract schema references from paths with context\n */\n private extractPathSchemaRefs(\n paths: OpenAPIV3.PathsObject\n ): Map<string, { operationId?: string; method?: string; path?: string }> {\n const refs = new Map<\n string,\n { operationId?: string; method?: string; path?: string }\n >();\n\n Object.entries(paths).forEach(([path, pathItem]) => {\n if (!pathItem) return;\n\n Object.entries(pathItem).forEach(([method, operation]) => {\n if (!operation || typeof operation !== \"object\") return;\n\n const context = {\n method,\n path,\n operationId: (operation as any).operationId,\n };\n\n this.extractSchemaRefsWithContext(operation, refs, context);\n });\n });\n\n return refs;\n }\n\n /**\n * Extract schema name from $ref\n * @example\n * \"#/components/schemas/CreateUserModelSchema\" -> \"CreateUserModelSchema\"\n */\n private getSchemaNameFromRef(ref: string): string | null {\n const match = ref.match(/#\\/components\\/schemas\\/(.+)$/);\n return match ? match[1] : null;\n }\n\n async generateMissingJsonSchemas(\n currentPaths: OpenAPIV3.PathsObject,\n currentJsonSchemas: Record<string, any>,\n arkosConfig: ArkosConfig\n ): Promise<Record<string, any>> {\n const missingSchemas: Record<string, any> = {};\n\n // Extract all schema references with their context (operationId, method, path)\n const schemaRefsWithContext = this.extractPathSchemaRefs(currentPaths);\n\n // Group missing schemas by model and collect required actions\n const modelActions = new Map<string, Set<string>>();\n\n for (const [ref, context] of schemaRefsWithContext) {\n const schemaName = this.getSchemaNameFromRef(ref);\n if (!schemaName) continue;\n\n // Check if schema already exists\n if (currentJsonSchemas[schemaName]) continue;\n\n // Only process ModelSchema references\n if (!schemaName.includes(\"ModelSchema\") && !schemaName.includes(\"Schema\"))\n continue;\n\n let modelName: string | null = null;\n let action: string | null = null;\n\n // First try to get model and action from operationId (more reliable)\n if (context.operationId) {\n modelName = this.extractModelNameFromOperationId(context.operationId);\n action = this.extractActionFromOperationId(context.operationId);\n }\n\n // Fallback to schema ref analysis if operationId didn't work\n if (!modelName || !action) {\n modelName = modelName || this.extractModelNameFromSchemaRef(ref);\n action = action || this.extractActionFromSchemaRef(ref);\n }\n\n if (modelName && action) {\n if (!modelActions.has(modelName))\n modelActions.set(modelName, new Set());\n\n modelActions.get(modelName)!.add(action);\n }\n }\n\n // Generate schemas for each model\n for (const [modelName, actions] of modelActions) {\n try {\n const actionsArray = Array.from(actions) as any[];\n\n const generatedSchemas =\n await PrismaJsonSchemaGenerator.generateModelSchemas({\n modelName,\n arkosConfig,\n schemasToGenerate: actionsArray,\n });\n\n // Map generated schemas to the expected naming convention\n Object.entries(generatedSchemas).forEach(([key, schema]) => {\n // The enhanced generator might use different naming conventions\n // We need to map them to match what's expected in the $refs\n let mappedKey = key;\n const authModuleModel = [\"auth\", \"login\", \"me\", \"password\", \"me\"];\n\n // Handle auth schemas\n if (authModuleModel.includes(modelName.toLowerCase())) {\n if (key === \"LoginSchema\") mappedKey = \"LoginSchema\";\n else if (key === \"SignupSchema\") mappedKey = \"SignupSchema\";\n else if (key === \"GetMeSchema\") mappedKey = \"GetMeSchema\";\n else if (key === \"UpdateMeSchema\") mappedKey = \"UpdateMeSchema\";\n else if (key === \"UpdatePasswordSchema\")\n mappedKey = \"UpdatePasswordSchema\";\n } else {\n // Handle model schemas - ensure they match the expected naming pattern\n if (key.includes(\"ModelSchema\")) {\n mappedKey = key;\n } else {\n // Add ModelSchema suffix if missing\n mappedKey = `${key}ModelSchema`;\n }\n }\n\n missingSchemas[mappedKey] = schema;\n });\n } catch (error) {\n // FIXME: check if all models are being generarted if so simply keep the error ssilent\n // console.warn(\n // `Failed to generate schemas for model ${modelName}:`,\n // error\n // );\n }\n }\n\n return missingSchemas;\n }\n\n /**\n * Legacy method - extract action type from schema reference (kept for backward compatibility)\n */\n private extractActionFromSchemaRef(schemaRef: string): string | null {\n if (schemaRef.includes(\"CreateMany\")) return \"createMany\";\n if (schemaRef.includes(\"Create\")) return \"createOne\";\n if (schemaRef.includes(\"UpdateMany\")) return \"updateMany\";\n if (\n schemaRef.includes(\"Update\") &&\n !schemaRef.includes(\"UpdateMe\") &&\n !schemaRef.includes(\"UpdatePassword\")\n )\n return \"updateOne\";\n if (schemaRef.includes(\"FindMany\")) return \"findMany\";\n if (schemaRef.includes(\"FindOne\")) return \"findOne\";\n if (schemaRef.includes(\"Login\")) return \"login\";\n if (schemaRef.includes(\"Signup\")) return \"signup\";\n if (schemaRef.includes(\"GetMe\")) return \"getMe\";\n if (schemaRef.includes(\"UpdateMe\")) return \"updateMe\";\n if (schemaRef.includes(\"UpdatePassword\")) return \"updatePassword\";\n\n return null;\n }\n\n /**\n * Debug method to analyze what schemas are missing with enhanced context\n */\n analyzeMissingSchemas(\n currentPaths: OpenAPIV3.PathsObject,\n currentJsonSchemas: Record<string, any>\n ): {\n allRefs: Array<{ ref: string; context: any }>;\n missingRefs: Array<{ ref: string; context: any }>;\n existingRefs: Array<{ ref: string; context: any }>;\n modelActions: {\n model: string;\n action: string;\n ref: string;\n operationId?: string;\n }[];\n } {\n const schemaRefsWithContext = this.extractPathSchemaRefs(currentPaths);\n\n const allRefs: Array<{ ref: string; context: any }> = [];\n const missingRefs: Array<{ ref: string; context: any }> = [];\n const existingRefs: Array<{ ref: string; context: any }> = [];\n const modelActions: {\n model: string;\n action: string;\n ref: string;\n operationId?: string;\n }[] = [];\n\n for (const [ref, context] of schemaRefsWithContext) {\n const refWithContext = { ref, context };\n allRefs.push(refWithContext);\n\n const schemaName = this.getSchemaNameFromRef(ref);\n if (!schemaName) continue;\n\n if (currentJsonSchemas[schemaName]) {\n existingRefs.push(refWithContext);\n } else {\n missingRefs.push(refWithContext);\n\n let modelName: string | null = null;\n let action: string | null = null;\n\n // Try operationId first\n if (context.operationId) {\n modelName = this.extractModelNameFromOperationId(context.operationId);\n action = this.extractActionFromOperationId(context.operationId);\n }\n\n // Fallback to schema ref\n if (!modelName || !action) {\n modelName = modelName || this.extractModelNameFromSchemaRef(ref);\n action = action || this.extractActionFromSchemaRef(ref);\n }\n\n if (modelName && action) {\n modelActions.push({\n model: modelName,\n action,\n ref,\n operationId: context.operationId,\n });\n }\n }\n }\n\n return {\n allRefs,\n missingRefs,\n existingRefs,\n modelActions,\n };\n }\n}\n\nconst missingJsonSchemaGenerator = new MissingJsonSchemasGenerator();\n\nexport default missingJsonSchemaGenerator;\n"]}
1
+ {"version":3,"file":"missing-json-schemas-generator.js","sourceRoot":"","sources":["../../../../../../src/modules/swagger/utils/helpers/missing-json-schemas-generator.ts"],"names":[],"mappings":";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AAe,0BAA0B,CAAC","sourcesContent":["import { OpenAPIV3 } from \"openapi-types\";\nimport { ArkosConfig } from \"../../../../exports\";\nimport PrismaJsonSchemaGenerator from \"../../../../utils/prisma/prisma-json-schema-generator\";\nimport { singular } from \"pluralize\";\n\n/**\n * Used to backfill missing json schema contained in paths in situation such as when using a `arkosConfig.swagger.mode` different from prisma and `strict` to false, in this situation the jsonSchemas paths are filled with $ref pointing to non existent jsonSchema components.\n */\nclass MissingJsonSchemasGenerator {\n /**\n * Extract model name from schema reference\n * @example\n * \"#/components/schemas/CreateUserModelSchema\" -> \"User\"\n * \"#/components/schemas/FindManyPostModelSchema\" -> \"Post\"\n */\n private extractModelNameFromSchemaRef(schemaRef: string): string | null {\n const match = schemaRef.match(\n /#\\/components\\/schemas\\/(?:Create|Update|UpdateMany|FindOne|FindMany|CreateMany)?(.+?)(?:ModelSchema|Schema)$/\n );\n if (match) {\n let modelName = match[1];\n // Handle special auth cases\n if (\n modelName.toLowerCase() === \"auth\" ||\n modelName.toLowerCase() === \"login\" ||\n modelName.toLowerCase() === \"signup\" ||\n modelName.toLowerCase() === \"getme\" ||\n modelName.toLowerCase() === \"updateme\" ||\n modelName.toLowerCase() === \"updatepassword\"\n ) {\n return \"Auth\";\n }\n return modelName;\n }\n return null;\n }\n\n /**\n * Extract action type from operationId\n * @example\n * \"createManyUser\" -> \"createMany\"\n * \"findUsers\" -> \"findMany\"\n * \"updateUser\" -> \"updateOne\"\n */\n private extractActionFromOperationId(operationId: string): string | null {\n if (!operationId) return null;\n // Handle bulk operations first (more specific patterns)\n if (operationId.includes(\"createMany\")) return \"createMany\";\n if (operationId.includes(\"updateMany\")) return \"updateMany\";\n if (operationId.includes(\"deleteMany\")) return \"deleteMany\";\n if (operationId.includes(\"updateMe\")) return \"updateMe\";\n if (operationId.includes(\"updatePassword\")) return \"updatePassword\";\n\n // Handle single operations\n if (operationId.startsWith(\"create\")) return \"createOne\";\n if (operationId.startsWith(\"update\")) return \"updateOne\";\n if (operationId.startsWith(\"delete\")) return \"deleteOne\";\n if (\n operationId.startsWith(\"find\") &&\n (operationId.includes(\"ById\") || operationId.includes(\"One\"))\n )\n return \"findOne\";\n if (operationId.startsWith(\"find\")) return \"findMany\";\n\n // Handle auth operations\n if (operationId.includes(\"login\") || operationId === \"login\")\n return \"login\";\n if (operationId.includes(\"signup\") || operationId === \"signup\")\n return \"signup\";\n if (operationId.includes(\"getMe\") || operationId === \"getMe\")\n return \"getMe\";\n if (operationId.includes(\"updateMe\") || operationId === \"updateMe\")\n return \"updateMe\";\n if (\n operationId.includes(\"updatePassword\") ||\n operationId === \"updatePassword\"\n )\n return \"updatePassword\";\n\n return null;\n }\n\n /**\n * Extract model name from operationId\n * @example\n * \"createManyUser\" -> \"User\"\n * \"findUsers\" -> \"User\"\n * \"updateUser\" -> \"User\"\n */\n private extractModelNameFromOperationId(operationId: string): string | null {\n if (!operationId) return null;\n // Remove common prefixes and suffixes to isolate model name\n let modelName = operationId\n .replace(/^(create|update|delete|find)Many/i, \"\")\n .replace(/^(create|update|delete|find)/i, \"\")\n .replace(/ById$/i, \"\");\n\n // Handle auth operations\n if (\n operationId.toLowerCase().includes(\"login\") ||\n operationId.toLowerCase().includes(\"signup\") ||\n operationId.toLowerCase().includes(\"getme\") ||\n operationId.toLowerCase().includes(\"updateme\") ||\n operationId.toLowerCase().includes(\"updatepassword\")\n ) {\n return \"Auth\";\n }\n\n return singular(modelName) || null;\n }\n\n /**\n * Recursively extract all $ref values from an object along with their context\n */\n private extractSchemaRefsWithContext(\n obj: any,\n refs: Map<\n string,\n { operationId?: string; method?: string; path?: string }\n > = new Map(),\n context: { operationId?: string; method?: string; path?: string } = {}\n ): Map<string, { operationId?: string; method?: string; path?: string }> {\n if (typeof obj !== \"object\" || obj === null) {\n return refs;\n }\n\n if (Array.isArray(obj)) {\n obj.forEach((item) =>\n this.extractSchemaRefsWithContext(item, refs, context)\n );\n return refs;\n }\n\n // Update context when we find operationId\n if (obj.operationId && typeof obj.operationId === \"string\") {\n context = { ...context, operationId: obj.operationId };\n }\n\n if (obj.$ref && typeof obj.$ref === \"string\") {\n refs.set(obj.$ref, { ...context });\n }\n\n Object.values(obj).forEach((value) => {\n this.extractSchemaRefsWithContext(value, refs, context);\n });\n\n return refs;\n }\n\n /**\n * Extract schema references from paths with context\n */\n private extractPathSchemaRefs(\n paths: OpenAPIV3.PathsObject\n ): Map<string, { operationId?: string; method?: string; path?: string }> {\n const refs = new Map<\n string,\n { operationId?: string; method?: string; path?: string }\n >();\n\n Object.entries(paths).forEach(([path, pathItem]) => {\n if (!pathItem) return;\n\n Object.entries(pathItem).forEach(([method, operation]) => {\n if (!operation || typeof operation !== \"object\") return;\n\n const context = {\n method,\n path,\n operationId: (operation as any).operationId,\n };\n\n this.extractSchemaRefsWithContext(operation, refs, context);\n });\n });\n\n return refs;\n }\n\n /**\n * Extract schema name from $ref\n * @example\n * \"#/components/schemas/CreateUserModelSchema\" -> \"CreateUserModelSchema\"\n */\n private getSchemaNameFromRef(ref: string): string | null {\n const match = ref.match(/#\\/components\\/schemas\\/(.+)$/);\n return match ? match[1] : null;\n }\n\n /**\n * When using swagger with strict set to false and needs fallback to prisma for the required json schemas that where not manually provided through zod schemas or class validator classes.\n */\n async generateMissingJsonSchemas(\n currentPaths: OpenAPIV3.PathsObject,\n currentJsonSchemas: Record<string, any>,\n arkosConfig: ArkosConfig\n ): Promise<Record<string, any>> {\n const missingSchemas: Record<string, any> = {};\n\n const schemaRefsWithContext = this.extractPathSchemaRefs(currentPaths);\n\n const modelActions = new Map<string, Set<string>>();\n\n for (const [ref, context] of schemaRefsWithContext) {\n const schemaName = this.getSchemaNameFromRef(ref);\n if (!schemaName) continue;\n\n if (currentJsonSchemas[schemaName]) continue;\n\n if (!schemaName.includes(\"ModelSchema\") && !schemaName.includes(\"Schema\"))\n continue;\n\n let modelName: string | null = null;\n let action: string | null = null;\n\n if (context.operationId) {\n modelName = this.extractModelNameFromOperationId(context.operationId);\n action = this.extractActionFromOperationId(context.operationId);\n }\n\n if (!modelName || !action) {\n modelName = modelName || this.extractModelNameFromSchemaRef(ref);\n action = action || this.extractActionFromSchemaRef(ref);\n }\n\n if (modelName && action) {\n if (!modelActions.has(modelName))\n modelActions.set(modelName, new Set());\n\n modelActions.get(modelName)!.add(action);\n }\n }\n\n // Generate schemas for each model\n for (const [modelName, actions] of modelActions) {\n try {\n const actionsArray = Array.from(actions) as any[];\n\n const generatedSchemas =\n await PrismaJsonSchemaGenerator.generateModelSchemas({\n modelName,\n arkosConfig,\n schemasToGenerate: actionsArray,\n });\n\n Object.entries(generatedSchemas).forEach(([key, schema]) => {\n // The enhanced generator might use different naming conventions\n // We need to map them to match what's expected in the $refs\n let mappedKey = key;\n const authModuleModel = [\"auth\", \"login\", \"me\", \"password\", \"me\"];\n\n if (authModuleModel.includes(modelName.toLowerCase())) {\n if (key === \"LoginSchema\") mappedKey = \"LoginSchema\";\n else if (key === \"SignupSchema\") mappedKey = \"SignupSchema\";\n else if (key === \"GetMeSchema\") mappedKey = \"GetMeSchema\";\n else if (key === \"UpdateMeSchema\") mappedKey = \"UpdateMeSchema\";\n else if (key === \"UpdatePasswordSchema\")\n mappedKey = \"UpdatePasswordSchema\";\n } else {\n if (key.includes(\"ModelSchema\")) mappedKey = key;\n else mappedKey = `${key}ModelSchema`;\n }\n\n missingSchemas[mappedKey] = schema;\n });\n } catch (error) {\n // console.warn(\n // `Failed to generate schemas for model ${modelName}:`,\n // error\n // );\n }\n }\n\n return missingSchemas;\n }\n\n /**\n * Legacy method - extract action type from schema reference (kept for backward compatibility)\n */\n private extractActionFromSchemaRef(schemaRef: string): string | null {\n if (schemaRef.includes(\"CreateMany\")) return \"createMany\";\n if (schemaRef.includes(\"Create\")) return \"createOne\";\n if (schemaRef.includes(\"UpdateMany\")) return \"updateMany\";\n if (\n schemaRef.includes(\"Update\") &&\n !schemaRef.includes(\"UpdateMe\") &&\n !schemaRef.includes(\"UpdatePassword\")\n )\n return \"updateOne\";\n if (schemaRef.includes(\"FindMany\")) return \"findMany\";\n if (schemaRef.includes(\"FindOne\")) return \"findOne\";\n if (schemaRef.includes(\"Login\")) return \"login\";\n if (schemaRef.includes(\"Signup\")) return \"signup\";\n if (schemaRef.includes(\"GetMe\")) return \"getMe\";\n if (schemaRef.includes(\"UpdateMe\")) return \"updateMe\";\n if (schemaRef.includes(\"UpdatePassword\")) return \"updatePassword\";\n\n return null;\n }\n\n /**\n * Debug method to analyze what schemas are missing with enhanced context\n */\n analyzeMissingSchemas(\n currentPaths: OpenAPIV3.PathsObject,\n currentJsonSchemas: Record<string, any>\n ): {\n allRefs: Array<{ ref: string; context: any }>;\n missingRefs: Array<{ ref: string; context: any }>;\n existingRefs: Array<{ ref: string; context: any }>;\n modelActions: {\n model: string;\n action: string;\n ref: string;\n operationId?: string;\n }[];\n } {\n const schemaRefsWithContext = this.extractPathSchemaRefs(currentPaths);\n\n const allRefs: Array<{ ref: string; context: any }> = [];\n const missingRefs: Array<{ ref: string; context: any }> = [];\n const existingRefs: Array<{ ref: string; context: any }> = [];\n const modelActions: {\n model: string;\n action: string;\n ref: string;\n operationId?: string;\n }[] = [];\n\n for (const [ref, context] of schemaRefsWithContext) {\n const refWithContext = { ref, context };\n allRefs.push(refWithContext);\n\n const schemaName = this.getSchemaNameFromRef(ref);\n if (!schemaName) continue;\n\n if (currentJsonSchemas[schemaName]) {\n existingRefs.push(refWithContext);\n } else {\n missingRefs.push(refWithContext);\n\n let modelName: string | null = null;\n let action: string | null = null;\n\n // Try operationId first\n if (context.operationId) {\n modelName = this.extractModelNameFromOperationId(context.operationId);\n action = this.extractActionFromOperationId(context.operationId);\n }\n\n // Fallback to schema ref\n if (!modelName || !action) {\n modelName = modelName || this.extractModelNameFromSchemaRef(ref);\n action = action || this.extractActionFromSchemaRef(ref);\n }\n\n if (modelName && action) {\n modelActions.push({\n model: modelName,\n action,\n ref,\n operationId: context.operationId,\n });\n }\n }\n }\n\n return {\n allRefs,\n missingRefs,\n existingRefs,\n modelActions,\n };\n }\n}\n\nconst missingJsonSchemaGenerator = new MissingJsonSchemasGenerator();\n\nexport default missingJsonSchemaGenerator;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"swagger.router.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/swagger/utils/helpers/swagger.router.helpers.ts"],"names":[],"mappings":";;;;;AAoBA,8EAeC;AAED,4DAwBC;AAED,oCAKC;AAED,oCAoCC;AAED,wDA+BC;AAUD,4DAWC;AA/JD,qDAAkE;AAElE,iFAA0E;AAC1E,kHAAsF;AACtF,mHAAwF;AACxF,0HAAmH;AACnH,wGAAkG;AAClG,4IAAoI;AACpI,iKAAmI;AACnI,kEAA0C;AAC1C,yGAA+E;AAC/E,qEAG0C;AAKnC,KAAK,UAAU,iCAAiC,CACrD,WAAwB;IAExB,QAAQ,WAAW,EAAE,OAAQ,CAAC,IAAI,EAAE,CAAC;QACnC,KAAK,QAAQ;YACX,OAAO,MAAM,IAAA,wDAAyB,EAAC,WAAW,CAAC,CAAC;QACtD,KAAK,iBAAiB;YACpB,OAAO,MAAM,IAAA,yEAAiC,GAAE,CAAC;QACnD,KAAK,KAAK;YACR,OAAO,MAAM,IAAA,mCAAsB,GAAE,CAAC;QACxC;YACE,MAAM,KAAK,CACT,wGAAwG,CACzG,CAAC;IACN,CAAC;AACH,CAAC;AAED,SAAgB,wBAAwB,CACtC,IAAY,EACZ,SAAiB,EACjB,MAAwB;IAExB,MAAM,eAAe,GAAG,IAAA,kBAAU,EAAC,SAAS,CAAC,CAAC;IAE9C,MAAM,GAAG,GAA2B;QAClC,KAAK,EAAE,eAAe;QACtB,MAAM,EAAE,SAAS,eAAe,EAAE;QAClC,UAAU,EAAE,aAAa,eAAe,EAAE;QAC1C,OAAO,EAAE,UAAU,eAAe,EAAE;QACpC,QAAQ,EAAE,WAAW,eAAe,EAAE;QACtC,MAAM,EAAE,SAAS,eAAe,EAAE;QAClC,UAAU,EAAE,aAAa,eAAe,EAAE;QAC1C,KAAK,EAAE,QAAQ,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elCase, pascalCase } from \"../../../../exports/utils\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport { getSystemJsonSchemaPaths } from \"./get-system-json-schema-paths\";\nimport getAuthenticationJsonSchemaPaths from \"./get-authentication-json-schema-paths\";\nimport generateZodJsonSchemas from \"./json-schema-generators/generate-zod-json-schemas\";\nimport { generateClassValidatorJsonSchemas } from \"./json-schema-generators/generate-class-validator-json-schemas\";\nimport { generatePrismaJsonSchemas } from \"./json-schema-generators/generate-prisma-json-schemas\";\nimport { generatePrismaModelMainRoutesPaths } from \"./json-schema-generators/prisma-models/generate-prisma-model-main-routes-paths\";\nimport generatePrismaModelParentRoutePaths from \"./json-schema-generators/prisma-models/generate-prisma-model-parent-routes-paths\";\nimport sheu from \"../../../../utils/sheu\";\nimport prismaSchemaParser from \"../../../../utils/prisma/prisma-schema-parser\";\nimport {\n getModuleComponents,\n ValidationFileMappingKey,\n} from \"../../../../utils/dynamic-loader\";\n\n/**\n * Helps choosing the right json schemas according to swagger configurations\n */\nexport async function getOpenAPIJsonSchemasByConfigMode(\n arkosConfig: ArkosConfig\n) {\n switch (arkosConfig?.swagger!.mode) {\n case \"prisma\":\n return await generatePrismaJsonSchemas(arkosConfig);\n case \"class-validator\":\n return await generateClassValidatorJsonSchemas();\n case \"zod\":\n return await generateZodJsonSchemas();\n default:\n throw Error(\n \"Unknown mode for auto documentation, supported values are prisma, class-validator, zod or json-schemas\"\n );\n }\n}\n\nexport function getCorrectJsonSchemaName(\n type: string,\n modelName: string,\n suffix: \"Dto\" | \"Schema\"\n): string {\n const pascalModelName = pascalCase(modelName);\n\n const map: Record<string, string> = {\n model: pascalModelName,\n create: `Create${pascalModelName}`,\n createMany: `CreateMany${pascalModelName}`,\n findOne: `FindOne${pascalModelName}`,\n findMany: `FindMany${pascalModelName}`,\n update: `Update${pascalModelName}`,\n updateMany: `UpdateMany${pascalModelName}`,\n query: `Query${pascalModelName}`,\n login: \"Login\",\n signup: \"Signup\",\n updateMe: \"UpdateMe\",\n updatePassword: \"UpdatePassword\",\n };\n\n const baseName = map[type] ?? pascalCase(type);\n return `${baseName}${suffix}`;\n}\n\nexport function kebabToHuman(kebabStr: string): string {\n return kebabStr\n .split(\"-\")\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join(\" \");\n}\n\nexport function getSchemaRef(\n schemaName: string,\n mode: \"prisma\" | \"zod\" | \"class-validator\"\n): string {\n schemaName = pascalCase(schemaName);\n // Check if schemaName (lowercase) contains any of the specified keywords\n const specialCases = [\n \"getme\",\n \"updateme\",\n \"login\",\n \"signup\",\n \"updatepassword\",\n \"password\",\n \"me\",\n ];\n const isSpecialCase = specialCases.some(\n (keyword) => keyword === schemaName.toLowerCase()\n );\n\n // If it's a special case and mode is prisma, return zod style instead\n if (isSpecialCase && mode === \"prisma\")\n return `#/components/schemas/${schemaName}Schema`;\n\n switch (mode) {\n case \"prisma\":\n return `#/components/schemas/${schemaName}ModelSchema`;\n case \"zod\":\n return `#/components/schemas/${schemaName}Schema`;\n case \"class-validator\":\n return `#/components/schemas/${schemaName}Dto`;\n default:\n sheu.error(\n `Unknown Arkos.js swagger documentation provided, available options are prisma, zod or class-validator but received ${mode}`\n );\n return \"\";\n }\n}\n\nexport async function generatePathsForModels(\n arkosConfig: ArkosConfig\n): Promise<OpenAPIV3.PathsObject> {\n const swaggerConfig = arkosConfig?.swagger;\n\n if (!swaggerConfig) return {};\n\n let paths: OpenAPIV3.PathsObject = {};\n const models = prismaSchemaParser.getModelsAsArrayOfStrings();\n\n for (const model of models) {\n // Generate main routes\n await generatePrismaModelMainRoutesPaths(model, paths, arkosConfig);\n\n // Generate parent routes if configured\n await generatePrismaModelParentRoutePaths(model, paths, arkosConfig);\n }\n\n // Add system routes\n paths = {\n ...paths,\n ...getSystemJsonSchemaPaths(),\n };\n\n // Add authentication routes\n paths = {\n ...paths,\n ...((await getAuthenticationJsonSchemaPaths(arkosConfig)) || {}),\n };\n\n return paths;\n}\n\n/**\n * Helps in finding out whether a given dto/schema file exits under the user project according to the validation arkos configuration.\n *\n * @param action {ValidationFileMappingKey} - the action of the dto, e.g: create, findMany.\n * @param modelName {string} - the model to be checked\n * @param arkosConfig {ArkosConfig} - the arkos.js configuration\n * @returns boolean\n */\nexport async function localValidatorFileExists(\n action: ValidationFileMappingKey,\n modelName: string,\n arkosConfig: ArkosConfig\n) {\n if (arkosConfig?.swagger?.mode === \"prisma\") return false;\n const moduleComponents = getModuleComponents(modelName) as any;\n\n return !!moduleComponents?.[\n arkosConfig.validation?.resolver === \"zod\" ? \"schemas\" : \"dtos\"\n ]?.[camelCase(action)];\n}\n"]}
1
+ {"version":3,"file":"swagger.router.helpers.js","sourceRoot":"","sources":["../../../../../../src/modules/swagger/utils/helpers/swagger.router.helpers.ts"],"names":[],"mappings":";;;;;AAoBA,8EAeC;AAED,4DAwBC;AAED,oCAKC;AAED,oCAkCC;AAED,wDA2BC;AAUD,4DAWC;AAzJD,qDAAkE;AAElE,iFAA0E;AAC1E,kHAAsF;AACtF,mHAAwF;AACxF,0HAAmH;AACnH,wGAAkG;AAClG,4IAAoI;AACpI,iKAAmI;AACnI,kEAA0C;AAC1C,yGAA+E;AAC/E,qEAG0C;AAKnC,KAAK,UAAU,iCAAiC,CACrD,WAAwB;IAExB,QAAQ,WAAW,EAAE,OAAQ,CAAC,IAAI,EAAE,CAAC;QACnC,KAAK,QAAQ;YACX,OAAO,MAAM,IAAA,wDAAyB,EAAC,WAAW,CAAC,CAAC;QACtD,KAAK,iBAAiB;YACpB,OAAO,MAAM,IAAA,yEAAiC,GAAE,CAAC;QACnD,KAAK,KAAK;YACR,OAAO,MAAM,IAAA,mCAAsB,GAAE,CAAC;QACxC;YACE,MAAM,KAAK,CACT,wGAAwG,CACzG,CAAC;IACN,CAAC;AACH,CAAC;AAED,SAAgB,wBAAwB,CACtC,IAAY,EACZ,SAAiB,EACjB,MAAwB;IAExB,MAAM,eAAe,GAAG,IAAA,kBAAU,EAAC,SAAS,CAAC,CAAC;IAE9C,MAAM,G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,EAAC,SAAS,CAAQ,CAAC;IAE/D,OAAO,CAAC,CAAC,gBAAgB,EAAE,CACzB,WAAW,CAAC,UAAU,EAAE,QAAQ,KAAK,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CAChE,EAAE,CAAC,IAAA,iBAAS,EAAC,MAAM,CAAC,CAAC,CAAC;AACzB,CAAC","sourcesContent":["import { ArkosConfig } from \"../../../../exports\";\nimport { camelCase, pascalCase } from \"../../../../exports/utils\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport { getSystemJsonSchemaPaths } from \"./get-system-json-schema-paths\";\nimport getAuthenticationJsonSchemaPaths from \"./get-authentication-json-schema-paths\";\nimport generateZodJsonSchemas from \"./json-schema-generators/generate-zod-json-schemas\";\nimport { generateClassValidatorJsonSchemas } from \"./json-schema-generators/generate-class-validator-json-schemas\";\nimport { generatePrismaJsonSchemas } from \"./json-schema-generators/generate-prisma-json-schemas\";\nimport { generatePrismaModelMainRoutesPaths } from \"./json-schema-generators/prisma-models/generate-prisma-model-main-routes-paths\";\nimport generatePrismaModelParentRoutePaths from \"./json-schema-generators/prisma-models/generate-prisma-model-parent-routes-paths\";\nimport sheu from \"../../../../utils/sheu\";\nimport prismaSchemaParser from \"../../../../utils/prisma/prisma-schema-parser\";\nimport {\n getModuleComponents,\n ValidationFileMappingKey,\n} from \"../../../../utils/dynamic-loader\";\n\n/**\n * Helps choosing the right json schemas according to swagger configurations\n */\nexport async function getOpenAPIJsonSchemasByConfigMode(\n arkosConfig: ArkosConfig\n) {\n switch (arkosConfig?.swagger!.mode) {\n case \"prisma\":\n return await generatePrismaJsonSchemas(arkosConfig);\n case \"class-validator\":\n return await generateClassValidatorJsonSchemas();\n case \"zod\":\n return await generateZodJsonSchemas();\n default:\n throw Error(\n \"Unknown mode for auto documentation, supported values are prisma, class-validator, zod or json-schemas\"\n );\n }\n}\n\nexport function getCorrectJsonSchemaName(\n type: string,\n modelName: string,\n suffix: \"Dto\" | \"Schema\"\n): string {\n const pascalModelName = pascalCase(modelName);\n\n const map: Record<string, string> = {\n model: pascalModelName,\n create: `Create${pascalModelName}`,\n createMany: `CreateMany${pascalModelName}`,\n findOne: `FindOne${pascalModelName}`,\n findMany: `FindMany${pascalModelName}`,\n update: `Update${pascalModelName}`,\n updateMany: `UpdateMany${pascalModelName}`,\n query: `Query${pascalModelName}`,\n login: \"Login\",\n signup: \"Signup\",\n updateMe: \"UpdateMe\",\n updatePassword: \"UpdatePassword\",\n };\n\n const baseName = map[type] ?? pascalCase(type);\n return `${baseName}${suffix}`;\n}\n\nexport function kebabToHuman(kebabStr: string): string {\n return kebabStr\n .split(\"-\")\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join(\" \");\n}\n\nexport function getSchemaRef(\n schemaName: string,\n mode: \"prisma\" | \"zod\" | \"class-validator\"\n): string {\n schemaName = pascalCase(schemaName);\n const specialCases = [\n \"getme\",\n \"updateme\",\n \"login\",\n \"signup\",\n \"updatepassword\",\n \"password\",\n \"me\",\n ];\n const isSpecialCase = specialCases.some(\n (keyword) => keyword === schemaName.toLowerCase()\n );\n\n if (isSpecialCase && mode === \"prisma\")\n return `#/components/schemas/${schemaName}Schema`;\n\n switch (mode) {\n case \"prisma\":\n return `#/components/schemas/${schemaName}ModelSchema`;\n case \"zod\":\n return `#/components/schemas/${schemaName}Schema`;\n case \"class-validator\":\n return `#/components/schemas/${schemaName}Dto`;\n default:\n sheu.error(\n `Unknown Arkos.js swagger documentation provided, available options are prisma, zod or class-validator but received ${mode}`\n );\n return \"\";\n }\n}\n\nexport async function generatePathsForModels(\n arkosConfig: ArkosConfig\n): Promise<OpenAPIV3.PathsObject> {\n const swaggerConfig = arkosConfig?.swagger;\n\n if (!swaggerConfig) return {};\n\n let paths: OpenAPIV3.PathsObject = {};\n const models = prismaSchemaParser.getModelsAsArrayOfStrings();\n\n for (const model of models) {\n await generatePrismaModelMainRoutesPaths(model, paths, arkosConfig);\n\n await generatePrismaModelParentRoutePaths(model, paths, arkosConfig);\n }\n\n paths = {\n ...paths,\n ...getSystemJsonSchemaPaths(),\n };\n\n paths = {\n ...paths,\n ...((await getAuthenticationJsonSchemaPaths(arkosConfig)) || {}),\n };\n\n return paths;\n}\n\n/**\n * Helps in finding out whether a given dto/schema file exits under the user project according to the validation arkos configuration.\n *\n * @param action {ValidationFileMappingKey} - the action of the dto, e.g: create, findMany.\n * @param modelName {string} - the model to be checked\n * @param arkosConfig {ArkosConfig} - the arkos.js configuration\n * @returns boolean\n */\nexport async function localValidatorFileExists(\n action: ValidationFileMappingKey,\n modelName: string,\n arkosConfig: ArkosConfig\n) {\n if (arkosConfig?.swagger?.mode === \"prisma\") return false;\n const moduleComponents = getModuleComponents(modelName) as any;\n\n return !!moduleComponents?.[\n arkosConfig.validation?.resolver === \"zod\" ? \"schemas\" : \"dtos\"\n ]?.[camelCase(action)];\n}\n"]}
@@ -19,6 +19,6 @@ function killServerChildProcess() {
19
19
  (0, start_1.killProductionServerChildProcess)();
20
20
  }
21
21
  function getVersion() {
22
- return "1.3.8-canary.9";
22
+ return "1.3.9-canary.2";
23
23
  }
24
24
  //# sourceMappingURL=cli.helpers.js.map
@@ -125,18 +125,7 @@ class PrismaJsonSchemaGenerator {
125
125
  if (schemasToGenerate.includes("updateMany") &&
126
126
  !this.isEndpointDisabled("updateMany", routerConfig) &&
127
127
  !(await (0, swagger_router_helpers_1.localValidatorFileExists)("updateMany", modelName, arkosConfig))) {
128
- const baseSchemaKey = await ensureBaseSchemaReference("Update", modelName);
129
- schemas[`UpdateMany${modelName}ModelSchema`] = {
130
- type: "object",
131
- properties: {
132
- data: {
133
- type: "object",
134
- $ref: `#/components/schemas/${baseSchemaKey}`,
135
- },
136
- where: { type: "object" },
137
- },
138
- required: ["data"],
139
- };
128
+ schemas[`UpdateMany${modelName}ModelSchema`] = this.generateUpdateSchema(model, this.resolvePrismaQueryOptions(queryOptions, "updateOne"));
140
129
  }
141
130
  if (schemasToGenerate.includes("findOne") &&
142
131
  !this.isEndpointDisabled("findOne", routerConfig) &&