arkos 1.4.0-canary.77 → 1.4.0-canary.79

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 (31) hide show
  1. package/dist/cjs/modules/auth/auth.router.js +1 -1
  2. package/dist/cjs/modules/auth/auth.router.js.map +1 -1
  3. package/dist/cjs/modules/base/base.middlewares.js +1 -1
  4. package/dist/cjs/modules/base/base.middlewares.js.map +1 -1
  5. package/dist/cjs/types/arkos-config.js.map +1 -1
  6. package/dist/cjs/types/new-arkos-config.js.map +1 -1
  7. package/dist/cjs/types/router-config.js.map +1 -1
  8. package/dist/cjs/utils/arkos-router/index.js +1 -1
  9. package/dist/cjs/utils/arkos-router/index.js.map +1 -1
  10. package/dist/cjs/utils/arkos-router/types/index.js.map +1 -1
  11. package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
  12. package/dist/cjs/utils/dynamic-loader.js +1 -1
  13. package/dist/cjs/utils/dynamic-loader.js.map +1 -1
  14. package/dist/esm/modules/auth/auth.router.js +1 -1
  15. package/dist/esm/modules/auth/auth.router.js.map +1 -1
  16. package/dist/esm/modules/base/base.middlewares.js +1 -1
  17. package/dist/esm/modules/base/base.middlewares.js.map +1 -1
  18. package/dist/esm/types/arkos-config.js.map +1 -1
  19. package/dist/esm/types/new-arkos-config.js.map +1 -1
  20. package/dist/esm/types/router-config.js.map +1 -1
  21. package/dist/esm/utils/arkos-router/index.js +1 -1
  22. package/dist/esm/utils/arkos-router/index.js.map +1 -1
  23. package/dist/esm/utils/arkos-router/types/index.js.map +1 -1
  24. package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
  25. package/dist/esm/utils/dynamic-loader.js +1 -1
  26. package/dist/esm/utils/dynamic-loader.js.map +1 -1
  27. package/dist/types/types/arkos-config.d.ts +1 -1
  28. package/dist/types/types/new-arkos-config.d.ts +3 -3
  29. package/dist/types/types/router-config.d.ts +3 -3
  30. package/dist/types/utils/arkos-router/types/index.d.ts +1 -1
  31. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"dynamic-loader.js","sourceRoot":"","sources":["../../../src/utils/dynamic-loader.ts"],"names":[],"mappings":";;;;;;AAwBA,kDAKC;AAED,kDAEC;AAaD,oFAyDC;AAED,0BAKC;AAED,kCAEC;AAED,sCAqDC;AAuGD,8DAWC;AAQD,oDAgDC;AASD,wDAoFC;AAaD,0DAwCC;AAreD,6BAAoC;AACpC,gDAAwB;AAExB,yDAAiE;AAEjE,kDAA0B;AAC1B,6EAI0C;AAC1C,uEAAsE;AACtE,qDAAiE;AACjE,6DAAwD;AACxD,yFAA+D;AAC/D,4FAAmE;AAMnE,IAAI,mBAAmB,GAAuC,EAAE,CAAC;AAGjE,SAAgB,mBAAmB,CACjC,SAAiB,EACjB,OAA2B;IAE3B,mBAAmB,CAAC,IAAA,gCAAU,EAAC,SAAS,CAAC,CAAC,GAAG,OAAO,CAAC;AACvD,CAAC;AAED,SAAgB,mBAAmB,CAAC,SAAiB;IACnD,OAAO,mBAAmB,CAAC,IAAA,gCAAU,EAAC,SAAS,CAAC,CAAC,CAAC;AACpD,CAAC;AAaD,SAAgB,oCAAoC,CAAC,SAAiB;IACpE,MAAM,cAAc,GAAG,IAAA,+BAAS,EAAC,SAAS,CAAC,CAAC,WAAW,EAAE,CAAC;IAC1D,MAAM,YAAY,GAAG,SAAS,CAAC,WAAW,EAAE,KAAK,MAAM,CAAC;IACxD,MAAM,GAAG,GAAG,IAAA,iCAAoB,GAAE,CAAC;IAEnC,OAAO;QACL,IAAI,EAAE;YACJ,KAAK,EAAE,GAAG,cAAc,UAAU,GAAG,EAAE;YACvC,YAAY,EAAE,GAAG,cAAc,iBAAiB,GAAG,EAAE;YACrD,eAAe,EAAE,GAAG,cAAc,gBAAgB,GAAG,EAAE;YACvD,WAAW,EAAE,GAAG,cAAc,SAAS,GAAG,EAAE;YAC5C,kBAAkB,EAAE,GAAG,cAAc,UAAU,GAAG,EAAE;YACpD,MAAM,EAAE,GAAG,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IAAA,+BAAS,EAAC,SAAS,CAAC,CACrB,CAAC;QACF,IAAI,MAAM,IAAA,mCAAU,EAAC,SAAS,CAAC;YAAE,eAAe,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACnE,CAAC,CAAC,CACH,CAAC;IAEF,MAAM,+BAA+B,GAAG,kBAAU,CAAC,GAAG,CACpD,KAAK,EAAE,SAAS,EAAE,EAAE,CAClB,MAAM,sBAAsB,CAC1B,SAAS,EACT,WAAW,EACX,eAAe,CAAC,QAAQ,CAAC,SAAS,CAAC,CACpC,CACJ,CAAC;IAEF,MAAM,iBAAiB,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,+BAA+B,CAAC,CAAC;IAC7E,0BAAe,CAAC,iCAAiC,CAC/C,iBAAiB,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,CAAC,EAAE,EAAE;QACtC,MAAM,SAAS,GAAG,cAAI,CAAC,OAAO,CAC5B,IAAA,gBAAG,GAAE,EACL,KAAK,EACL,SAAS,EACT,IAAA,+BAAS,EAAC,kBAAU,CAAC,CAAC,CAAC,CAAC,CACzB,CAAC;QAEF,OAAO;YACL,UAAU,EAAE,IAAA,+BAAS,EAAC,kBAAU,CAAC,CAAC,CAAC,CAAC;YACpC,SAAS;YACT,UAAU;SACX,CAAC;IACJ,CAAC,CAAC,CACH,CAAC;AACJ,CAAC","sourcesContent":["import { z, ZodTypeAny } from \"zod\";\nimport path from \"path\";\nimport { AuthConfigs } from \"../types/auth\";\nimport { killServerChildProcess } from \"./cli/utils/cli.helpers\";\nimport { ArkosConfig, RouterConfig } from \"../exports\";\nimport sheu from \"./sheu\";\nimport {\n applyStrictRoutingRules,\n pathExists,\n validateRouterConfigConsistency,\n} from \"./helpers/dynamic-loader.helpers\";\nimport { kebabCase, pascalCase } from \"./helpers/change-case.helpers\";\nimport { crd, getUserFileExtension } from \"./helpers/fs.helpers\";\nimport { importModule } from \"./helpers/global.helpers\";\nimport prismaSchemaParser from \"./prisma/prisma-schema-parser\";\nimport debuggerService from \"../modules/debugger/debugger.service\";\nimport { PrismaQueryOptions } from \"../types\";\nimport { ServiceHook } from \"../modules/base/utils/service-hooks-manager\";\n\ntype AppModuleComponent = Awaited<ReturnType<typeof importModuleComponents>>;\n\nlet prismaModelsModules: Record<string, AppModuleComponent> = {};\n\n/** This was a workaround when testing and also when cjs was generated while `prismaModelsModules` was exported there where some problems */\nexport function setModuleComponents(\n modelName: string,\n modules: AppModuleComponent\n) {\n prismaModelsModules[pascalCase(modelName)] = modules;\n}\n\nexport function getModuleComponents(modelName: string) {\n return prismaModelsModules[pascalCase(modelName)];\n}\n\n/**\n * To be reused on other part of code for correct typing\n *\n * @param key\n * @param fileName\n * @param result\n */\nexport type ValidationFileMappingKey = keyof ReturnType<\n typeof getFileModuleComponentsFileStructure\n>[\"dtos\"];\n\nexport function getFileModuleComponentsFileStructure(modelName: string) {\n const kebabModelName = kebabCase(modelName).toLowerCase();\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n const ext = getUserFileExtension();\n\n return {\n core: {\n hooks: `${kebabModelName}.hooks.${ext}`,\n interceptors: `${kebabModelName}.interceptors.${ext}`,\n interceptorsOld: `${kebabModelName}.middlewares.${ext}`,\n authConfigs: `${kebabModelName}.auth.${ext}`,\n prismaQueryOptions: `${kebabModelName}.query.${ext}`,\n router: `${kebabModelName}.router.${ext}`,\n },\n dtos: isAuthModule\n ? {\n login: `login.dto.${ext}`,\n signup: `signup.dto.${ext}`,\n getMe: `get-me.dto.${ext}`,\n updateMe: `update-me.dto.${ext}`,\n updatePassword: `update-password.dto.${ext}`,\n }\n : {\n model: `${kebabModelName}.dto.${ext}`,\n create: `create-${kebabModelName}.dto.${ext}`,\n createOne: `create-${kebabModelName}.dto.${ext}`, // just for sake of completion and reusability around other parts of code\n createMany: ``,\n update: `update-${kebabModelName}.dto.${ext}`,\n updateOne: `update-${kebabModelName}.dto.${ext}`, // same as createOne\n updateMany: ``,\n query: `query-${kebabModelName}.dto.${ext}`,\n // looking for some better naming convetion\n findOne: ``,\n findMany: ``,\n },\n schemas: isAuthModule\n ? {\n login: `login.schema.${ext}`,\n signup: `signup.schema.${ext}`,\n getMe: `get-me.schema.${ext}`,\n updateMe: `update-me.schema.${ext}`,\n updatePassword: `update-password.schema.${ext}`,\n }\n : {\n model: `${kebabModelName}.schema.${ext}`,\n create: `create-${kebabModelName}.schema.${ext}`,\n createOne: `create-${kebabModelName}.schema.${ext}`,\n createMany: ``, // just for sake of completion and reusability around other parts of code\n update: `update-${kebabModelName}.schema.${ext}`,\n updateOne: `update-${kebabModelName}.schema.${ext}`, // same as createOne\n updateMany: ``,\n query: `query-${kebabModelName}.schema.${ext}`,\n // looking for some better naming convetion\n findOne: ``,\n findMany: ``,\n },\n };\n}\n\nexport function isClass(value: any): boolean {\n return (\n typeof value === \"function\" &&\n /^class\\s/.test(Function.prototype.toString.call(value))\n );\n}\n\nexport function isZodSchema(value: any): value is ZodTypeAny {\n return value instanceof z.ZodType;\n}\n\nexport async function processSubdir(\n modelName: string,\n type: \"dtos\" | \"schemas\"\n) {\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n const subdir = path.join(moduleDir, type);\n const fileStructure = getFileModuleComponentsFileStructure(modelName);\n const result: Record<string, any> = {};\n\n if (!(await pathExists(subdir))) return result;\n\n try {\n await Promise.all(\n Object.entries(fileStructure[type]).map(async ([key, fileName]) => {\n const filePath = path.join(subdir, fileName);\n if (!fileName || !(await pathExists(filePath))) return;\n\n try {\n const module = await importModule(filePath).catch(\n async (err: any) => {\n if (await pathExists(filePath)) {\n sheu.error(`Failed to import ${fileName}: `);\n console.error(err);\n killServerChildProcess();\n process.exit(1);\n }\n }\n );\n\n const cleanFilePath = `src/modules/${kebabCase(modelName)}/${fileName}`;\n if (type === \"dtos\" && !isClass(module?.default))\n throw Error(\n `ValidationError: Please export as default a valid class under ${cleanFilePath}, in order to use as Dto.`\n );\n else if (type === \"schemas\" && !isZodSchema(module?.default))\n throw Error(\n `ValidationError: Please export as default a valid zod schema under ${cleanFilePath}, in order to use as Schema`\n );\n\n if (module && module?.default) result[key] = module.default;\n } catch (err: any) {\n if (err?.message?.includes(\"ValidationError\")) throw err;\n console.error(err);\n }\n })\n );\n } catch (err: any) {\n if (err?.message?.includes(\"ValidationError\")) throw err;\n console.error(err);\n }\n\n return result;\n}\n\nexport type ModuleComponents = Omit<\n ImportModuleComponentsReturnType,\n \"authConfigsNew\" | \"prismaQueryOptionsNew\"\n>;\n\ntype ImportModuleComponentsReturnType = {\n hooks?: Record<string, ServiceHook | ServiceHook[]>;\n interceptors?: Record<string, Function | Function[]>;\n authConfigs?: AuthConfigs;\n interceptorsOld?: any;\n authConfigsNew?: AuthConfigs;\n prismaQueryOptions?: PrismaQueryOptions<any>;\n prismaQueryOptionsNew?: PrismaQueryOptions<any>;\n router?: { config?: RouterConfig<any>; default: RouterConfig };\n dtos?: {\n create?: any;\n update?: any;\n signup?: any;\n login?: any;\n updatePassword?: any;\n updateMe?: any;\n };\n schemas?: {\n create?: any;\n update?: any;\n signup?: any;\n login?: any;\n updatePassword?: any;\n updateMe?: any;\n };\n};\n\nconst availableInterceptors = {\n auth: [\n \"beforeGetMe\",\n \"afterGetMe\",\n \"onGetMeError\",\n \"beforeUpdateMe\",\n \"afterUpdateMe\",\n \"onUpdateMeError\",\n \"beforeLogin\",\n \"afterLogin\",\n \"onLoginError\",\n \"beforeLogout\",\n \"afterLogout\",\n \"onLogoutError\",\n \"beforeSignup\",\n \"afterSignup\",\n \"onSignupError\",\n \"beforeUpdatePassword\",\n \"afterUpdatePassword\",\n \"onUpdatePasswordError\",\n ],\n \"file-upload\": [\n \"beforeFindFile\",\n \"onFindFileError\",\n \"beforeUploadFile\",\n \"afterUploadFile\",\n \"onUploadFileError\",\n \"beforeUpdateFile\",\n \"afterUpdateFile\",\n \"onUpdateFileError\",\n \"beforeDeleteFile\",\n \"afterDeleteFile\",\n \"onDeleteFileError\",\n ],\n prisma: [\n \"beforeCreateOne\",\n \"afterCreateOne\",\n \"onCreateOneError\",\n \"beforeFindOne\",\n \"afterFindOne\",\n \"onFindOneError\",\n \"beforeFindMany\",\n \"afterFindMany\",\n \"onFindManyError\",\n \"beforeUpdateOne\",\n \"afterUpdateOne\",\n \"onUpdateOneError\",\n \"beforeDeleteOne\",\n \"afterDeleteOne\",\n \"onDeleteOneError\",\n \"beforeCreateMany\",\n \"afterCreateMany\",\n \"onCreateManyError\",\n \"beforeUpdateMany\",\n \"afterUpdateMany\",\n \"onUpdateManyError\",\n \"beforeDeleteMany\",\n \"afterDeleteMany\",\n \"onDeleteManyError\",\n ],\n};\n\n/**\n * Validates naming convention conflicts for prismaQueryOptions and authConfigs\n * @param {string} key - The current file key being processed\n * @param {string} fileName - The filename being imported\n * @param {ImportModuleComponentsReturnType} result - The current result object\n * @throws {Error} When conflicting naming conventions are detected\n */\nexport function validateNamingConventions(\n key: string,\n fileName: string,\n result: ImportModuleComponentsReturnType\n): void {\n if (key === \"interceptorsOld\") {\n if (!result.interceptors)\n sheu.warn(\n `Found deprecated ${fileName} that will removed from v1.5.0-beta, consider switching to ${fileName.replace(\"middlewares\", \"interceptors\")}`\n );\n }\n}\n\n/**\n * Processes and assigns module to the result object based on the key\n * @param {string} key - The file key being processed\n * @param {any} module - The imported module\n * @param {ImportModuleComponentsReturnType} result - The result object to modify\n */\nexport function assignModuleToResult(\n appModule: string,\n key: string,\n module: any,\n result: ImportModuleComponentsReturnType,\n arkosConfig: ArkosConfig\n): void {\n if (key === \"interceptors\") result.interceptors = module;\n else if (key === \"interceptorsOld\") {\n const kebabCaseAppModule = kebabCase(appModule);\n const moduleName =\n kebabCaseAppModule === \"auth\"\n ? \"auth\"\n : kebabCaseAppModule === \"file-upload\"\n ? \"file-upload\"\n : \"prisma\";\n\n if (\n result.interceptors &&\n Object.keys(module).some((interceptorName) =>\n availableInterceptors[moduleName].includes(interceptorName)\n )\n ) {\n const exportedInterceptors = Object.keys(module).filter(\n (interceptorName) =>\n availableInterceptors[moduleName].includes(interceptorName)\n );\n const ext = getUserFileExtension();\n sheu.warn(\n `Found ${kebabCaseAppModule}.middlewares.${ext} exporting ${exportedInterceptors.join(\", \")}. Which by convention should go at ${kebabCaseAppModule}.interceptors.${ext} This is simply a warning that will stop from v1.5.0-beta`\n );\n } else if (!result.interceptors) result.interceptors = module;\n } else if (key === \"router\") {\n result[key] = {\n ...module,\n config: applyStrictRoutingRules(\n appModule,\n arkosConfig,\n module?.config || {}\n ),\n };\n validateRouterConfigConsistency(\n kebabCase(appModule),\n result[key]?.config || {}\n );\n } else {\n result[key as keyof typeof result] = module.default || module;\n }\n}\n\n/**\n * Dynamically imports model-specific modules for a given model with optimized file handling.\n * Includes special handling for the Auth module.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\", \"Post\", \"Auth\").\n * @returns {Promise<Object>} An object containing the imported modules\n */\nexport async function importModuleComponents(\n modelName: string,\n arkosConfig: ArkosConfig,\n moduleDirExists?: boolean\n): Promise<ImportModuleComponentsReturnType> {\n const result: ImportModuleComponentsReturnType = {\n dtos: {},\n schemas: {},\n };\n const usingStrictRouting = arkosConfig.routers?.strict;\n\n if (!moduleDirExists && !usingStrictRouting) return result;\n\n if (getModuleComponents(modelName)) return getModuleComponents(modelName);\n\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n const fileStructure = getFileModuleComponentsFileStructure(modelName);\n\n const validationSubdir = arkosConfig.validation?.resolver\n ? arkosConfig.validation.resolver === \"zod\"\n ? \"schemas\"\n : \"dtos\"\n : null;\n\n const [validators] = await Promise.all([\n validationSubdir && processSubdir(modelName, validationSubdir),\n ...Object.entries(fileStructure.core).map(async ([key, fileName]) => {\n if (\n [\"createMany\", \"findMany\", \"findOne\", \"updateMany\"].includes(key) ||\n !fileName\n )\n return;\n\n const filePath = path.join(moduleDir, fileName);\n\n if (\n key === \"router\" &&\n !usingStrictRouting &&\n !(await pathExists(filePath))\n )\n return;\n else if (\n key !== \"router\" &&\n usingStrictRouting &&\n !(await pathExists(filePath))\n )\n return;\n\n try {\n let module = await importModule(filePath).catch(async (err) => {\n try {\n if (await pathExists(filePath)) {\n sheu.error(`Failed to import ${fileName}`);\n console.error(err);\n killServerChildProcess();\n process.exit(1);\n }\n } catch (err) {}\n });\n\n if (!module && key === \"router\" && usingStrictRouting) module = {};\n\n if (module) {\n (result as any)[key] = module;\n validateNamingConventions(key, fileName, result);\n assignModuleToResult(modelName, key, module, result, arkosConfig);\n }\n } catch (err: any) {\n if (err.message?.includes(\"Cannot use both\")) throw err;\n console.error(err);\n killServerChildProcess();\n }\n }),\n ]);\n\n prismaModelsModules[pascalCase(modelName)] = {\n ...result,\n ...(validationSubdir && { [validationSubdir]: validators }),\n };\n\n return {\n ...result,\n ...(validationSubdir && { [validationSubdir]: validators }),\n };\n}\n\nexport const appModules = Array.from(\n new Set([\n \"auth\",\n \"file-upload\",\n ...(prismaSchemaParser.getModelsAsArrayOfStrings() || []),\n ])\n);\n\n/**\n * Allows to asynchronously load all app modules components at once to speed up app start time.\n */\nexport async function loadAllModuleComponents(arkosConfig: ArkosConfig) {\n const moduleDirExists: string[] = [];\n await Promise.all(\n appModules.map(async (appModule) => {\n const moduleDir = path.resolve(\n crd(),\n \"src\",\n \"modules\",\n kebabCase(appModule)\n );\n if (await pathExists(moduleDir)) moduleDirExists.push(appModule);\n })\n );\n\n const modulesComponentsImportPromises = appModules.map(\n async (appModule) =>\n await importModuleComponents(\n appModule,\n arkosConfig,\n moduleDirExists.includes(appModule)\n )\n );\n\n const modulesComponents = await Promise.all(modulesComponentsImportPromises);\n debuggerService.logDynamicLoadedModulesComponents(\n modulesComponents.map((components, i) => {\n const moduleDir = path.resolve(\n crd(),\n \"src\",\n \"modules\",\n kebabCase(appModules[i])\n );\n\n return {\n moduleName: kebabCase(appModules[i]),\n moduleDir,\n components,\n };\n })\n );\n}\n"]}
