arkos 1.6.5-beta → 1.6.6-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/cjs/exports/index.js +3 -1
  2. package/dist/cjs/exports/index.js.map +1 -1
  3. package/dist/cjs/modules/email/email.service.js +13 -7
  4. package/dist/cjs/modules/email/email.service.js.map +1 -1
  5. package/dist/cjs/modules/error-handler/error-handler.controller.js +4 -3
  6. package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
  7. package/dist/cjs/modules/file-upload/file-upload.router.js +9 -2
  8. package/dist/cjs/modules/file-upload/file-upload.router.js.map +1 -1
  9. package/dist/cjs/modules/swagger/swagger.router.js +40 -9
  10. package/dist/cjs/modules/swagger/swagger.router.js.map +1 -1
  11. package/dist/cjs/modules/swagger/utils/helpers/openapi-schema-converter.js +4 -2
  12. package/dist/cjs/modules/swagger/utils/helpers/openapi-schema-converter.js.map +1 -1
  13. package/dist/cjs/types/arkos.js.map +1 -1
  14. package/dist/cjs/types/index.js.map +1 -1
  15. package/dist/cjs/types/new-arkos-config.js.map +1 -1
  16. package/dist/cjs/types/upload.js +3 -0
  17. package/dist/cjs/types/upload.js.map +1 -0
  18. package/dist/cjs/utils/arkos-router/arkos-router-openapi-manager.js +3 -9
  19. package/dist/cjs/utils/arkos-router/arkos-router-openapi-manager.js.map +1 -1
  20. package/dist/cjs/utils/arkos-router/index.js +15 -3
  21. package/dist/cjs/utils/arkos-router/index.js.map +1 -1
  22. package/dist/cjs/utils/arkos-router/types/index.js.map +1 -1
  23. package/dist/cjs/utils/arkos-router/utils/helpers/upload-manager.js +5 -0
  24. package/dist/cjs/utils/arkos-router/utils/helpers/upload-manager.js.map +1 -1
  25. package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
  26. package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js +53 -17
  27. package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js.map +1 -1
  28. package/dist/cjs/utils/cli/utils/template-generator/templates/zod-schema-generator.js +18 -18
  29. package/dist/cjs/utils/cli/utils/template-generator/templates/zod-schema-generator.js.map +1 -1
  30. package/dist/cjs/utils/features/api.features.js.map +1 -1
  31. package/dist/cjs/utils/helpers/arkos-config.helpers.js.map +1 -1
  32. package/dist/esm/exports/index.js +2 -1
  33. package/dist/esm/exports/index.js.map +1 -1
  34. package/dist/esm/modules/email/email.service.js +13 -7
  35. package/dist/esm/modules/email/email.service.js.map +1 -1
  36. package/dist/esm/modules/error-handler/error-handler.controller.js +4 -3
  37. package/dist/esm/modules/error-handler/error-handler.controller.js.map +1 -1
  38. package/dist/esm/modules/file-upload/file-upload.router.js +9 -2
  39. package/dist/esm/modules/file-upload/file-upload.router.js.map +1 -1
  40. package/dist/esm/modules/swagger/swagger.router.js +7 -9
  41. package/dist/esm/modules/swagger/swagger.router.js.map +1 -1
  42. package/dist/esm/modules/swagger/utils/helpers/openapi-schema-converter.js +4 -2
  43. package/dist/esm/modules/swagger/utils/helpers/openapi-schema-converter.js.map +1 -1
  44. package/dist/esm/types/arkos.js.map +1 -1
  45. package/dist/esm/types/index.js.map +1 -1
  46. package/dist/esm/types/new-arkos-config.js.map +1 -1
  47. package/dist/esm/types/upload.js +2 -0
  48. package/dist/esm/types/upload.js.map +1 -0
  49. package/dist/esm/utils/arkos-router/arkos-router-openapi-manager.js +3 -9
  50. package/dist/esm/utils/arkos-router/arkos-router-openapi-manager.js.map +1 -1
  51. package/dist/esm/utils/arkos-router/index.js +15 -3
  52. package/dist/esm/utils/arkos-router/index.js.map +1 -1
  53. package/dist/esm/utils/arkos-router/types/index.js.map +1 -1
  54. package/dist/esm/utils/arkos-router/utils/helpers/upload-manager.js +5 -0
  55. package/dist/esm/utils/arkos-router/utils/helpers/upload-manager.js.map +1 -1
  56. package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
  57. package/dist/esm/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js +53 -17
  58. package/dist/esm/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js.map +1 -1
  59. package/dist/esm/utils/cli/utils/template-generator/templates/zod-schema-generator.js +18 -18
  60. package/dist/esm/utils/cli/utils/template-generator/templates/zod-schema-generator.js.map +1 -1
  61. package/dist/esm/utils/features/api.features.js.map +1 -1
  62. package/dist/esm/utils/helpers/arkos-config.helpers.js.map +1 -1
  63. package/dist/types/exports/index.d.ts +3 -1
  64. package/dist/types/types/arkos.d.ts +1 -1
  65. package/dist/types/types/index.d.ts +5 -5
  66. package/dist/types/types/new-arkos-config.d.ts +1 -1
  67. package/dist/types/types/upload.d.ts +10 -0
  68. package/dist/types/utils/arkos-router/types/index.d.ts +15 -14
  69. package/dist/types/utils/arkos-router/utils/helpers/upload-manager.d.ts +1 -0
  70. package/dist/types/utils/cli/utils/template-generator/templates/class-validator-dto-generator.d.ts +7 -0
  71. package/dist/types/utils/features/api.features.d.ts +1 -2
  72. package/dist/types/utils/helpers/arkos-config.helpers.d.ts +5 -0
  73. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/types/index.ts"],"names":[],"mappings":";;;AA8JA,IAAY,oBAKX;AALD,WAAY,oBAAoB;IAC9B,yCAAiB,CAAA;IACjB,qCAAa,CAAA;IACb,yCAAiB,CAAA;IACjB,yCAAiB,CAAA;AACnB,CAAC,EALW,oBAAoB,oCAApB,oBAAoB,QAK/B","sourcesContent":["import { NextFunction, Response, Request } from \"express\";\nimport { PrismaModels } from \"../generated\";\n\n/**\n * Type definition for authentication-related Prisma query operations\n * @template T - The Prisma model delegate type\n */\nexport type AuthPrismaQueryOptions<T extends Record<string, any>> = {\n // User profile endpoints\n /**\n * Options for retrieving the current authenticated user's profile\n */\n getMe?: Partial<Parameters<T[\"findUnique\"]>[0]>;\n /**\n * Options for updating the current authenticated user's profile\n */\n updateMe?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Options for soft deleting or deactivating the current authenticated user's account\n */\n deleteMe?: Partial<Parameters<T[\"update\"]>[0]>;\n // Authentication endpoints\n /**\n * Options for user login authentication queries\n */\n login?: Partial<Parameters<T[\"findFirst\"]>[0]>;\n /**\n * Options for user registration and account creation\n */\n signup?: Partial<Parameters<T[\"create\"]>[0]>;\n /**\n * Options for updating the current authenticated user's password\n */\n updatePassword?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Options for finding multiple auth actions\n */\n findManyAuthAction?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * Options for finding a single auth action\n */\n findOneAuthAction?: Partial<Parameters<T[\"findFirst\"]>[0]>;\n};\n\n/**\n * Base Prisma query options for standard CRUD operations\n * @template T - The Prisma model delegate type\n */\ntype BasePrismaQueryOptions<T extends Record<string, any>> = {\n /**\n * @deprecated Use `global` instead for general query options\n */\n queryOptions?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * Global query options that can be used for all operations\n * Replaces the deprecated queryOptions\n */\n global?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * General find options for findMany and findOne operations\n */\n find?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * General create options for createOne and createMany operations\n */\n create?: Partial<Parameters<T[\"create\"]>[0]>;\n /**\n * General update options for updateOne and updateMany operations\n */\n update?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * General delete options for deleteOne and deleteMany operations\n */\n delete?: Partial<Parameters<T[\"delete\"]>[0]>;\n /**\n * General save options for createOne, createMany, updateOne, updateMany operations\n */\n save?:\n | Partial<Parameters<T[\"create\"]>[0]>\n | Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Save options for single record operations (createOne, updateOne)\n */\n saveOne?:\n | Partial<Parameters<T[\"create\"]>[0]>\n | Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Save options for multiple record operations (createMany, updateMany)\n */\n saveMany?:\n | Partial<Parameters<T[\"createMany\"]>[0]>\n | Partial<Parameters<T[\"updateMany\"]>[0]>;\n /**\n * Options for finding a single record (first match)\n */\n findOne?: Partial<Parameters<T[\"findFirst\"]>[0]>;\n /**\n * Options for finding multiple records\n */\n findMany?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * Options for creating a single record\n */\n createOne?: Partial<Parameters<T[\"create\"]>[0]>;\n /**\n * Options for creating multiple records\n */\n createMany?: Partial<Parameters<T[\"createMany\"]>[0]>;\n /**\n * Options for updating a single record\n */\n updateOne?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Options for updating multiple records\n */\n updateMany?: Partial<Parameters<T[\"updateMany\"]>[0]>;\n /**\n * Options for deleting a single record\n */\n deleteOne?: Partial<Parameters<T[\"delete\"]>[0]>;\n /**\n * Options for deleting multiple records\n */\n deleteMany?: Partial<Parameters<T[\"deleteMany\"]>[0]>;\n};\n\n/**\n * Type definition for Prisma query operations with flexible options\n * Conditionally provides auth-specific options when ModelName is \"auth\"\n * @template T - The Prisma model delegate type\n * @template ModelName - The model name (defaults to string for standard models)\n */\nexport type PrismaQueryOptions<\n T extends Record<string, any>,\n ModelName extends string = string,\n> = ModelName extends \"auth\"\n ? AuthPrismaQueryOptions<T>\n : BasePrismaQueryOptions<T>;\n\nexport interface UserRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n roleId: string;\n role: AuthRole;\n user: User;\n userId: string;\n}\n\nexport interface AuthRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n name: string;\n permissions: AuthPermission[];\n userRoles: UserRole[];\n}\n\nexport enum AuthPermissionAction {\n Create = \"Create\",\n View = \"View\",\n Update = \"Update\",\n Delete = \"Delete\",\n}\n\nexport interface AuthPermission {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n resource: string;\n action: AuthPermissionAction;\n roleId: string;\n role: AuthRole;\n}\n\nexport interface BaseUser extends Record<string, any> {\n id: string;\n isSuperUser: boolean;\n password: string;\n passwordChangedAt?: Date;\n deletedSelfAccountAt: Date;\n isActive: boolean;\n}\n\ntype UserModelPayload =\n PrismaModels<{}> extends { user: infer U }\n ? U extends { GetPayload: infer P }\n ? P\n : never\n : never;\n\nexport type User = UserModelPayload extends never ? BaseUser : UserModelPayload;\n\nexport interface ArkosRequest<\n P extends Record<string, any> = any,\n ResBody = any,\n ReqBody = any,\n Query extends Record<string, any> = any,\n> extends Request<P, ResBody, ReqBody, Query> {\n // /**\n // * Request signals used to control Arkos's built-in request handling pipeline.\n // *\n // * @since v1.6.0-beta\n // */\n // signals?: {\n // /**\n // * When set to `true` in a `before` hook, Arkos skips its built-in logic for the current pipeline step (e.g. CRUD, authentication, authorization).\n // * Automatically reset to `false` after the step completes.\n // *\n // * @example\n // * ```ts\n // * before: (req, res, next) => {\n // * req.user = myCustomAuth(req);\n // * req.signals.skip = true;\n // * next();\n // * }\n // * ```\n // */\n // skip?: boolean;\n // };\n /**\n * Authenticated user\n */\n user?: User;\n /**\n * Single uploaded file, populated when using `multer.single()`\n */\n file?: Express.Multer.File;\n /**\n * Uploaded files, populated when using `multer.array()` or `multer.fields()`.\n *\n */\n files?: Express.Multer.File[] | Record<string, Express.Multer.File[]>;\n\n /**\n * Fields to include in relational queries\n */\n relationFields?: Record<string, boolean>;\n\n /**\n * Prisma include options for related data\n */\n include?: Record<string, any>;\n\n /**\n * Data to be sent in the response\n */\n responseData?: Record<string, any> | null;\n\n /**\n * Additional context data\n */\n additionalData?: Record<string, any> | null;\n\n /**\n * HTTP status code for the response\n */\n responseStatus?: number;\n\n /**\n * Typed request body\n */\n body: ReqBody;\n\n /**\n * Prisma query options (where, orderBy, select, etc.)\n */\n prismaQueryOptions?: Record<string, any>;\n\n /**\n * Typed query parameters\n */\n query: Query;\n\n /**\n * JWT token used in authentication process\n */\n accessToken?: string;\n\n /**\n * Query parameters after being handled and transformed by middleware\n */\n transformedQuery?: Record<string, any>;\n\n /**\n * Processed filters from APIFeatures.filters\n */\n filters?: Record<string, any>;\n\n /**\n * Name of the Prisma model being queried\n */\n modelName?: string;\n}\n\nexport interface ArkosResponse<\n ResBody = any,\n Locals extends Record<string, any> = Record<string, any>,\n> extends Response<ResBody, Locals> {}\n\nexport interface ArkosNextFunction extends NextFunction {}\n\nexport type ArkosRequestHandler<\n P extends Record<string, any> = any,\n ResBody = any,\n ReqBody = any,\n ReqQuery extends Record<string, any> = any,\n Locals extends Record<string, any> = Record<string, any>,\n> = (\n req: ArkosRequest<P, ResBody, ReqBody, ReqQuery>,\n res: ArkosResponse<ResBody, Locals>,\n next: ArkosNextFunction\n) => void | Promise<void>;\n\nexport type ArkosErrorRequestHandler<\n P extends Record<string, any> = any,\n ResBody = any,\n ReqBody = any,\n ReqQuery extends Record<string, any> = any,\n Locals extends Record<string, any> = Record<string, any>,\n> = (\n err: any,\n req: ArkosRequest<P, ResBody, ReqBody, ReqQuery>,\n res: ArkosResponse<ResBody, Locals>,\n next: ArkosNextFunction\n) => void | Promise<void>;\n\nexport type ArkosAnyRequestHandler<\n P extends Record<string, any> = any,\n ResBody = any,\n ReqBody = any,\n ReqQuery extends Record<string, any> = any,\n Locals extends Record<string, any> = Record<string, any>,\n> =\n | ArkosRequestHandler<P, ResBody, ReqBody, ReqQuery, Locals>\n | ArkosErrorRequestHandler<P, ResBody, ReqBody, ReqQuery, Locals>\n | Array<\n | ArkosRequestHandler<P, ResBody, ReqBody, ReqQuery, Locals>\n | ArkosErrorRequestHandler<P, ResBody, ReqBody, ReqQuery, Locals>\n >;\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/types/index.ts"],"names":[],"mappings":";;;AA+JA,IAAY,oBAKX;AALD,WAAY,oBAAoB;IAC9B,yCAAiB,CAAA;IACjB,qCAAa,CAAA;IACb,yCAAiB,CAAA;IACjB,yCAAiB,CAAA;AACnB,CAAC,EALW,oBAAoB,oCAApB,oBAAoB,QAK/B","sourcesContent":["import { NextFunction, Response, Request } from \"express\";\nimport { PrismaModels } from \"../generated\";\nimport { ArkosFile } from \"./upload\";\n\n/**\n * Type definition for authentication-related Prisma query operations\n * @template T - The Prisma model delegate type\n */\nexport type AuthPrismaQueryOptions<T extends Record<string, any>> = {\n // User profile endpoints\n /**\n * Options for retrieving the current authenticated user's profile\n */\n getMe?: Partial<Parameters<T[\"findUnique\"]>[0]>;\n /**\n * Options for updating the current authenticated user's profile\n */\n updateMe?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Options for soft deleting or deactivating the current authenticated user's account\n */\n deleteMe?: Partial<Parameters<T[\"update\"]>[0]>;\n // Authentication endpoints\n /**\n * Options for user login authentication queries\n */\n login?: Partial<Parameters<T[\"findFirst\"]>[0]>;\n /**\n * Options for user registration and account creation\n */\n signup?: Partial<Parameters<T[\"create\"]>[0]>;\n /**\n * Options for updating the current authenticated user's password\n */\n updatePassword?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Options for finding multiple auth actions\n */\n findManyAuthAction?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * Options for finding a single auth action\n */\n findOneAuthAction?: Partial<Parameters<T[\"findFirst\"]>[0]>;\n};\n\n/**\n * Base Prisma query options for standard CRUD operations\n * @template T - The Prisma model delegate type\n */\ntype BasePrismaQueryOptions<T extends Record<string, any>> = {\n /**\n * @deprecated Use `global` instead for general query options\n */\n queryOptions?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * Global query options that can be used for all operations\n * Replaces the deprecated queryOptions\n */\n global?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * General find options for findMany and findOne operations\n */\n find?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * General create options for createOne and createMany operations\n */\n create?: Partial<Parameters<T[\"create\"]>[0]>;\n /**\n * General update options for updateOne and updateMany operations\n */\n update?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * General delete options for deleteOne and deleteMany operations\n */\n delete?: Partial<Parameters<T[\"delete\"]>[0]>;\n /**\n * General save options for createOne, createMany, updateOne, updateMany operations\n */\n save?:\n | Partial<Parameters<T[\"create\"]>[0]>\n | Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Save options for single record operations (createOne, updateOne)\n */\n saveOne?:\n | Partial<Parameters<T[\"create\"]>[0]>\n | Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Save options for multiple record operations (createMany, updateMany)\n */\n saveMany?:\n | Partial<Parameters<T[\"createMany\"]>[0]>\n | Partial<Parameters<T[\"updateMany\"]>[0]>;\n /**\n * Options for finding a single record (first match)\n */\n findOne?: Partial<Parameters<T[\"findFirst\"]>[0]>;\n /**\n * Options for finding multiple records\n */\n findMany?: Partial<Parameters<T[\"findMany\"]>[0]>;\n /**\n * Options for creating a single record\n */\n createOne?: Partial<Parameters<T[\"create\"]>[0]>;\n /**\n * Options for creating multiple records\n */\n createMany?: Partial<Parameters<T[\"createMany\"]>[0]>;\n /**\n * Options for updating a single record\n */\n updateOne?: Partial<Parameters<T[\"update\"]>[0]>;\n /**\n * Options for updating multiple records\n */\n updateMany?: Partial<Parameters<T[\"updateMany\"]>[0]>;\n /**\n * Options for deleting a single record\n */\n deleteOne?: Partial<Parameters<T[\"delete\"]>[0]>;\n /**\n * Options for deleting multiple records\n */\n deleteMany?: Partial<Parameters<T[\"deleteMany\"]>[0]>;\n};\n\n/**\n * Type definition for Prisma query operations with flexible options\n * Conditionally provides auth-specific options when ModelName is \"auth\"\n * @template T - The Prisma model delegate type\n * @template ModelName - The model name (defaults to string for standard models)\n */\nexport type PrismaQueryOptions<\n T extends Record<string, any>,\n ModelName extends string = string,\n> = ModelName extends \"auth\"\n ? AuthPrismaQueryOptions<T>\n : BasePrismaQueryOptions<T>;\n\nexport interface UserRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n roleId: string;\n role: AuthRole;\n user: User;\n userId: string;\n}\n\nexport interface AuthRole {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n name: string;\n permissions: AuthPermission[];\n userRoles: UserRole[];\n}\n\nexport enum AuthPermissionAction {\n Create = \"Create\",\n View = \"View\",\n Update = \"Update\",\n Delete = \"Delete\",\n}\n\nexport interface AuthPermission {\n id: string;\n createdAt: Date;\n deletedAt?: Date;\n resource: string;\n action: AuthPermissionAction;\n roleId: string;\n role: AuthRole;\n}\n\nexport interface BaseUser extends Record<string, any> {\n id: string;\n isSuperUser: boolean;\n password: string;\n passwordChangedAt?: Date;\n deletedSelfAccountAt: Date;\n isActive: boolean;\n}\n\ntype UserModelPayload =\n PrismaModels<{}> extends { user: infer U }\n ? U extends { GetPayload: infer P }\n ? P\n : never\n : never;\n\nexport type User = UserModelPayload extends never ? BaseUser : UserModelPayload;\n\nexport interface ArkosRequest<\n P extends Record<string, any> = any,\n ResBody = any,\n ReqBody = any,\n Query extends Record<string, any> = any,\n> extends Request<P, ResBody, ReqBody, Query> {\n // /**\n // * Request signals used to control Arkos's built-in request handling pipeline.\n // *\n // * @since v1.6.0-beta\n // */\n // signals?: {\n // /**\n // * When set to `true` in a `before` hook, Arkos skips its built-in logic for the current pipeline step (e.g. CRUD, authentication, authorization).\n // * Automatically reset to `false` after the step completes.\n // *\n // * @example\n // * ```ts\n // * before: (req, res, next) => {\n // * req.user = myCustomAuth(req);\n // * req.signals.skip = true;\n // * next();\n // * }\n // * ```\n // */\n // skip?: boolean;\n // };\n /**\n * Authenticated user\n */\n user?: User;\n /**\n * Single uploaded file, populated when using `{ uploads: { type: \"single\" }}`\n */\n file?: ArkosFile;\n /**\n * Uploaded files, populated when using `{ uploads: { type: \"array\" }}` or `{ uploads: { type: \"fileds\" }}`.\n */\n files?: ArkosFile[] | Record<string, ArkosFile[]>;\n\n /**\n * Fields to include in relational queries\n */\n relationFields?: Record<string, boolean>;\n\n /**\n * Prisma include options for related data\n */\n include?: Record<string, any>;\n\n /**\n * Data to be sent in the response\n */\n responseData?: Record<string, any> | null;\n\n /**\n * Additional context data\n */\n additionalData?: Record<string, any> | null;\n\n /**\n * HTTP status code for the response\n */\n responseStatus?: number;\n\n /**\n * Typed request body\n */\n body: ReqBody;\n\n /**\n * Prisma query options (where, orderBy, select, etc.)\n */\n prismaQueryOptions?: Record<string, any>;\n\n /**\n * Typed query parameters\n */\n query: Query;\n\n /**\n * JWT token used in authentication process\n */\n accessToken?: string;\n\n /**\n * Query parameters after being handled and transformed by middleware\n */\n transformedQuery?: Record<string, any>;\n\n /**\n * Processed filters from APIFeatures.filters\n */\n filters?: Record<string, any>;\n\n /**\n * Name of the Prisma model being queried\n */\n modelName?: string;\n}\n\nexport interface ArkosResponse<\n ResBody = any,\n Locals extends Record<string, any> = Record<string, any>,\n> extends Response<ResBody, Locals> {}\n\nexport interface ArkosNextFunction extends NextFunction {}\n\nexport type ArkosRequestHandler<\n P extends Record<string, any> = any,\n ResBody = any,\n ReqBody = any,\n ReqQuery extends Record<string, any> = any,\n Locals extends Record<string, any> = Record<string, any>,\n> = (\n req: ArkosRequest<P, ResBody, ReqBody, ReqQuery>,\n res: ArkosResponse<ResBody, Locals>,\n next: ArkosNextFunction\n) => void | Promise<void>;\n\nexport type ArkosErrorRequestHandler<\n P extends Record<string, any> = any,\n ResBody = any,\n ReqBody = any,\n ReqQuery extends Record<string, any> = any,\n Locals extends Record<string, any> = Record<string, any>,\n> = (\n err: any,\n req: ArkosRequest<P, ResBody, ReqBody, ReqQuery>,\n res: ArkosResponse<ResBody, Locals>,\n next: ArkosNextFunction\n) => void | Promise<void>;\n\nexport type ArkosAnyRequestHandler<\n P extends Record<string, any> = any,\n ResBody = any,\n ReqBody = any,\n ReqQuery extends Record<string, any> = any,\n Locals extends Record<string, any> = Record<string, any>,\n> =\n | ArkosRequestHandler<P, ResBody, ReqBody, ReqQuery, Locals>\n | ArkosErrorRequestHandler<P, ResBody, ReqBody, ReqQuery, Locals>\n | Array<\n | ArkosRequestHandler<P, ResBody, ReqBody, ReqQuery, Locals>\n | ArkosErrorRequestHandler<P, ResBody, ReqBody, ReqQuery, Locals>\n >;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"new-arkos-config.js","sourceRoot":"","sources":["../../../src/types/new-arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import cors from \"cors\";\nimport express, { CookieOptions } from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport type { ApiReferenceConfiguration } from \"@scalar/express-api-reference\" with { \"resolution-mode\": \"import\" };\nimport nodemailer from \"nodemailer\";\nimport { ModuleComponents } from \"../utils/dynamic-loader\";\nimport { ArkosRequestHandler } from \".\";\nimport {\n AuthenticateHookHandler,\n AuthenticateAfterHookHandler,\n AuthenticateErrorHookHandler,\n AuthorizeHookHandler,\n AuthorizeAfterHookHandler,\n AuthorizeErrorHookHandler,\n} from \"./arkos-config/utils\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /**\n * Configuration for resolving your Arkos application's source files at runtime.\n *\n * @since 1.6.1-canary.2\n *\n */\n source?: {\n /**\n * The entry point file of your Arkos application, resolved at runtime.\n *\n * This should point to the file where `app.listen()` or `app.listen(server)`\n * is called to start the HTTP server.\n *\n * Supports both TypeScript and JavaScript projects.\n *\n * @type {string}\n *\n * @default \"src/app.ts\" (TypeScript) | \"src/app.js\" (JavaScript)\n *\n * @since 1.6.1-canary.2\n *\n * @example\n * ```ts\n * // TypeScript project\n * entryPoint: \"src/app.ts\"\n *\n * // JavaScript project\n * entryPoint: \"src/app.js\"\n *\n * // Custom path\n * entryPoint: \"src/server/main.ts\"\n * ```\n */\n entryPoint?: string;\n };\n /**\n * The global prefixer for the whole application\n *\n * @default \"/api\"\n */\n readonly globalPrefix?: string;\n /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for passing prisma query options.\n *\n * See more\n */\n allowDangerousPrismaQueryOptions?: boolean;\n };\n };\n /** Message you would like to send, as Json and 200 response when\n * ```curl\n * GET /api\n * ```\n *\n * ```json\n * { \"message\": \"Welcome to YourAppName\" }\n * ```\n *\n * default message is: Welcome to our Rest API generated by Arkos, find more about Arkos at www.arkosjs.com.\n *\n *\n * */\n welcomeMessage?: string;\n /**\n * Port where the application will run, can be set in 3 ways:\n *\n * 1. default is 8000\n * 2. PORT under environment variables (Lower precedence)\n * 3. this config option (Higher precedence)\n */\n port?: number | undefined;\n /**\n * Allows to listen on a different host than localhost only\n */\n host?: string;\n /**\n * Defines authentication related configurations, by default is undefined.\n *\n * See [www.arkosjs.com/docs/core-concepts/authentication/setup](https://www.arkosjs.com/docs/core-concepts/authentication/setup) for details.\n */\n authentication?: {\n /**\n * Lifecycle hooks for the built-in authentication and authorization pipeline.\n *\n * These hooks only apply to **auto-generated Arkos routes**. On custom routes using\n * `authService.authenticate` directly, chain them manually as standard middlewares.\n *\n * Hooks run as standard Express middlewares — call `next()` to continue or\n * `next(error)` to abort and forward to the global error handler.\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication/hooks}\n */\n hooks?: {\n authenticate?: {\n /**\n * Runs before JWT extraction and verification.\n *\n * @example\n * ```ts\n * before: ({ req, skip, action, resource, rule }) => {\n * req.authContext = { startedAt: Date.now() };\n * }\n * ```\n *\n * @example Skip core logic entirely (e.g. custom auth)\n * ```ts\n * before: ({ req, skip, action, resource, rule }) => {\n * req.user = myCustomAuth(req);\n * skip();\n * }\n * ```\n */\n before?: AuthenticateHookHandler | AuthenticateHookHandler[];\n\n /**\n * Runs after `req.user` has been set.\n *\n * @example\n * ```ts\n * after: ({ req }) => {\n * if (!req.user.hasChangedPassword) {\n * throw new AppError(\"Password change required.\", 403, \"PasswordChangeRequired\");\n * }\n * }\n * ```\n */\n after?: AuthenticateAfterHookHandler | AuthenticateAfterHookHandler[];\n\n /**\n * Runs when authentication throws — invalid token, expired token, user not found, etc.\n * Throw to forward to the global error handler, or call `skip()` to suppress and jump to `after` hooks.\n *\n * @example\n * ```ts\n * onError: ({ req, error, skip, action, resource, rule }) => {\n * console.warn(`Auth failed:`, error);\n * throw error;\n * }\n * ```\n *\n * @example Suppress error and continue\n * ```ts\n * onError: ({ req, skip, action, resource, rule }) => {\n * req.user = guestUser;\n * skip();\n * }\n * ```\n */\n onError?: AuthenticateErrorHookHandler | AuthenticateErrorHookHandler[];\n };\n\n authorize?: {\n /**\n * Runs before the role/permission check.\n *\n * @example\n * ```ts\n * before: ({ req }) => {\n * if (req.headers[\"x-elevated-access\"] === process.env.ELEVATION_KEY) {\n * req.user.role = \"admin\";\n * }\n * }\n * ```\n *\n * @example Skip permission check entirely\n * ```ts\n * before: ({ req, skip, action, resource, rule }) => {\n * req.user.role = myCustomRoleResolver(req);\n * skip();\n * }\n * ```\n */\n before?: AuthorizeHookHandler | AuthorizeHookHandler[];\n\n /**\n * Runs after the permission check passes.\n *\n * @example\n * ```ts\n * after: ({ req }) => {\n * auditLog.record({ userId: req.user.id, path: req.path });\n * }\n * ```\n */\n after?: AuthorizeAfterHookHandler | AuthorizeAfterHookHandler[];\n\n /**\n * Runs when the user lacks sufficient permissions (403).\n * Throw to forward to the global error handler, or call `skip()` to suppress and jump to `after` hooks.\n *\n * @example\n * ```ts\n * onError: ({ req, error, action, resource, rule }) => {\n * auditLog.record({ userId: req.user?.id, reason: \"insufficient_permissions\" });\n * throw error;\n * }\n * ```\n *\n * @example Suppress error and continue\n * ```ts\n * onError: ({ req, skip, action, resource, rule }) => {\n * req.user.role = \"guest\";\n * skip();\n * }\n * ```\n */\n onError?: AuthorizeErrorHookHandler | AuthorizeErrorHookHandler[];\n };\n };\n enabled?: boolean;\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/authentication/setup](https://www.arkosjs.com/docs/core-concepts/authentication/setup) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /**\n * Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * See more at [www.arkosjs.com/docs/core-concepts/authentication/setup#login-with-different-fileds](https://www.arkosjs.com/docs/core-concepts/authentication/setup#login-with-different-fileds)\n *\n * By specifing here another field for username, for example passing \"email\", \"companyCode\" or something else your json will be like:\n *\n * **Example with email**\n *\n * ```json\n * {\n * \"email\": \"john.doe@example.com\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n */\n allowedUsernames?: string[];\n /** Defines wether to send the access token in response after login or only send as cookie, defeault is both.*/\n sendAccessTokenThrough?: \"cookie-only\" | \"response-only\" | \"both\";\n };\n /**\n * Specifies the regex pattern used by the authentication system to enforce password strength requirements.\n *\n * **Important**: If using validation libraries like Zod or class-validator, this will be completely overwritten.\n *\n * **Default**: ```/^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/``` - Ensures the password contains at least one uppercase letter, one lowercase letter, and one numeric digit.\n *\n * **message**: (Optional) A custom error message to display when the password does not meet the required strength criteria.\n * @deprecated will stop working on v2.0\n */\n passwordValidation?: { regex: RegExp; message?: string };\n /**\n * Allows to specify the request rate limit for all authentication endpoints but `/api/users/me`.\n * \n * #### Default\n *{\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n *@see This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n rateLimit?: Partial<RateLimitOptions>;\n /**\n * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n *@see Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n *\n * @env `JWT_COOKIE_SECURE`\n */\n secure?: boolean;\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n *\n * @env `JWT_COOKIE_HTTP_ONLY`\n */\n httpOnly?: boolean;\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n *\n * @env `JWT_COOKIE_SAME_SITE`\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n /**\n * Expiry date of the cookie in GMT. If not specified (undefined), creates a session cookie.\n *\n * @default `now() + authentication.jwt.expireIn | JWT_EXPIRES_IN`\n *\n * @since 1.5.11-beta\n */\n expires?: Date | undefined;\n /**\n * Domain for the cookie. Use a leading dot (e.g. `.example.com`) to include all subdomains.\n *\n * @env `JWT_COOKIE_DOMAIN`\n *\n * @since 1.5.11-beta\n */\n domain?: string | undefined;\n } & Omit<\n CookieOptions,\n \"secure\" | \"httpOnly\" | \"sameSite\" | \"expires\" | \"domain\"\n >;\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * @See [www.arkosjs.com/docs/guides/validation/setup](https://www.arkosjs.com/docs/guides/validation/setup) for more details.\n */\n validation?: {\n /**\n * Defines whether to use strict request validation, it means in every request using `ArkosRouter()` you must pass the validation options with all options (e.g: query, params, body, etc.).\n *\n * **How It Works:**\n * - If it is true, Arkos will require all the options a stated above on the routes and if you don't pass it will throw an error.\n * **What if you don't want to pass a validator to some options?**\n * - You will need to pass `undefined` to the validator option (see example below), this way Arkos will throw an error if something is passed to `req.query` if you passed undefined as validator into `validation.query`\n *\n * ```ts\n * import { ArkosRouter } from \"arkos\"\n *\n * const router = ArkosRouter()\n *\n * router.get({\n * route: \"/api/posts\",\n * validation: {\n * query: undefined\n * }\n * })\n *\n * ```\n *\n * @since 1.4.0-beta\n */\n strict?: boolean;\n } & (\n | {\n resolver: \"class-validator\";\n /**\n * ValidatorOptions to used while validating request data.\n *\n * **Default**:\n * ```ts\n * {\n * whitelist: true\n * forbidNonWhitelisted: true\n * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver: \"zod\";\n /**\n * @since v1.5.0-beta\n */\n validationOptions?: {\n /**\n * Throws an error for know whitelisted fields\n *\n * @default true\n */\n forbidNonWhitelisted?: boolean;\n };\n }\n );\n /**\n * Defines file upload configurations\n *\n * See {@link https://www.arkosjs.com/docs/guides/file-uploads/setup}\n */\n fileUpload?: {\n /**\n * Disables built-in file upload\n *\n * @since 1.5.11-beta\n */\n enabled?: boolean;\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n expressStatic?: Parameters<typeof express.static>[1];\n /**\n * Defines upload restrictions for each file type: image, video, document or other.\n *\n * #### Important:\n * Passing an object without overriding everything will only cause it\n * to be deepmerged with the default options.\n *\n * See [www.arkosjs.com/docs/reference/default-supported-upload-files](https://www.arkosjs.com/docs/reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n restrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n files?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * Defines express middlewares configurations\n */\n middlewares?: {\n /**\n * Allows to define options for npm package compression\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/compression](https://www.npmjs.com/package/compression) for further details.\n */\n compression?: false | compression.CompressionOptions | ArkosRequestHandler;\n /**\n * Allows to specify the request rate limit for all endpoints.\n * \n * #### Default\n *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n ```\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n rateLimit?: false | Partial<RateLimitOptions> | ArkosRequestHandler;\n /**\n * Configuration for CORS (Cross-Origin Resource Sharing).\n *\n * Accepts:\n * - `false` — disables CORS middleware entirely.\n * - `cors.CorsOptions` — passed directly to the `cors` middleware.\n * - `cors.CorsOptionsDelegate` — a delegate function passed directly to the `cors` middleware.\n * - `ArkosRequestHandler` — a full Express middleware that replaces the cors middleware entirely.\n * - An object with deprecated `allowedOrigins`, `options`, and `customHandler` properties.\n *\n * In development, defaults to `origin: true, credentials: true`.\n * In production, defaults to `origin: \"*\"` (equivalent to plain `cors()`).\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?:\n | false\n | cors.CorsOptions\n | cors.CorsOptionsDelegate\n | {\n /**\n * Defines allowed origins to access the API.\n *\n * @deprecated Use `cors: { origin: string | string[] }` (cors.CorsOptions) directly instead.\n */\n allowedOrigins?: string | string[] | \"*\" | true;\n /**\n * Additional cors options.\n *\n * @deprecated Pass cors.CorsOptions directly instead: `cors: { origin: \"...\", credentials: true }`.\n */\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware.\n *\n * @deprecated Pass the handler directly instead: `cors: myCorsHandler`.\n */\n customHandler?: cors.CorsOptionsDelegate;\n }\n | ArkosRequestHandler;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n expressJson?:\n | false\n | Parameters<typeof express.json>[0]\n | ArkosRequestHandler;\n /**\n * Allows to pass paremeters to cookieParser from npm package cookie-parser\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/cookie-parser](https://www.npmjs.com/package/cookie-parser) for further details.\n */\n cookieParser?:\n | false\n | {\n secret?: string | string[];\n options?: Parameters<typeof cookieParser>[1];\n }\n | ArkosRequestHandler;\n /**\n * Options to define how query must be parsed.\n *\n * #### for example:\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n * \n * #### Default:\n * \n * {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n parseNumber: true,\n }\n * \n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n * \n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParser?: false | QueryParserOptions | ArkosRequestHandler;\n /**\n * Configuration for request logger middleware.\n *\n * Logs incoming HTTP requests with details such as method, URL, status code, and response time.\n * Useful for debugging and monitoring API traffic.\n */\n requestLogger?: false | ArkosRequestHandler;\n /**\n * Configuration for global error handler middleware.\n *\n * Catches and processes errors thrown in route handlers and other middlewares.\n * Provides a centralized way to format error responses and log errors.\n */\n errorHandler?: false | express.ErrorRequestHandler;\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Strict mode configuration for routing security\n *\n * @default false\n * - all CRUD + Auth (if using auth) endpoits are enabled and avialable by default.\n *\n * When enabled:\n * - If `true`: All CRUD endpoints start disabled and must be explicitly enabled\n * in each model's router configuration\n * - If `'no-bulk'`: Bulk operations (createMany, updateMany, deleteMany) are disabled\n * by default, while individual operations can be enabled per model\n *\n * This provides enhanced security by ensuring no routes are accidentally exposed.\n * Use this in production environments to follow the principle of least privilege.\n *\n * See documentation: https://www.arkosjs.com/docs/guide/security#strict-mode\n */\n strict?: boolean | \"no-bulk\";\n /**\n * Replace the default welcome endpoint handler\n * @param req Express request object\n * @param res Express response object\n * @param next Express next function\n */\n welcomeRoute?: false | ArkosRequestHandler;\n };\n /**\n * Allows to configure email configurations for sending emails through `emailService`\n *\n * See [www.arkosjs.com/docs/guides/email-service](https://www.arkosjs.com/docs/guides/email-service)\n */\n email?: {\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n /**\n * Your email provider url\n */\n host: string;\n /**\n * Email provider SMTP port, Default is `465`\n */\n port?: number;\n /**\n * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n } & Parameters<typeof nodemailer.createTransport>[0];\n /**\n * Defines Swagger and OpenApi specifications for auto generating swagger documentation UI using whether it is Prisma Schemas, Class-validator DTOs, Zod Schemas or JSON-Schemas.\n *\n * **Important**: Is worth mentioning that this works alongside `@scalar/express-api-reference` npm package, you define it's ApiReferenceConfiguration under ``. also consider checking the package documentation at []\n *\n * **Usage**\n *\n * ```ts\n * // src/app.ts\n *\n * import arkos from \"arkos\"\n *\n * arkos.init({\n * // other configs\n * swagger: {\n * mode: \"zod\",\n * options: {\n * defintion: {\n * info: {\n * openapi: \"3.0.0\",\n * title: \"API Generated By Arkos.js\",\n * description: \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n * }\n * }\n * }\n * }\n * })\n * ```\n * @see {@link https://www.arkosjs.com/docs/guides/open-api-documentation/setup}\n */\n swagger?: {\n /**\n * By default Arkos will disable API Documentation when the project is built `npm run build`, it does not matter what node environment is set. If you want to use it even after the `arkos build` command just set this to `true`.\n * */\n enableAfterBuild?: boolean;\n /**\n * Whether to require superUser authentication to access docs in production.\n * Default: true after build\n */\n authenticate?: boolean;\n /**\n * Endpoint where the Swagger UI will be available.\n *\n * @default \"/api/api-docs\"\n */\n endpoint?: string;\n /**\n * Determines how your API schemas should be generated.\n *\n * - \"prisma\": Generates schemas based on Prisma models\n * - \"class-validator\": Uses class-validator and class-transformer DTO classes\n * - \"zod\": Uses OpenAPI-compliant schemas directly\n *\n */\n mode: \"prisma\" | \"class-validator\" | \"zod\";\n /**\n * Allows `Arkos.js` to fallback to prisma schema and use them as json schema for defining request body and response data\n * when a given zod Schema or class-validator Class is not found to be transformed to json schema.\n *\n * @default false\n */\n strict?: boolean;\n /**\n * Defines your swagger configurations\n */\n options?: {\n /**\n * Swagger definition according to OpenAPI Specification.\n */\n definition?: {\n /**\n * OpenAPI version.\n *\n * @default \"3.0.0\"\n */\n openapi?: string;\n\n /**\n * Information about your API.\n */\n info?: {\n /**\n * Title of the API documentation.\n *\n *\n * @example \"My API\"\n *\n * @default \"API Generated By Arkos.js\"\n */\n title?: string;\n\n /**\n * Version of the API.\n *\n * @example \"1.0.0\"\n */\n version?: string;\n\n /**\n * Description of the API.\n *\n * @default \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n */\n description?: string;\n };\n\n /**\n * Server configurations for the API.\n *\n * @default [{ url: \"http://localhost:8000\", description: \"Development server\" }]\n *\n * This can be overridden automatically by Arkos based on CLI, .env, or `arkos.init()`.\n */\n servers?: {\n /**\n * Base URL of the server.\n *\n * @example \"http://localhost:8000\"\n */\n url: string;\n\n /**\n * Human-readable description of the server.\n *\n * @example \"Development Server\"\n */\n description?: string;\n }[];\n /**\n * Allows adding more paths for your OpenAPI documentation\n *\n * */\n paths?: OpenAPIV3.PathsObject;\n /**\n * (Optional) Additional metadata such as terms of service, contact, or license.\n *\n * See: https://swagger.io/specification/#infoObject\n */\n termsOfService?: string;\n contact?: {\n name?: string;\n url?: string;\n email?: string;\n };\n license?: {\n name: string;\n url?: string;\n };\n\n /**\n * Tags to group and describe endpoints.\n */\n tags?: {\n name: string;\n description?: string;\n }[];\n\n /**\n * Security definitions (e.g., Bearer Auth).\n */\n components?: {\n securitySchemes?: Record<string, any>;\n schemas?: Record<string, any>;\n };\n\n /**\n * Global security requirements.\n */\n security?: Array<Record<string, string[]>>;\n };\n\n /**\n * Glob patterns defining where Swagger should look for API route definitions and comments.\n *\n * @default \n * ```ts\n * [\"./src/routers/*.router.{ts,js}\", \"./src/modules/**\\/*.router.{ts,js}\"]\n ```\n *\n * Adjust depending on TypeScript or JavaScript usage.\n */\n apis?: string[];\n\n /**\n * Enables deep linking in the Swagger UI.\n *\n * @default true\n */\n deepLinking?: boolean;\n\n /**\n * Enable/disable the \"Try it out\" button globally.\n *\n * @default true\n */\n tryItOutEnabled?: boolean;\n\n /**\n * Whether to persist authorization data across page reloads.\n *\n * @default false\n */\n persistAuthorization?: boolean;\n };\n /**\n * Custom `@scalar/express-api-reference` package options.\n *\n * @see {@link https://guides.scalar.com/scalar/scalar-api-references/integrations/express}\n */\n scalarApiReferenceConfiguration?: Partial<ApiReferenceConfiguration>;\n };\n /**\n * Helps in debugging some of the variables values that are used inside arkos from dynamic loaded components towhat is used into the generated api.\n *\n */\n debugging?: {\n /**\n * Controls debugging over HTTP request level\n */\n requests?: {\n level?: 0 | 1 | 2 | 3;\n filter?: (\n | \"Query\"\n | \"Body\"\n | \"Params\"\n | \"TransformedQuery\"\n | \"ServiceArgs\"\n | \"PrismaFinalQueryArgs\"\n )[];\n };\n /**\n * Controls debugging over the dynamic loaded modules and it's components on app starting\n */\n dynamicLoader?: {\n /**\n * Adjusts logging details\n *\n * 1 - Loaded modules and list of it's components files\n * 2 - All from 1 and detailed inspection per module component\n * 3 - All from 1 and 2, plus the final router component after merged with autho generated router.\n */\n level?: 0 | 1 | 2 | 3;\n filters?: {\n /**\n * Allows filtering by specific modules.\n *\n * Supports only searching for the starting parts of the module name, e.g: If there is`user-profile`, `user`, `posts`, passing `[\"user\"]` will match both `user-profile` and `user`.\n */\n modules?: string[];\n /**\n * Allows filtering by component's names\n */\n components?: keyof ModuleComponents[];\n };\n };\n };\n /**\n * Allows to suppress specific warnings emitted by Arkos at startup or runtime.\n *\n * @since 1.5.10-beta\n */\n warnings?: {\n /**\n * Suppresses specific warning messages.\n */\n suppress?: {\n /**\n * Suppresses Prisma-related warnings.\n */\n prisma?: {\n /**\n * Suppresses the warning emitted when no Prisma instance is found.\n */\n noInstanceFound?: boolean;\n /**\n * Suppresses the warning emitted when no Prisma schema is found.\n */\n noSchemaFound?: boolean;\n };\n };\n };\n};\n"]}