1
+ {"version":3,"file":"dynamic-loader.js","sourceRoot":"","sources":["../../../src/utils/dynamic-loader.ts"],"names":[],"mappings":";;;;;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AAC,SAAS,CAAC,CAAC;IACnE,CAAC,CAAC,CACH,CAAC;IAEF,MAAM,+BAA+B,GAAG,kBAAU,CAAC,GAAG,CACpD,KAAK,EAAE,SAAS,EAAE,EAAE,CAClB,MAAM,sBAAsB,CAC1B,SAAS,EACT,WAAW,EACX,eAAe,CAAC,QAAQ,CAAC,SAAS,CAAC,CACpC,CACJ,CAAC;IAEF,MAAM,iBAAiB,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,+BAA+B,CAAC,CAAC;IAC7E,0BAAe,CAAC,iCAAiC,CAC/C,iBAAiB,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,CAAC,EAAE,EAAE;QACtC,MAAM,SAAS,GAAG,cAAI,CAAC,OAAO,CAC5B,IAAA,gBAAG,GAAE,EACL,KAAK,EACL,SAAS,EACT,IAAA,+BAAS,EAAC,kBAAU,CAAC,CAAC,CAAC,CAAC,CACzB,CAAC;QAEF,OAAO;YACL,UAAU,EAAE,IAAA,+BAAS,EAAC,kBAAU,CAAC,CAAC,CAAC,CAAC;YACpC,SAAS;YACT,UAAU;SACX,CAAC;IACJ,CAAC,CAAC,CACH,CAAC;AACJ,CAAC","sourcesContent":["import { z, ZodTypeAny } from \"zod\";\nimport path from \"path\";\nimport { AuthConfigs } from \"../types/auth\";\nimport { killServerChildProcess } from \"./cli/utils/cli.helpers\";\nimport { ArkosConfig, RouterConfig } from \"../exports\";\nimport sheu from \"./sheu\";\nimport {\n applyStrictRoutingRules,\n pathExists,\n validateRouterConfigConsistency,\n} from \"./helpers/dynamic-loader.helpers\";\nimport { kebabCase, pascalCase } from \"./helpers/change-case.helpers\";\nimport { crd, getUserFileExtension } from \"./helpers/fs.helpers\";\nimport { importModule } from \"./helpers/global.helpers\";\nimport prismaSchemaParser from \"./prisma/prisma-schema-parser\";\nimport debuggerService from \"../modules/debugger/debugger.service\";\nimport { PrismaQueryOptions } from \"../types\";\nimport { ServiceHook } from \"../modules/base/utils/service-hooks-manager\";\n\ntype AppModuleComponent = Awaited<ReturnType<typeof importModuleComponents>>;\n\nlet prismaModelsModules: Record<string, AppModuleComponent> = {};\n\n/** This was a workaround when testing and also when cjs was generated while `prismaModelsModules` was exported there where some problems */\nexport function setModuleComponents(\n modelName: string,\n modules: AppModuleComponent\n) {\n prismaModelsModules[pascalCase(modelName)] = modules;\n}\n\nexport function getModuleComponents(modelName: string) {\n return prismaModelsModules[pascalCase(modelName)];\n}\n\n/**\n * To be reused on other part of code for correct typing\n *\n * @param key\n * @param fileName\n * @param result\n */\nexport type ValidationFileMappingKey = keyof ReturnType<\n typeof getFileModuleComponentsFileStructure\n>[\"dtos\"];\n\nexport function getFileModuleComponentsFileStructure(modelName: string) {\n const kebabModelName = kebabCase(modelName).toLowerCase();\n const isAuthModule = modelName.toLowerCase() === \"auth\";\n const ext = getUserFileExtension();\n\n return {\n core: {\n hooks: `${kebabModelName}.hooks.${ext}`,\n interceptors: `${kebabModelName}.interceptors.${ext}`,\n interceptorsOld: `${kebabModelName}.middlewares.${ext}`,\n authConfigs: `${kebabModelName}.auth.${ext}`,\n prismaQueryOptions: `${kebabModelName}.query.${ext}`,\n router: `${kebabModelName}.router.${ext}`,\n },\n dtos: isAuthModule\n ? {\n login: `login.dto.${ext}`,\n signup: `signup.dto.${ext}`,\n getMe: `get-me.dto.${ext}`,\n updateMe: `update-me.dto.${ext}`,\n updatePassword: `update-password.dto.${ext}`,\n }\n : {\n model: `${kebabModelName}.dto.${ext}`,\n create: `create-${kebabModelName}.dto.${ext}`,\n createOne: `create-${kebabModelName}.dto.${ext}`, // just for sake of completion and reusability around other parts of code\n createMany: ``,\n update: `update-${kebabModelName}.dto.${ext}`,\n updateOne: `update-${kebabModelName}.dto.${ext}`, // same as createOne\n updateMany: ``,\n query: `query-${kebabModelName}.dto.${ext}`,\n // looking for some better naming convetion\n findOne: ``,\n findMany: ``,\n },\n schemas: isAuthModule\n ? {\n login: `login.schema.${ext}`,\n signup: `signup.schema.${ext}`,\n getMe: `get-me.schema.${ext}`,\n updateMe: `update-me.schema.${ext}`,\n updatePassword: `update-password.schema.${ext}`,\n }\n : {\n model: `${kebabModelName}.schema.${ext}`,\n create: `create-${kebabModelName}.schema.${ext}`,\n createOne: `create-${kebabModelName}.schema.${ext}`,\n createMany: ``, // just for sake of completion and reusability around other parts of code\n update: `update-${kebabModelName}.schema.${ext}`,\n updateOne: `update-${kebabModelName}.schema.${ext}`, // same as createOne\n updateMany: ``,\n query: `query-${kebabModelName}.schema.${ext}`,\n // looking for some better naming convetion\n findOne: ``,\n findMany: ``,\n },\n };\n}\n\nexport function isClass(value: any): boolean {\n return (\n typeof value === \"function\" &&\n /^class\\s/.test(Function.prototype.toString.call(value))\n );\n}\n\nexport function isZodSchema(value: any): value is ZodTypeAny {\n return value instanceof z.ZodType;\n}\n\nexport async function processSubdir(\n modelName: string,\n type: \"dtos\" | \"schemas\"\n) {\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n\n const subdir = path.join(moduleDir, type);\n const fileStructure = getFileModuleComponentsFileStructure(modelName);\n const result: Record<string, any> = {};\n\n if (!(await pathExists(subdir))) return result;\n\n try {\n await Promise.all(\n Object.entries(fileStructure[type]).map(async ([key, fileName]) => {\n const filePath = path.join(subdir, fileName);\n if (!fileName || !(await pathExists(filePath))) return;\n\n try {\n const module = await importModule(filePath).catch(\n async (err: any) => {\n if (await pathExists(filePath)) {\n sheu.error(`Failed to import ${fileName}: `);\n console.error(err);\n killServerChildProcess();\n process.exit(1);\n }\n }\n );\n\n const cleanFilePath = `src/modules/${kebabCase(modelName)}/${fileName}`;\n if (type === \"dtos\" && !isClass(module?.default))\n throw Error(\n `ValidationError: Please export as default a valid class under ${cleanFilePath}, in order to use as Dto.`\n );\n else if (type === \"schemas\" && !isZodSchema(module?.default))\n throw Error(\n `ValidationError: Please export as default a valid zod schema under ${cleanFilePath}, in order to use as Schema`\n );\n\n if (module && module?.default) result[key] = module.default;\n } catch (err: any) {\n if (err?.message?.includes(\"ValidationError\")) throw err;\n console.error(err);\n }\n })\n );\n } catch (err: any) {\n if (err?.message?.includes(\"ValidationError\")) throw err;\n console.error(err);\n }\n\n return result;\n}\n\nexport type ModuleComponents = Omit<\n ImportModuleComponentsReturnType,\n \"authConfigsNew\" | \"prismaQueryOptionsNew\"\n>;\n\ntype ImportModuleComponentsReturnType = {\n hooks?: Record<string, ServiceHook | ServiceHook[]>;\n interceptors?: Record<string, Function | Function[]>;\n authConfigs?: AuthConfigs;\n interceptorsOld?: any;\n authConfigsNew?: AuthConfigs;\n prismaQueryOptions?: PrismaQueryOptions<any>;\n prismaQueryOptionsNew?: PrismaQueryOptions<any>;\n router?: { config?: RouterConfig<any>; default: RouterConfig };\n dtos?: {\n create?: any;\n update?: any;\n signup?: any;\n login?: any;\n updatePassword?: any;\n updateMe?: any;\n };\n schemas?: {\n create?: any;\n update?: any;\n signup?: any;\n login?: any;\n updatePassword?: any;\n updateMe?: any;\n };\n};\n\nconst availableInterceptors = {\n auth: [\n \"beforeGetMe\",\n \"afterGetMe\",\n \"onGetMeError\",\n \"beforeUpdateMe\",\n \"afterUpdateMe\",\n \"onUpdateMeError\",\n \"beforeLogin\",\n \"afterLogin\",\n \"onLoginError\",\n \"beforeLogout\",\n \"afterLogout\",\n \"onLogoutError\",\n \"beforeSignup\",\n \"afterSignup\",\n \"onSignupError\",\n \"beforeUpdatePassword\",\n \"afterUpdatePassword\",\n \"onUpdatePasswordError\",\n ],\n \"file-upload\": [\n \"beforeFindFile\",\n \"onFindFileError\",\n \"beforeUploadFile\",\n \"afterUploadFile\",\n \"onUploadFileError\",\n \"beforeUpdateFile\",\n \"afterUpdateFile\",\n \"onUpdateFileError\",\n \"beforeDeleteFile\",\n \"afterDeleteFile\",\n \"onDeleteFileError\",\n ],\n prisma: [\n \"beforeCreateOne\",\n \"afterCreateOne\",\n \"onCreateOneError\",\n \"beforeFindOne\",\n \"afterFindOne\",\n \"onFindOneError\",\n \"beforeFindMany\",\n \"afterFindMany\",\n \"onFindManyError\",\n \"beforeUpdateOne\",\n \"afterUpdateOne\",\n \"onUpdateOneError\",\n \"beforeDeleteOne\",\n \"afterDeleteOne\",\n \"onDeleteOneError\",\n \"beforeCreateMany\",\n \"afterCreateMany\",\n \"onCreateManyError\",\n \"beforeUpdateMany\",\n \"afterUpdateMany\",\n \"onUpdateManyError\",\n \"beforeDeleteMany\",\n \"afterDeleteMany\",\n \"onDeleteManyError\",\n ],\n};\n\n/**\n * Validates naming convention conflicts for prismaQueryOptions and authConfigs\n * @param {string} key - The current file key being processed\n * @param {string} fileName - The filename being imported\n * @param {ImportModuleComponentsReturnType} result - The current result object\n * @throws {Error} When conflicting naming conventions are detected\n */\nexport function validateNamingConventions(\n key: string,\n fileName: string,\n result: ImportModuleComponentsReturnType\n): void {\n if (key === \"interceptorsOld\") {\n if (!result.interceptors)\n sheu.warn(\n `Found deprecated ${fileName} that will removed from v1.6.0-beta, consider switching to ${fileName.replace(\"middlewares\", \"interceptors\")}`\n );\n }\n}\n\n/**\n * Processes and assigns module to the result object based on the key\n * @param {string} key - The file key being processed\n * @param {any} module - The imported module\n * @param {ImportModuleComponentsReturnType} result - The result object to modify\n */\nexport function assignModuleToResult(\n appModule: string,\n key: string,\n module: any,\n result: ImportModuleComponentsReturnType,\n arkosConfig: ArkosConfig\n): void {\n if (key === \"interceptors\") result.interceptors = module;\n else if (key === \"interceptorsOld\") {\n const kebabCaseAppModule = kebabCase(appModule);\n const moduleName =\n kebabCaseAppModule === \"auth\"\n ? \"auth\"\n : kebabCaseAppModule === \"file-upload\"\n ? \"file-upload\"\n : \"prisma\";\n\n if (\n result.interceptors &&\n Object.keys(module).some((interceptorName) =>\n availableInterceptors[moduleName].includes(interceptorName)\n )\n ) {\n const exportedInterceptors = Object.keys(module).filter(\n (interceptorName) =>\n availableInterceptors[moduleName].includes(interceptorName)\n );\n const ext = getUserFileExtension();\n sheu.warn(\n `Found ${kebabCaseAppModule}.middlewares.${ext} exporting ${exportedInterceptors.join(\", \")}. Which by convention should go at ${kebabCaseAppModule}.interceptors.${ext} This is simply a warning that will stop from v1.5.0-beta`\n );\n } else if (!result.interceptors) result.interceptors = module;\n } else if (key === \"router\") {\n result[key] = {\n ...module,\n config: applyStrictRoutingRules(\n appModule,\n arkosConfig,\n module?.config || {}\n ),\n };\n validateRouterConfigConsistency(\n kebabCase(appModule),\n result[key]?.config || {}\n );\n } else {\n result[key as keyof typeof result] = module.default || module;\n }\n}\n\n/**\n * Dynamically imports model-specific modules for a given model with optimized file handling.\n * Includes special handling for the Auth module.\n *\n * @param {string} modelName - The name of the model (e.g., \"User\", \"Post\", \"Auth\").\n * @returns {Promise<Object>} An object containing the imported modules\n */\nexport async function importModuleComponents(\n modelName: string,\n arkosConfig: ArkosConfig,\n moduleDirExists?: boolean\n): Promise<ImportModuleComponentsReturnType> {\n const result: ImportModuleComponentsReturnType = {\n dtos: {},\n schemas: {},\n };\n const usingStrictRouting = arkosConfig.routers?.strict;\n\n if (!moduleDirExists && !usingStrictRouting) return result;\n\n if (getModuleComponents(modelName)) return getModuleComponents(modelName);\n\n const moduleDir = path.resolve(crd(), \"src\", \"modules\", kebabCase(modelName));\n const fileStructure = getFileModuleComponentsFileStructure(modelName);\n\n const validationSubdir = arkosConfig.validation?.resolver\n ? arkosConfig.validation.resolver === \"zod\"\n ? \"schemas\"\n : \"dtos\"\n : null;\n\n const [validators] = await Promise.all([\n validationSubdir && processSubdir(modelName, validationSubdir),\n ...Object.entries(fileStructure.core).map(async ([key, fileName]) => {\n if (\n [\"createMany\", \"findMany\", \"findOne\", \"updateMany\"].includes(key) ||\n !fileName\n )\n return;\n\n const filePath = path.join(moduleDir, fileName);\n\n if (\n key === \"router\" &&\n !usingStrictRouting &&\n !(await pathExists(filePath))\n )\n return;\n else if (\n key !== \"router\" &&\n usingStrictRouting &&\n !(await pathExists(filePath))\n )\n return;\n\n try {\n let module = await importModule(filePath).catch(async (err) => {\n try {\n if (await pathExists(filePath)) {\n sheu.error(`Failed to import ${fileName}`);\n console.error(err);\n killServerChildProcess();\n process.exit(1);\n }\n } catch (err) {}\n });\n\n if (!module && key === \"router\" && usingStrictRouting) module = {};\n\n if (module) {\n (result as any)[key] = module;\n validateNamingConventions(key, fileName, result);\n assignModuleToResult(modelName, key, module, result, arkosConfig);\n }\n } catch (err: any) {\n if (err.message?.includes(\"Cannot use both\")) throw err;\n console.error(err);\n killServerChildProcess();\n }\n }),\n ]);\n\n prismaModelsModules[pascalCase(modelName)] = {\n ...result,\n ...(validationSubdir && { [validationSubdir]: validators }),\n };\n\n return {\n ...result,\n ...(validationSubdir && { [validationSubdir]: validators }),\n };\n}\n\nexport const appModules = Array.from(\n new Set([\n \"auth\",\n \"file-upload\",\n ...(prismaSchemaParser.getModelsAsArrayOfStrings() || []),\n ])\n);\n\n/**\n * Allows to asynchronously load all app modules components at once to speed up app start time.\n */\nexport async function loadAllModuleComponents(arkosConfig: ArkosConfig) {\n const moduleDirExists: string[] = [];\n await Promise.all(\n appModules.map(async (appModule) => {\n const moduleDir = path.resolve(\n crd(),\n \"src\",\n \"modules\",\n kebabCase(appModule)\n );\n if (await pathExists(moduleDir)) moduleDirExists.push(appModule);\n })\n );\n\n const modulesComponentsImportPromises = appModules.map(\n async (appModule) =>\n await importModuleComponents(\n appModule,\n arkosConfig,\n moduleDirExists.includes(appModule)\n )\n );\n\n const modulesComponents = await Promise.all(modulesComponentsImportPromises);\n debuggerService.logDynamicLoadedModulesComponents(\n modulesComponents.map((components, i) => {\n const moduleDir = path.resolve(\n crd(),\n \"src\",\n \"modules\",\n kebabCase(appModules[i])\n );\n\n return {\n moduleName: kebabCase(appModules[i]),\n moduleDir,\n components,\n };\n })\n );\n}\n"]}
@@ -54,7 +54,7 @@ export function getAuthRouter(arkosConfigs) {
54
54
  message: "Too many requests, please try again later",
55
55
  });
56
56
  },
57
- }, arkosConfigs?.authentication?.requestRateLimitOptions || {})));
57
+ }, arkosConfigs?.authentication?.rateLimit || {})));
58
58
  }
59
59
  if (!isEndpointDisabled(routerConfig, "login")) {
60
60
  router.post(createRouteConfig("login", "auth", "/login", routerConfig, "auth", false, getValidationSchemaOrDto("login")), addPrismaQueryOptionsToRequest(prismaQueryOptions, "login"), ...processMiddleware(interceptors?.beforeLogin), authController.login, ...processMiddleware(interceptors?.afterLogin), sendResponse, ...processMiddleware(interceptors?.onLoginError, { type: "error" }));
@@ -1 +1 @@
1
- {"version":3,"file":"auth.router.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.router.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,SAAS,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EACL,8BAA8B,EAC9B,YAAY,GACb,MAAM,0BAA0B,CAAC;AAElC,OAAO,SAAS,MAAM,sCAAsC,CAAC;AAE7D,OAAO,EACL,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,2CAA2C,CAAC;AAC/E,OAAO,eAAe,MAAM,8BAA8B,CAAC;AAC3D,OAAO,eAAe,MAAM,gCAAgC,CAAC;AAC7D,OAAO,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,WAAW,MAAM,0BAA0B,CAAC;AAEnD,MAAM,MAAM,GAAG,WAAW,EAAE,CAAC;AAE7B,MAAM,UAAU,aAAa,CAAC,YAAyB;IACrD,MAAM,EACJ,YAAY,EACZ,IAAI,EACJ,OAAO,EACP,kBAAkB,EAClB,MAAM,EAAE,kBAAkB,EAC1B,WAAW,GACZ,GAAG,mBAAmB,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;IAEtC,MAAM,YAAY,GAAG,kBAAkB,EAAE,MAAM,IAAI,EAAE,CAAC;IACtD,MAAM,YAAY,GAAG,kBAAkB,EAAE,OAAiB,CAAC;IAE3D,IAAI,YAAY,IAAI,kBAAkB,EA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,iBAAiB,CAAC,YAAY,EAAE,wBAAwB,CAAC,EAC5D,cAAc,CAAC,kBAAkB,EACjC,GAAG,iBAAiB,CAAC,YAAY,EAAE,uBAAuB,CAAC,EAC3D,YAAY,EACZ,GAAG,iBAAiB,CAAC,YAAY,EAAE,yBAAyB,EAAE;YAC5D,IAAI,EAAE,OAAO;SACd,CAAC,CACH,CAAC;IACJ,CAAC;IAGD,IAAI,CAAC,kBAAkB,CAAC,YAAY,EAAE,mBAAmB,CAAC,EAAE,CAAC;QAC3D,MAAM,CAAC,GAAG,CACR,iBAAiB,CACf,mBAAmB,EACnB,cAAc,EACd,gBAAgB,EAChB,YAAY,EACZ,MAAM,EACN,WAAW,CACZ,EACD,GAAG,iBAAiB,CAAC,YAAY,EAAE,uBAAuB,CAAC,EAC3D,cAAc,CAAC,iBAAiB,EAChC,GAAG,iBAAiB,CAAC,YAAY,EAAE,sBAAsB,CAAC,EAC1D,YAAY,EACZ,GAAG,iBAAiB,CAAC,YAAY,EAAE,wBAAwB,EAAE;YAC3D,IAAI,EAAE,OAAO;SACd,CAAC,CACH,CAAC;IACJ,CAAC;IAED,eAAe,CAAC,oBAAoB,CAAC,MAAM,EAAE,MAAa,CAAC,CAAC;IAC5D,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { authControllerFactory } from \"./auth.controller\";\nimport rateLimit from \"express-rate-limit\";\nimport { getModuleComponents } from \"../../utils/dynamic-loader\";\nimport {\n addPrismaQueryOptionsToRequest,\n sendResponse,\n} from \"../base/base.middlewares\";\nimport { ArkosConfig } from \"../../types/new-arkos-config\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { AuthPrismaQueryOptions } from \"../../types\";\nimport {\n processMiddleware,\n createRouteConfig,\n} from \"../../utils/helpers/routers.helpers\";\nimport { isEndpointDisabled } from \"../base/utils/helpers/base.router.helpers\";\nimport debuggerService from \"../debugger/debugger.service\";\nimport routerValidator from \"../base/utils/router-validator\";\nimport { getUserFileExtension } from \"../../utils/helpers/fs.helpers\";\nimport ArkosRouter from \"../../utils/arkos-router\";\n\nconst router = ArkosRouter();\n\nexport function getAuthRouter(arkosConfigs: ArkosConfig) {\n const {\n interceptors,\n dtos,\n schemas,\n prismaQueryOptions,\n router: customRouterModule,\n authConfigs,\n } = getModuleComponents(\"auth\") || {};\n\n const routerConfig = customRouterModule?.config || {};\n const customRouter = customRouterModule?.default as Router;\n\n if (customRouter && customRouterModule) {\n if (routerValidator.isExpressRouter(customRouter))\n router.use(`/auth`, customRouter);\n else\n throw Error(\n `ValidationError: The exported router from auth.router.${getUserFileExtension()} is not a valid express or arkos Router.`\n );\n }\n\n const authController = authControllerFactory(interceptors);\n\n if (routerConfig?.disable === true) return router;\n\n const getValidationSchemaOrDto = (\n key: \"updateMe\" | \"updatePassword\" | \"login\" | \"signup\"\n ) => {\n const validationConfigs = arkosConfigs?.validation;\n if (validationConfigs?.resolver === \"class-validator\") return dtos?.[key];\n else if (validationConfigs?.resolver === \"zod\") return schemas?.[key];\n\n return undefined;\n };\n\n // GET /users/me - Get current user\n if (!isEndpointDisabled(routerConfig, \"getMe\")) {\n router.get(\n createRouteConfig(\"getMe\", \"users\", \"/me\", routerConfig, \"auth\", true),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"getMe\"\n ),\n ...processMiddleware(interceptors?.beforeGetMe),\n authController.getMe,\n ...processMiddleware(interceptors?.afterGetMe),\n sendResponse,\n ...processMiddleware(interceptors?.onGetMeError, { type: \"error\" })\n );\n }\n\n // PATCH /users/me - Update current user\n if (!isEndpointDisabled(routerConfig, \"updateMe\")) {\n router.patch(\n createRouteConfig(\n \"updateMe\",\n \"users\",\n \"/me\",\n routerConfig,\n \"auth\",\n true,\n getValidationSchemaOrDto(\"updateMe\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"updateMe\"\n ),\n ...processMiddleware(interceptors?.beforeUpdateMe),\n authController.updateMe,\n ...processMiddleware(interceptors?.afterUpdateMe),\n sendResponse,\n ...processMiddleware(interceptors?.onUpdateMeError, { type: \"error\" })\n );\n }\n\n // DELETE /users/me - Delete current user\n if (!isEndpointDisabled(routerConfig, \"deleteMe\")) {\n router.delete(\n createRouteConfig(\"deleteMe\", \"users\", \"/me\", routerConfig, \"auth\", true),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"deleteMe\"\n ),\n ...processMiddleware(interceptors?.beforeDeleteMe),\n authController.deleteMe,\n ...processMiddleware(interceptors?.afterDeleteMe),\n sendResponse,\n ...processMiddleware(interceptors?.onDeleteMeError, { type: \"error\" })\n );\n }\n\n // Apply rate limiting to auth routes\n if (\n !isEndpointDisabled(routerConfig, \"login\") ||\n !isEndpointDisabled(routerConfig, \"logout\") ||\n !isEndpointDisabled(routerConfig, \"signup\") ||\n !isEndpointDisabled(routerConfig, \"updatePassword\")\n ) {\n router.use(\n \"/auth\",\n rateLimit(\n deepmerge(\n {\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n handler: (_, res) => {\n res.status(429).json({\n message: \"Too many requests, please try again later\",\n });\n },\n },\n arkosConfigs?.authentication?.requestRateLimitOptions || {}\n )\n )\n );\n }\n\n // POST /auth/login - Login\n if (!isEndpointDisabled(routerConfig, \"login\")) {\n router.post(\n createRouteConfig(\n \"login\",\n \"auth\",\n \"/login\",\n routerConfig,\n \"auth\",\n false,\n getValidationSchemaOrDto(\"login\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"login\"\n ),\n ...processMiddleware(interceptors?.beforeLogin),\n authController.login,\n ...processMiddleware(interceptors?.afterLogin),\n sendResponse,\n ...processMiddleware(interceptors?.onLoginError, { type: \"error\" })\n );\n }\n\n // DELETE /auth/logout - Logout\n if (!isEndpointDisabled(routerConfig, \"logout\")) {\n router.delete(\n createRouteConfig(\n \"logout\",\n \"auth\",\n \"/logout\",\n routerConfig,\n \"auth\",\n true\n ),\n ...processMiddleware(interceptors?.beforeLogout),\n authController.logout,\n ...processMiddleware(interceptors?.afterLogout),\n sendResponse,\n ...processMiddleware(interceptors?.onLogoutError, { type: \"error\" })\n );\n }\n\n // POST /auth/signup - Signup\n if (!isEndpointDisabled(routerConfig, \"signup\")) {\n router.post(\n createRouteConfig(\n \"signup\",\n \"auth\",\n \"/signup\",\n routerConfig,\n \"auth\",\n false,\n getValidationSchemaOrDto(\"signup\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"signup\"\n ),\n ...processMiddleware(interceptors?.beforeSignup),\n authController.signup,\n ...processMiddleware(interceptors?.afterSignup),\n sendResponse,\n ...processMiddleware(interceptors?.onSignupError, { type: \"error\" })\n );\n }\n\n // POST /auth/update-password - Update password\n if (!isEndpointDisabled(routerConfig, \"updatePassword\")) {\n router.post(\n createRouteConfig(\n \"updatePassword\",\n \"auth\",\n \"/update-password\",\n routerConfig,\n \"auth\",\n true,\n getValidationSchemaOrDto(\"updatePassword\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"updatePassword\"\n ),\n ...processMiddleware(interceptors?.beforeUpdatePassword),\n authController.updatePassword,\n ...processMiddleware(interceptors?.afterUpdatePassword),\n sendResponse,\n ...processMiddleware(interceptors?.onUpdatePasswordError, {\n type: \"error\",\n })\n );\n }\n\n // GET /auth-actions - Find many auth actions\n if (!isEndpointDisabled(routerConfig, \"findManyAuthAction\")) {\n router.get(\n createRouteConfig(\n \"findManyAuthAction\",\n \"auth-actions\",\n \"\",\n routerConfig,\n \"auth\",\n authConfigs\n ),\n ...processMiddleware(interceptors?.beforeFindManyAuthAction),\n authController.findManyAuthAction,\n ...processMiddleware(interceptors?.afterFindManyAuthAction),\n sendResponse,\n ...processMiddleware(interceptors?.onFindManyAuthActionError, {\n type: \"error\",\n })\n );\n }\n\n // GET /auth-actions/:resourceName - Find one auth action\n if (!isEndpointDisabled(routerConfig, \"findOneAuthAction\")) {\n router.get(\n createRouteConfig(\n \"findOneAuthAction\",\n \"auth-actions\",\n \"/:resourceName\",\n routerConfig,\n \"auth\",\n authConfigs\n ),\n ...processMiddleware(interceptors?.beforeFindOneAuthAction),\n authController.findOneAuthAction,\n ...processMiddleware(interceptors?.afterFindOneAuthAction),\n sendResponse,\n ...processMiddleware(interceptors?.onFindOneAuthActionError, {\n type: \"error\",\n })\n );\n }\n\n debuggerService.logModuleFinalRouter(\"auth\", router as any);\n return router;\n}\n"]}
1
+ {"version":3,"file":"auth.router.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.router.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,SAAS,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EACL,8BAA8B,EAC9B,YAAY,GACb,MAAM,0BAA0B,CAAC;AAElC,OAAO,SAAS,MAAM,sCAAsC,CAAC;AAE7D,OAAO,EACL,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,2CAA2C,CAAC;AAC/E,OAAO,eAAe,MAAM,8BAA8B,CAAC;AAC3D,OAAO,eAAe,MAAM,gCAAgC,CAAC;AAC7D,OAAO,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,WAAW,MAAM,0BAA0B,CAAC;AAEnD,MAAM,MAAM,GAAG,WAAW,EAAE,CAAC;AAE7B,MAAM,UAAU,aAAa,CAAC,YAAyB;IACrD,MAAM,EACJ,YAAY,EACZ,IAAI,EACJ,OAAO,EACP,kBAAkB,EAClB,MAAM,EAAE,kBAAkB,EAC1B,WAAW,GACZ,GAAG,mBAAm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AAI,CAAC,kBAAkB,CAAC,YAAY,EAAE,oBAAoB,CAAC,EAAE,CAAC;QAC5D,MAAM,CAAC,GAAG,CACR,iBAAiB,CACf,oBAAoB,EACpB,cAAc,EACd,EAAE,EACF,YAAY,EACZ,MAAM,EACN,WAAW,CACZ,EACD,GAAG,iBAAiB,CAAC,YAAY,EAAE,wBAAwB,CAAC,EAC5D,cAAc,CAAC,kBAAkB,EACjC,GAAG,iBAAiB,CAAC,YAAY,EAAE,uBAAuB,CAAC,EAC3D,YAAY,EACZ,GAAG,iBAAiB,CAAC,YAAY,EAAE,yBAAyB,EAAE;YAC5D,IAAI,EAAE,OAAO;SACd,CAAC,CACH,CAAC;IACJ,CAAC;IAGD,IAAI,CAAC,kBAAkB,CAAC,YAAY,EAAE,mBAAmB,CAAC,EAAE,CAAC;QAC3D,MAAM,CAAC,GAAG,CACR,iBAAiB,CACf,mBAAmB,EACnB,cAAc,EACd,gBAAgB,EAChB,YAAY,EACZ,MAAM,EACN,WAAW,CACZ,EACD,GAAG,iBAAiB,CAAC,YAAY,EAAE,uBAAuB,CAAC,EAC3D,cAAc,CAAC,iBAAiB,EAChC,GAAG,iBAAiB,CAAC,YAAY,EAAE,sBAAsB,CAAC,EAC1D,YAAY,EACZ,GAAG,iBAAiB,CAAC,YAAY,EAAE,wBAAwB,EAAE;YAC3D,IAAI,EAAE,OAAO;SACd,CAAC,CACH,CAAC;IACJ,CAAC;IAED,eAAe,CAAC,oBAAoB,CAAC,MAAM,EAAE,MAAa,CAAC,CAAC;IAC5D,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { authControllerFactory } from \"./auth.controller\";\nimport rateLimit from \"express-rate-limit\";\nimport { getModuleComponents } from \"../../utils/dynamic-loader\";\nimport {\n addPrismaQueryOptionsToRequest,\n sendResponse,\n} from \"../base/base.middlewares\";\nimport { ArkosConfig } from \"../../types/new-arkos-config\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { AuthPrismaQueryOptions } from \"../../types\";\nimport {\n processMiddleware,\n createRouteConfig,\n} from \"../../utils/helpers/routers.helpers\";\nimport { isEndpointDisabled } from \"../base/utils/helpers/base.router.helpers\";\nimport debuggerService from \"../debugger/debugger.service\";\nimport routerValidator from \"../base/utils/router-validator\";\nimport { getUserFileExtension } from \"../../utils/helpers/fs.helpers\";\nimport ArkosRouter from \"../../utils/arkos-router\";\n\nconst router = ArkosRouter();\n\nexport function getAuthRouter(arkosConfigs: ArkosConfig) {\n const {\n interceptors,\n dtos,\n schemas,\n prismaQueryOptions,\n router: customRouterModule,\n authConfigs,\n } = getModuleComponents(\"auth\") || {};\n\n const routerConfig = customRouterModule?.config || {};\n const customRouter = customRouterModule?.default as Router;\n\n if (customRouter && customRouterModule) {\n if (routerValidator.isExpressRouter(customRouter))\n router.use(`/auth`, customRouter);\n else\n throw Error(\n `ValidationError: The exported router from auth.router.${getUserFileExtension()} is not a valid express or arkos Router.`\n );\n }\n\n const authController = authControllerFactory(interceptors);\n\n if (routerConfig?.disable === true) return router;\n\n const getValidationSchemaOrDto = (\n key: \"updateMe\" | \"updatePassword\" | \"login\" | \"signup\"\n ) => {\n const validationConfigs = arkosConfigs?.validation;\n if (validationConfigs?.resolver === \"class-validator\") return dtos?.[key];\n else if (validationConfigs?.resolver === \"zod\") return schemas?.[key];\n\n return undefined;\n };\n\n // GET /users/me - Get current user\n if (!isEndpointDisabled(routerConfig, \"getMe\")) {\n router.get(\n createRouteConfig(\"getMe\", \"users\", \"/me\", routerConfig, \"auth\", true),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"getMe\"\n ),\n ...processMiddleware(interceptors?.beforeGetMe),\n authController.getMe,\n ...processMiddleware(interceptors?.afterGetMe),\n sendResponse,\n ...processMiddleware(interceptors?.onGetMeError, { type: \"error\" })\n );\n }\n\n // PATCH /users/me - Update current user\n if (!isEndpointDisabled(routerConfig, \"updateMe\")) {\n router.patch(\n createRouteConfig(\n \"updateMe\",\n \"users\",\n \"/me\",\n routerConfig,\n \"auth\",\n true,\n getValidationSchemaOrDto(\"updateMe\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"updateMe\"\n ),\n ...processMiddleware(interceptors?.beforeUpdateMe),\n authController.updateMe,\n ...processMiddleware(interceptors?.afterUpdateMe),\n sendResponse,\n ...processMiddleware(interceptors?.onUpdateMeError, { type: \"error\" })\n );\n }\n\n // DELETE /users/me - Delete current user\n if (!isEndpointDisabled(routerConfig, \"deleteMe\")) {\n router.delete(\n createRouteConfig(\"deleteMe\", \"users\", \"/me\", routerConfig, \"auth\", true),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"deleteMe\"\n ),\n ...processMiddleware(interceptors?.beforeDeleteMe),\n authController.deleteMe,\n ...processMiddleware(interceptors?.afterDeleteMe),\n sendResponse,\n ...processMiddleware(interceptors?.onDeleteMeError, { type: \"error\" })\n );\n }\n\n // Apply rate limiting to auth routes\n if (\n !isEndpointDisabled(routerConfig, \"login\") ||\n !isEndpointDisabled(routerConfig, \"logout\") ||\n !isEndpointDisabled(routerConfig, \"signup\") ||\n !isEndpointDisabled(routerConfig, \"updatePassword\")\n ) {\n router.use(\n \"/auth\",\n rateLimit(\n deepmerge(\n {\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n handler: (_, res) => {\n res.status(429).json({\n message: \"Too many requests, please try again later\",\n });\n },\n },\n arkosConfigs?.authentication?.rateLimit || {}\n )\n )\n );\n }\n\n // POST /auth/login - Login\n if (!isEndpointDisabled(routerConfig, \"login\")) {\n router.post(\n createRouteConfig(\n \"login\",\n \"auth\",\n \"/login\",\n routerConfig,\n \"auth\",\n false,\n getValidationSchemaOrDto(\"login\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"login\"\n ),\n ...processMiddleware(interceptors?.beforeLogin),\n authController.login,\n ...processMiddleware(interceptors?.afterLogin),\n sendResponse,\n ...processMiddleware(interceptors?.onLoginError, { type: \"error\" })\n );\n }\n\n // DELETE /auth/logout - Logout\n if (!isEndpointDisabled(routerConfig, \"logout\")) {\n router.delete(\n createRouteConfig(\n \"logout\",\n \"auth\",\n \"/logout\",\n routerConfig,\n \"auth\",\n true\n ),\n ...processMiddleware(interceptors?.beforeLogout),\n authController.logout,\n ...processMiddleware(interceptors?.afterLogout),\n sendResponse,\n ...processMiddleware(interceptors?.onLogoutError, { type: \"error\" })\n );\n }\n\n // POST /auth/signup - Signup\n if (!isEndpointDisabled(routerConfig, \"signup\")) {\n router.post(\n createRouteConfig(\n \"signup\",\n \"auth\",\n \"/signup\",\n routerConfig,\n \"auth\",\n false,\n getValidationSchemaOrDto(\"signup\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"signup\"\n ),\n ...processMiddleware(interceptors?.beforeSignup),\n authController.signup,\n ...processMiddleware(interceptors?.afterSignup),\n sendResponse,\n ...processMiddleware(interceptors?.onSignupError, { type: \"error\" })\n );\n }\n\n // POST /auth/update-password - Update password\n if (!isEndpointDisabled(routerConfig, \"updatePassword\")) {\n router.post(\n createRouteConfig(\n \"updatePassword\",\n \"auth\",\n \"/update-password\",\n routerConfig,\n \"auth\",\n true,\n getValidationSchemaOrDto(\"updatePassword\")\n ),\n addPrismaQueryOptionsToRequest<any>(\n prismaQueryOptions as AuthPrismaQueryOptions<any>,\n \"updatePassword\"\n ),\n ...processMiddleware(interceptors?.beforeUpdatePassword),\n authController.updatePassword,\n ...processMiddleware(interceptors?.afterUpdatePassword),\n sendResponse,\n ...processMiddleware(interceptors?.onUpdatePasswordError, {\n type: \"error\",\n })\n );\n }\n\n // GET /auth-actions - Find many auth actions\n if (!isEndpointDisabled(routerConfig, \"findManyAuthAction\")) {\n router.get(\n createRouteConfig(\n \"findManyAuthAction\",\n \"auth-actions\",\n \"\",\n routerConfig,\n \"auth\",\n authConfigs\n ),\n ...processMiddleware(interceptors?.beforeFindManyAuthAction),\n authController.findManyAuthAction,\n ...processMiddleware(interceptors?.afterFindManyAuthAction),\n sendResponse,\n ...processMiddleware(interceptors?.onFindManyAuthActionError, {\n type: \"error\",\n })\n );\n }\n\n // GET /auth-actions/:resourceName - Find one auth action\n if (!isEndpointDisabled(routerConfig, \"findOneAuthAction\")) {\n router.get(\n createRouteConfig(\n \"findOneAuthAction\",\n \"auth-actions\",\n \"/:resourceName\",\n routerConfig,\n \"auth\",\n authConfigs\n ),\n ...processMiddleware(interceptors?.beforeFindOneAuthAction),\n authController.findOneAuthAction,\n ...processMiddleware(interceptors?.afterFindOneAuthAction),\n sendResponse,\n ...processMiddleware(interceptors?.onFindOneAuthActionError, {\n type: \"error\",\n })\n );\n }\n\n debuggerService.logModuleFinalRouter(\"auth\", router as any);\n return router;\n}\n"]}
@@ -185,7 +185,7 @@ export function validateRequestInputs(routeConfig) {
185
185
  if (key in validators &&
186
186
  validators?.[key] !== undefined &&
187
187
  !isValidValidator(validators[key]))
188
- throw Error(`Your validation resolver is set to ${arkosConfig.validation.resolver}, please provide a valid ${validatorName} in order to use in { validation: { ${key}: ${validatorNameType} } } under route ${routeConfig.route}`);
188
+ throw Error(`Your validation resolver is set to ${arkosConfig.validation.resolver}, please provide a valid ${validatorName} in order to use in { validation: { ${key}: ${validatorNameType} } } under route ${routeConfig.path}`);
189
189
  });