1
+ {"version":3,"file":"new-arkos-config.js","sourceRoot":"","sources":["../../../src/types/new-arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import cors from \"cors\";\nimport express, { CookieOptions } from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport type { ApiReferenceConfiguration } from \"@scalar/express-api-reference\" with { \"resolution-mode\": \"import\" };\nimport nodemailer from \"nodemailer\";\nimport { ModuleComponents } from \"../utils/dynamic-loader\";\nimport { ArkosRequestHandler } from \".\";\nimport {\n AuthenticateHookHandler,\n AuthenticateAfterHookHandler,\n AuthenticateErrorHookHandler,\n AuthorizeHookHandler,\n AuthorizeAfterHookHandler,\n AuthorizeErrorHookHandler,\n} from \"./arkos-config/utils\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /**\n * Configuration for resolving your Arkos application's source files at runtime.\n *\n * @since 1.6.1-canary.2\n *\n */\n source?: {\n /**\n * The entry point file of your Arkos application, resolved at runtime.\n *\n * This should point to the file where `app.listen()` or `app.listen(server)`\n * is called to start the HTTP server.\n *\n * Supports both TypeScript and JavaScript projects.\n *\n * @type {string}\n *\n * @default \"src/app.ts\" (TypeScript) | \"src/app.js\" (JavaScript)\n *\n * @since 1.6.1-canary.2\n *\n * @example\n * ```ts\n * // TypeScript project\n * entryPoint: \"src/app.ts\"\n *\n * // JavaScript project\n * entryPoint: \"src/app.js\"\n *\n * // Custom path\n * entryPoint: \"src/server/main.ts\"\n * ```\n */\n entryPoint?: string;\n };\n /**\n * The global prefixer for the whole application\n *\n * @default \"/api\"\n */\n readonly globalPrefix?: string;\n /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for passing prisma query options.\n *\n * See more\n */\n allowDangerousPrismaQueryOptions?: boolean;\n };\n };\n /** Message you would like to send, as Json and 200 response when\n * ```curl\n * GET /api\n * ```\n *\n * ```json\n * { \"message\": \"Welcome to YourAppName\" }\n * ```\n *\n * default message is: Welcome to our Rest API generated by Arkos, find more about Arkos at www.arkosjs.com.\n *\n *\n * */\n welcomeMessage?: string;\n /**\n * Port where the application will run, can be set in 3 ways:\n *\n * 1. default is 8000\n * 2. PORT under environment variables (Lower precedence)\n * 3. this config option (Higher precedence)\n */\n port?: number | undefined;\n /**\n * Allows to listen on a different host than localhost only\n */\n host?: string;\n /**\n * Defines authentication related configurations, by default is undefined.\n *\n * See [www.arkosjs.com/docs/core-concepts/authentication/setup](https://www.arkosjs.com/docs/core-concepts/authentication/setup) for details.\n */\n authentication?: {\n /**\n * Lifecycle hooks for the built-in authentication and authorization pipeline.\n *\n * These hooks only apply to **auto-generated Arkos routes**. On custom routes using\n * `authService.authenticate` directly, chain them manually as standard middlewares.\n *\n * Hooks run as standard Express middlewares — call `next()` to continue or\n * `next(error)` to abort and forward to the global error handler.\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication/hooks}\n */\n hooks?: {\n authenticate?: {\n /**\n * Runs before JWT extraction and verification.\n *\n * @example\n * ```ts\n * before: ({ req, skip, action, resource, rule }) => {\n * req.authContext = { startedAt: Date.now() };\n * }\n * ```\n *\n * @example Skip core logic entirely (e.g. custom auth)\n * ```ts\n * before: ({ req, skip, action, resource, rule }) => {\n * req.user = myCustomAuth(req);\n * skip();\n * }\n * ```\n */\n before?: AuthenticateHookHandler | AuthenticateHookHandler[];\n\n /**\n * Runs after `req.user` has been set.\n *\n * @example\n * ```ts\n * after: ({ req }) => {\n * if (!req.user.hasChangedPassword) {\n * throw new AppError(\"Password change required.\", 403, \"PasswordChangeRequired\");\n * }\n * }\n * ```\n */\n after?: AuthenticateAfterHookHandler | AuthenticateAfterHookHandler[];\n\n /**\n * Runs when authentication throws — invalid token, expired token, user not found, etc.\n * Throw to forward to the global error handler, or call `skip()` to suppress and jump to `after` hooks.\n *\n * @example\n * ```ts\n * onError: ({ req, error, skip, action, resource, rule }) => {\n * console.warn(`Auth failed:`, error);\n * throw error;\n * }\n * ```\n *\n * @example Suppress error and continue\n * ```ts\n * onError: ({ req, skip, action, resource, rule }) => {\n * req.user = guestUser;\n * skip();\n * }\n * ```\n */\n onError?: AuthenticateErrorHookHandler | AuthenticateErrorHookHandler[];\n };\n\n authorize?: {\n /**\n * Runs before the role/permission check.\n *\n * @example\n * ```ts\n * before: ({ req }) => {\n * if (req.headers[\"x-elevated-access\"] === process.env.ELEVATION_KEY) {\n * req.user.role = \"admin\";\n * }\n * }\n * ```\n *\n * @example Skip permission check entirely\n * ```ts\n * before: ({ req, skip, action, resource, rule }) => {\n * req.user.role = myCustomRoleResolver(req);\n * skip();\n * }\n * ```\n */\n before?: AuthorizeHookHandler | AuthorizeHookHandler[];\n\n /**\n * Runs after the permission check passes.\n *\n * @example\n * ```ts\n * after: ({ req }) => {\n * auditLog.record({ userId: req.user.id, path: req.path });\n * }\n * ```\n */\n after?: AuthorizeAfterHookHandler | AuthorizeAfterHookHandler[];\n\n /**\n * Runs when the user lacks sufficient permissions (403).\n * Throw to forward to the global error handler, or call `skip()` to suppress and jump to `after` hooks.\n *\n * @example\n * ```ts\n * onError: ({ req, error, action, resource, rule }) => {\n * auditLog.record({ userId: req.user?.id, reason: \"insufficient_permissions\" });\n * throw error;\n * }\n * ```\n *\n * @example Suppress error and continue\n * ```ts\n * onError: ({ req, skip, action, resource, rule }) => {\n * req.user.role = \"guest\";\n * skip();\n * }\n * ```\n */\n onError?: AuthorizeErrorHookHandler | AuthorizeErrorHookHandler[];\n };\n };\n enabled?: boolean;\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/authentication/setup](https://www.arkosjs.com/docs/core-concepts/authentication/setup) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /**\n * Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * See more at [www.arkosjs.com/docs/core-concepts/authentication/setup#login-with-different-fileds](https://www.arkosjs.com/docs/core-concepts/authentication/setup#login-with-different-fileds)\n *\n * By specifing here another field for username, for example passing \"email\", \"companyCode\" or something else your json will be like:\n *\n * **Example with email**\n *\n * ```json\n * {\n * \"email\": \"john.doe@example.com\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n */\n allowedUsernames?: string[];\n /** Defines wether to send the access token in response after login or only send as cookie, defeault is both.*/\n sendAccessTokenThrough?: \"cookie-only\" | \"response-only\" | \"both\";\n };\n /**\n * Specifies the regex pattern used by the authentication system to enforce password strength requirements.\n *\n * **Important**: If using validation libraries like Zod or class-validator, this will be completely overwritten.\n *\n * **Default**: ```/^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/``` - Ensures the password contains at least one uppercase letter, one lowercase letter, and one numeric digit.\n *\n * **message**: (Optional) A custom error message to display when the password does not meet the required strength criteria.\n * @deprecated will stop working on v2.0\n */\n passwordValidation?: { regex: RegExp; message?: string };\n /**\n * Allows to specify the request rate limit for all authentication endpoints but `/api/users/me`.\n * \n * #### Default\n *{\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n *@see This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n rateLimit?: Partial<RateLimitOptions>;\n /**\n * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n *@see Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n *\n * @env `JWT_COOKIE_SECURE`\n */\n secure?: boolean;\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n *\n * @env `JWT_COOKIE_HTTP_ONLY`\n */\n httpOnly?: boolean;\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n *\n * @env `JWT_COOKIE_SAME_SITE`\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n /**\n * Expiry date of the cookie in GMT. If not specified (undefined), creates a session cookie.\n *\n * @default `now() + authentication.jwt.expireIn | JWT_EXPIRES_IN`\n *\n * @since 1.5.11-beta\n */\n expires?: Date | undefined;\n /**\n * Domain for the cookie. Use a leading dot (e.g. `.example.com`) to include all subdomains.\n *\n * @env `JWT_COOKIE_DOMAIN`\n *\n * @since 1.5.11-beta\n */\n domain?: string | undefined;\n } & Omit<\n CookieOptions,\n \"secure\" | \"httpOnly\" | \"sameSite\" | \"expires\" | \"domain\"\n >;\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * @See [www.arkosjs.com/docs/guides/validation/setup](https://www.arkosjs.com/docs/guides/validation/setup) for more details.\n */\n validation?: {\n /**\n * Defines whether to use strict request validation, it means in every request using `ArkosRouter()` you must pass the validation options with all options (e.g: query, params, body, etc.).\n *\n * **How It Works:**\n * - If it is true, Arkos will require all the options a stated above on the routes and if you don't pass it will throw an error.\n * **What if you don't want to pass a validator to some options?**\n * - You will need to pass `undefined` to the validator option (see example below), this way Arkos will throw an error if something is passed to `req.query` if you passed undefined as validator into `validation.query`\n *\n * ```ts\n * import { ArkosRouter } from \"arkos\"\n *\n * const router = ArkosRouter()\n *\n * router.get({\n * route: \"/api/posts\",\n * validation: {\n * query: undefined\n * }\n * })\n *\n * ```\n *\n * @since 1.4.0-beta\n */\n strict?: boolean;\n } & (\n | {\n resolver: \"class-validator\";\n /**\n * ValidatorOptions to used while validating request data.\n *\n * **Default**:\n * ```ts\n * {\n * whitelist: true\n * forbidNonWhitelisted: true\n * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver: \"zod\";\n /**\n * @since v1.5.0-beta\n */\n validationOptions?: {\n /**\n * Throws an error for know whitelisted fields\n *\n * @default true\n */\n forbidNonWhitelisted?: boolean;\n };\n }\n );\n /**\n * Defines file upload configurations\n *\n * See {@link https://www.arkosjs.com/docs/guides/file-uploads/setup}\n */\n fileUpload?: {\n /**\n * Disables built-in file upload\n *\n * @since 1.5.11-beta\n */\n enabled?: boolean;\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: false,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n expressStatic?: Parameters<typeof express.static>[1];\n /**\n * Defines upload restrictions for each file type: image, video, document or other.\n *\n * #### Important:\n * Passing an object without overriding everything will only cause it\n * to be deepmerged with the default options.\n *\n * See [www.arkosjs.com/docs/reference/default-supported-upload-files](https://www.arkosjs.com/docs/reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n restrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n files?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * Defines express middlewares configurations\n */\n middlewares?: {\n /**\n * Allows to define options for npm package compression\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/compression](https://www.npmjs.com/package/compression) for further details.\n */\n compression?: false | compression.CompressionOptions | ArkosRequestHandler;\n /**\n * Allows to specify the request rate limit for all endpoints.\n * \n * #### Default\n *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n ```\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n rateLimit?: false | Partial<RateLimitOptions> | ArkosRequestHandler;\n /**\n * Configuration for CORS (Cross-Origin Resource Sharing).\n *\n * Accepts:\n * - `false` — disables CORS middleware entirely.\n * - `cors.CorsOptions` — passed directly to the `cors` middleware.\n * - `cors.CorsOptionsDelegate` — a delegate function passed directly to the `cors` middleware.\n * - `ArkosRequestHandler` — a full Express middleware that replaces the cors middleware entirely.\n * - An object with deprecated `allowedOrigins`, `options`, and `customHandler` properties.\n *\n * In development, defaults to `origin: true, credentials: true`.\n * In production, defaults to `origin: \"*\"` (equivalent to plain `cors()`).\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?:\n | false\n | cors.CorsOptions\n | cors.CorsOptionsDelegate\n | {\n /**\n * Defines allowed origins to access the API.\n *\n * @deprecated Use `cors: { origin: string | string[] }` (cors.CorsOptions) directly instead.\n */\n allowedOrigins?: string | string[] | \"*\" | true;\n /**\n * Additional cors options.\n *\n * @deprecated Pass cors.CorsOptions directly instead: `cors: { origin: \"...\", credentials: true }`.\n */\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware.\n *\n * @deprecated Pass the handler directly instead: `cors: myCorsHandler`.\n */\n customHandler?: cors.CorsOptionsDelegate;\n }\n | ArkosRequestHandler;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n expressJson?:\n | false\n | Parameters<typeof express.json>[0]\n | ArkosRequestHandler;\n /**\n * Allows to pass paremeters to cookieParser from npm package cookie-parser\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/cookie-parser](https://www.npmjs.com/package/cookie-parser) for further details.\n */\n cookieParser?:\n | false\n | {\n secret?: string | string[];\n options?: Parameters<typeof cookieParser>[1];\n }\n | ArkosRequestHandler;\n /**\n * Options to define how query must be parsed.\n *\n * #### for example:\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n * \n * #### Default:\n * \n * {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n parseNumber: true,\n }\n * \n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n * \n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParser?: false | QueryParserOptions | ArkosRequestHandler;\n /**\n * Configuration for request logger middleware.\n *\n * Logs incoming HTTP requests with details such as method, URL, status code, and response time.\n * Useful for debugging and monitoring API traffic.\n */\n requestLogger?: false | ArkosRequestHandler;\n /**\n * Configuration for global error handler middleware.\n *\n * Catches and processes errors thrown in route handlers and other middlewares.\n * Provides a centralized way to format error responses and log errors.\n */\n errorHandler?: false | express.ErrorRequestHandler;\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Strict mode configuration for routing security\n *\n * @default false\n * - all CRUD + Auth (if using auth) endpoits are enabled and avialable by default.\n *\n * When enabled:\n * - If `true`: All CRUD endpoints start disabled and must be explicitly enabled\n * in each model's router configuration\n * - If `'no-bulk'`: Bulk operations (createMany, updateMany, deleteMany) are disabled\n * by default, while individual operations can be enabled per model\n *\n * This provides enhanced security by ensuring no routes are accidentally exposed.\n * Use this in production environments to follow the principle of least privilege.\n *\n * See documentation: https://www.arkosjs.com/docs/guide/security#strict-mode\n */\n strict?: boolean | \"no-bulk\";\n /**\n * Replace the default welcome endpoint handler\n * @param req Express request object\n * @param res Express response object\n * @param next Express next function\n */\n welcomeRoute?: false | ArkosRequestHandler;\n };\n /**\n * Allows to configure email configurations for sending emails through `emailService`\n *\n * See [www.arkosjs.com/docs/guides/email-service](https://www.arkosjs.com/docs/guides/email-service)\n */\n email?: {\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n /**\n * Your email provider url\n */\n host: string;\n /**\n * Email provider SMTP port, Default is `465`\n */\n port?: number;\n /**\n * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n } & Parameters<typeof nodemailer.createTransport>[0];\n /**\n * Defines Swagger and OpenApi specifications for auto generating swagger documentation UI using whether it is Prisma Schemas, Class-validator DTOs, Zod Schemas or JSON-Schemas.\n *\n * **Important**: Is worth mentioning that this works alongside `@scalar/express-api-reference` npm package, you define it's ApiReferenceConfiguration under ``. also consider checking the package documentation at []\n *\n * **Usage**\n *\n * ```ts\n * // src/app.ts\n *\n * import arkos from \"arkos\"\n *\n * arkos.init({\n * // other configs\n * swagger: {\n * mode: \"zod\",\n * options: {\n * defintion: {\n * info: {\n * openapi: \"3.0.0\",\n * title: \"API Generated By Arkos.js\",\n * description: \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n * }\n * }\n * }\n * }\n * })\n * ```\n * @see {@link https://www.arkosjs.com/docs/guides/open-api-documentation/setup}\n */\n swagger?: {\n /**\n * By default Arkos will disable API Documentation when the project is built `npm run build`, it does not matter what node environment is set. If you want to use it even after the `arkos build` command just set this to `true`.\n * */\n enableAfterBuild?: boolean;\n /**\n * Whether to require superUser authentication to access docs in production.\n * Default: true after build\n */\n authenticate?: boolean;\n /**\n * Endpoint where the Swagger UI will be available.\n *\n * @default \"/api/api-docs\"\n */\n endpoint?: string;\n /**\n * Determines how your API schemas should be generated.\n *\n * - \"prisma\": Generates schemas based on Prisma models\n * - \"class-validator\": Uses class-validator and class-transformer DTO classes\n * - \"zod\": Uses OpenAPI-compliant schemas directly\n *\n */\n mode: \"prisma\" | \"class-validator\" | \"zod\";\n /**\n * Allows `Arkos.js` to fallback to prisma schema and use them as json schema for defining request body and response data\n * when a given zod Schema or class-validator Class is not found to be transformed to json schema.\n *\n * @default false\n */\n strict?: boolean;\n /**\n * Defines your swagger configurations\n */\n options?: {\n /**\n * Swagger definition according to OpenAPI Specification.\n */\n definition?: {\n /**\n * OpenAPI version.\n *\n * @default \"3.0.0\"\n */\n openapi?: string;\n\n /**\n * Information about your API.\n */\n info?: {\n /**\n * Title of the API documentation.\n *\n *\n * @example \"My API\"\n *\n * @default \"API Generated By Arkos.js\"\n */\n title?: string;\n\n /**\n * Version of the API.\n *\n * @example \"1.0.0\"\n */\n version?: string;\n\n /**\n * Description of the API.\n *\n * @default \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n */\n description?: string;\n };\n\n /**\n * Server configurations for the API.\n *\n * @default [{ url: \"http://localhost:8000\", description: \"Development server\" }]\n *\n * This can be overridden automatically by Arkos based on CLI, .env, or `arkos.init()`.\n */\n servers?: {\n /**\n * Base URL of the server.\n *\n * @example \"http://localhost:8000\"\n */\n url: string;\n\n /**\n * Human-readable description of the server.\n *\n * @example \"Development Server\"\n */\n description?: string;\n }[];\n /**\n * Allows adding more paths for your OpenAPI documentation\n *\n * */\n paths?: OpenAPIV3.PathsObject;\n /**\n * (Optional) Additional metadata such as terms of service, contact, or license.\n *\n * See: https://swagger.io/specification/#infoObject\n */\n termsOfService?: string;\n contact?: {\n name?: string;\n url?: string;\n email?: string;\n };\n license?: {\n name: string;\n url?: string;\n };\n\n /**\n * Tags to group and describe endpoints.\n */\n tags?: {\n name: string;\n description?: string;\n }[];\n\n /**\n * Security definitions (e.g., Bearer Auth).\n */\n components?: {\n securitySchemes?: Record<string, any>;\n schemas?: Record<string, any>;\n };\n\n /**\n * Global security requirements.\n */\n security?: Array<Record<string, string[]>>;\n };\n\n /**\n * Glob patterns defining where Swagger should look for API route definitions and comments.\n *\n * @default \n * ```ts\n * [\"./src/routers/*.router.{ts,js}\", \"./src/modules/**\\/*.router.{ts,js}\"]\n ```\n *\n * Adjust depending on TypeScript or JavaScript usage.\n */\n apis?: string[];\n\n /**\n * Enables deep linking in the Swagger UI.\n *\n * @default true\n */\n deepLinking?: boolean;\n\n /**\n * Enable/disable the \"Try it out\" button globally.\n *\n * @default true\n */\n tryItOutEnabled?: boolean;\n\n /**\n * Whether to persist authorization data across page reloads.\n *\n * @default false\n */\n persistAuthorization?: boolean;\n };\n /**\n * Custom `@scalar/express-api-reference` package options.\n *\n * @see {@link https://guides.scalar.com/scalar/scalar-api-references/integrations/express}\n */\n scalarApiReferenceConfiguration?: Partial<ApiReferenceConfiguration>;\n };\n /**\n * Helps in debugging some of the variables values that are used inside arkos from dynamic loaded components towhat is used into the generated api.\n *\n */\n debugging?: {\n /**\n * Controls debugging over HTTP request level\n */\n requests?: {\n level?: 0 | 1 | 2 | 3;\n filter?: (\n | \"Query\"\n | \"Body\"\n | \"Params\"\n | \"TransformedQuery\"\n | \"ServiceArgs\"\n | \"PrismaFinalQueryArgs\"\n )[];\n };\n /**\n * Controls debugging over the dynamic loaded modules and it's components on app starting\n */\n dynamicLoader?: {\n /**\n * Adjusts logging details\n *\n * 1 - Loaded modules and list of it's components files\n * 2 - All from 1 and detailed inspection per module component\n * 3 - All from 1 and 2, plus the final router component after merged with autho generated router.\n */\n level?: 0 | 1 | 2 | 3;\n filters?: {\n /**\n * Allows filtering by specific modules.\n *\n * Supports only searching for the starting parts of the module name, e.g: If there is`user-profile`, `user`, `posts`, passing `[\"user\"]` will match both `user-profile` and `user`.\n */\n modules?: string[];\n /**\n * Allows filtering by component's names\n */\n components?: keyof ModuleComponents[];\n };\n };\n };\n /**\n * Allows to suppress specific warnings emitted by Arkos at startup or runtime.\n *\n * @since 1.5.10-beta\n */\n warnings?: {\n /**\n * Suppresses specific warning messages.\n */\n suppress?: {\n /**\n * Suppresses Prisma-related warnings.\n */\n prisma?: {\n /**\n * Suppresses the warning emitted when no Prisma instance is found.\n */\n noInstanceFound?: boolean;\n /**\n * Suppresses the warning emitted when no Prisma schema is found.\n */\n noSchemaFound?: boolean;\n };\n };\n };\n};\n"]}
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=upload.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upload.js","sourceRoot":"","sources":["../../../src/types/upload.ts"],"names":[],"mappings":"","sourcesContent":["export interface ArkosFile extends Express.Multer.File {\n /**\n * The file pathname without the server host\n */\n pathname: string;\n /**\n * The file full URL\n */\n url: string;\n}\n"]}
@@ -15,9 +15,7 @@ class ArkosRouterOpenAPIManager {
15
15
  uploadSchema.properties[uploadConfig.field] = {
16
16
  type: "string",
17
17
  format: "binary",
18
- ...(uploadConfig.maxSize && {
19
- description: `Max size: ${uploadConfig.maxSize} bytes`,
20
- }),
18
+ description: `Single file field${uploadConfig.maxSize ? `, max size: ${uploadConfig.maxSize} bytes` : ""}`,
21
19
  };
22
20
  if (uploadConfig.required !== false) {
23
21
  uploadSchema.required.push(uploadConfig.field);
@@ -31,9 +29,7 @@ class ArkosRouterOpenAPIManager {
31
29
  format: "binary",
32
30
  },
33
31
  ...(uploadConfig.maxCount && { maxItems: uploadConfig.maxCount }),
34
- ...(uploadConfig.maxSize && {
35
- description: `Max size per file: ${uploadConfig.maxSize} bytes`,
36
- }),
32
+ description: `Array file field${uploadConfig.maxSize ? `, max size per file: ${uploadConfig.maxSize} bytes` : ""}`,
37
33
  };
38
34
  if (uploadConfig.required !== false) {
39
35
  uploadSchema.required.push(uploadConfig.field);
@@ -48,9 +44,7 @@ class ArkosRouterOpenAPIManager {
48
44
  format: "binary",
49
45
  },
50
46
  ...(field.maxCount && { maxItems: field.maxCount }),
51
- ...(uploadConfig.maxSize && {
52
- description: `Max size per file: ${uploadConfig.maxSize} bytes`,
53
- }),
47
+ description: `Array file field${uploadConfig.maxSize ? `, max size per file: ${uploadConfig.maxSize} bytes` : ""}`,
54
48
  };
55
49
  if (uploadConfig.required !== false) {
56
50
  uploadSchema.required.push(field.name);
@@ -1 +1 @@
1
- {"version":3,"file":"arkos-router-openapi-manager.js","sourceRoot":"","sources":["../../../../src/utils/arkos-router/arkos-router-openapi-manager.ts"],"names":[],"mappings":";;;;;AACA,mFAAoD;AAGpD,MAAM,yBAAyB;IAsB7B,eAAe,CACb,YAA0B,EAC1B,iBAAyC,EAAE;QAE3C,MAAM,YAAY,GAAQ;YACxB,IAAI,EAAE,QAAQ;YACd,UAAU,EAAE,EAAE;YACd,QAAQ,EAAE,EAAE;SACb,CAAC;QAEF,IAAI,YAAY,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;YACnC,YAAY,CAAC,UAAU,CAAC,YAAY,CAAC,KAAK,CAAC,GAAG;gBAC5C,IAAI,EAAE,QAAQ;gBACd,MAAM,EAAE,QAAQ;gBAChB,GAAG,CAAC,YAAY,CAAC,OAAO,IAAI;oBAC1B,WAAW,EAAE,aAAa,YAAY,CAAC,OAAO,QAAQ;iBACvD,CAAC;aACH,CAAC;YACF,IAAI,YAAY,CAAC,QAAQ,KAAK,KAAK,EAAE,CAAC;gBACpC,YAAY,CAAC,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;YACjD,CAAC;QACH,CAAC;aAAM,IAAI,YAAY,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;YACzC,YAAY,CAAC,UAAU,CAAC,YAAY,CAAC,KAAK,CAAC,GAAG;gBAC5C,IAAI,EAAE,OAAO;gBACb,KAAK,EAAE;oBACL,IAAI,EAAE,QAAQ;oBACd,MAAM,EAAE,QAAQ;iBACjB;gBACD,GAAG,CAAC,YAAY,CAAC,QAAQ,IAAI,EAAE,QAAQ,EAAE,YAAY,CAAC,QAAQ,EAAE,CAAC;gBACjE,GAAG,CAAC,YAAY,CAAC,OAAO,IAAI;oBAC1B,WAAW,EAAE,sBAAsB,YAAY,CAAC,OAAO,QAAQ;iBAChE,CAAC;aACH,CAAC;YACF,IAAI,YAAY,CAAC,QAAQ,KAAK,KAAK,EAAE,CAAC;gBACp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iB,IAAI,qCAAqC,WAAW,CAAC,MAAM,IAAI,WAAW,GAAG,CAC/F,CAAC;YACN,CAAC;iBAAM,IAAI,YAAY,KAAK,OAAO,EAAE,CAAC;gBACpC,IAAI,WAAW,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;oBACjC,MAAM,CAAC,IAAI,CACT,iBAAiB,IAAI,kCAAkC,WAAW,CAAC,IAAI,GAAG,CAC3E,CAAC;gBACJ,CAAC;qBAAM,IACL,CAAC,WAAW,CAAC,KAAK;oBAClB,WAAW,CAAC,KAAK,CAAC,IAAI,KAAK,QAAQ;oBACnC,WAAW,CAAC,KAAK,CAAC,MAAM,KAAK,QAAQ;oBAErC,MAAM,CAAC,IAAI,CACT,iBAAiB,IAAI,0DAA0D,CAChF,CAAC;YACN,CAAC;YAED,MAAM,gBAAgB,GAAG,cAAc,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;YACvD,IAAI,QAAQ,IAAI,CAAC,gBAAgB;gBAC/B,MAAM,CAAC,IAAI,CACT,iBAAiB,IAAI,8DAA8D,CACpF,CAAC;YAEJ,IAAI,CAAC,QAAQ,IAAI,gBAAgB;gBAC/B,MAAM,CAAC,IAAI,CACT,iBAAiB,IAAI,8DAA8D,CACpF,CAAC;QACN,CAAC;QAED,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACtB,MAAM,IAAI,KAAK,CACb,kEAAkE,SAAS,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAC7H,CAAC;QACJ,CAAC;IACH,CAAC;CACF;AAED,MAAM,yBAAyB,GAAG,IAAI,yBAAyB,EAAE,CAAC;AAElE,kBAAe,yBAAyB,CAAC","sourcesContent":["import { OpenAPIV3 } from \"openapi-types\";\nimport deepmerge from \"../helpers/deepmerge.helper\";\nimport { UploadConfig } from \"./types/upload-config\";\n\nclass ArkosRouterOpenAPIManager {\n /**\n * Generates OpenAPI schema for file upload fields in multipart/form-data requests.\n * Converts upload configuration into OpenAPI-compliant schema and merges with existing body schema.\n *\n * @param {UploadConfig} uploadConfig - The upload configuration from config.experimental.uploads\n * @param {any} existingSchema - Existing JSON schema from config.validation.body (optional)\n * @returns {{ schema: any }} OpenAPI schema object for multipart/form-data content type\n *\n * @example\n * // Single file upload\n * addUploadFields({ type: 'single', field: 'avatar', maxSize: 5242880 })\n * // Returns: { schema: { type: 'object', properties: { avatar: { type: 'string', format: 'binary' } } } }\n *\n * @example\n * // Array file upload\n * addUploadFields({ type: 'array', field: 'gallery', maxCount: 10 })\n *\n * @example\n * // Multiple fields upload\n * addUploadFields({ type: 'fields', fields: [{ name: 'avatar', maxCount: 1 }, { name: 'resume', maxCount: 1 }] })\n */\n addUploadFields(\n uploadConfig: UploadConfig,\n existingSchema: OpenAPIV3.SchemaObject = {}\n ): OpenAPIV3.SchemaObject {\n const uploadSchema: any = {\n type: \"object\",\n properties: {},\n required: [],\n };\n\n if (uploadConfig.type === \"single\") {\n uploadSchema.properties[uploadConfig.field] = {\n type: \"string\",\n format: \"binary\",\n ...(uploadConfig.maxSize && {\n description: `Max size: ${uploadConfig.maxSize} bytes`,\n }),\n };\n if (uploadConfig.required !== false) {\n uploadSchema.required.push(uploadConfig.field);\n }\n } else if (uploadConfig.type === \"array\") {\n uploadSchema.properties[uploadConfig.field] = {\n type: \"array\",\n items: {\n type: \"string\",\n format: \"binary\",\n },\n ...(uploadConfig.maxCount && { maxItems: uploadConfig.maxCount }),\n ...(uploadConfig.maxSize && {\n description: `Max size per file: ${uploadConfig.maxSize} bytes`,\n }),\n };\n if (uploadConfig.required !== false) {\n uploadSchema.required.push(uploadConfig.field);\n }\n } else if (uploadConfig.type === \"fields\") {\n for (const field of uploadConfig.fields) {\n uploadSchema.properties[field.name] = {\n type: \"array\",\n items: {\n type: \"string\",\n format: \"binary\",\n },\n ...(field.maxCount && { maxItems: field.maxCount }),\n ...(uploadConfig.maxSize && {\n description: `Max size per file: ${uploadConfig.maxSize} bytes`,\n }),\n };\n if (uploadConfig.required !== false) {\n uploadSchema.required.push(field.name);\n }\n }\n }\n\n // Clean up empty required array\n if (uploadSchema.required.length === 0) delete uploadSchema.required;\n\n return deepmerge(existingSchema as any, uploadSchema);\n }\n\n /**\n * Validates that a user-defined multipart/form-data schema includes all required upload fields\n * with correct types, formats, and required flags.\n *\n * @param {any} userDefinedMultipartSchema - The schema object from openapi.requestBody.content['multipart/form-data'].schema\n * @param {UploadConfig} uploadConfig - The upload configuration from config.experimental.uploads\n * @param {string} routePath - The route path for error context\n * @throws {Error} If upload fields are missing or incorrectly defined\n *\n * @example\n * validateMultipartFormDocs(\n * { type: 'object', properties: { avatar: { type: 'string', format: 'binary' } } },\n * { type: 'single', field: 'avatar', required: true },\n * '/users/:id/avatar'\n * )\n */\n validateMultipartFormDocs(\n userDefinedMultipartSchema: any,\n routePath: string,\n uploadConfig?: UploadConfig\n ): void {\n const errors: string[] = [];\n const properties = userDefinedMultipartSchema?.properties || {};\n const requiredFields = userDefinedMultipartSchema?.required || [];\n\n const expectedFields: Array<{\n name: string;\n required: boolean;\n expectedType: \"single\" | \"array\";\n }> = [];\n\n if (uploadConfig?.type === \"single\") {\n expectedFields.push({\n name: uploadConfig.field,\n required: uploadConfig.required !== false,\n expectedType: \"single\",\n });\n } else if (uploadConfig?.type === \"array\") {\n expectedFields.push({\n name: uploadConfig.field,\n required: uploadConfig.required !== false,\n expectedType: \"array\",\n });\n } else if (uploadConfig?.type === \"fields\") {\n for (const field of uploadConfig.fields) {\n expectedFields.push({\n name: field.name,\n required: uploadConfig.required !== false,\n expectedType: \"array\",\n });\n }\n }\n\n for (const { name, required, expectedType } of expectedFields) {\n const fieldSchema = properties[name];\n\n if (!fieldSchema) {\n errors.push(\n `Missing upload field '${name}' in multipart/form-data schema`\n );\n continue;\n }\n\n if (expectedType === \"single\") {\n if (fieldSchema.type !== \"string\")\n errors.push(\n `Upload field '${name}' must have type 'string', got '${fieldSchema.type}'`\n );\n\n if (fieldSchema.format !== \"binary\")\n errors.push(\n `Upload field '${name}' must have format 'binary', got '${fieldSchema.format || \"undefined\"}'`\n );\n } else if (expectedType === \"array\") {\n if (fieldSchema.type !== \"array\") {\n errors.push(\n `Upload field '${name}' must have type 'array', got '${fieldSchema.type}'`\n );\n } else if (\n !fieldSchema.items ||\n fieldSchema.items.type !== \"string\" ||\n fieldSchema.items.format !== \"binary\"\n )\n errors.push(\n `Upload field '${name}' must have items with type 'string' and format 'binary'`\n );\n }\n\n const isMarkedRequired = requiredFields.includes(name);\n if (required && !isMarkedRequired)\n errors.push(\n `Upload field '${name}' is required in config but not marked as required in schema`\n );\n\n if (!required && isMarkedRequired)\n errors.push(\n `Upload field '${name}' is not required in config but marked as required in schema`\n );\n }\n\n if (errors.length > 0) {\n throw new Error(\n `ValidationError: Invalid multipart/form-data schema for route '${routePath}':\\n${errors.map((e) => ` - ${e}`).join(\"\\n\")}`\n );\n }\n }\n}\n\nconst arkosRouterOpenApiManager = new ArkosRouterOpenAPIManager();\n\nexport default arkosRouterOpenApiManager;\n"]}
1
+ {"version":3,"file":"arkos-router-openapi-manager.js","sourceRoot":"","sources":["../../../../src/utils/arkos-router/arkos-router-openapi-manager.ts"],"names":[],"mappings":";;;;;AACA,mFAAoD;AAGpD,MAAM,yBAAyB;IAsB7B,eAAe,CACb,YAA0B,EAC1B,iBAAyC,EAAE;QAE3C,MAAM,YAAY,GAAQ;YACxB,IAAI,EAAE,QAAQ;YACd,UAAU,EAAE,EAAE;YACd,QAAQ,EAAE,EAAE;SACb,CAAC;QAEF,IAAI,YAAY,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;YACnC,YAAY,CAAC,UAAU,CAAC,YAAY,CAAC,KAAK,CAAC,GAAG;gBAC5C,IAAI,EAAE,QAAQ;gBACd,MAAM,EAAE,QAAQ;gBAChB,WAAW,EAAE,oBAAoB,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC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AAC;YACN,CAAC;YAED,MAAM,gBAAgB,GAAG,cAAc,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;YACvD,IAAI,QAAQ,IAAI,CAAC,gBAAgB;gBAC/B,MAAM,CAAC,IAAI,CACT,iBAAiB,IAAI,8DAA8D,CACpF,CAAC;YAEJ,IAAI,CAAC,QAAQ,IAAI,gBAAgB;gBAC/B,MAAM,CAAC,IAAI,CACT,iBAAiB,IAAI,8DAA8D,CACpF,CAAC;QACN,CAAC;QAED,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACtB,MAAM,IAAI,KAAK,CACb,kEAAkE,SAAS,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAC7H,CAAC;QACJ,CAAC;IACH,CAAC;CACF;AAED,MAAM,yBAAyB,GAAG,IAAI,yBAAyB,EAAE,CAAC;AAElE,kBAAe,yBAAyB,CAAC","sourcesContent":["import { OpenAPIV3 } from \"openapi-types\";\nimport deepmerge from \"../helpers/deepmerge.helper\";\nimport { UploadConfig } from \"./types/upload-config\";\n\nclass ArkosRouterOpenAPIManager {\n /**\n * Generates OpenAPI schema for file upload fields in multipart/form-data requests.\n * Converts upload configuration into OpenAPI-compliant schema and merges with existing body schema.\n *\n * @param {UploadConfig} uploadConfig - The upload configuration from config.experimental.uploads\n * @param {any} existingSchema - Existing JSON schema from config.validation.body (optional)\n * @returns {{ schema: any }} OpenAPI schema object for multipart/form-data content type\n *\n * @example\n * // Single file upload\n * addUploadFields({ type: 'single', field: 'avatar', maxSize: 5242880 })\n * // Returns: { schema: { type: 'object', properties: { avatar: { type: 'string', format: 'binary' } } } }\n *\n * @example\n * // Array file upload\n * addUploadFields({ type: 'array', field: 'gallery', maxCount: 10 })\n *\n * @example\n * // Multiple fields upload\n * addUploadFields({ type: 'fields', fields: [{ name: 'avatar', maxCount: 1 }, { name: 'resume', maxCount: 1 }] })\n */\n addUploadFields(\n uploadConfig: UploadConfig,\n existingSchema: OpenAPIV3.SchemaObject = {}\n ): OpenAPIV3.SchemaObject {\n const uploadSchema: any = {\n type: \"object\",\n properties: {},\n required: [],\n };\n\n if (uploadConfig.type === \"single\") {\n uploadSchema.properties[uploadConfig.field] = {\n type: \"string\",\n format: \"binary\",\n description: `Single file field${uploadConfig.maxSize ? `, max size: ${uploadConfig.maxSize} bytes` : \"\"}`,\n };\n if (uploadConfig.required !== false) {\n uploadSchema.required.push(uploadConfig.field);\n }\n } else if (uploadConfig.type === \"array\") {\n uploadSchema.properties[uploadConfig.field] = {\n type: \"array\",\n items: {\n type: \"string\",\n format: \"binary\",\n },\n ...(uploadConfig.maxCount && { maxItems: uploadConfig.maxCount }),\n description: `Array file field${uploadConfig.maxSize ? `, max size per file: ${uploadConfig.maxSize} bytes` : \"\"}`,\n };\n if (uploadConfig.required !== false) {\n uploadSchema.required.push(uploadConfig.field);\n }\n } else if (uploadConfig.type === \"fields\") {\n for (const field of uploadConfig.fields) {\n uploadSchema.properties[field.name] = {\n type: \"array\",\n items: {\n type: \"string\",\n format: \"binary\",\n },\n ...(field.maxCount && { maxItems: field.maxCount }),\n description: `Array file field${uploadConfig.maxSize ? `, max size per file: ${uploadConfig.maxSize} bytes` : \"\"}`,\n };\n if (uploadConfig.required !== false) {\n uploadSchema.required.push(field.name);\n }\n }\n }\n\n // Clean up empty required array\n if (uploadSchema.required.length === 0) delete uploadSchema.required;\n\n return deepmerge(existingSchema as any, uploadSchema);\n }\n\n /**\n * Validates that a user-defined multipart/form-data schema includes all required upload fields\n * with correct types, formats, and required flags.\n *\n * @param {any} userDefinedMultipartSchema - The schema object from openapi.requestBody.content['multipart/form-data'].schema\n * @param {UploadConfig} uploadConfig - The upload configuration from config.experimental.uploads\n * @param {string} routePath - The route path for error context\n * @throws {Error} If upload fields are missing or incorrectly defined\n *\n * @example\n * validateMultipartFormDocs(\n * { type: 'object', properties: { avatar: { type: 'string', format: 'binary' } } },\n * { type: 'single', field: 'avatar', required: true },\n * '/users/:id/avatar'\n * )\n */\n validateMultipartFormDocs(\n userDefinedMultipartSchema: any,\n routePath: string,\n uploadConfig?: UploadConfig\n ): void {\n const errors: string[] = [];\n const properties = userDefinedMultipartSchema?.properties || {};\n const requiredFields = userDefinedMultipartSchema?.required || [];\n\n const expectedFields: Array<{\n name: string;\n required: boolean;\n expectedType: \"single\" | \"array\";\n }> = [];\n\n if (uploadConfig?.type === \"single\") {\n expectedFields.push({\n name: uploadConfig.field,\n required: uploadConfig.required !== false,\n expectedType: \"single\",\n });\n } else if (uploadConfig?.type === \"array\") {\n expectedFields.push({\n name: uploadConfig.field,\n required: uploadConfig.required !== false,\n expectedType: \"array\",\n });\n } else if (uploadConfig?.type === \"fields\") {\n for (const field of uploadConfig.fields) {\n expectedFields.push({\n name: field.name,\n required: uploadConfig.required !== false,\n expectedType: \"array\",\n });\n }\n }\n\n for (const { name, required, expectedType } of expectedFields) {\n const fieldSchema = properties[name];\n\n if (!fieldSchema) {\n errors.push(\n `Missing upload field '${name}' in multipart/form-data schema`\n );\n continue;\n }\n\n if (expectedType === \"single\") {\n if (fieldSchema.type !== \"string\")\n errors.push(\n `Upload field '${name}' must have type 'string', got '${fieldSchema.type}'`\n );\n\n if (fieldSchema.format !== \"binary\")\n errors.push(\n `Upload field '${name}' must have format 'binary', got '${fieldSchema.format || \"undefined\"}'`\n );\n } else if (expectedType === \"array\") {\n if (fieldSchema.type !== \"array\") {\n errors.push(\n `Upload field '${name}' must have type 'array', got '${fieldSchema.type}'`\n );\n } else if (\n !fieldSchema.items ||\n fieldSchema.items.type !== \"string\" ||\n fieldSchema.items.format !== \"binary\"\n )\n errors.push(\n `Upload field '${name}' must have items with type 'string' and format 'binary'`\n );\n }\n\n const isMarkedRequired = requiredFields.includes(name);\n if (required && !isMarkedRequired)\n errors.push(\n `Upload field '${name}' is required in config but not marked as required in schema`\n );\n\n if (!required && isMarkedRequired)\n errors.push(\n `Upload field '${name}' is not required in config but marked as required in schema`\n );\n }\n\n if (errors.length > 0) {\n throw new Error(\n `ValidationError: Invalid multipart/form-data schema for route '${routePath}':\\n${errors.map((e) => ` - ${e}`).join(\"\\n\")}`\n );\n }\n }\n}\n\nconst arkosRouterOpenApiManager = new ArkosRouterOpenAPIManager();\n\nexport default arkosRouterOpenApiManager;\n"]}
@@ -13,6 +13,7 @@ const class_validator_to_json_schema_1 = __importDefault(require("../../modules/
13
13
  const openapi_schema_converter_1 = __importDefault(require("../../modules/swagger/utils/helpers/openapi-schema-converter.js"));
14
14
  const arkos_router_openapi_manager_1 = __importDefault(require("./arkos-router-openapi-manager.js"));
15
15
  const apply_arkos_router_proxy_1 = require("./utils/helpers/apply-arkos-router-proxy.js");
16
+ const upload_manager_1 = __importDefault(require("./utils/helpers/upload-manager.js"));
16
17
  function ArkosRouter(options) {
17
18
  const router = (0, express_1.Router)(options);
18
19
  return (0, apply_arkos_router_proxy_1.applyArkosRouterProxy)(router, options);
@@ -96,6 +97,9 @@ function generateOpenAPIFromApp(app) {
96
97
  delete convertedOpenAPI.parameters;
97
98
  const hasUploadFields = Object.keys(config?.experimental?.uploads || {}).length > 0;
98
99
  const multipartFormSchema = convertedOpenAPI?.requestBody?.content?.["multipart/form-data"];
100
+ const allUploadFieldsAreRequired = hasUploadFields
101
+ ? upload_manager_1.default.isAllFieldRequired(config?.experimental?.uploads)
102
+ : false;
99
103
  if (hasUploadFields && multipartFormSchema)
100
104
  arkos_router_openapi_manager_1.default.validateMultipartFormDocs(multipartFormSchema, path, config?.experimental?.uploads);
101
105
  paths[path][method.toLowerCase()] = {
@@ -123,9 +127,11 @@ function generateOpenAPIFromApp(app) {
123
127
  schema: openapi_schema_converter_1.default.flattenSchema(arkos_router_openapi_manager_1.default.addUploadFields(config.experimental?.uploads, schema)),
124
128
  },
125
129
  }),
126
- "application/json": {
127
- schema,
128
- },
130
+ ...(!allUploadFieldsAreRequired && {
131
+ "application/json": {
132
+ schema,
133
+ },
134
+ }),
129
135
  };
130
136
  })(),
131
137
  },
@@ -137,11 +143,17 @@ function generateOpenAPIFromApp(app) {
137
143
  content: (() => {
138
144
  const schema = convertedOpenAPI?.requestBody?.content?.["application/json"]
139
145
  ?.schema || {};
146
+ delete convertedOpenAPI?.requestBody?.content?.["application/json"];
140
147
  return {
141
148
  "multipart/form-data": {
142
149
  schema: openapi_schema_converter_1.default.flattenSchema(arkos_router_openapi_manager_1.default.addUploadFields(config?.experimental?.uploads || {}, schema)),
143
150
  },
144
151
  ...convertedOpenAPI?.requestBody?.content,
152
+ ...(!allUploadFieldsAreRequired && {
153
+ "application/json": {
154
+ schema,
155
+ },
156
+ }),
145
157
  };
146
158
  })(),
147
159
  },
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/utils/arkos-router/index.ts"],"names":[],"mappings":";;;;;AA8GA,8BAKC;AAID,wDA+LC;AAtTD,qCAAgD;AAGhD,6CAAwE;AACxE,2CAA+C;AAC/C,4EAAiD;AACjD,wIAA4G;AAC5G,4HAAkG;AAClG,kGAAuE;AACvE,uFAAiF;AAqGjF,SAAwB,WAAW,CACjC,OAA4C;IAE5C,MAAM,MAAM,GAAG,IAAA,gBAAM,EAAC,OAAO,CAAC,CAAC;IAC/B,OAAO,IAAA,gDAAqB,EAAC,MAAM,EAAE,OAAO,CAAiB,CAAC;AAChE,CAAC;AAED,MAAM,iBAAiB,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAEnE,SAAgB,sBAAsB,CAAC,GAAU;IAC/C,MAAM,MAAM,GAAG,IAAA,4BAAkB,EAAC,GAAG,CAAC,CAAC;IACvC,MAAM,WAAW,GAAG,IAAA,wBAAc,GAAE,CAAC;IAErC,IAAI,KAAK,GAGL,EAAE,CAAC;IAEP,MAAM,CAAC,OAAO,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,YAA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aACF,CAAC;YACJ,GAAG,CAAC,CAAC,mBAAmB;gBACtB,CAAE,MAAc,EAAE,UAAU,EAAE,IAAI;gBAClC,eAAe,IAAI;gBACjB,WAAW,EAAE;oBACX,OAAO,EAAE,CAAC,GAAG,EAAE;wBACb,MAAM,MAAM,GACV,gBAAgB,EAAE,WAAW,EAAE,OAAO,EAAE,CAAC,kBAAkB,CAAC;4BAC1D,EAAE,MAAM,IAAI,EAAE,CAAC;wBAEnB,OAAO;4BACL,qBAAqB,EAAE;gCACrB,MAAM,EAAE,kCAAsB,CAAC,aAAa,CAC1C,sCAAyB,CAAC,eAAe,CACvC,MAAM,EAAE,YAAY,EAAE,OAAQ,IAAI,EAAE,EACpC,MAAM,CACP,CACF;6BACF;4BACD,GAAG,gBAAgB,EAAE,WAAW,EAAE,OAAO;yBAC1C,CAAC;oBACJ,CAAC,CAAC,EAAE;iBACL;aACF,CAAC;SACuB,CAAC;IAChC,CAAC,CAAC,CAAC;IAEH,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { Router, RouterOptions } from \"express\";\nimport { IArkosRouter } from \"./types\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport { extractArkosRoutes, extractPathParams } from \"./utils/helpers\";\nimport { getArkosConfig } from \"../../exports\";\nimport zodToJsonSchema from \"zod-to-json-schema\";\nimport classValidatorToJsonSchema from \"../../modules/swagger/utils/helpers/class-validator-to-json-schema\";\nimport openApiSchemaConverter from \"../../modules/swagger/utils/helpers/openapi-schema-converter\";\nimport arkosRouterOpenApiManager from \"./arkos-router-openapi-manager\";\nimport { applyArkosRouterProxy } from \"./utils/helpers/apply-arkos-router-proxy\";\nimport { Arkos } from \"../../types/arkos\";\n\nexport type ArkosRouterOptions = {\n /**\n * Prefix to apply to all routes in this router.\n * Nested routers inherit and concatenate prefixes from parent routers.\n *\n * @since 1.5.0-beta\n * @example\n * // All routes in this router will be prefixed with \"/api\"\n * prefix: \"/api\"\n */\n prefix?: string | RegExp | Array<string | RegExp>;\n /**\n * OpenAPI metadata to apply to all routes in this router.\n * Nested routers inherit from parent routers unless explicitly overridden.\n * Route-level openapi config fully replaces inherited values when defined.\n *\n * @since 1.6.0-beta\n * @example\n * openapi: {\n * tags: [\"Users\"],\n * security: [{ bearerAuth: [] }]\n * }\n */\n openapi?: {\n /**\n * Tags to apply to all routes in this router, used to group them in OpenAPI documentation.\n * Route-level tags fully replaces this value when defined.\n *\n * @since 1.6.0-beta\n * @example\n * // Group all routes in this router under \"Users\"\n * tags: [\"Users\"]\n */\n tags?: string[];\n /**\n * Security requirements to apply to all routes in this router.\n * Route-level security fully replaces this value when defined.\n *\n * @since 1.6.2-canary.1\n * @example\n * // Require bearer auth for all routes in this router\n * security: [{ bearerAuth: [] }]\n *\n * // Explicitly make all routes public (overridable per route)\n * security: []\n */\n security?: OpenAPIV3.SecurityRequirementObject[];\n\n /**\n * Server definitions to apply to all routes in this router.\n * Follows the OpenAPI 3.0 Server Object specification.\n * Route-level servers fully replaces this value when defined.\n *\n * @since 1.6.2-canary.1\n * @example\n * servers: [{ url: \"https://api.example.com/v2\", description: \"V2 API\" }]\n */\n servers?: OpenAPIV3.ServerObject[];\n /**\n * External documentation to apply to all routes in this router.\n * Route-level externalDocs fully replaces this value when defined.\n *\n * @since 1.6.2-canary.1\n * @example\n * externalDocs: {\n * description: \"Find more information here\",\n * url: \"https://docs.example.com/users\"\n * }\n */\n externalDocs?: OpenAPIV3.ExternalDocumentationObject;\n };\n};\n\n/**\n * Creates an enhanced Express Router with features like OpenAPI documentation capabilities and smart data validation.\n *\n * The ArkosRouter extends the standard Express Router with the ability to\n * automatically capture OpenAPI metadata from route configurations.\n *\n * @example\n * const router = ArkosRouter();\n *\n * router.get(\n * {\n * path: \"/users/:id\",\n * openapi: {\n * summary: \"Get user by ID\",\n * tags: [\"Users\"]\n * }\n * },\n * (req, res) => { ... }\n * );\n *\n * @returns {IArkosRouter} A proxied Express Router instance with enhanced OpenAPI capabilities\n *\n * @see {@link https://www.arkosjs.com/docs/reference/arkos-router} for configuration options\n * @since 1.4.0-beta\n */\nexport default function ArkosRouter(\n options?: RouterOptions & ArkosRouterOptions\n): IArkosRouter {\n const router = Router(options);\n return applyArkosRouterProxy(router, options) as IArkosRouter;\n}\n\nconst hasDuplicatedPath = (path: string) => /^(\\/.+)\\1/.test(path);\n\nexport function generateOpenAPIFromApp(app: Arkos) {\n const routes = extractArkosRoutes(app);\n const arkosConfig = getArkosConfig();\n\n let paths: Record<\n string,\n Record<string, Partial<OpenAPIV3.OperationObject>>\n > = {};\n\n routes.forEach(({ path, method, config, routeOptions }) => {\n if (config?.experimental?.openapi === false || hasDuplicatedPath(path))\n return;\n const originalPath = path;\n\n const pathParatemersFromRoutePath = extractPathParams(path);\n for (const parameter of pathParatemersFromRoutePath) {\n path = path.replaceAll(\n `:${parameter}`,\n parameter.endsWith(\"?\") ? `{${parameter}}?` : `{${parameter}}`\n );\n }\n\n let wildcardCount = (path.match(/\\*/g) || []).length;\n let wildcardIndex = 0;\n path = path.replace(/\\*/g, () => {\n wildcardIndex++;\n return wildcardCount === 1 ? \"{path}\" : `{path${wildcardIndex}}`;\n });\n\n if (!paths[path]) paths[path] = {};\n\n if (typeof config?.experimental?.openapi === \"boolean\") {\n config = {\n ...config,\n experimental: {\n ...config.experimental,\n openapi: {},\n },\n };\n }\n\n const openapi =\n typeof config?.experimental?.openapi === \"object\" &&\n config.experimental.openapi !== null\n ? config.experimental.openapi\n : {};\n\n const validatorToJsonSchema =\n arkosConfig?.validation?.resolver === \"zod\"\n ? zodToJsonSchema\n : classValidatorToJsonSchema;\n\n let parameters = [];\n const validationToParameterMapping = {\n query: \"query\",\n params: \"path\",\n headers: \"header\",\n cookies: \"cookie\",\n };\n\n if (typeof config?.validation !== \"boolean\" && config?.validation) {\n for (const [key, val] of Object.entries(config?.validation)) {\n if ([\"body\"].includes(key)) continue;\n if ((config?.validation as any)[key]) {\n const jsonSchema = validatorToJsonSchema(val as any);\n const params = openApiSchemaConverter.jsonSchemaToOpenApiParameters(\n (validationToParameterMapping as any)[key],\n jsonSchema\n );\n parameters.push(...params);\n }\n }\n }\n\n const convertedOpenAPI =\n openApiSchemaConverter.convertOpenAPIConfig(openapi);\n\n const allParameters: OpenAPIV3.ParameterObject[] = [\n ...(convertedOpenAPI.parameters || []),\n ...parameters,\n ];\n\n for (const parameter of pathParatemersFromRoutePath) {\n if (\n !allParameters.find(\n ({ name, in: paramIn }) =>\n name === parameter.replace(\"?\", \"\") && paramIn === \"path\"\n )\n )\n allParameters.push({\n name: parameter,\n in: \"path\",\n required: !parameter.includes(\"?\"),\n schema: { type: \"string\" },\n });\n }\n\n for (const param of allParameters) {\n if (\n !pathParatemersFromRoutePath.includes(param.name) &&\n !pathParatemersFromRoutePath.includes(`${param.name}?`) &&\n param.in === \"path\" &&\n param.name !== \"*\"\n )\n throw new Error(\n `ValidationError: Trying to define path parameter '${param.name}' but it is not present in your pathname ${originalPath}`\n );\n }\n\n delete convertedOpenAPI.parameters;\n const hasUploadFields =\n Object.keys(config?.experimental?.uploads || {}).length > 0;\n const multipartFormSchema =\n convertedOpenAPI?.requestBody?.content?.[\"multipart/form-data\"];\n\n if (hasUploadFields && multipartFormSchema)\n arkosRouterOpenApiManager.validateMultipartFormDocs(\n multipartFormSchema,\n path,\n config?.experimental?.uploads\n );\n\n (paths as any)[path][method.toLowerCase()] = {\n ...convertedOpenAPI,\n summary: openapi?.summary || `${path}`,\n description: openapi?.description || `${method} ${path}`,\n servers: openapi?.servers || routeOptions?.openapi?.servers || undefined,\n security:\n openapi?.security || routeOptions?.openapi?.security || undefined,\n externalDocs:\n openapi?.externalDocs ||\n routeOptions?.openapi?.externalDocs ||\n undefined,\n tags: openapi?.tags || routeOptions?.openapi?.tags || [\"Defaults\"],\n operationId: openapi.operationId || `${method.toLowerCase()}:${path}`,\n parameters: allParameters,\n ...(!convertedOpenAPI.requestBody &&\n config?.validation &&\n config?.validation?.body && {\n requestBody: {\n content: (() => {\n const schema = validatorToJsonSchema(\n config?.validation?.body as any\n );\n\n return {\n ...convertedOpenAPI?.requestBody?.content,\n ...(hasUploadFields && {\n \"multipart/form-data\": {\n schema: openApiSchemaConverter.flattenSchema(\n arkosRouterOpenApiManager.addUploadFields(\n config.experimental?.uploads!,\n schema\n )\n ),\n },\n }),\n \"application/json\": {\n schema,\n },\n };\n })(),\n },\n }),\n ...(!multipartFormSchema &&\n !(config as any)?.validation?.body &&\n hasUploadFields && {\n requestBody: {\n content: (() => {\n const schema =\n convertedOpenAPI?.requestBody?.content?.[\"application/json\"]\n ?.schema || {};\n\n return {\n \"multipart/form-data\": {\n schema: openApiSchemaConverter.flattenSchema(\n arkosRouterOpenApiManager.addUploadFields(\n config?.experimental?.uploads! || {},\n schema\n )\n ),\n },\n ...convertedOpenAPI?.requestBody?.content,\n };\n })(),\n },\n }),\n } as OpenAPIV3.PathItemObject;\n });\n\n return paths;\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/utils/arkos-router/index.ts"],"names":[],"mappings":";;;;;AA+GA,8BAKC;AAID,wDA8MC;AAtUD,qCAAgD;AAGhD,6CAAwE;AACxE,2CAA+C;AAC/C,4EAAiD;AACjD,wIAA4G;AAC5G,4HAAkG;AAClG,kGAAuE;AACvE,uFAAiF;AAEjF,oFAA2D;AAoG3D,SAAwB,WAAW,CACjC,OAA4C;IAE5C,MAAM,MAAM,GAAG,IAAA,gBAAM,EAAC,OAAO,CAAC,CAAC;IAC/B,OAAO,IAAA,gDAAqB,EAAC,MAAM,EAAE,OAAO,CAAiB,CAAC;AAChE,CAAC;AAED,MAAM,iBAAiB,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAEnE,SAAgB,sBAAsB,CAAC,GAAU;IAC/C,MAAM,MAAM,GAAG,IAAA,4BAAkB,EAAC,GAAG,CAAC,CAAC;IACvC,MAAM,WAAW,GAAG,IAAA,wBAAc,GAAE,CAAC;IAErC,IAAI,KAA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ACrB,qBAAqB,EAAE;oCACrB,MAAM,EAAE,kCAAsB,CAAC,aAAa,CAC1C,sCAAyB,CAAC,eAAe,CACvC,MAAM,CAAC,YAAY,EAAE,OAAQ,EAC7B,MAAM,CACP,CACF;iCACF;6BACF,CAAC;4BACF,GAAG,CAAC,CAAC,0BAA0B,IAAI;gCACjC,kBAAkB,EAAE;oCAClB,MAAM;iCACP;6BACF,CAAC;yBACH,CAAC;oBACJ,CAAC,CAAC,EAAE;iBACL;aACF,CAAC;YACJ,GAAG,CAAC,CAAC,mBAAmB;gBACtB,CAAE,MAAc,EAAE,UAAU,EAAE,IAAI;gBAClC,eAAe,IAAI;gBACjB,WAAW,EAAE;oBACX,OAAO,EAAE,CAAC,GAAG,EAAE;wBACb,MAAM,MAAM,GACV,gBAAgB,EAAE,WAAW,EAAE,OAAO,EAAE,CAAC,kBAAkB,CAAC;4BAC1D,EAAE,MAAM,IAAI,EAAE,CAAC;wBAEnB,OAAO,gBAAgB,EAAE,WAAW,EAAE,OAAO,EAAE,CAC7C,kBAAkB,CACnB,CAAC;wBAEF,OAAO;4BACL,qBAAqB,EAAE;gCACrB,MAAM,EAAE,kCAAsB,CAAC,aAAa,CAC1C,sCAAyB,CAAC,eAAe,CACvC,MAAM,EAAE,YAAY,EAAE,OAAQ,IAAI,EAAE,EACpC,MAAM,CACP,CACF;6BACF;4BACD,GAAG,gBAAgB,EAAE,WAAW,EAAE,OAAO;4BACzC,GAAG,CAAC,CAAC,0BAA0B,IAAI;gCACjC,kBAAkB,EAAE;oCAClB,MAAM;iCACP;6BACF,CAAC;yBACH,CAAC;oBACJ,CAAC,CAAC,EAAE;iBACL;aACF,CAAC;SACuB,CAAC;IAChC,CAAC,CAAC,CAAC;IAEH,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { Router, RouterOptions } from \"express\";\nimport { IArkosRouter } from \"./types\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport { extractArkosRoutes, extractPathParams } from \"./utils/helpers\";\nimport { getArkosConfig } from \"../../exports\";\nimport zodToJsonSchema from \"zod-to-json-schema\";\nimport classValidatorToJsonSchema from \"../../modules/swagger/utils/helpers/class-validator-to-json-schema\";\nimport openApiSchemaConverter from \"../../modules/swagger/utils/helpers/openapi-schema-converter\";\nimport arkosRouterOpenApiManager from \"./arkos-router-openapi-manager\";\nimport { applyArkosRouterProxy } from \"./utils/helpers/apply-arkos-router-proxy\";\nimport { Arkos } from \"../../types/arkos\";\nimport uploadManager from \"./utils/helpers/upload-manager\";\n\nexport type ArkosRouterOptions = {\n /**\n * Prefix to apply to all routes in this router.\n * Nested routers inherit and concatenate prefixes from parent routers.\n *\n * @since 1.5.0-beta\n * @example\n * // All routes in this router will be prefixed with \"/api\"\n * prefix: \"/api\"\n */\n prefix?: string | RegExp | Array<string | RegExp>;\n /**\n * OpenAPI metadata to apply to all routes in this router.\n * Nested routers inherit from parent routers unless explicitly overridden.\n * Route-level openapi config fully replaces inherited values when defined.\n *\n * @since 1.6.0-beta\n * @example\n * openapi: {\n * tags: [\"Users\"],\n * security: [{ bearerAuth: [] }]\n * }\n */\n openapi?: {\n /**\n * Tags to apply to all routes in this router, used to group them in OpenAPI documentation.\n * Route-level tags fully replaces this value when defined.\n *\n * @since 1.6.0-beta\n * @example\n * // Group all routes in this router under \"Users\"\n * tags: [\"Users\"]\n */\n tags?: string[];\n /**\n * Security requirements to apply to all routes in this router.\n * Route-level security fully replaces this value when defined.\n *\n * @since 1.6.2-canary.1\n * @example\n * // Require bearer auth for all routes in this router\n * security: [{ bearerAuth: [] }]\n *\n * // Explicitly make all routes public (overridable per route)\n * security: []\n */\n security?: OpenAPIV3.SecurityRequirementObject[];\n\n /**\n * Server definitions to apply to all routes in this router.\n * Follows the OpenAPI 3.0 Server Object specification.\n * Route-level servers fully replaces this value when defined.\n *\n * @since 1.6.2-canary.1\n * @example\n * servers: [{ url: \"https://api.example.com/v2\", description: \"V2 API\" }]\n */\n servers?: OpenAPIV3.ServerObject[];\n /**\n * External documentation to apply to all routes in this router.\n * Route-level externalDocs fully replaces this value when defined.\n *\n * @since 1.6.2-canary.1\n * @example\n * externalDocs: {\n * description: \"Find more information here\",\n * url: \"https://docs.example.com/users\"\n * }\n */\n externalDocs?: OpenAPIV3.ExternalDocumentationObject;\n };\n};\n\n/**\n * Creates an enhanced Express Router with features like OpenAPI documentation capabilities and smart data validation.\n *\n * The ArkosRouter extends the standard Express Router with the ability to\n * automatically capture OpenAPI metadata from route configurations.\n *\n * @example\n * const router = ArkosRouter();\n *\n * router.get(\n * {\n * path: \"/users/:id\",\n * openapi: {\n * summary: \"Get user by ID\",\n * tags: [\"Users\"]\n * }\n * },\n * (req, res) => { ... }\n * );\n *\n * @returns {IArkosRouter} A proxied Express Router instance with enhanced OpenAPI capabilities\n *\n * @see {@link https://www.arkosjs.com/docs/reference/arkos-router} for configuration options\n * @since 1.4.0-beta\n */\nexport default function ArkosRouter(\n options?: RouterOptions & ArkosRouterOptions\n): IArkosRouter {\n const router = Router(options);\n return applyArkosRouterProxy(router, options) as IArkosRouter;\n}\n\nconst hasDuplicatedPath = (path: string) => /^(\\/.+)\\1/.test(path);\n\nexport function generateOpenAPIFromApp(app: Arkos) {\n const routes = extractArkosRoutes(app);\n const arkosConfig = getArkosConfig();\n\n let paths: Record<\n string,\n Record<string, Partial<OpenAPIV3.OperationObject>>\n > = {};\n\n routes.forEach(({ path, method, config, routeOptions }) => {\n if (config?.experimental?.openapi === false || hasDuplicatedPath(path))\n return;\n const originalPath = path;\n\n const pathParatemersFromRoutePath = extractPathParams(path);\n for (const parameter of pathParatemersFromRoutePath) {\n path = path.replaceAll(\n `:${parameter}`,\n parameter.endsWith(\"?\") ? `{${parameter}}?` : `{${parameter}}`\n );\n }\n\n let wildcardCount = (path.match(/\\*/g) || []).length;\n let wildcardIndex = 0;\n path = path.replace(/\\*/g, () => {\n wildcardIndex++;\n return wildcardCount === 1 ? \"{path}\" : `{path${wildcardIndex}}`;\n });\n\n if (!paths[path]) paths[path] = {};\n\n if (typeof config?.experimental?.openapi === \"boolean\") {\n config = {\n ...config,\n experimental: {\n ...config.experimental,\n openapi: {},\n },\n };\n }\n\n const openapi =\n typeof config?.experimental?.openapi === \"object\" &&\n config.experimental.openapi !== null\n ? config.experimental.openapi\n : {};\n\n const validatorToJsonSchema =\n arkosConfig?.validation?.resolver === \"zod\"\n ? zodToJsonSchema\n : classValidatorToJsonSchema;\n\n let parameters = [];\n const validationToParameterMapping = {\n query: \"query\",\n params: \"path\",\n headers: \"header\",\n cookies: \"cookie\",\n };\n\n if (typeof config?.validation !== \"boolean\" && config?.validation) {\n for (const [key, val] of Object.entries(config?.validation)) {\n if ([\"body\"].includes(key)) continue;\n if ((config?.validation as any)[key]) {\n const jsonSchema = validatorToJsonSchema(val as any);\n const params = openApiSchemaConverter.jsonSchemaToOpenApiParameters(\n (validationToParameterMapping as any)[key],\n jsonSchema\n );\n parameters.push(...params);\n }\n }\n }\n\n const convertedOpenAPI =\n openApiSchemaConverter.convertOpenAPIConfig(openapi);\n\n const allParameters: OpenAPIV3.ParameterObject[] = [\n ...(convertedOpenAPI.parameters || []),\n ...parameters,\n ];\n\n for (const parameter of pathParatemersFromRoutePath) {\n if (\n !allParameters.find(\n ({ name, in: paramIn }) =>\n name === parameter.replace(\"?\", \"\") && paramIn === \"path\"\n )\n )\n allParameters.push({\n name: parameter,\n in: \"path\",\n required: !parameter.includes(\"?\"),\n schema: { type: \"string\" },\n });\n }\n\n for (const param of allParameters) {\n if (\n !pathParatemersFromRoutePath.includes(param.name) &&\n !pathParatemersFromRoutePath.includes(`${param.name}?`) &&\n param.in === \"path\" &&\n param.name !== \"*\"\n )\n throw new Error(\n `ValidationError: Trying to define path parameter '${param.name}' but it is not present in your pathname ${originalPath}`\n );\n }\n\n delete convertedOpenAPI.parameters;\n const hasUploadFields =\n Object.keys(config?.experimental?.uploads || {}).length > 0;\n const multipartFormSchema =\n convertedOpenAPI?.requestBody?.content?.[\"multipart/form-data\"];\n\n const allUploadFieldsAreRequired = hasUploadFields\n ? uploadManager.isAllFieldRequired(config?.experimental?.uploads!)\n : false;\n\n if (hasUploadFields && multipartFormSchema)\n arkosRouterOpenApiManager.validateMultipartFormDocs(\n multipartFormSchema,\n path,\n config?.experimental?.uploads\n );\n\n (paths as any)[path][method.toLowerCase()] = {\n ...convertedOpenAPI,\n summary: openapi?.summary || `${path}`,\n description: openapi?.description || `${method} ${path}`,\n servers: openapi?.servers || routeOptions?.openapi?.servers || undefined,\n security:\n openapi?.security || routeOptions?.openapi?.security || undefined,\n externalDocs:\n openapi?.externalDocs ||\n routeOptions?.openapi?.externalDocs ||\n undefined,\n tags: openapi?.tags || routeOptions?.openapi?.tags || [\"Defaults\"],\n operationId: openapi.operationId || `${method.toLowerCase()}:${path}`,\n parameters: allParameters,\n ...(!convertedOpenAPI.requestBody &&\n config?.validation &&\n config?.validation?.body && {\n requestBody: {\n content: (() => {\n const schema = validatorToJsonSchema(\n config?.validation?.body as any\n );\n\n return {\n ...convertedOpenAPI?.requestBody?.content,\n ...(hasUploadFields && {\n \"multipart/form-data\": {\n schema: openApiSchemaConverter.flattenSchema(\n arkosRouterOpenApiManager.addUploadFields(\n config.experimental?.uploads!,\n schema\n )\n ),\n },\n }),\n ...(!allUploadFieldsAreRequired && {\n \"application/json\": {\n schema,\n },\n }),\n };\n })(),\n },\n }),\n ...(!multipartFormSchema &&\n !(config as any)?.validation?.body &&\n hasUploadFields && {\n requestBody: {\n content: (() => {\n const schema =\n convertedOpenAPI?.requestBody?.content?.[\"application/json\"]\n ?.schema || {};\n\n delete convertedOpenAPI?.requestBody?.content?.[\n \"application/json\"\n ];\n\n return {\n \"multipart/form-data\": {\n schema: openApiSchemaConverter.flattenSchema(\n arkosRouterOpenApiManager.addUploadFields(\n config?.experimental?.uploads! || {},\n schema\n )\n ),\n },\n ...convertedOpenAPI?.requestBody?.content,\n ...(!allUploadFieldsAreRequired && {\n \"application/json\": {\n schema,\n },\n }),\n };\n })(),\n },\n }),\n } as OpenAPIV3.PathItemObject;\n });\n\n return paths;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/utils/arkos-router/types/index.ts"],"names":[],"mappings":"","sourcesContent":["import {\n Application,\n IRoute,\n IRouter,\n IRouterHandler,\n IRouterMatcher,\n Locals,\n} from \"express\";\nimport { z, ZodSchema } from \"zod\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport { Options as QueryParserOptions } from \"../../../utils/helpers/query-parser.helpers\";\nimport { DetailedAccessControlRule } from \"../../../types/auth\";\nimport {\n ArkosAnyRequestHandler,\n ArkosErrorRequestHandler,\n ArkosRequestHandler,\n} from \"../../../types\";\nimport compression from \"compression\";\nimport { OpenApiConfig } from \"./openapi-config\";\nimport { UploadConfig } from \"./upload-config\";\nimport { BodyParserConfig } from \"./body-parser-config\";\nimport { ArkosRouterOptions } from \"..\";\nimport { Validator } from \"../../../types/validation/validator\";\n\nexport type ArkosUseConfig = Pick<\n ArkosRouteConfig,\n | \"authentication\"\n | \"rateLimit\"\n | \"compression\"\n | \"queryParser\"\n | \"bodyParser\"\n | \"disabled\"\n> & {\n path?: PathParams; // optional unlike ArkosRouteConfig where path is required\n};\n\ntype InferValidationType<T, Fallback> = T extends ZodSchema\n ? z.infer<T>\n : T extends new (...args: any[]) => infer I\n ? I\n : Fallback;\n\nexport type PathParams = string | RegExp | Array<string | RegExp>;\n\nexport type InternalIArkosRouter = IArkosRouter & {\n _arkos: {\n options?: ArkosRouterOptions;\n routes: Array<{\n handler: ArkosAnyRequestHandler;\n config: ArkosRouteConfig;\n method: string;\n }>;\n };\n};\n\n/**\n * Handler function for HTTP methods that accepts route configuration and request handlers.\n *\n * @param {ArkosRouteConfig} config - The route configuration object.\n * @param {...(ArkosRequestHandler | ArkosErrorRequestHandler)[]} handlers - Request and error handlers for the route.\n * @returns {IRouter} The Express router instance.\n */\ntype RouterMethodHandler<T> = IRouterHandler<T> &\n IRouterMatcher<T> & {\n // (config: PathParams, ...handlers: Array<ArkosAnyRequestHandler>): T;\n <\n TQuery extends Validator = any,\n TBody extends Validator = any,\n TParams extends Validator = any,\n >(\n config: ArkosRouteConfig<TQuery, TBody, TParams>,\n ...handlers: Array<\n | ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n | Array<\n ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n >\n >\n ): T;\n <\n TQuery extends Validator = any,\n TBody extends Validator = any,\n TParams extends Validator = any,\n >(\n config: ArkosRouteConfig<TQuery, TBody, TParams>,\n ...handlers: Array<\n | ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n | Array<\n ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n >\n >\n ): T;\n\n <\n TQuery extends Validator = any,\n TBody extends Validator = any,\n TParams extends Validator = any,\n >(\n config: ArkosRouteConfig<TQuery, TBody, TParams>,\n subApplication: Application\n ): T;\n };\n\nexport type ArkosRouteMethodHandler<T> = {\n (\n config: ArkosAnyRequestHandler | Omit<ArkosRouteConfig, \"path\">,\n ...handlers: Array<\n | ArkosRequestHandler\n | ArkosErrorRequestHandler\n | Array<ArkosRequestHandler | ArkosErrorRequestHandler>\n >\n ): T;\n <\n TQuery extends Validator = any,\n TBody extends Validator = any,\n TParams extends Validator = any,\n >(\n config: Omit<ArkosRouteConfig<TQuery, TBody, TParams>, \"path\">,\n ...handlers: Array<\n | ArkosAnyRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n | Array<\n ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n >\n >\n ): T;\n\n <\n TQuery extends Validator = any,\n TBody extends Validator = any,\n TParams extends Validator = any,\n >(\n config: Omit<ArkosRouteConfig<TQuery, TBody, TParams>, \"path\">,\n ...handlers: Array<\n | ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n | Array<\n ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n >\n >\n ): T;\n};\n\n/**\n * Handler function for `use` that accepts route configuration and middleware handlers.\n *\n * @param {ArkosUseConfig} config - The use configuration object or path.\n * @param {...ArkosAnyRequestHandler} handlers - Middleware handlers.\n * @returns {T} The router instance.\n */\n\nexport type UseMethodHandler<T> = IRouterHandler<T> &\n IRouterMatcher<T> & {\n (\n config: ArkosUseConfig,\n ...handlers: Array<ArkosRequestHandler | Array<ArkosRequestHandler>>\n ): T;\n (\n config: ArkosUseConfig,\n ...handlers: Array<\n ArkosErrorRequestHandler | Array<ArkosErrorRequestHandler>\n >\n ): T;\n (...handlers: Array<ArkosRequestHandler | Array<ArkosRequestHandler>>): T;\n };\n\nexport interface IArkosRoute extends IRoute {\n /** GET method handler with route configuration support */\n get: ArkosRouteMethodHandler<this>;\n /** POST method handler with route configuration support */\n post: ArkosRouteMethodHandler<this>;\n /** PUT method handler with route configuration support */\n put: ArkosRouteMethodHandler<this>;\n /** PATCH method handler with route configuration support */\n patch: ArkosRouteMethodHandler<this>;\n /** DELETE method handler with route configuration support */\n delete: ArkosRouteMethodHandler<this>;\n /** OPTIONS method handler with route configuration support */\n options: ArkosRouteMethodHandler<this>;\n /** HEAD method handler with route configuration support */\n head: ArkosRouteMethodHandler<this>;\n // /** TRACE method handler with route configuration support */\n trace: ArkosRouteMethodHandler<this>;\n /** ALL methods handler with route configuration support */\n all: ArkosRouteMethodHandler<this>;\n}\n\n/**\n * Creates an enhanced Express Router with features like OpenAPI documentation capabilities and smart data validation.\n *\n * The ArkosRouter extends the standard Express Router with the ability to\n * automatically capture OpenAPI metadata from route configurations.\n *\n * @example\n * const router = ArkosRouter();\n *\n * router.get(\n * {\n * path: \"/users/:id\",\n * openapi: {\n * summary: \"Get user by ID\",\n * tags: [\"Users\"]\n * }\n * },\n * (req, res) => { ... }\n * );\n *\n * @returns {IArkosRouter} A proxied Express Router instance with enhanced OpenAPI capabilities\n *\n * @see {@link ArkosRouteConfig} for configuration options\n */\nexport interface IArkosRouter extends IRouter {\n /** GET method handler with route configuration support */\n get: RouterMethodHandler<this>;\n /** POST method handler with route configuration support */\n post: RouterMethodHandler<this>;\n /** PUT method handler with route configuration support */\n put: RouterMethodHandler<this>;\n /** PATCH method handler with route configuration support */\n patch: RouterMethodHandler<this>;\n /** DELETE method handler with route configuration support */\n delete: RouterMethodHandler<this>;\n /** OPTIONS method handler with route configuration support */\n options: RouterMethodHandler<this>;\n /** HEAD method handler with route configuration support */\n head: RouterMethodHandler<this>;\n // /** TRACE method handler with route configuration support */\n trace: RouterMethodHandler<this>;\n /** ALL methods handler with route configuration support */\n all: RouterMethodHandler<this>;\n use: UseMethodHandler<this>;\n route<T extends string>(prefix: T): IArkosRoute;\n route(prefix: PathParams): IArkosRoute;\n}\n\n/**\n * Configuration object for defining routes in Arkos.js.\n */\nexport type ArkosRouteConfig<\n TQuery extends Validator = any,\n TBody extends Validator = any,\n TParams extends Validator = any,\n> = {\n /**\n * Disables the route by not mounting it internally.\n */\n disabled?: boolean;\n /**\n * The URL path pattern for the route.\n *\n * @example \"/api/users/:id\"\n */\n path: PathParams;\n /**\n * Authentication and authorization configuration.\n *\n * @remarks\n * - Set to `true` to require authentication without specific permissions.\n * - Set to `false` or omit to allow unauthenticated access.\n * - Provide an object to specify resource-based access control with resource name, action, and optional custom rules.\n */\n authentication?:\n | boolean\n | {\n resource: string;\n action: string;\n rule?: DetailedAccessControlRule | string[] | \"*\";\n };\n /**\n * Request validation configuration using Zod schemas or class constructors.\n *\n * @remarks\n * - Set to `false` to disable all validation.\n * - Set to `null` to forbidden all request inputs.\n * - Provide an object with `query`, `body`, and/or `params` properties to validate specific parts of the request.\n * - Each property accepts a Zod schema, a class constructor, or `false` to disable validation for that part.\n */\n validation?:\n | false\n | null\n | {\n query?: TQuery;\n body?: TBody;\n params?: TParams;\n };\n /**\n * Rate limiting configuration for this route.\n *\n * @see {@link https://www.npmjs.com/package/express-rate-limit express-rate-limit} for available options.\n */\n rateLimit?: Partial<RateLimitOptions>;\n\n /**\n * Allows to define options for npm package compression.\n * Nothing is passed by default.\n *\n * @see {@link https://www.npmjs.com/package/compression compression} for further details.\n */\n compression?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * @example\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n *\n * @default\n * ```\n * {\n * parseNull: true,\n * parseUndefined: true,\n * parseBoolean: true,\n * }\n * ```\n *\n * @remarks\n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n *\n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParser?: QueryParserOptions;\n /**\n * Configuration for request body parsing.\n *\n * @property {(\"json\" | \"urlencoded\" | \"raw\" | \"text\")} parser - The type of body parser to use.\n * @property {object} [options] - Parser-specific options passed to the corresponding Express body parser middleware.\n *\n * @remarks\n * - When `parser` is `\"json\"`, options are passed to `express.json()`.\n * - When `parser` is `\"urlencoded\"`, options are passed to `express.urlencoded()`.\n * - When `parser` is `\"raw\"`, options are passed to `express.raw()`.\n * - When `parser` is `\"text\"`, options are passed to `express.text()`.\n * - Set to `false` to disable body parsing for this route.\n *\n * @see {@link https://expressjs.com/en/api.html#express.json Express body parser documentation}\n */\n bodyParser?: BodyParserConfig | BodyParserConfig[] | false;\n /**\n * Experimental features to be battled tested before being stable\n *\n * PS: These features may be changed without any previous warning.\n */\n experimental?: {\n /**\n * OpenAPI specification for this route.\n *\n * @remarks\n * - Set to `false` to exclude this route from OpenAPI documentation.\n * - Provide a partial OpenAPI operation object to document the route.\n */\n openapi?: false | OpenApiConfig;\n /**\n * Configuration for file upload handling in routes.\n * Supports single file, multiple files from same field, or multiple fields with files.\n */\n uploads?: UploadConfig;\n };\n};\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/utils/arkos-router/types/index.ts"],"names":[],"mappings":"","sourcesContent":["import {\n Application,\n IRoute,\n IRouter,\n IRouterHandler,\n IRouterMatcher,\n Locals,\n} from \"express\";\nimport { z, ZodSchema } from \"zod\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport { Options as QueryParserOptions } from \"../../../utils/helpers/query-parser.helpers\";\nimport { DetailedAccessControlRule } from \"../../../types/auth\";\nimport {\n ArkosAnyRequestHandler,\n ArkosErrorRequestHandler,\n ArkosRequestHandler,\n} from \"../../../types\";\nimport compression from \"compression\";\nimport { OpenApiConfig } from \"./openapi-config\";\nimport { UploadConfig } from \"./upload-config\";\nimport { BodyParserConfig } from \"./body-parser-config\";\nimport { ArkosRouterOptions } from \"..\";\nimport { Validator } from \"../../../types/validation/validator\";\n\nexport type ArkosUseConfig = Pick<\n ArkosRouteConfig,\n | \"authentication\"\n | \"rateLimit\"\n | \"compression\"\n | \"queryParser\"\n | \"bodyParser\"\n | \"disabled\"\n> & {\n path?: PathParams; // optional unlike ArkosRouteConfig where path is required\n};\n\ntype InferValidationType<T, Fallback> = T extends ZodSchema\n ? z.infer<T>\n : T extends new (...args: any[]) => infer I\n ? I\n : Fallback;\n\nexport type PathParams = string | RegExp | Array<string | RegExp>;\n\nexport type InternalIArkosRouter = IArkosRouter & {\n _arkos: {\n options?: ArkosRouterOptions;\n routes: Array<{\n handler: ArkosAnyRequestHandler;\n config: ArkosRouteConfig;\n method: string;\n }>;\n };\n};\n\n/**\n * Handler function for HTTP methods that accepts route configuration and request handlers.\n *\n * @param {ArkosRouteConfig} config - The route configuration object.\n * @param {...(ArkosRequestHandler | ArkosErrorRequestHandler)[]} handlers - Request and error handlers for the route.\n * @returns {IRouter} The Express router instance.\n */\ntype IArkosRouterMethodHandler<T> = IRouterHandler<T> &\n IRouterMatcher<T> & {\n <\n TQuery extends Validator = any,\n TBody extends Validator = any,\n TParams extends Validator = any,\n >(\n config: ArkosRouteConfig<TQuery, TBody, TParams>,\n ...handlers: Array<\n | ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n | Array<\n ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n >\n >\n ): T;\n <\n TQuery extends Validator = any,\n TBody extends Validator = any,\n TParams extends Validator = any,\n >(\n config: ArkosRouteConfig<TQuery, TBody, TParams> | PathParams,\n ...handlers: Array<\n | ArkosAnyRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n | Array<\n | ArkosAnyRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n | Array<\n ArkosErrorRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n any\n >\n >\n >\n >\n ): T;\n\n <\n TQuery extends Validator = any,\n TBody extends Validator = any,\n TParams extends Validator = any,\n >(\n config: ArkosRouteConfig<TQuery, TBody, TParams>,\n subApplication: Application\n ): T;\n };\n\nexport type ArkosRouteMethodHandler<T> = {\n <\n TQuery extends Validator = any,\n TBody extends Validator = any,\n TParams extends Validator = any,\n >(\n config: ArkosAnyRequestHandler | Omit<ArkosRouteConfig, \"path\">,\n ...handlers: Array<\n ArkosAnyRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n >\n ): T;\n <\n TQuery extends Validator = any,\n TBody extends Validator = any,\n TParams extends Validator = any,\n >(\n config: Omit<ArkosRouteConfig<TQuery, TBody, TParams>, \"path\">,\n ...handlers: Array<\n | ArkosAnyRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n | Array<\n ArkosRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n >\n >\n ): T;\n <\n TQuery extends Validator = any,\n TBody extends Validator = any,\n TParams extends Validator = any,\n >(\n config: Omit<ArkosRouteConfig<TQuery, TBody, TParams>, \"path\">,\n ...handlers: Array<\n | ArkosAnyRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n | Array<\n ArkosAnyRequestHandler<\n InferValidationType<TParams, Record<string, string>>,\n any,\n InferValidationType<TBody, any>,\n InferValidationType<TQuery, qs.ParsedQs>,\n Locals\n >\n >\n >\n ): T;\n};\n\n/**\n * Handler function for `use` that accepts route configuration and middleware handlers.\n *\n * @param {ArkosUseConfig} config - The use configuration object or path.\n * @param {...ArkosAnyRequestHandler} handlers - Middleware handlers.\n * @returns {T} The router instance.\n */\n\nexport type UseMethodHandler<T> = IRouterHandler<T> &\n IRouterMatcher<T> & {\n (\n config: ArkosUseConfig,\n ...handlers: Array<ArkosRequestHandler | Array<ArkosRequestHandler>>\n ): T;\n (\n config: ArkosUseConfig,\n ...handlers: Array<\n ArkosErrorRequestHandler | Array<ArkosErrorRequestHandler>\n >\n ): T;\n (\n config: ArkosUseConfig,\n ...handlers: Array<\n | ArkosRequestHandler\n | ArkosErrorRequestHandler\n | Array<ArkosRequestHandler | ArkosErrorRequestHandler>\n >\n ): T;\n (\n ...handlers: Array<\n | ArkosRequestHandler\n | ArkosErrorRequestHandler\n | Array<ArkosRequestHandler | ArkosErrorRequestHandler>\n >\n ): T;\n };\n\nexport interface IArkosRoute extends IRoute {\n /** GET method handler with route configuration support */\n get: ArkosRouteMethodHandler<this>;\n /** POST method handler with route configuration support */\n post: ArkosRouteMethodHandler<this>;\n /** PUT method handler with route configuration support */\n put: ArkosRouteMethodHandler<this>;\n /** PATCH method handler with route configuration support */\n patch: ArkosRouteMethodHandler<this>;\n /** DELETE method handler with route configuration support */\n delete: ArkosRouteMethodHandler<this>;\n /** OPTIONS method handler with route configuration support */\n options: ArkosRouteMethodHandler<this>;\n /** HEAD method handler with route configuration support */\n head: ArkosRouteMethodHandler<this>;\n // /** TRACE method handler with route configuration support */\n trace: ArkosRouteMethodHandler<this>;\n /** ALL methods handler with route configuration support */\n all: ArkosRouteMethodHandler<this>;\n}\n\n/**\n * Creates an enhanced Express Router with features like OpenAPI documentation capabilities and smart data validation.\n *\n * The ArkosRouter extends the standard Express Router with the ability to\n * automatically capture OpenAPI metadata from route configurations.\n *\n * @example\n * const router = ArkosRouter();\n *\n * router.get(\n * {\n * path: \"/users/:id\",\n * openapi: {\n * summary: \"Get user by ID\",\n * tags: [\"Users\"]\n * }\n * },\n * (req, res) => { ... }\n * );\n *\n * @returns {IArkosRouter} A proxied Express Router instance with enhanced OpenAPI capabilities\n *\n * @see {@link ArkosRouteConfig} for configuration options\n */\nexport interface IArkosRouter extends IRouter {\n /** GET method handler with route configuration support */\n get: IArkosRouterMethodHandler<this>;\n /** POST method handler with route configuration support */\n post: IArkosRouterMethodHandler<this>;\n /** PUT method handler with route configuration support */\n put: IArkosRouterMethodHandler<this>;\n /** PATCH method handler with route configuration support */\n patch: IArkosRouterMethodHandler<this>;\n /** DELETE method handler with route configuration support */\n delete: IArkosRouterMethodHandler<this>;\n /** OPTIONS method handler with route configuration support */\n options: IArkosRouterMethodHandler<this>;\n /** HEAD method handler with route configuration support */\n head: IArkosRouterMethodHandler<this>;\n // /** TRACE method handler with route configuration support */\n trace: IArkosRouterMethodHandler<this>;\n /** ALL methods handler with route configuration support */\n all: IArkosRouterMethodHandler<this>;\n use: UseMethodHandler<this>;\n route<T extends string>(prefix: T): IArkosRoute;\n route(prefix: PathParams): IArkosRoute;\n}\n\n/**\n * Configuration object for defining routes in Arkos.js.\n */\nexport type ArkosRouteConfig<\n TQuery extends Validator = any,\n TBody extends Validator = any,\n TParams extends Validator = any,\n> = {\n /**\n * Disables the route by not mounting it internally.\n */\n disabled?: boolean;\n /**\n * The URL path pattern for the route.\n *\n * @example \"/api/users/:id\"\n */\n path: PathParams;\n /**\n * Authentication and authorization configuration.\n *\n * @remarks\n * - Set to `true` to require authentication without specific permissions.\n * - Set to `false` or omit to allow unauthenticated access.\n * - Provide an object to specify resource-based access control with resource name, action, and optional custom rules.\n */\n authentication?:\n | boolean\n | {\n resource: string;\n action: string;\n rule?: DetailedAccessControlRule | string[] | \"*\";\n };\n /**\n * Request validation configuration using Zod schemas or class constructors.\n *\n * @remarks\n * - Set to `false` to disable all validation.\n * - Set to `null` to forbidden all request inputs.\n * - Provide an object with `query`, `body`, and/or `params` properties to validate specific parts of the request.\n * - Each property accepts a Zod schema, a class constructor, or `false` to disable validation for that part.\n */\n validation?:\n | false\n | null\n | {\n query?: TQuery;\n body?: TBody;\n params?: TParams;\n };\n /**\n * Rate limiting configuration for this route.\n *\n * @see {@link https://www.npmjs.com/package/express-rate-limit express-rate-limit} for available options.\n */\n rateLimit?: Partial<RateLimitOptions>;\n\n /**\n * Allows to define options for npm package compression.\n * Nothing is passed by default.\n *\n * @see {@link https://www.npmjs.com/package/compression compression} for further details.\n */\n compression?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * @example\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n *\n * @default\n * ```\n * {\n * parseNull: true,\n * parseUndefined: true,\n * parseBoolean: true,\n * }\n * ```\n *\n * @remarks\n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n *\n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParser?: QueryParserOptions;\n /**\n * Configuration for request body parsing.\n *\n * @property {(\"json\" | \"urlencoded\" | \"raw\" | \"text\")} parser - The type of body parser to use.\n * @property {object} [options] - Parser-specific options passed to the corresponding Express body parser middleware.\n *\n * @remarks\n * - When `parser` is `\"json\"`, options are passed to `express.json()`.\n * - When `parser` is `\"urlencoded\"`, options are passed to `express.urlencoded()`.\n * - When `parser` is `\"raw\"`, options are passed to `express.raw()`.\n * - When `parser` is `\"text\"`, options are passed to `express.text()`.\n * - Set to `false` to disable body parsing for this route.\n *\n * @see {@link https://expressjs.com/en/api.html#express.json Express body parser documentation}\n */\n bodyParser?: BodyParserConfig | BodyParserConfig[] | false;\n /**\n * Experimental features to be battled tested before being stable\n *\n * PS: These features may be changed without any previous warning.\n */\n experimental?: {\n /**\n * OpenAPI specification for this route.\n *\n * @remarks\n * - Set to `false` to exclude this route from OpenAPI documentation.\n * - Provide a partial OpenAPI operation object to document the route.\n */\n openapi?: false | OpenApiConfig;\n /**\n * Configuration for file upload handling in routes.\n * Supports single file, multiple files from same field, or multiple fields with files.\n */\n uploads?: UploadConfig;\n };\n};\n"]}
@@ -278,6 +278,11 @@ class UploadManager {
278
278
  next();
279
279
  });
280
280
  }
281
+ isAllFieldRequired(uploadConfig) {
282
+ if (!uploadConfig)
283
+ return false;
284
+ return uploadConfig.required !== false;
285
+ }
281
286
  }
282
287
  const uploadManager = new UploadManager();
283
288
  exports.default = uploadManager;