190
190
  return catchAsync(async (req, _, next) => {
191
191
  for (const key of validatorsKey) {
@@ -1 +1 @@
1
- {"version":3,"file":"base.middlewares.js","sourceRoot":"","sources":["../../../../src/modules/base/base.middlewares.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,SAAS,MAAM,sCAAsC,CAAC;AAC7D,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AACnE,OA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,CAChB,cAAc,GAAG,2BAA2B,EAC5C,GAAG,EACH,YAAY,UAAU,CAAC,GAAG,CAAC,SAAS,EACpC,EAAE,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,GAAG,CAAC,EAAE,CACpB,CAAC;YAEJ,IAAI,SAAS;gBACX,GAAG,CAAC,GAAG,CAAC,GAAG,MAAM,WAAW,CAC1B,SAAS,EACT,GAAG,CAAC,GAAG,CAAC,EACR,WAAW,CAAC,UAAU,EAAE,iBAAiB,CAC1C,CAAC;QACN,CAAC;QAED,IAAI,EAAE,CAAC;IACT,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport {\n PrismaQueryOptions,\n ArkosNextFunction,\n ArkosRequest,\n ArkosRequestHandler,\n ArkosResponse,\n AuthPrismaQueryOptions,\n} from \"../../types\";\nimport { getArkosConfig } from \"../../server\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { AppError, catchAsync } from \"../../exports/error-handler\";\nimport validateDto from \"../../utils/validate-dto\";\nimport validateSchema from \"../../utils/validate-schema\";\nimport { ZodSchema } from \"zod\";\nimport { ClassConstructor } from \"class-transformer\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { resolvePrismaQueryOptions } from \"./utils/helpers/base.middlewares.helpers\";\nimport { ArkosRouteConfig } from \"../../utils/arkos-router/types\";\nimport { capitalize } from \"../../utils/helpers/text.helpers\";\nimport { isClass, isZodSchema } from \"../../utils/dynamic-loader\";\n\nexport function callNext(_: Request, _1: Response, next: NextFunction) {\n next();\n}\n\n/**\n * Deep comparison helper for objects\n */\nfunction deepEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (a == null || b == null) return false;\n if (typeof a !== \"object\" || typeof b !== \"object\") return a === b;\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if (!keysB.includes(key)) return false;\n if (!deepEqual(a[key], b[key])) return false;\n }\n\n return true;\n}\n\n/**\n * Sends response with backward compatibility support\n * Compares current values against original values to detect middleware changes\n * If values were modified by subsequent middleware, use the modified version\n */\nexport function sendResponse(req: ArkosRequest, res: ArkosResponse) {\n let responseData;\n let responseStatus;\n\n const originalData = (res as any).originalData;\n const originalStatus = (res as any).originalStatus;\n\n const currentReqData = req.responseData;\n const currentReqStatus = req.responseStatus;\n const currentLocalsData = res.locals?.data;\n const currentLocalsStatus = res.locals?.status;\n\n if (\n currentReqData !== undefined &&\n !deepEqual(currentReqData, originalData)\n ) {\n responseData = currentReqData;\n } else if (\n currentLocalsData !== undefined &&\n !deepEqual(currentLocalsData, originalData)\n ) {\n responseData = currentLocalsData;\n } else if (originalData !== undefined) {\n responseData = originalData;\n } else {\n responseData = currentReqData ?? currentLocalsData;\n }\n\n if (currentReqStatus !== undefined && currentReqStatus !== originalStatus) {\n responseStatus = currentReqStatus;\n } else if (\n currentLocalsStatus !== undefined &&\n currentLocalsStatus !== originalStatus\n ) {\n responseStatus = currentLocalsStatus;\n } else if (originalStatus !== undefined) {\n responseStatus = originalStatus;\n } else {\n responseStatus = currentReqStatus ?? currentLocalsStatus;\n }\n\n // Send response\n\n if (Number(responseStatus) === 204) {\n res.status(Number(responseStatus)).send();\n } else if (\n (responseData !== undefined || responseData !== null) &&\n responseStatus\n ) {\n res.status(Number(responseStatus)).json(responseData);\n } else if (\n Number(responseStatus) &&\n (responseData === undefined || responseData === null)\n ) {\n res.status(Number(responseStatus)).send();\n } else {\n res.status(500).json({\n message: \"No status or data attached to the response\",\n });\n }\n}\n\n/**\n * Type representing all possible actions that can be performed on a controller\n * Combines both standard CRUD operations and auth-specific operations\n */\nexport type ControllerActions =\n | keyof PrismaQueryOptions<any>\n | keyof Omit<AuthPrismaQueryOptions<any>, keyof PrismaQueryOptions<any>>;\n\n/**\n * Middleware to add Prisma query options to the request's query parameters.\n *\n * @template T - The type of the Prisma model.\n * @param {PrismaQueryOptions<T> | AuthPrismaQueryOptions<T>} prismaQueryOptions - The Prisma query options to attach.\n * @param {ControllerActions} action - The controller action to apply.\n * @returns A middleware function that attaches the query options to the request.\n */\nexport function addPrismaQueryOptionsToRequest<T extends Record<string, any>>(\n prismaQueryOptions: PrismaQueryOptions<T> | AuthPrismaQueryOptions<T>,\n action: ControllerActions\n) {\n return (req: ArkosRequest, _: ArkosResponse, next: NextFunction) => {\n const configs = getArkosConfig();\n\n const resolvedOptions = resolvePrismaQueryOptions(\n prismaQueryOptions,\n action\n );\n\n const requestQueryOptions = configs?.request?.parameters\n ?.allowDangerousPrismaQueryOptions\n ? JSON.parse((req.query?.prismaQueryOptions as string) || \"{}\")\n : {};\n\n req.prismaQueryOptions = deepmerge(resolvedOptions, requestQueryOptions);\n\n next();\n };\n}\n\n/**\n * Logs request events with colored text such as errors, requests responses.\n *\n */\nexport function handleRequestLogs(\n req: Request,\n res: Response,\n next: NextFunction\n) {\n const startTime = Date.now();\n\n const methodColors = {\n GET: \"\\x1b[36m\", // Cyan\n POST: \"\\x1b[32m\", // Green\n PUT: \"\\x1b[33m\", // Orange/Yellow\n PATCH: \"\\x1b[33m\", // Orange/Yellow\n DELETE: \"\\x1b[31m\", // Red\n HEAD: \"\\x1b[34m\", // Blue\n OPTIONS: \"\\x1b[34m\", // Blue\n };\n\n const getStatusColor = (statusCode: number) => {\n if (statusCode >= 200 && statusCode < 300) return \"\\x1b[32m\";\n if (statusCode >= 300 && statusCode < 400) return \"\\x1b[33m\";\n if (statusCode >= 400 && statusCode < 500) return \"\\x1b[33m\";\n if (statusCode >= 500) return \"\\x1b[31m\";\n return \"\\x1b[0m\";\n };\n\n res.on(\"finish\", () => {\n const duration = Date.now() - startTime;\n\n const now = new Date();\n const time = now.toTimeString().split(\" \")[0];\n\n const methodColor =\n methodColors[req.method as keyof typeof methodColors] || \"\\x1b[0m\";\n const statusColor = getStatusColor(res.statusCode);\n\n console.info(\n `[\\x1b[36mInfo\\x1b[0m] \\x1b[90m${time}\\x1b[0m ${methodColor}${\n req.method\n }\\x1b[0m ${decodeURIComponent(req.originalUrl)} ${statusColor}${\n res.statusCode\n }\\x1b[0m \\x1b[35m${duration}ms\\x1b[0m`\n );\n });\n\n next();\n}\n\nexport function handleRequestBodyValidationAndTransformation<T extends object>(\n schemaOrDtoClass?: ClassConstructor<T>,\n classValidatorValidationOptions?: ValidatorOptions\n): ArkosRequestHandler;\nexport function handleRequestBodyValidationAndTransformation<T extends object>(\n schemaOrDtoClass?: ZodSchema<T>\n): ArkosRequestHandler;\nexport function handleRequestBodyValidationAndTransformation<T extends object>(\n schemaOrDtoClass?: ZodSchema<T> | ClassConstructor<T>,\n classValidatorValidationOptions?: ValidatorOptions\n) {\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n const validationConfigs = getArkosConfig()?.validation;\n let body = req.body;\n\n if (validationConfigs?.resolver === \"class-validator\" && schemaOrDtoClass)\n req.body = await validateDto(\n schemaOrDtoClass as ClassConstructor<T>,\n body,\n deepmerge(\n {\n whitelist: true,\n ...classValidatorValidationOptions,\n },\n validationConfigs?.validationOptions || {}\n )\n );\n else if (validationConfigs?.resolver === \"zod\" && schemaOrDtoClass)\n req.body = await validateSchema(schemaOrDtoClass as ZodSchema<T>, body);\n\n next();\n }\n );\n}\n\nexport function validateRequestInputs(routeConfig: ArkosRouteConfig) {\n const arkosConfig = getArkosConfig();\n const validationConfig = arkosConfig.validation;\n const strictValidation = validationConfig?.strict;\n const validators = routeConfig?.validation;\n const openapi = routeConfig?.experimental?.openapi;\n\n const validationToParameterMapping = {\n query: \"query\",\n params: \"path\",\n headers: \"header\",\n cookies: \"cookie\",\n };\n\n if (!validationConfig?.resolver && validators)\n throw Error(\n \"Trying to pass validators into route config validation option without choosing a validation resolver under arkos config { validation: {} }.\"\n );\n\n if ((validators as any) === true)\n throw Error(\n `Invalid value ${validators} passed to validation option, it can only receive false or object of { query, body, params }.`\n );\n\n const validatorFn: (validator: any, data: any, options: any) => Promise<any> =\n validationConfig?.resolver == \"zod\" ? validateSchema : validateDto;\n const validatorsKey: (\"body\" | \"query\" | \"params\")[] = [\n \"body\",\n \"query\",\n \"params\",\n ];\n\n const isValidValidator =\n validationConfig?.resolver == \"zod\" ? isZodSchema : isClass;\n const validatorName =\n validationConfig?.resolver == \"zod\" ? \"zod schema\" : \"class-validator dto\";\n const validatorNameType =\n validationConfig?.resolver == \"zod\" ? \"Schema\" : \"Dto\";\n\n if (typeof validators === \"object\")\n validatorsKey.forEach((key) => {\n if (\n openapi &&\n typeof openapi === \"object\" &&\n key != \"body\" &&\n openapi.parameters?.some(\n (parameter: any) => parameter.in === validationToParameterMapping[key]\n ) &&\n validators[key]\n ) {\n throw Error(\n `When usign validation.${key} you must not define parameters under openapi.parameters as documentation of req.${key} because the ${validatorName} you passed under validation.${key} will be added as jsonSchema into the api documenation, if you wish to define documenation by yourself do not define validation.${key}.`\n );\n }\n\n if (\n openapi &&\n typeof openapi === \"object\" &&\n openapi.requestBody &&\n validators[key] &&\n key === \"body\"\n ) {\n throw Error(\n `When usign validation.${key} you must not define json-schema under openapi.requestBody as documentation for req.${key}, because the ${validatorName} you passed under validation.${key} will be added as json-schema into the api documenation, if you wish to define documenation by yourself do not define validation.${key}.`\n );\n }\n\n if (strictValidation && !(key in validators))\n throw Error(\n `No { validation: { ${key}: ${validatorNameType} } } was found, while using strict validation you will need to pass undefined into ${key} in order to deny any request ${key} input.`\n );\n\n if (\n key in validators &&\n validators?.[key] !== undefined &&\n !isValidValidator(validators[key])\n )\n throw Error(\n `Your validation resolver is set to ${arkosConfig.validation!.resolver}, please provide a valid ${validatorName} in order to use in { validation: { ${key}: ${validatorNameType} } } under route ${routeConfig.route}`\n );\n });\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n for (const key of validatorsKey) {\n if (typeof validators === \"boolean\" && validators === false)\n throw new AppError(\n `No request ${key} is allowed on this route`,\n 400,\n `NoRequest${capitalize(key)}Allowed`,\n { [key]: req[key] }\n );\n\n const validator = validators?.[key];\n\n if (strictValidation && !validator && Object.keys(req[key]).length > 0)\n throw new AppError(\n `No request ${key} is allowed on this route`,\n 400,\n `NoRequest${capitalize(key)}Allowed`,\n { [key]: req[key] }\n );\n\n if (validator)\n req[key] = await validatorFn(\n validator,\n req[key],\n arkosConfig.validation?.validationOptions\n );\n }\n\n next();\n }\n );\n}\n"]}
1
+ {"version":3,"file":"base.middlewares.js","sourceRoot":"","sources":["../../../../src/modules/base/base.middlewares.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,SAAS,MAAM,sCAAsC,CAAC;AAC7D,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,WAAW,MAAM,0BAA0B,CAAC;AACnD,OAAO,cAAc,MAAM,6BAA6B,CAAC;AAIzD,OAAO,EAAE,yBAAyB,EAAE,MAAM,0CAA0C,CAAC;AAErF,OAAO,EAAE,UAAU,EAAE,MAAM,kCAAkC,CAAC;AAC9D,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAElE,MAAM,UAAU,QAAQ,CAAC,CAAU,EAAE,EAAY,EAAE,IAAkB;IACnE,IAAI,EAAE,CAAC;AACT,CAAC;AAKD,SAAS,SAAS,CAAC,CAAM,EAAE,CAAM;IAC/B,IAAI,CAAC,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IACzB,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,IAAI;QAAE,OAAO,KAAK,CAAC;IACzC,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,OAAO,CAAC,KAAK,QAAQ;QAAE,OAAO,CAAC,KAAK,CAAC,CAAC;IAEnE,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAC7B,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAE7B,IAA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AAa,EAAE,CAAC;YAChC,IAAI,OAAO,UAAU,KAAK,SAAS,IAAI,UAAU,KAAK,KAAK;gBACzD,MAAM,IAAI,QAAQ,CAChB,cAAc,GAAG,2BAA2B,EAC5C,GAAG,EACH,YAAY,UAAU,CAAC,GAAG,CAAC,SAAS,EACpC,EAAE,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,GAAG,CAAC,EAAE,CACpB,CAAC;YAEJ,MAAM,SAAS,GAAG,UAAU,EAAE,CAAC,GAAG,CAAC,CAAC;YAEpC,IAAI,gBAAgB,IAAI,CAAC,SAAS,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC;gBACpE,MAAM,IAAI,QAAQ,CAChB,cAAc,GAAG,2BAA2B,EAC5C,GAAG,EACH,YAAY,UAAU,CAAC,GAAG,CAAC,SAAS,EACpC,EAAE,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,GAAG,CAAC,EAAE,CACpB,CAAC;YAEJ,IAAI,SAAS;gBACX,GAAG,CAAC,GAAG,CAAC,GAAG,MAAM,WAAW,CAC1B,SAAS,EACT,GAAG,CAAC,GAAG,CAAC,EACR,WAAW,CAAC,UAAU,EAAE,iBAAiB,CAC1C,CAAC;QACN,CAAC;QAED,IAAI,EAAE,CAAC;IACT,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport {\n PrismaQueryOptions,\n ArkosNextFunction,\n ArkosRequest,\n ArkosRequestHandler,\n ArkosResponse,\n AuthPrismaQueryOptions,\n} from \"../../types\";\nimport { getArkosConfig } from \"../../server\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { AppError, catchAsync } from \"../../exports/error-handler\";\nimport validateDto from \"../../utils/validate-dto\";\nimport validateSchema from \"../../utils/validate-schema\";\nimport { ZodSchema } from \"zod\";\nimport { ClassConstructor } from \"class-transformer\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { resolvePrismaQueryOptions } from \"./utils/helpers/base.middlewares.helpers\";\nimport { ArkosRouteConfig } from \"../../utils/arkos-router/types\";\nimport { capitalize } from \"../../utils/helpers/text.helpers\";\nimport { isClass, isZodSchema } from \"../../utils/dynamic-loader\";\n\nexport function callNext(_: Request, _1: Response, next: NextFunction) {\n next();\n}\n\n/**\n * Deep comparison helper for objects\n */\nfunction deepEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (a == null || b == null) return false;\n if (typeof a !== \"object\" || typeof b !== \"object\") return a === b;\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if (!keysB.includes(key)) return false;\n if (!deepEqual(a[key], b[key])) return false;\n }\n\n return true;\n}\n\n/**\n * Sends response with backward compatibility support\n * Compares current values against original values to detect middleware changes\n * If values were modified by subsequent middleware, use the modified version\n */\nexport function sendResponse(req: ArkosRequest, res: ArkosResponse) {\n let responseData;\n let responseStatus;\n\n const originalData = (res as any).originalData;\n const originalStatus = (res as any).originalStatus;\n\n const currentReqData = req.responseData;\n const currentReqStatus = req.responseStatus;\n const currentLocalsData = res.locals?.data;\n const currentLocalsStatus = res.locals?.status;\n\n if (\n currentReqData !== undefined &&\n !deepEqual(currentReqData, originalData)\n ) {\n responseData = currentReqData;\n } else if (\n currentLocalsData !== undefined &&\n !deepEqual(currentLocalsData, originalData)\n ) {\n responseData = currentLocalsData;\n } else if (originalData !== undefined) {\n responseData = originalData;\n } else {\n responseData = currentReqData ?? currentLocalsData;\n }\n\n if (currentReqStatus !== undefined && currentReqStatus !== originalStatus) {\n responseStatus = currentReqStatus;\n } else if (\n currentLocalsStatus !== undefined &&\n currentLocalsStatus !== originalStatus\n ) {\n responseStatus = currentLocalsStatus;\n } else if (originalStatus !== undefined) {\n responseStatus = originalStatus;\n } else {\n responseStatus = currentReqStatus ?? currentLocalsStatus;\n }\n\n // Send response\n\n if (Number(responseStatus) === 204) {\n res.status(Number(responseStatus)).send();\n } else if (\n (responseData !== undefined || responseData !== null) &&\n responseStatus\n ) {\n res.status(Number(responseStatus)).json(responseData);\n } else if (\n Number(responseStatus) &&\n (responseData === undefined || responseData === null)\n ) {\n res.status(Number(responseStatus)).send();\n } else {\n res.status(500).json({\n message: \"No status or data attached to the response\",\n });\n }\n}\n\n/**\n * Type representing all possible actions that can be performed on a controller\n * Combines both standard CRUD operations and auth-specific operations\n */\nexport type ControllerActions =\n | keyof PrismaQueryOptions<any>\n | keyof Omit<AuthPrismaQueryOptions<any>, keyof PrismaQueryOptions<any>>;\n\n/**\n * Middleware to add Prisma query options to the request's query parameters.\n *\n * @template T - The type of the Prisma model.\n * @param {PrismaQueryOptions<T> | AuthPrismaQueryOptions<T>} prismaQueryOptions - The Prisma query options to attach.\n * @param {ControllerActions} action - The controller action to apply.\n * @returns A middleware function that attaches the query options to the request.\n */\nexport function addPrismaQueryOptionsToRequest<T extends Record<string, any>>(\n prismaQueryOptions: PrismaQueryOptions<T> | AuthPrismaQueryOptions<T>,\n action: ControllerActions\n) {\n return (req: ArkosRequest, _: ArkosResponse, next: NextFunction) => {\n const configs = getArkosConfig();\n\n const resolvedOptions = resolvePrismaQueryOptions(\n prismaQueryOptions,\n action\n );\n\n const requestQueryOptions = configs?.request?.parameters\n ?.allowDangerousPrismaQueryOptions\n ? JSON.parse((req.query?.prismaQueryOptions as string) || \"{}\")\n : {};\n\n req.prismaQueryOptions = deepmerge(resolvedOptions, requestQueryOptions);\n\n next();\n };\n}\n\n/**\n * Logs request events with colored text such as errors, requests responses.\n *\n */\nexport function handleRequestLogs(\n req: Request,\n res: Response,\n next: NextFunction\n) {\n const startTime = Date.now();\n\n const methodColors = {\n GET: \"\\x1b[36m\", // Cyan\n POST: \"\\x1b[32m\", // Green\n PUT: \"\\x1b[33m\", // Orange/Yellow\n PATCH: \"\\x1b[33m\", // Orange/Yellow\n DELETE: \"\\x1b[31m\", // Red\n HEAD: \"\\x1b[34m\", // Blue\n OPTIONS: \"\\x1b[34m\", // Blue\n };\n\n const getStatusColor = (statusCode: number) => {\n if (statusCode >= 200 && statusCode < 300) return \"\\x1b[32m\";\n if (statusCode >= 300 && statusCode < 400) return \"\\x1b[33m\";\n if (statusCode >= 400 && statusCode < 500) return \"\\x1b[33m\";\n if (statusCode >= 500) return \"\\x1b[31m\";\n return \"\\x1b[0m\";\n };\n\n res.on(\"finish\", () => {\n const duration = Date.now() - startTime;\n\n const now = new Date();\n const time = now.toTimeString().split(\" \")[0];\n\n const methodColor =\n methodColors[req.method as keyof typeof methodColors] || \"\\x1b[0m\";\n const statusColor = getStatusColor(res.statusCode);\n\n console.info(\n `[\\x1b[36mInfo\\x1b[0m] \\x1b[90m${time}\\x1b[0m ${methodColor}${\n req.method\n }\\x1b[0m ${decodeURIComponent(req.originalUrl)} ${statusColor}${\n res.statusCode\n }\\x1b[0m \\x1b[35m${duration}ms\\x1b[0m`\n );\n });\n\n next();\n}\n\nexport function handleRequestBodyValidationAndTransformation<T extends object>(\n schemaOrDtoClass?: ClassConstructor<T>,\n classValidatorValidationOptions?: ValidatorOptions\n): ArkosRequestHandler;\nexport function handleRequestBodyValidationAndTransformation<T extends object>(\n schemaOrDtoClass?: ZodSchema<T>\n): ArkosRequestHandler;\nexport function handleRequestBodyValidationAndTransformation<T extends object>(\n schemaOrDtoClass?: ZodSchema<T> | ClassConstructor<T>,\n classValidatorValidationOptions?: ValidatorOptions\n) {\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n const validationConfigs = getArkosConfig()?.validation;\n let body = req.body;\n\n if (validationConfigs?.resolver === \"class-validator\" && schemaOrDtoClass)\n req.body = await validateDto(\n schemaOrDtoClass as ClassConstructor<T>,\n body,\n deepmerge(\n {\n whitelist: true,\n ...classValidatorValidationOptions,\n },\n validationConfigs?.validationOptions || {}\n )\n );\n else if (validationConfigs?.resolver === \"zod\" && schemaOrDtoClass)\n req.body = await validateSchema(schemaOrDtoClass as ZodSchema<T>, body);\n\n next();\n }\n );\n}\n\nexport function validateRequestInputs(routeConfig: ArkosRouteConfig) {\n const arkosConfig = getArkosConfig();\n const validationConfig = arkosConfig.validation;\n const strictValidation = validationConfig?.strict;\n const validators = routeConfig?.validation;\n const openapi = routeConfig?.experimental?.openapi;\n\n const validationToParameterMapping = {\n query: \"query\",\n params: \"path\",\n headers: \"header\",\n cookies: \"cookie\",\n };\n\n if (!validationConfig?.resolver && validators)\n throw Error(\n \"Trying to pass validators into route config validation option without choosing a validation resolver under arkos config { validation: {} }.\"\n );\n\n if ((validators as any) === true)\n throw Error(\n `Invalid value ${validators} passed to validation option, it can only receive false or object of { query, body, params }.`\n );\n\n const validatorFn: (validator: any, data: any, options: any) => Promise<any> =\n validationConfig?.resolver == \"zod\" ? validateSchema : validateDto;\n const validatorsKey: (\"body\" | \"query\" | \"params\")[] = [\n \"body\",\n \"query\",\n \"params\",\n ];\n\n const isValidValidator =\n validationConfig?.resolver == \"zod\" ? isZodSchema : isClass;\n const validatorName =\n validationConfig?.resolver == \"zod\" ? \"zod schema\" : \"class-validator dto\";\n const validatorNameType =\n validationConfig?.resolver == \"zod\" ? \"Schema\" : \"Dto\";\n\n if (typeof validators === \"object\")\n validatorsKey.forEach((key) => {\n if (\n openapi &&\n typeof openapi === \"object\" &&\n key != \"body\" &&\n openapi.parameters?.some(\n (parameter: any) => parameter.in === validationToParameterMapping[key]\n ) &&\n validators[key]\n ) {\n throw Error(\n `When usign validation.${key} you must not define parameters under openapi.parameters as documentation of req.${key} because the ${validatorName} you passed under validation.${key} will be added as jsonSchema into the api documenation, if you wish to define documenation by yourself do not define validation.${key}.`\n );\n }\n\n if (\n openapi &&\n typeof openapi === \"object\" &&\n openapi.requestBody &&\n validators[key] &&\n key === \"body\"\n ) {\n throw Error(\n `When usign validation.${key} you must not define json-schema under openapi.requestBody as documentation for req.${key}, because the ${validatorName} you passed under validation.${key} will be added as json-schema into the api documenation, if you wish to define documenation by yourself do not define validation.${key}.`\n );\n }\n\n if (strictValidation && !(key in validators))\n throw Error(\n `No { validation: { ${key}: ${validatorNameType} } } was found, while using strict validation you will need to pass undefined into ${key} in order to deny any request ${key} input.`\n );\n\n if (\n key in validators &&\n validators?.[key] !== undefined &&\n !isValidValidator(validators[key])\n )\n throw Error(\n `Your validation resolver is set to ${arkosConfig.validation!.resolver}, please provide a valid ${validatorName} in order to use in { validation: { ${key}: ${validatorNameType} } } under route ${routeConfig.path}`\n );\n });\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n for (const key of validatorsKey) {\n if (typeof validators === \"boolean\" && validators === false)\n throw new AppError(\n `No request ${key} is allowed on this route`,\n 400,\n `NoRequest${capitalize(key)}Allowed`,\n { [key]: req[key] }\n );\n\n const validator = validators?.[key];\n\n if (strictValidation && !validator && Object.keys(req[key]).length > 0)\n throw new AppError(\n `No request ${key} is allowed on this route`,\n 400,\n `NoRequest${capitalize(key)}Allowed`,\n { [key]: req[key] }\n );\n\n if (validator)\n req[key] = await validatorFn(\n validator,\n req[key],\n arkosConfig.validation?.validationOptions\n );\n }\n\n next();\n }\n );\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"arkos-config.js","sourceRoot":"","sources":["../../../src/types/arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import http from \"http\";\nimport express from \"express\";\nimport { IArkosRouter } from \"../utils/arkos-router/types\";\nimport { ArkosErrorRequestHandler, ArkosRequestHandler } from \".\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosInitConfig = {\n /**\n * Allows to add an array of custom express routers/middlewares into the default middleware/routers stack.\n *\n * **Tip**: If you would like to acess the express app before everthing use `configureApp` and pass a function.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order](https://www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order)\n *\n * **Note**: If you want to use custom global error handler middleware use `middlewares.replace.globalErrorHandler`.\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n use?: IArkosRouter[] | ArkosRequestHandler[] | ArkosErrorRequestHandler[];\n /**\n * Gives acess to the underlying express app so that you can add custom configurations beyong **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `app.listen` for you.\n *\n * If you want to call `app.listen` by yourself pass port as `undefined` and then use the return app from `arkos.init()`.\n *\n * See how to call `app.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app](https://www.arkosjs.com/docs/guide/accessing-the-express-app) for further details on the method configureApp.\n *\n * @param {express.Express} app\n * @returns {any}\n */\n configureApp?: (app: express.Express) => Promise<any> | any;\n /**\n * Gives access to the underlying HTTP server so that you can add custom configurations beyond **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `server.listen` for you.\n *\n * If you want to call `server.listen` by yourself pass port as `undefined` and then use the return server from `arkos.init()`.\n *\n * See how to call `server.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#creating-your-own-http-server](https://www.arkosjs.com/docs/guide/accessing-the-express-app#creating-your-own-http-server)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app#accessing-the-http-server](https://www.arkosjs.com/docs/guide/accessing-the-express-app#accessing-the-http-server) for further details on the method configureServer.\n *\n * @param {http.Server} server - The HTTP server instance\n * @returns {any}\n */\n configureServer?: (server: http.Server) => Promise<any> | any;\n};\n"]}
1
+ {"version":3,"file":"arkos-config.js","sourceRoot":"","sources":["../../../src/types/arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import http from \"http\";\nimport express from \"express\";\nimport { IArkosRouter } from \"../utils/arkos-router/types\";\nimport { ArkosErrorRequestHandler, ArkosRequestHandler } from \".\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosInitConfig = {\n /**\n * Allows to add an array of custom express routers/middlewares into the default middleware/routers stack.\n *\n * **Tip**: If you would like to acess the express app before everthing use `configureApp` and pass a function.\n *\n * **Where will these be placed?**: see [www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order](https://www.arkosjs.com/docs/advanced-guide/replace-or-disable-built-in-middlewares#middleware-execution-order)\n *\n * **Note**: If you want to use custom global error handler middleware use `middlewares.replace.globalErrorHandler`.\n *\n * Read more about The Arkos Middleware Stack at [www.arkosjs.com/docs/the-middleware-stack](https://www.arkosjs.com/docs/the-middleware-stack) for in-depth details.\n */\n use?:\n | express.Router[]\n | IArkosRouter[]\n | ArkosRequestHandler[]\n | ArkosErrorRequestHandler[];\n /**\n * Gives acess to the underlying express app so that you can add custom configurations beyong **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `app.listen` for you.\n *\n * If you want to call `app.listen` by yourself pass port as `undefined` and then use the return app from `arkos.init()`.\n *\n * See how to call `app.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself](https://www.arkosjs.com/docs/guide/accessing-the-express-app#calling-applisten-by-yourself)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app](https://www.arkosjs.com/docs/guide/accessing-the-express-app) for further details on the method configureApp.\n *\n * @param {express.Express} app\n * @returns {any}\n */\n configureApp?: (app: express.Express) => Promise<any> | any;\n /**\n * Gives access to the underlying HTTP server so that you can add custom configurations beyond **Arkos** customization capabilities\n *\n * **Note**: In the end **Arkos** will call `server.listen` for you.\n *\n * If you want to call `server.listen` by yourself pass port as `undefined` and then use the return server from `arkos.init()`.\n *\n * See how to call `server.listen` correctly [www.arkosjs.com/docs/guide/accessing-the-express-app#creating-your-own-http-server](https://www.arkosjs.com/docs/guide/accessing-the-express-app#creating-your-own-http-server)\n *\n * See [www.arkosjs.com/docs/guide/accessing-the-express-app#accessing-the-http-server](https://www.arkosjs.com/docs/guide/accessing-the-express-app#accessing-the-http-server) for further details on the method configureServer.\n *\n * @param {http.Server} server - The HTTP server instance\n * @returns {any}\n */\n configureServer?: (server: http.Server) => Promise<any> | any;\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 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 \".\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for 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-system](https://www.arkosjs.com/docs/core-concepts/authentication-system) for details.\n */\n authentication?: {\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-system](https://www.arkosjs.com/docs/core-concepts/authentication-system) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /**\n * Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * See more at [www.arkosjs.com/docs/core-concepts/authentication-system#login-with-different-fileds](https://www.arkosjs.com/docs/core-concepts/authentication-system#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 */\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 requestRateLimitOptions?: 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 * ⚠️ Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n */\n secure?: boolean;\n\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n */\n httpOnly?: boolean;\n\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n };\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * @See [www.arkosjs.com/docs/core-concepts/request-data-validation](https://www.arkosjs.com/docs/core-concepts/request-data-validation) for more details.\n */\n validation?: {\n /**\n * 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 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 * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver?: \"zod\";\n validationOptions?: Record<string, any>;\n }\n );\n /**\n * Defines file upload configurations\n *\n * See [www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations](https://www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations)\n */\n fileUpload?: {\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n 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/api-reference/default-supported-upload-files](https://www.arkosjs.com/docs/api-reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n restrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n files?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * 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 * @property {string | string[] | \"all\"} [allowedOrigins] - List of allowed origins. If set to `\"all\"`, all origins are accepted.\n * @property {import('cors').CorsOptions} [options] - Additional CORS options passed directly to the `cors` middleware.\n * @property {import('cors').CorsOptionsDelegate} [customHandler] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customHandler` is provided, both `allowedOrigins` and `options` will be ignored in favor of the custom logic.\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?:\n | false\n | {\n /**\n * Defines allowed origins to acess the API.\n */\n allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware\n *\n * see\n */\n customHandler?: cors.CorsOptionsDelegate;\n }\n | 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 | Parameters<typeof cookieParser>\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/core-concepts/sending-emails](https://www.arkosjs.com/docs/core-concepts/sending-emails)\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/core-concepts/swagger-api-documentation}\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 * 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 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 | \"FinalPrismaQueryArgs\"\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"]}
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 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 \".\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for 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-system](https://www.arkosjs.com/docs/core-concepts/authentication-system) for details.\n */\n authentication?: {\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-system](https://www.arkosjs.com/docs/core-concepts/authentication-system) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /**\n * Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * See more at [www.arkosjs.com/docs/core-concepts/authentication-system#login-with-different-fileds](https://www.arkosjs.com/docs/core-concepts/authentication-system#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 */\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 * ⚠️ Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n */\n secure?: boolean;\n\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n */\n httpOnly?: boolean;\n\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n };\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * @See [www.arkosjs.com/docs/core-concepts/request-data-validation](https://www.arkosjs.com/docs/core-concepts/request-data-validation) for more details.\n */\n validation?: {\n /**\n * 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 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 * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver: \"zod\";\n validationOptions?: Record<string, any>;\n }\n );\n /**\n * Defines file upload configurations\n *\n * See [www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations](https://www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations)\n */\n fileUpload?: {\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n 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/api-reference/default-supported-upload-files](https://www.arkosjs.com/docs/api-reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n restrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n files?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * 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 * @property {string | string[] | \"all\"} [allowedOrigins] - List of allowed origins. If set to `\"all\"`, all origins are accepted.\n * @property {import('cors').CorsOptions} [options] - Additional CORS options passed directly to the `cors` middleware.\n * @property {import('cors').CorsOptionsDelegate} [customHandler] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customHandler` is provided, both `allowedOrigins` and `options` will be ignored in favor of the custom logic.\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?:\n | false\n | {\n /**\n * Defines allowed origins to acess the API.\n */\n allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware\n *\n * see\n */\n customHandler?: cors.CorsOptionsDelegate;\n }\n | 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 | Parameters<typeof cookieParser>\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/core-concepts/sending-emails](https://www.arkosjs.com/docs/core-concepts/sending-emails)\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/core-concepts/swagger-api-documentation}\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 * 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 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 | \"FinalPrismaQueryArgs\"\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"]}
@@ -1 +1 @@
1
- {"version":3,"file":"router-config.js","sourceRoot":"","sources":["../../../src/types/router-config.ts"],"names":[],"mappings":"","sourcesContent":["import { ArkosRouteConfig } from \"../exports\";\n\nexport type RouterEndpoint =\n | \"createOne\"\n | \"findOne\"\n | \"updateOne\"\n | \"deleteOne\"\n | \"findMany\"\n | \"createMany\"\n | \"updateMany\"\n | \"deleteMany\";\n\nexport type AuthRouterEndpoint =\n | \"getMe\"\n | \"updateMe\"\n | \"deleteMe\"\n | \"login\"\n | \"logout\"\n | \"signup\"\n | \"updatePassword\"\n | \"findManyAuthAction\"\n | \"findOneAuthAction\";\n\nexport type FileUploadRouterEndpoint =\n | \"findFile\"\n | \"uploadFile\"\n | \"updateFile\"\n | \"deleteFile\";\n\ninterface PrismaBaseRouterConfig {\n parent?: {\n model?: string;\n foreignKeyField?: string;\n endpoints?: \"*\" | RouterEndpoint[];\n };\n}\n\ntype BaseRouterConfig = PrismaBaseRouterConfig & {\n /**\n * Backward compatibility (prior 1.4.0-beta) - disables/enables endpoints\n *\n * prefer to rather to use the following:\n *\n * ```ts\n * export const config = {\n * findMany: {\n * disabled: true\n * }\n * }\n * ```\n */\n disable?:\n | boolean\n | {\n [K in RouterEndpoint]?: boolean;\n };\n} & {\n [K in RouterEndpoint]?: Omit<ArkosRouteConfig, \"route\">;\n};\n\ntype AuthRouterConfig = {\n /**\n * Backward compatibility (prior 1.4.0-beta) - disables/enables endpoints\n *\n * prefer to rather to use the following:\n *\n * ```ts\n * export const config = {\n * getMe: {\n * disabled: true\n * }\n * }\n * ```\n */\n disable?:\n | boolean\n | {\n [K in AuthRouterEndpoint]?: boolean;\n };\n} & {\n [K in AuthRouterEndpoint]?: Omit<ArkosRouteConfig, \"route\">;\n};\n\ntype FileUploadRouterConfig = {\n /**\n * Backward compatibility (prior 1.4.0-beta) - disables/enables endpoints\n *\n * prefer to rather to use the following:\n *\n * ```ts\n * export const config = {\n * deleteFile: {\n * disabled: true\n * }\n * }\n * ```\n */\n disable?:\n | boolean\n | {\n [K in FileUploadRouterEndpoint]?: boolean;\n };\n} & {\n [K in FileUploadRouterEndpoint]?: Omit<ArkosRouteConfig, \"route\" | \"uploads\">;\n};\n\nexport type RouterConfig<T extends string = string> = T extends \"auth\"\n ? AuthRouterConfig\n : T extends \"file-upload\"\n ? FileUploadRouterConfig\n : BaseRouterConfig;\n"]}
1
+ {"version":3,"file":"router-config.js","sourceRoot":"","sources":["../../../src/types/router-config.ts"],"names":[],"mappings":"","sourcesContent":["import { ArkosRouteConfig } from \"../exports\";\n\nexport type RouterEndpoint =\n | \"createOne\"\n | \"findOne\"\n | \"updateOne\"\n | \"deleteOne\"\n | \"findMany\"\n | \"createMany\"\n | \"updateMany\"\n | \"deleteMany\";\n\nexport type AuthRouterEndpoint =\n | \"getMe\"\n | \"updateMe\"\n | \"deleteMe\"\n | \"login\"\n | \"logout\"\n | \"signup\"\n | \"updatePassword\"\n | \"findManyAuthAction\"\n | \"findOneAuthAction\";\n\nexport type FileUploadRouterEndpoint =\n | \"findFile\"\n | \"uploadFile\"\n | \"updateFile\"\n | \"deleteFile\";\n\ninterface PrismaBaseRouterConfig {\n parent?: {\n model?: string;\n foreignKeyField?: string;\n endpoints?: \"*\" | RouterEndpoint[];\n };\n}\n\ntype BaseRouterConfig = PrismaBaseRouterConfig & {\n /**\n * Backward compatibility (prior 1.4.0-beta) - disables/enables endpoints\n *\n * prefer to rather to use the following:\n *\n * ```ts\n * export const config = {\n * findMany: {\n * disabled: true\n * }\n * }\n * ```\n */\n disable?:\n | boolean\n | {\n [K in RouterEndpoint]?: boolean;\n };\n} & {\n [K in RouterEndpoint]?: Omit<ArkosRouteConfig, \"path\">;\n};\n\ntype AuthRouterConfig = {\n /**\n * Backward compatibility (prior 1.4.0-beta) - disables/enables endpoints\n *\n * prefer to rather to use the following:\n *\n * ```ts\n * export const config = {\n * getMe: {\n * disabled: true\n * }\n * }\n * ```\n */\n disable?:\n | boolean\n | {\n [K in AuthRouterEndpoint]?: boolean;\n };\n} & {\n [K in AuthRouterEndpoint]?: Omit<ArkosRouteConfig, \"path\">;\n};\n\ntype FileUploadRouterConfig = {\n /**\n * Backward compatibility (prior 1.4.0-beta) - disables/enables endpoints\n *\n * prefer to rather to use the following:\n *\n * ```ts\n * export const config = {\n * deleteFile: {\n * disabled: true\n * }\n * }\n * ```\n */\n disable?:\n | boolean\n | {\n [K in FileUploadRouterEndpoint]?: boolean;\n };\n} & {\n [K in FileUploadRouterEndpoint]?: Omit<ArkosRouteConfig, \"path\" | \"uploads\">;\n};\n\nexport type RouterConfig<T extends string = string> = T extends \"auth\"\n ? AuthRouterConfig\n : T extends \"file-upload\"\n ? FileUploadRouterConfig\n : BaseRouterConfig;\n"]}
@@ -28,7 +28,7 @@ export default function ArkosRouter() {
28
28
  return function (config, ...handlers) {
29
29
  if (config.disabled)
30
30
  return;
31
- const route = config.route;
31
+ const route = config.path;
32
32
  if (!RouteConfigValidator.isArkosRouteConfig(config))
33
33
  throw Error(`First argument of ArkosRouter().${prop}() must be a valid ArkosRouteConfig but recevied ${config}`);
34
34
  const method = prop;
@@ -1 +1 @@
1
- {"version":3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AAG,MAAM,CAAC,CAAC;gBAC7B,CAAC;YACH,CAAC;QACH,CAAC;QAED,MAAM,gBAAgB,GACpB,sBAAsB,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC;QAEtD,KAAa,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC,GAAG;YAC3C,OAAO,EAAE,OAAO,EAAE,OAAO,IAAI,GAAG,MAAM,IAAI,IAAI,EAAE;YAChD,WAAW,EAAE,OAAO,EAAE,WAAW,IAAI,GAAG,MAAM,IAAI,IAAI,EAAE;YACxD,IAAI,EAAE,OAAO,EAAE,IAAI,IAAI,CAAC,UAAU,CAAC;YACnC,WAAW,EAAE,GAAG,MAAM,CAAC,WAAW,EAAE,IAAI,IAAI,EAAE;YAC9C,UAAU,EAAE,CAAC,GAAG,CAAC,gBAAgB,CAAC,UAAU,IAAI,EAAE,CAAC,EAAE,GAAG,UAAU,CAAC;YACnE,GAAG,CAAC,CAAC,gBAAgB,CAAC,WAAW;gBAC/B,MAAM,EAAE,UAAU;gBAClB,MAAM,EAAE,UAAU,EAAE,IAAI,IAAI;gBAC1B,WAAW,EAAE;oBACX,OAAO,EAAE;wBACP,kBAAkB,EAAE;4BAClB,MAAM,EAAE,qBAAqB,CAAC,MAAM,EAAE,UAAU,EAAE,IAAW,CAAC;yBAC/D;qBACF;iBACF;aACF,CAAC;YACJ,GAAG,gBAAgB;SACpB,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { IArkosRouter, ArkosRouteConfig } from \"./types\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport RouteConfigValidator from \"./route-config-validator\";\nimport RouteConfigRegistry from \"./route-config-registry\";\nimport { extractArkosRoutes, getMiddlewareStack } from \"./utils/helpers\";\nimport { getArkosConfig } from \"../../exports\";\nimport { catchAsync } from \"../../exports/error-handler\";\nimport { ArkosErrorRequestHandler, ArkosRequestHandler } from \"../../types\";\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 uploadManager from \"./utils/helpers/upload-manager\";\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 * route: \"/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 default function ArkosRouter(): IArkosRouter {\n const router: IArkosRouter = Router();\n\n return new Proxy(router, {\n get(target, prop, receiver) {\n const originalMethod = Reflect.get(target, prop, receiver);\n\n const httpMethods = [\n \"get\",\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n \"all\",\n \"head\",\n \"trace\",\n \"options\",\n ];\n\n type ArkosAnyRequestHandler =\n | ArkosRequestHandler\n | ArkosErrorRequestHandler;\n\n if (httpMethods.includes(prop as string)) {\n return function (\n config: ArkosRouteConfig,\n ...handlers: ArkosAnyRequestHandler[]\n ) {\n if (config.disabled) return;\n\n const route = config.route;\n\n if (!RouteConfigValidator.isArkosRouteConfig(config))\n throw Error(\n `First argument of ArkosRouter().${prop as string}() must be a valid ArkosRouteConfig but recevied ${config}`\n );\n\n const method = prop as string;\n\n if (handlers.length > 0) {\n handlers = handlers.map(\n (handler: ArkosAnyRequestHandler | ArkosAnyRequestHandler[]) => {\n return typeof handler === \"function\"\n ? catchAsync(handler, {\n type: handler.length > 3 ? \"error\" : \"normal\",\n })\n : handler.map((nesteHandler: any) =>\n catchAsync(nesteHandler, {\n type: handler.length > 3 ? \"error\" : \"normal\",\n })\n );\n }\n );\n\n const finalHandler = handlers[handlers.length - 1];\n RouteConfigRegistry.register(finalHandler, config, method);\n }\n\n const arkosConfig = getArkosConfig();\n const validationConfig = arkosConfig.validation;\n const authenticationConfig = arkosConfig.authentication;\n const strictValidation = validationConfig?.strict;\n\n if (\n strictValidation &&\n (!(\"validation\" in config) ||\n (\"validation\" in config &&\n !config.validation &&\n config.validation !== undefined))\n )\n throw Error(\n \"When using strict validation you must either pass { validation: false } in order to explicitly tell that no input will be received, or pass `undefined` for each input type e.g { validation: { query: undefined } } in order to deny the input of given request input.\"\n );\n\n if (!validationConfig?.resolver && config.validation)\n throw Error(\n \"Trying to pass validators into route config validation option without choosing a validation resolver under arkos.init({ validation: { resolver: '' } })\"\n );\n\n if (config.authentication && !authenticationConfig?.mode)\n throw Error(\n \"Trying to authenticate a route without choosing an authentication mode under arkos.init({ authentication: { mode: '' } })\"\n );\n\n handlers = [...getMiddlewareStack(config), ...handlers];\n\n if (\n config.experimental?.uploads &&\n config.experimental.uploads.deleteOnError !== false\n )\n handlers.push(\n catchAsync(\n uploadManager.handleFileCleanup(config.experimental.uploads),\n { type: \"error\" }\n )\n );\n\n return originalMethod.call(target, route, ...handlers);\n };\n }\n // }\n return originalMethod;\n },\n }) as IArkosRouter;\n}\n\nexport function generateOpenAPIFromApp(app: any) {\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 }) => {\n if (config?.experimental?.openapi === false) return;\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.jsonSchemaToOpeApiParameters(\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 (paths as any)[path][method.toLowerCase()] = {\n summary: openapi?.summary || `${method} ${path}`,\n description: openapi?.description || `${method} ${path}`,\n tags: openapi?.tags || [\"Defaults\"],\n operationId: `${method.toLowerCase()}:${path}`,\n parameters: [...(convertedOpenAPI.parameters || []), ...parameters],\n ...(!convertedOpenAPI.requestBody &&\n config?.validation &&\n config?.validation?.body && {\n requestBody: {\n content: {\n \"application/json\": {\n schema: validatorToJsonSchema(config?.validation?.body as any),\n },\n },\n },\n }),\n ...convertedOpenAPI,\n };\n });\n\n return paths;\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/utils/arkos-router/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAGjC,OAAO,oBAAoB,MAAM,0BAA0B,CAAC;AAC5D,OAAO,mBAAmB,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACzE,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAEzD,OAAO,eAAe,MAAM,oBAAoB,CAAC;AACjD,OAAO,0BAA0B,MAAM,oEAAoE,CAAC;AAC5G,OAAO,sBAAsB,M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,EAAE;YAC9C,UAAU,EAAE,CAAC,GAAG,CAAC,gBAAgB,CAAC,UAAU,IAAI,EAAE,CAAC,EAAE,GAAG,UAAU,CAAC;YACnE,GAAG,CAAC,CAAC,gBAAgB,CAAC,WAAW;gBAC/B,MAAM,EAAE,UAAU;gBAClB,MAAM,EAAE,UAAU,EAAE,IAAI,IAAI;gBAC1B,WAAW,EAAE;oBACX,OAAO,EAAE;wBACP,kBAAkB,EAAE;4BAClB,MAAM,EAAE,qBAAqB,CAAC,MAAM,EAAE,UAAU,EAAE,IAAW,CAAC;yBAC/D;qBACF;iBACF;aACF,CAAC;YACJ,GAAG,gBAAgB;SACpB,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { IArkosRouter, ArkosRouteConfig } from \"./types\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport RouteConfigValidator from \"./route-config-validator\";\nimport RouteConfigRegistry from \"./route-config-registry\";\nimport { extractArkosRoutes, getMiddlewareStack } from \"./utils/helpers\";\nimport { getArkosConfig } from \"../../exports\";\nimport { catchAsync } from \"../../exports/error-handler\";\nimport { ArkosErrorRequestHandler, ArkosRequestHandler } from \"../../types\";\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 uploadManager from \"./utils/helpers/upload-manager\";\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 default function ArkosRouter(): IArkosRouter {\n const router: IArkosRouter = Router();\n\n return new Proxy(router, {\n get(target, prop, receiver) {\n const originalMethod = Reflect.get(target, prop, receiver);\n\n const httpMethods = [\n \"get\",\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n \"all\",\n \"head\",\n \"trace\",\n \"options\",\n ];\n\n type ArkosAnyRequestHandler =\n | ArkosRequestHandler\n | ArkosErrorRequestHandler;\n\n if (httpMethods.includes(prop as string)) {\n return function (\n config: ArkosRouteConfig,\n ...handlers: ArkosAnyRequestHandler[]\n ) {\n if (config.disabled) return;\n\n const route = config.path;\n\n if (!RouteConfigValidator.isArkosRouteConfig(config))\n throw Error(\n `First argument of ArkosRouter().${prop as string}() must be a valid ArkosRouteConfig but recevied ${config}`\n );\n\n const method = prop as string;\n\n if (handlers.length > 0) {\n handlers = handlers.map(\n (handler: ArkosAnyRequestHandler | ArkosAnyRequestHandler[]) => {\n return typeof handler === \"function\"\n ? catchAsync(handler, {\n type: handler.length > 3 ? \"error\" : \"normal\",\n })\n : handler.map((nesteHandler: any) =>\n catchAsync(nesteHandler, {\n type: handler.length > 3 ? \"error\" : \"normal\",\n })\n );\n }\n );\n\n const finalHandler = handlers[handlers.length - 1];\n RouteConfigRegistry.register(finalHandler, config, method);\n }\n\n const arkosConfig = getArkosConfig();\n const validationConfig = arkosConfig.validation;\n const authenticationConfig = arkosConfig.authentication;\n const strictValidation = validationConfig?.strict;\n\n if (\n strictValidation &&\n (!(\"validation\" in config) ||\n (\"validation\" in config &&\n !config.validation &&\n config.validation !== undefined))\n )\n throw Error(\n \"When using strict validation you must either pass { validation: false } in order to explicitly tell that no input will be received, or pass `undefined` for each input type e.g { validation: { query: undefined } } in order to deny the input of given request input.\"\n );\n\n if (!validationConfig?.resolver && config.validation)\n throw Error(\n \"Trying to pass validators into route config validation option without choosing a validation resolver under arkos.init({ validation: { resolver: '' } })\"\n );\n\n if (config.authentication && !authenticationConfig?.mode)\n throw Error(\n \"Trying to authenticate a route without choosing an authentication mode under arkos.init({ authentication: { mode: '' } })\"\n );\n\n handlers = [...getMiddlewareStack(config), ...handlers];\n\n if (\n config.experimental?.uploads &&\n config.experimental.uploads.deleteOnError !== false\n )\n handlers.push(\n catchAsync(\n uploadManager.handleFileCleanup(config.experimental.uploads),\n { type: \"error\" }\n )\n );\n\n return originalMethod.call(target, route, ...handlers);\n };\n }\n // }\n return originalMethod;\n },\n }) as IArkosRouter;\n}\n\nexport function generateOpenAPIFromApp(app: any) {\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 }) => {\n if (config?.experimental?.openapi === false) return;\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.jsonSchemaToOpeApiParameters(\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 (paths as any)[path][method.toLowerCase()] = {\n summary: openapi?.summary || `${method} ${path}`,\n description: openapi?.description || `${method} ${path}`,\n tags: openapi?.tags || [\"Defaults\"],\n operationId: `${method.toLowerCase()}:${path}`,\n parameters: [...(convertedOpenAPI.parameters || []), ...parameters],\n ...(!convertedOpenAPI.requestBody &&\n config?.validation &&\n config?.validation?.body && {\n requestBody: {\n content: {\n \"application/json\": {\n schema: validatorToJsonSchema(config?.validation?.body as any),\n },\n },\n },\n }),\n ...convertedOpenAPI,\n };\n });\n\n return paths;\n}\n"]}