arkos 1.2.14-test.1 → 1.2.15-beta
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/app.js.map +1 -1
- package/dist/cjs/modules/base/base.middlewares.js +1 -1
- package/dist/cjs/modules/base/base.middlewares.js.map +1 -1
- package/dist/cjs/modules/error-handler/error-handler.controller.js +1 -1
- package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/cjs/server.js +2 -2
- package/dist/cjs/server.js.map +1 -1
- package/dist/cjs/utils/cli/build.js +2 -3
- package/dist/cjs/utils/cli/build.js.map +1 -1
- package/dist/cjs/utils/cli/dev.js +5 -5
- package/dist/cjs/utils/cli/dev.js.map +1 -1
- package/dist/cjs/utils/cli/start.js +1 -5
- package/dist/cjs/utils/cli/start.js.map +1 -1
- package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/cjs/utils/cli/utils/watermark-stamper.js +3 -0
- package/dist/cjs/utils/cli/utils/watermark-stamper.js.map +1 -0
- package/dist/cjs/utils/features/api.features.js +1 -1
- package/dist/cjs/utils/features/api.features.js.map +1 -1
- package/dist/cjs/utils/features/port-and-host-allocator.js +1 -0
- package/dist/cjs/utils/features/port-and-host-allocator.js.map +1 -0
- package/dist/cjs/utils/helpers/api.features.helpers.js +1 -1
- package/dist/cjs/utils/helpers/api.features.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/models.helpers.js +1 -1
- package/dist/cjs/utils/helpers/models.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/prisma.helpers.js +1 -1
- package/dist/cjs/utils/helpers/prisma.helpers.js.map +1 -1
- package/dist/cjs/utils/helpers/routers.helpers.js +1 -1
- package/dist/cjs/utils/helpers/routers.helpers.js.map +1 -1
- package/dist/cjs/utils/prisma/enhaced-prisma-json-schema-generator.js.map +1 -1
- package/dist/cjs/utils/prisma/prisma-schema-parser.js.map +1 -1
- package/dist/cjs/utils/sheu.js +1 -1
- package/dist/cjs/utils/sheu.js.map +1 -1
- package/dist/esm/app.js.map +1 -1
- package/dist/esm/modules/base/base.middlewares.js +1 -1
- package/dist/esm/modules/base/base.middlewares.js.map +1 -1
- package/dist/esm/modules/error-handler/error-handler.controller.js +2 -2
- package/dist/esm/modules/error-handler/error-handler.controller.js.map +1 -1
- package/dist/esm/server.js +3 -3
- package/dist/esm/server.js.map +1 -1
- package/dist/esm/utils/cli/build.js +3 -4
- package/dist/esm/utils/cli/build.js.map +1 -1
- package/dist/esm/utils/cli/dev.js +5 -5
- package/dist/esm/utils/cli/dev.js.map +1 -1
- package/dist/esm/utils/cli/start.js +1 -5
- package/dist/esm/utils/cli/start.js.map +1 -1
- package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/esm/utils/cli/utils/watermark-stamper.js +3 -0
- package/dist/esm/utils/cli/utils/watermark-stamper.js.map +1 -0
- package/dist/esm/utils/features/api.features.js +1 -1
- package/dist/esm/utils/features/api.features.js.map +1 -1
- package/dist/esm/utils/features/port-and-host-allocator.js +1 -0
- package/dist/esm/utils/features/port-and-host-allocator.js.map +1 -0
- package/dist/esm/utils/helpers/api.features.helpers.js +1 -1
- package/dist/esm/utils/helpers/api.features.helpers.js.map +1 -1
- package/dist/esm/utils/helpers/models.helpers.js +1 -1
- package/dist/esm/utils/helpers/models.helpers.js.map +1 -1
- package/dist/esm/utils/helpers/prisma.helpers.js +1 -1
- package/dist/esm/utils/helpers/prisma.helpers.js.map +1 -1
- package/dist/esm/utils/helpers/routers.helpers.js +1 -1
- package/dist/esm/utils/helpers/routers.helpers.js.map +1 -1
- package/dist/esm/utils/prisma/enhaced-prisma-json-schema-generator.js.map +1 -1
- package/dist/esm/utils/prisma/prisma-schema-parser.js.map +1 -1
- package/dist/esm/utils/sheu.js +1 -1
- package/dist/esm/utils/sheu.js.map +1 -1
- package/dist/types/modules/error-handler/error-handler.controller.d.ts +1 -1
- package/dist/types/utils/cli/utils/watermark-stamper.d.ts +9 -0
- package/dist/types/utils/features/port-and-host-allocator.d.ts +21 -0
- package/dist/types/utils/prisma/enhaced-prisma-json-schema-generator.d.ts +1 -1
- package/package.json +10 -9
- package/dist/cjs/utils/prisma/prisma-json-schema-generator.js +0 -1
- package/dist/cjs/utils/prisma/prisma-json-schema-generator.js.map +0 -1
- package/dist/esm/utils/prisma/prisma-json-schema-generator.js +0 -1
- package/dist/esm/utils/prisma/prisma-json-schema-generator.js.map +0 -1
- package/dist/types/utils/prisma/prisma-json-schema-generator.d.ts +0 -10
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"enhaced-prisma-json-schema-generator.js","sourceRoot":"","sources":["../../../../src/utils/prisma/enhaced-prisma-json-schema-generator.ts"],"names":[],"mappings":";;;;;;AAEA,mFAAoD;AACpD,8DAImC;AACnC,kFAAwD;AAsBxD,MAAa,iCAAiC;IAA9C;QACU,WAAM,GAAG,8BAAkB,CAAC,KAAK,EAAE,CAAC;IAkzB9C,CAAC;IA7yBC,KAAK,CAAC,oBAAoB,CACxB,MAA8B;QAE9B,MAAM,EACJ,SAAS,EACT,WAAW,EACX,iBAAiB,GAAG;YAClB,OAAO;YACP,OAAO;YACP,QAAQ;YACR,OAAO;YACP,UAAU;YACV,gBAAgB;YAChB,QAAQ;YACR,WAAW;YACX,YAAY;YACZ,QAAQ;YACR,WAAW;YACX,YAAY;YACZ,OAAO;YACP,SAAS;YACT,UAAU;SACX,GACF,GAAG,MAAM,CAAC;QAEX,MAAM,YAAY,GAAG,MAAM,IAAA,yCAAwB,EAAC,SAAS,EAAE,WAAW,CAAC,CAAC;QAC5E,MAAM,YAAY,GAAG,YAAY,EAAE,MAAM,EAAE,MAAM,IAAI,EAAE,CAAC;QACxD,MAAM,kBAAkB,GAAG,YAAY,EAAE,kBAAkB,IAAI,EAAE,CAAC;QAClE,MAAM,eAAe,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;QACtE,MAAM,YAAY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AAE,CAAC,CAAC,CAAC,IAAI,KAAK,KAAK,CAAC,IAAI,CAAC,CAAC;YACrE,IAAI,OAAO,EAAE,CAAC;gBACZ,QAAQ,CAAC,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC;YACjC,CAAC;QACH,CAAC;QAED,OAAO,QAAQ,CAAC;IAClB,CAAC;IAEO,yBAAyB,CAAC,UAAkB;QAClD,MAAM,OAAO,GAA8B;YACzC,MAAM,EAAE,QAAQ;YAChB,GAAG,EAAE,QAAQ;YACb,KAAK,EAAE,QAAQ;YACf,OAAO,EAAE,SAAS;YAClB,QAAQ,EAAE,QAAQ;YAClB,IAAI,EAAE,QAAQ;YACd,KAAK,EAAE,QAAQ;SAChB,CAAC;QAEF,IAAI,OAAO,CAAC,UAAU,CAAC;YAAE,OAAO,OAAO,CAAC,UAAU,CAAC,CAAC;QAEpD,IAAI,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC;YAAE,OAAO,QAAQ,CAAC;QAE7C,IAAI,IAAI,CAAC,eAAe,CAAC,UAAU,CAAC;YAAE,OAAO,QAAQ,CAAC;QAEtD,OAAO,QAAQ,CAAC;IAClB,CAAC;IAEO,MAAM,CAAC,QAAgB;QAC7B,OAAO,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC;IAC5D,CAAC;CACF;AAnzBD,8EAmzBC;AAED,MAAM,iCAAiC,GACrC,IAAI,iCAAiC,EAAE,CAAC;AAE1C,kBAAe,iCAAiC,CAAC","sourcesContent":["import { ArkosConfig, RouterConfig } from \"../../exports\";\nimport { AuthPrismaQueryOptions, PrismaQueryOptions } from \"../../types\";\nimport deepmerge from \"../helpers/deepmerge.helper\";\nimport {\n importPrismaModelModules,\n localValidatorFileExists,\n ValidationFileMappingKey,\n} from \"../helpers/models.helpers\";\nimport prismaSchemaParser from \"./prisma-schema-parser\";\nimport {\n PrismaModel,\n PrismaField,\n JsonSchema,\n JsonSchemaProperty,\n} from \"./types\";\n\n// Add these types to your existing types file\nexport interface SchemaGenerationConfig {\n modelName: string;\n arkosConfig: ArkosConfig;\n schemasToGenerate?: ValidationFileMappingKey[];\n}\n\nexport interface GeneratedSchemas {\n [key: string]: JsonSchema;\n}\n\n/**\n * Enhanced JSON Schema generator that creates schemas based on Prisma models and query options\n */\nexport class EnhancedPrismaJsonSchemaGenerator {\n private schema = prismaSchemaParser.parse();\n\n /**\n * Main method to generate all schemas for a model\n */\n async generateModelSchemas(\n config: SchemaGenerationConfig\n ): Promise<GeneratedSchemas> {\n const {\n modelName,\n arkosConfig,\n schemasToGenerate = [\n \"model\",\n \"login\",\n \"signup\",\n \"getMe\",\n \"updateMe\",\n \"updatePassword\",\n \"create\",\n \"createOne\",\n \"createMany\",\n \"update\",\n \"updateOne\",\n \"updateMany\",\n \"query\",\n \"findOne\",\n \"findMany\",\n ],\n } = config;\n\n const modelModules = await importPrismaModelModules(modelName, arkosConfig);\n const routerConfig = modelModules?.router?.config || {};\n const prismaQueryOptions = modelModules?.prismaQueryOptions || {};\n const authModuleModel = [\"auth\", \"me\", \"password\", \"signup\", \"login\"];\n const isAuthModule = authModuleModel.includes(modelName.toLowerCase());\n\n // Check if generation should be skipped\n if (arkosConfig?.swagger?.strict && arkosConfig.swagger.mode !== \"prisma\")\n return {};\n\n // Check if router is disabled\n if (routerConfig?.disable === true) return {};\n\n const model = this.schema.models.find(\n (m) => m.name.toLowerCase() === modelName.toLowerCase()\n );\n if (!model && !isAuthModule) return {};\n // throw new Error(`Model ${modelName} not found in schema`);\n\n const schemas: { [key: string]: JsonSchema } = {};\n\n if (isAuthModule) {\n // Generate auth-specific schemas\n await this.generateAuthSchemas(\n this.schema.models.find((m) => m.name.toLowerCase() === \"user\")!,\n schemas,\n arkosConfig,\n schemasToGenerate,\n prismaQueryOptions as AuthPrismaQueryOptions<any>\n );\n } else {\n // Generate standard CRUD schemas\n if (model)\n await this.generateCrudSchemas(\n model,\n schemas,\n arkosConfig,\n schemasToGenerate,\n prismaQueryOptions as PrismaQueryOptions<any>,\n routerConfig\n );\n }\n\n return { ...schemas };\n }\n\n /**\n * Generate auth-specific schemas\n */\n private async generateAuthSchemas(\n model: PrismaModel,\n schemas: { [key: string]: JsonSchema },\n arkosConfig: ArkosConfig,\n schemasToGenerate: ValidationFileMappingKey[],\n queryOptions?: AuthPrismaQueryOptions<any>,\n routerConfig?: RouterConfig\n ) {\n const modelName = \"Auth\";\n\n // if no auth activated forget those json schemas\n if (!arkosConfig?.authentication) return schemas;\n\n // Login schema (input)\n if (\n schemasToGenerate.includes(\"login\") &&\n !this.isEndpointDisabled(\"login\", routerConfig) &&\n !(await localValidatorFileExists(\"login\", modelName, arkosConfig))\n ) {\n schemas[`LoginSchema`] = this.generateLoginSchema(arkosConfig);\n }\n\n // Signup schema (input)\n if (\n schemasToGenerate.includes(\"signup\") &&\n !this.isEndpointDisabled(\"signup\", routerConfig) &&\n !(await localValidatorFileExists(\"signup\", modelName, arkosConfig))\n ) {\n schemas[`SignupSchema`] = this.generateSignupSchema(\n model,\n queryOptions?.signup\n );\n }\n\n // UpdateMe schema (input)\n if (\n schemasToGenerate.includes(\"updateMe\") &&\n !this.isEndpointDisabled(\"updateMe\", routerConfig) &&\n !(await localValidatorFileExists(\"updateMe\", modelName, arkosConfig))\n ) {\n schemas[`UpdateMeSchema`] = this.generateUpdateMeSchema(\n model,\n queryOptions?.updateMe\n );\n }\n\n // UpdatePassword schema (input)\n if (\n schemasToGenerate.includes(\"updatePassword\") &&\n !this.isEndpointDisabled(\"updatePassword\", routerConfig) &&\n !(await localValidatorFileExists(\n \"updatePassword\",\n modelName,\n arkosConfig\n ))\n ) {\n schemas[`UpdatePasswordSchema`] = this.generateUpdatePasswordSchema(\n model,\n queryOptions?.updatePassword\n );\n }\n\n // GetMe response schema\n if (\n schemasToGenerate.includes(\"getMe\") &&\n !this.isEndpointDisabled(\"getMe\", routerConfig) &&\n !(await localValidatorFileExists(\"getMe\", modelName, arkosConfig))\n ) {\n schemas[`GetMeSchema`] = this.generateResponseSchema(\n model,\n queryOptions?.getMe || {},\n \"findOne\"\n );\n }\n }\n\n /**\n * Generate standard CRUD schemas\n */\n private async generateCrudSchemas(\n model: PrismaModel,\n schemas: { [key: string]: JsonSchema },\n arkosConfig: ArkosConfig,\n schemasToGenerate: ValidationFileMappingKey[],\n queryOptions?: PrismaQueryOptions<any>,\n routerConfig?: RouterConfig\n ) {\n const modelName = model.name;\n\n // // Create schemas\n // if (\n // schemasToGenerate.includes(\"createOne\") &&\n // !this.isEndpointDisabled(\"createOne\", routerConfig) &&\n // !(await localValidatorFileExists(\"createOne\", modelName, arkosConfig))\n // ) {\n // schemas[`Create${modelName}ModelSchema`] = this.generateCreateSchema(\n // model,\n // this.resolvePrismaQueryOptions(queryOptions, \"createOne\")\n // );\n // }\n\n // if (\n // schemasToGenerate.includes(\"createMany\") &&\n // !this.isEndpointDisabled(\"createMany\", routerConfig) &&\n // !(await localValidatorFileExists(\"createMany\", modelName, arkosConfig))\n // ) {\n // schemas[`CreateMany${modelName}ModelSchema`] = {\n // type: \"array\",\n // items: { $ref: `#/components/schemas/Create${modelName}ModelSchema` },\n // };\n // }\n\n // // Update schemas\n // if (\n // schemasToGenerate.includes(\"updateOne\") &&\n // !this.isEndpointDisabled(\"updateOne\", routerConfig) &&\n // !(await localValidatorFileExists(\"updateOne\", modelName, arkosConfig))\n // ) {\n // schemas[`Update${modelName}ModelSchema`] = this.generateUpdateSchema(\n // model,\n // this.resolvePrismaQueryOptions(queryOptions, \"updateOne\")\n // );\n // }\n\n // if (\n // schemasToGenerate.includes(\"updateMany\") &&\n // !this.isEndpointDisabled(\"updateMany\", routerConfig) &&\n // !(await localValidatorFileExists(\"updateMany\", modelName, arkosConfig))\n // ) {\n // schemas[`UpdateMany${modelName}ModelSchema`] = {\n // type: \"object\",\n // properties: {\n // data: {\n // type: \"object\",\n // $ref: `#/components/schemas/Update${modelName}ModelSchema`,\n // },\n // where: { type: \"object\" },\n // },\n // required: [\"data\"],\n // };\n // }\n // Helper function to ensure base schema exists\n\n const ensureBaseSchemaReference = async (\n operation: string,\n modelName: string\n ) => {\n const suffix =\n arkosConfig.validation?.resolver === \"zod\" ? \"Schema\" : \"Dto\";\n\n // Check if local validator file exists for single operation\n const singleOpName = operation === \"Create\" ? \"createOne\" : \"updateOne\";\n const hasLocalValidator = await localValidatorFileExists(\n singleOpName,\n modelName,\n arkosConfig\n );\n\n if (hasLocalValidator) {\n // Point to local validator schema (Schema or Dto)\n return `${operation}${modelName}${suffix}`;\n } else {\n // Point to ModelSchema, generate if doesn't exist\n const modelSchemaKey = `${operation}${modelName}ModelSchema`;\n\n if (!schemas[modelSchemaKey]) {\n // Generate ModelSchema as fallback\n if (operation === \"Create\") {\n schemas[modelSchemaKey] = this.generateCreateSchema(\n model,\n this.resolvePrismaQueryOptions(queryOptions, \"createOne\")\n );\n } else if (operation === \"Update\") {\n schemas[modelSchemaKey] = this.generateUpdateSchema(\n model,\n this.resolvePrismaQueryOptions(queryOptions, \"updateOne\")\n );\n }\n }\n\n return modelSchemaKey;\n }\n };\n\n // Create schemas (unchanged)\n if (\n schemasToGenerate.includes(\"createOne\") &&\n !this.isEndpointDisabled(\"createOne\", routerConfig) &&\n !(await localValidatorFileExists(\"createOne\", modelName, arkosConfig))\n ) {\n schemas[`Create${modelName}ModelSchema`] = this.generateCreateSchema(\n model,\n this.resolvePrismaQueryOptions(queryOptions, \"createOne\")\n );\n }\n\n if (\n schemasToGenerate.includes(\"createMany\") &&\n !this.isEndpointDisabled(\"createMany\", routerConfig) &&\n !(await localValidatorFileExists(\"createMany\", modelName, arkosConfig))\n ) {\n // Only fix the reference\n const baseSchemaKey = await ensureBaseSchemaReference(\n \"Create\",\n modelName\n );\n schemas[`CreateMany${modelName}ModelSchema`] = {\n type: \"array\",\n items: { $ref: `#/components/schemas/${baseSchemaKey}` },\n };\n }\n\n // Update schemas (unchanged)\n if (\n schemasToGenerate.includes(\"updateOne\") &&\n !this.isEndpointDisabled(\"updateOne\", routerConfig) &&\n !(await localValidatorFileExists(\"updateOne\", modelName, arkosConfig))\n ) {\n schemas[`Update${modelName}ModelSchema`] = this.generateUpdateSchema(\n model,\n this.resolvePrismaQueryOptions(queryOptions, \"updateOne\")\n );\n }\n\n if (\n schemasToGenerate.includes(\"updateMany\") &&\n !this.isEndpointDisabled(\"updateMany\", routerConfig) &&\n !(await localValidatorFileExists(\"updateMany\", modelName, arkosConfig))\n ) {\n // Only fix the reference\n\n const baseSchemaKey = await ensureBaseSchemaReference(\n \"Update\",\n modelName\n );\n schemas[`UpdateMany${modelName}ModelSchema`] = {\n type: \"object\",\n properties: {\n data: {\n type: \"object\",\n $ref: `#/components/schemas/${baseSchemaKey}`,\n },\n where: { type: \"object\" },\n },\n required: [\"data\"],\n };\n }\n // Response schemas\n if (\n schemasToGenerate.includes(\"findOne\") &&\n !this.isEndpointDisabled(\"findOne\", routerConfig) &&\n !(await localValidatorFileExists(\"findOne\", modelName, arkosConfig))\n ) {\n schemas[`FindOne${modelName}ModelSchema`] = this.generateResponseSchema(\n model,\n this.resolvePrismaQueryOptions(queryOptions, \"findOne\"),\n \"findOne\"\n );\n }\n\n if (\n schemasToGenerate.includes(\"findMany\") &&\n !this.isEndpointDisabled(\"findMany\", routerConfig) &&\n !(await localValidatorFileExists(\"findMany\", modelName, arkosConfig))\n ) {\n schemas[`FindMany${modelName}ModelSchema`] = {\n type: \"array\",\n items: this.generateResponseSchema(\n model,\n this.resolvePrismaQueryOptions(queryOptions, \"findMany\"),\n \"findMany\"\n ),\n };\n }\n }\n\n /**\n * Generate create schema (excludes ID, includes relation IDs only)\n */\n private generateCreateSchema(\n model: PrismaModel,\n _: Record<string, any>\n ): JsonSchema {\n const properties: { [key: string]: JsonSchemaProperty } = {};\n const required: string[] = [];\n const restrictedFields = [\"createdAt\", \"updatedAt\", \"deletedAt\", \"id\"];\n\n if (model.name.toLowerCase() === \"auth\")\n restrictedFields.push(\n \"roles\",\n \"role\",\n \"isActive\",\n \"isStaff\",\n \"isSuperUser\",\n \"passwordChangedAt\",\n \"deletedSelfAccountAt\",\n \"lastLoginAt\"\n );\n\n for (const field of model.fields) {\n // Skip ID fields\n if (field.isId || restrictedFields.includes(field.name)) continue;\n\n // Handle relations\n if (this.isModelRelation(field.type)) {\n // For single relations, include only the ID field\n if (!field.isArray) {\n properties[field.connectionField] = {\n type: this.mapPrismaTypeToJsonSchema(\n model.fields.find(\n (_field) => _field.name === field.connectionField\n )?.type || \"String\"\n ),\n };\n\n // Check if relation ID is required\n if (!field.isOptional && field.defaultValue === undefined)\n required.push(field.name);\n }\n // Skip array relations in create schema\n continue;\n }\n\n const property = this.convertFieldToJsonSchema(field);\n properties[field.name] = property;\n\n // Field is required if not optional, no default, and not array\n if (\n !field.isOptional &&\n field.defaultValue === undefined &&\n !field.isArray\n ) {\n required.push(field.name);\n }\n }\n\n return {\n type: \"object\",\n properties,\n required,\n };\n }\n\n /**\n * Generate update schema (all fields optional, includes relation IDs only)\n */\n private generateUpdateSchema(\n model: PrismaModel,\n _: Record<string, any>\n ): JsonSchema {\n const properties: { [key: string]: JsonSchemaProperty } = {};\n const autoFillFields = [\"createdAt\", \"updatedAt\", \"deletedAt\", \"id\"];\n\n for (const field of model.fields) {\n // Skip ID fields\n if (field.isId || autoFillFields.includes(field.name)) continue;\n\n // Handle relations\n if (this.isModelRelation(field.type)) {\n // For single relations, include only the ID field\n if (!field.isArray)\n properties[field.connectionField] = {\n type: this.mapPrismaTypeToJsonSchema(\n model.fields.find(\n (_field) => _field.name === field.connectionField\n )?.type || \"String\"\n ),\n };\n\n // Skip array relations in update schema\n continue;\n }\n\n const property = this.convertFieldToJsonSchema(field);\n properties[field.name] = property;\n }\n\n return {\n type: \"object\",\n properties,\n required: [], // All fields are optional in update\n };\n }\n\n /**\n * Generate response schema (includes nested relations based on query options)\n */\n private generateResponseSchema(\n model: PrismaModel,\n options: Record<string, any>,\n _: \"findOne\" | \"findMany\"\n ): JsonSchema {\n const properties: { [key: string]: JsonSchemaProperty } = {};\n const required: string[] = [];\n\n // Get select and include options\n const selectFields = options?.select;\n const includeRelations = options?.include;\n\n for (const field of model.fields) {\n // Skip password fields\n if (field.name.toLowerCase().includes(\"password\")) continue;\n\n // If select is specified, only include selected fields\n if (selectFields && !selectFields[field.name]) continue;\n\n // Handle relations\n if (this.isModelRelation(field.type)) {\n // Include relation if specified in include option\n if (includeRelations?.[field.name]) {\n const relationModel = this.schema.models.find(\n (m) => m.name === field.type\n );\n if (relationModel) {\n const relationSchema = this.generateNestedRelationSchema(\n relationModel,\n includeRelations[field.name]\n );\n properties[field.name] = field.isArray\n ? { type: \"array\", items: relationSchema }\n : relationSchema;\n }\n }\n continue;\n }\n\n const property = this.convertFieldToJsonSchema(field);\n properties[field.name] = property;\n\n // Field is required if not optional (for response schemas, we include all by default)\n if (!field.isOptional) required.push(field.name);\n }\n\n return {\n type: \"object\",\n properties,\n required,\n };\n }\n\n /**\n * Generate nested relation schema\n */\n private generateNestedRelationSchema(\n model: PrismaModel,\n includeOptions: any\n ): JsonSchemaProperty {\n const properties: { [key: string]: JsonSchemaProperty } = {};\n const required: string[] = [];\n\n // Handle nested select\n const selectFields = includeOptions?.select;\n const nestedIncludes = includeOptions?.include;\n\n for (const field of model.fields) {\n // Skip password fields\n if (field.name.toLowerCase().includes(\"password\")) {\n continue;\n }\n\n if (selectFields && !selectFields[field.name]) {\n continue;\n }\n\n if (this.isModelRelation(field.type)) {\n if (nestedIncludes?.[field.name]) {\n const relationModel = this.schema.models.find(\n (m) => m.name === field.type\n );\n if (relationModel) {\n const nestedSchema = this.generateNestedRelationSchema(\n relationModel,\n nestedIncludes[field.name]\n );\n properties[field.name] = field.isArray\n ? { type: \"array\", items: nestedSchema }\n : nestedSchema;\n }\n }\n continue;\n }\n\n const property = this.convertFieldToJsonSchema(field);\n properties[field.name] = property;\n\n if (!field.isOptional) {\n required.push(field.name);\n }\n }\n\n return {\n type: \"object\",\n properties,\n required,\n };\n }\n\n /**\n * Auth-specific schema generators\n */\n private generateLoginSchema(arkosConfig?: ArkosConfig): JsonSchema {\n const userNameFields =\n arkosConfig?.authentication?.login?.allowedUsernames || [];\n\n // Helper function to get display name for nested fields\n const getDisplayName = (field: string) => {\n if (field.includes(\".\")) return field.split(\".\").pop() || field; // Get the part after the last dot\n return field;\n };\n\n // Base schema with password (always required)\n const baseSchema: JsonSchemaProperty = {\n type: \"object\",\n properties: {\n password: {\n type: \"string\",\n minLength: 8,\n },\n },\n required: [\"password\"],\n };\n\n // Add all username fields to properties\n userNameFields.forEach((field) => {\n const displayName = getDisplayName(field);\n baseSchema.properties![displayName] = {\n type: \"string\",\n format: \"string\",\n description: `Username field: ${field}`, // Optional: show original field path\n };\n });\n\n // At least one username field must be provided along with password\n if (userNameFields.length > 0) {\n const usernameDisplayNames = userNameFields.map(getDisplayName);\n\n return {\n ...baseSchema,\n anyOf: usernameDisplayNames.map(() => ({\n required: [...baseSchema.required!],\n })),\n };\n }\n\n return baseSchema;\n }\n private generateSignupSchema(\n model: PrismaModel,\n options?: Record<string, any>\n ): JsonSchema {\n // Similar to create but might have specific required fields\n const singupSchema = this.generateCreateSchema(model, options || {});\n\n const restrictedFields = [\n \"roles\",\n \"role\",\n \"isActive\",\n \"isStaff\",\n \"isSuperUser\",\n \"passwordChangedAt\",\n \"deletedSelfAccountAt\",\n \"lastLoginAt\",\n ];\n restrictedFields.forEach((field) => {\n delete singupSchema?.properties?.[field];\n });\n\n return singupSchema;\n }\n\n private generateUpdateMeSchema(\n model: PrismaModel,\n options?: Record<string, any>\n ): JsonSchema {\n // Similar to update but might exclude certain fields like role, etc.\n const updateSchema = this.generateUpdateSchema(model, options || {});\n\n // Remove sensitive fields that users shouldn't update themselves\n const restrictedFields = [\n \"roles\",\n \"role\",\n \"isActive\",\n \"isStaff\",\n \"isSuperUser\",\n \"passwordChangedAt\",\n \"deletedSelfAccountAt\",\n \"password\",\n \"lastLoginAt\",\n ];\n restrictedFields.forEach((field) => {\n delete updateSchema?.properties?.[field];\n });\n\n return updateSchema;\n }\n\n private generateUpdatePasswordSchema(\n _: PrismaModel,\n _1?: Record<string, any>\n ): JsonSchema {\n return {\n type: \"object\",\n properties: {\n currentPassword: { type: \"string\" },\n newPassword: { type: \"string\", minLength: 8 },\n },\n required: [\"currentPassword\", \"newPassword\"],\n };\n }\n\n /**\n * Utility methods\n */\n private resolvePrismaQueryOptions(\n prismaQueryOptions?: PrismaQueryOptions<any> | AuthPrismaQueryOptions<any>,\n action?: ValidationFileMappingKey\n ): Record<string, any> {\n if (!prismaQueryOptions || !action) {\n return {};\n }\n\n const options = prismaQueryOptions as any;\n const actionOptions = options[action] || {};\n\n // Start with deprecated queryOptions (for backward compatibility)\n let mergedOptions = options.queryOptions || {};\n\n // Apply global options (replaces queryOptions)\n if (options.global)\n mergedOptions = deepmerge(mergedOptions, options.global);\n\n // Apply general operation options based on action type\n const generalOptions = this.getGeneralOptionsForAction(options, action);\n if (generalOptions)\n mergedOptions = deepmerge(mergedOptions, generalOptions);\n\n // Finally apply specific action options (highest priority)\n if (actionOptions) mergedOptions = deepmerge(mergedOptions, actionOptions);\n\n return mergedOptions;\n }\n\n /**\n * Helps in remmaping those prisma query options that combines many operations for example find, save...\n */\n private getGeneralOptionsForAction(\n options: any,\n action: ValidationFileMappingKey\n ): Record<string, any> | null {\n const actionMap: { [key: string]: string[] } = {\n find: [\"findOne\", \"findMany\"],\n create: [\"createOne\", \"createMany\"],\n update: [\"updateOne\", \"updateMany\"],\n delete: [\"deleteOne\", \"deleteMany\"],\n save: [\"createOne\", \"createMany\", \"updateOne\", \"updateMany\"],\n saveOne: [\"createOne\", \"updateOne\"],\n saveMany: [\"createMany\", \"updateMany\"],\n };\n\n for (const [optionKey, actions] of Object.entries(actionMap)) {\n if (actions.includes(action) && options[optionKey]) {\n return options[optionKey];\n }\n }\n\n return null;\n }\n\n private isEndpointDisabled(\n endpoint: string,\n routerConfig?: RouterConfig\n ): boolean {\n if (!routerConfig?.disable) return false;\n\n if (typeof routerConfig.disable === \"boolean\") {\n return routerConfig.disable;\n }\n\n return (\n routerConfig.disable[endpoint as keyof typeof routerConfig.disable] ||\n false\n );\n }\n\n private isModelRelation(typeName: string): boolean {\n return this.schema.models.some((m) => m.name === typeName);\n }\n\n private convertFieldToJsonSchema(field: PrismaField): JsonSchemaProperty {\n // Reuse the existing method from the original generator\n const baseType = this.mapPrismaTypeToJsonSchema(field.type);\n const property: JsonSchemaProperty = { type: baseType };\n\n if (field.isArray) {\n property.type = \"array\";\n property.items = { type: this.mapPrismaTypeToJsonSchema(field.type) };\n }\n\n if (field.defaultValue !== undefined) {\n property.default = field.defaultValue;\n }\n\n if (field.type === \"DateTime\") {\n property.format = \"date-time\";\n }\n\n if (this.isEnum(field.type)) {\n const enumDef = this.schema.enums.find((e) => e.name === field.type);\n if (enumDef) {\n property.enum = enumDef.values;\n }\n }\n\n return property;\n }\n\n private mapPrismaTypeToJsonSchema(prismaType: string): string {\n const typeMap: { [key: string]: string } = {\n String: \"string\",\n Int: \"number\",\n Float: \"number\",\n Boolean: \"boolean\",\n DateTime: \"string\",\n Json: \"object\",\n Bytes: \"string\",\n };\n\n if (typeMap[prismaType]) return typeMap[prismaType];\n\n if (this.isEnum(prismaType)) return \"string\";\n\n if (this.isModelRelation(prismaType)) return \"object\";\n\n return \"string\";\n }\n\n private isEnum(typeName: string): boolean {\n return this.schema.enums.some((e) => e.name === typeName);\n }\n}\n\nconst enhancedPrismaJsonSchemaGenerator =\n new EnhancedPrismaJsonSchemaGenerator();\n\nexport default enhancedPrismaJsonSchemaGenerator;\n"]}
|
|
1
|
+
{"version":3,"file":"enhaced-prisma-json-schema-generator.js","sourceRoot":"","sources":["../../../../src/utils/prisma/enhaced-prisma-json-schema-generator.ts"],"names":[],"mappings":";;;;;;AAEA,mFAAoD;AACpD,8DAImC;AACnC,kFAAwD;AAsBxD,MAAa,iCAAiC;IAA9C;QACE,WAAM,GAAG,8BAAkB,CAAC,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AU,CAAC;YAAE,OAAO,QAAQ,CAAC;QAE7C,IAAI,IAAI,CAAC,eAAe,CAAC,UAAU,CAAC;YAAE,OAAO,QAAQ,CAAC;QAEtD,OAAO,QAAQ,CAAC;IAClB,CAAC;IAEO,MAAM,CAAC,QAAgB;QAC7B,OAAO,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC;IAC5D,CAAC;CACF;AAnzBD,8EAmzBC;AAED,MAAM,iCAAiC,GACrC,IAAI,iCAAiC,EAAE,CAAC;AAE1C,kBAAe,iCAAiC,CAAC","sourcesContent":["import { ArkosConfig, RouterConfig } from \"../../exports\";\nimport { AuthPrismaQueryOptions, PrismaQueryOptions } from \"../../types\";\nimport deepmerge from \"../helpers/deepmerge.helper\";\nimport {\n importPrismaModelModules,\n localValidatorFileExists,\n ValidationFileMappingKey,\n} from \"../helpers/models.helpers\";\nimport prismaSchemaParser from \"./prisma-schema-parser\";\nimport {\n PrismaModel,\n PrismaField,\n JsonSchema,\n JsonSchemaProperty,\n} from \"./types\";\n\n// Add these types to your existing types file\nexport interface SchemaGenerationConfig {\n modelName: string;\n arkosConfig: ArkosConfig;\n schemasToGenerate?: ValidationFileMappingKey[];\n}\n\nexport interface GeneratedSchemas {\n [key: string]: JsonSchema;\n}\n\n/**\n * Enhanced JSON Schema generator that creates schemas based on Prisma models and query options\n */\nexport class EnhancedPrismaJsonSchemaGenerator {\n schema = prismaSchemaParser.parse();\n\n /**\n * Main method to generate all schemas for a model\n */\n async generateModelSchemas(\n config: SchemaGenerationConfig\n ): Promise<GeneratedSchemas> {\n const {\n modelName,\n arkosConfig,\n schemasToGenerate = [\n \"model\",\n \"login\",\n \"signup\",\n \"getMe\",\n \"updateMe\",\n \"updatePassword\",\n \"create\",\n \"createOne\",\n \"createMany\",\n \"update\",\n \"updateOne\",\n \"updateMany\",\n \"query\",\n \"findOne\",\n \"findMany\",\n ],\n } = config;\n\n const modelModules = await importPrismaModelModules(modelName, arkosConfig);\n const routerConfig = modelModules?.router?.config || {};\n const prismaQueryOptions = modelModules?.prismaQueryOptions || {};\n const authModuleModel = [\"auth\", \"me\", \"password\", \"signup\", \"login\"];\n const isAuthModule = authModuleModel.includes(modelName.toLowerCase());\n\n // Check if generation should be skipped\n if (arkosConfig?.swagger?.strict && arkosConfig.swagger.mode !== \"prisma\")\n return {};\n\n // Check if router is disabled\n if (routerConfig?.disable === true) return {};\n\n const model = this.schema.models.find(\n (m) => m.name.toLowerCase() === modelName.toLowerCase()\n );\n if (!model && !isAuthModule) return {};\n // throw new Error(`Model ${modelName} not found in schema`);\n\n const schemas: { [key: string]: JsonSchema } = {};\n\n if (isAuthModule) {\n // Generate auth-specific schemas\n await this.generateAuthSchemas(\n this.schema.models.find((m) => m.name.toLowerCase() === \"user\")!,\n schemas,\n arkosConfig,\n schemasToGenerate,\n prismaQueryOptions as AuthPrismaQueryOptions<any>\n );\n } else {\n // Generate standard CRUD schemas\n if (model)\n await this.generateCrudSchemas(\n model,\n schemas,\n arkosConfig,\n schemasToGenerate,\n prismaQueryOptions as PrismaQueryOptions<any>,\n routerConfig\n );\n }\n\n return { ...schemas };\n }\n\n /**\n * Generate auth-specific schemas\n */\n private async generateAuthSchemas(\n model: PrismaModel,\n schemas: { [key: string]: JsonSchema },\n arkosConfig: ArkosConfig,\n schemasToGenerate: ValidationFileMappingKey[],\n queryOptions?: AuthPrismaQueryOptions<any>,\n routerConfig?: RouterConfig\n ) {\n const modelName = \"Auth\";\n\n // if no auth activated forget those json schemas\n if (!arkosConfig?.authentication) return schemas;\n\n // Login schema (input)\n if (\n schemasToGenerate.includes(\"login\") &&\n !this.isEndpointDisabled(\"login\", routerConfig) &&\n !(await localValidatorFileExists(\"login\", modelName, arkosConfig))\n ) {\n schemas[`LoginSchema`] = this.generateLoginSchema(arkosConfig);\n }\n\n // Signup schema (input)\n if (\n schemasToGenerate.includes(\"signup\") &&\n !this.isEndpointDisabled(\"signup\", routerConfig) &&\n !(await localValidatorFileExists(\"signup\", modelName, arkosConfig))\n ) {\n schemas[`SignupSchema`] = this.generateSignupSchema(\n model,\n queryOptions?.signup\n );\n }\n\n // UpdateMe schema (input)\n if (\n schemasToGenerate.includes(\"updateMe\") &&\n !this.isEndpointDisabled(\"updateMe\", routerConfig) &&\n !(await localValidatorFileExists(\"updateMe\", modelName, arkosConfig))\n ) {\n schemas[`UpdateMeSchema`] = this.generateUpdateMeSchema(\n model,\n queryOptions?.updateMe\n );\n }\n\n // UpdatePassword schema (input)\n if (\n schemasToGenerate.includes(\"updatePassword\") &&\n !this.isEndpointDisabled(\"updatePassword\", routerConfig) &&\n !(await localValidatorFileExists(\n \"updatePassword\",\n modelName,\n arkosConfig\n ))\n ) {\n schemas[`UpdatePasswordSchema`] = this.generateUpdatePasswordSchema(\n model,\n queryOptions?.updatePassword\n );\n }\n\n // GetMe response schema\n if (\n schemasToGenerate.includes(\"getMe\") &&\n !this.isEndpointDisabled(\"getMe\", routerConfig) &&\n !(await localValidatorFileExists(\"getMe\", modelName, arkosConfig))\n ) {\n schemas[`GetMeSchema`] = this.generateResponseSchema(\n model,\n queryOptions?.getMe || {},\n \"findOne\"\n );\n }\n }\n\n /**\n * Generate standard CRUD schemas\n */\n private async generateCrudSchemas(\n model: PrismaModel,\n schemas: { [key: string]: JsonSchema },\n arkosConfig: ArkosConfig,\n schemasToGenerate: ValidationFileMappingKey[],\n queryOptions?: PrismaQueryOptions<any>,\n routerConfig?: RouterConfig\n ) {\n const modelName = model.name;\n\n // // Create schemas\n // if (\n // schemasToGenerate.includes(\"createOne\") &&\n // !this.isEndpointDisabled(\"createOne\", routerConfig) &&\n // !(await localValidatorFileExists(\"createOne\", modelName, arkosConfig))\n // ) {\n // schemas[`Create${modelName}ModelSchema`] = this.generateCreateSchema(\n // model,\n // this.resolvePrismaQueryOptions(queryOptions, \"createOne\")\n // );\n // }\n\n // if (\n // schemasToGenerate.includes(\"createMany\") &&\n // !this.isEndpointDisabled(\"createMany\", routerConfig) &&\n // !(await localValidatorFileExists(\"createMany\", modelName, arkosConfig))\n // ) {\n // schemas[`CreateMany${modelName}ModelSchema`] = {\n // type: \"array\",\n // items: { $ref: `#/components/schemas/Create${modelName}ModelSchema` },\n // };\n // }\n\n // // Update schemas\n // if (\n // schemasToGenerate.includes(\"updateOne\") &&\n // !this.isEndpointDisabled(\"updateOne\", routerConfig) &&\n // !(await localValidatorFileExists(\"updateOne\", modelName, arkosConfig))\n // ) {\n // schemas[`Update${modelName}ModelSchema`] = this.generateUpdateSchema(\n // model,\n // this.resolvePrismaQueryOptions(queryOptions, \"updateOne\")\n // );\n // }\n\n // if (\n // schemasToGenerate.includes(\"updateMany\") &&\n // !this.isEndpointDisabled(\"updateMany\", routerConfig) &&\n // !(await localValidatorFileExists(\"updateMany\", modelName, arkosConfig))\n // ) {\n // schemas[`UpdateMany${modelName}ModelSchema`] = {\n // type: \"object\",\n // properties: {\n // data: {\n // type: \"object\",\n // $ref: `#/components/schemas/Update${modelName}ModelSchema`,\n // },\n // where: { type: \"object\" },\n // },\n // required: [\"data\"],\n // };\n // }\n // Helper function to ensure base schema exists\n\n const ensureBaseSchemaReference = async (\n operation: string,\n modelName: string\n ) => {\n const suffix =\n arkosConfig.validation?.resolver === \"zod\" ? \"Schema\" : \"Dto\";\n\n // Check if local validator file exists for single operation\n const singleOpName = operation === \"Create\" ? \"createOne\" : \"updateOne\";\n const hasLocalValidator = await localValidatorFileExists(\n singleOpName,\n modelName,\n arkosConfig\n );\n\n if (hasLocalValidator) {\n // Point to local validator schema (Schema or Dto)\n return `${operation}${modelName}${suffix}`;\n } else {\n // Point to ModelSchema, generate if doesn't exist\n const modelSchemaKey = `${operation}${modelName}ModelSchema`;\n\n if (!schemas[modelSchemaKey]) {\n // Generate ModelSchema as fallback\n if (operation === \"Create\") {\n schemas[modelSchemaKey] = this.generateCreateSchema(\n model,\n this.resolvePrismaQueryOptions(queryOptions, \"createOne\")\n );\n } else if (operation === \"Update\") {\n schemas[modelSchemaKey] = this.generateUpdateSchema(\n model,\n this.resolvePrismaQueryOptions(queryOptions, \"updateOne\")\n );\n }\n }\n\n return modelSchemaKey;\n }\n };\n\n // Create schemas (unchanged)\n if (\n schemasToGenerate.includes(\"createOne\") &&\n !this.isEndpointDisabled(\"createOne\", routerConfig) &&\n !(await localValidatorFileExists(\"createOne\", modelName, arkosConfig))\n ) {\n schemas[`Create${modelName}ModelSchema`] = this.generateCreateSchema(\n model,\n this.resolvePrismaQueryOptions(queryOptions, \"createOne\")\n );\n }\n\n if (\n schemasToGenerate.includes(\"createMany\") &&\n !this.isEndpointDisabled(\"createMany\", routerConfig) &&\n !(await localValidatorFileExists(\"createMany\", modelName, arkosConfig))\n ) {\n // Only fix the reference\n const baseSchemaKey = await ensureBaseSchemaReference(\n \"Create\",\n modelName\n );\n schemas[`CreateMany${modelName}ModelSchema`] = {\n type: \"array\",\n items: { $ref: `#/components/schemas/${baseSchemaKey}` },\n };\n }\n\n // Update schemas (unchanged)\n if (\n schemasToGenerate.includes(\"updateOne\") &&\n !this.isEndpointDisabled(\"updateOne\", routerConfig) &&\n !(await localValidatorFileExists(\"updateOne\", modelName, arkosConfig))\n ) {\n schemas[`Update${modelName}ModelSchema`] = this.generateUpdateSchema(\n model,\n this.resolvePrismaQueryOptions(queryOptions, \"updateOne\")\n );\n }\n\n if (\n schemasToGenerate.includes(\"updateMany\") &&\n !this.isEndpointDisabled(\"updateMany\", routerConfig) &&\n !(await localValidatorFileExists(\"updateMany\", modelName, arkosConfig))\n ) {\n // Only fix the reference\n\n const baseSchemaKey = await ensureBaseSchemaReference(\n \"Update\",\n modelName\n );\n schemas[`UpdateMany${modelName}ModelSchema`] = {\n type: \"object\",\n properties: {\n data: {\n type: \"object\",\n $ref: `#/components/schemas/${baseSchemaKey}`,\n },\n where: { type: \"object\" },\n },\n required: [\"data\"],\n };\n }\n // Response schemas\n if (\n schemasToGenerate.includes(\"findOne\") &&\n !this.isEndpointDisabled(\"findOne\", routerConfig) &&\n !(await localValidatorFileExists(\"findOne\", modelName, arkosConfig))\n ) {\n schemas[`FindOne${modelName}ModelSchema`] = this.generateResponseSchema(\n model,\n this.resolvePrismaQueryOptions(queryOptions, \"findOne\"),\n \"findOne\"\n );\n }\n\n if (\n schemasToGenerate.includes(\"findMany\") &&\n !this.isEndpointDisabled(\"findMany\", routerConfig) &&\n !(await localValidatorFileExists(\"findMany\", modelName, arkosConfig))\n ) {\n schemas[`FindMany${modelName}ModelSchema`] = {\n type: \"array\",\n items: this.generateResponseSchema(\n model,\n this.resolvePrismaQueryOptions(queryOptions, \"findMany\"),\n \"findMany\"\n ),\n };\n }\n }\n\n /**\n * Generate create schema (excludes ID, includes relation IDs only)\n */\n private generateCreateSchema(\n model: PrismaModel,\n _: Record<string, any>\n ): JsonSchema {\n const properties: { [key: string]: JsonSchemaProperty } = {};\n const required: string[] = [];\n const restrictedFields = [\"createdAt\", \"updatedAt\", \"deletedAt\", \"id\"];\n\n if (model.name.toLowerCase() === \"auth\")\n restrictedFields.push(\n \"roles\",\n \"role\",\n \"isActive\",\n \"isStaff\",\n \"isSuperUser\",\n \"passwordChangedAt\",\n \"deletedSelfAccountAt\",\n \"lastLoginAt\"\n );\n\n for (const field of model.fields) {\n // Skip ID fields\n if (field.isId || restrictedFields.includes(field.name)) continue;\n\n // Handle relations\n if (this.isModelRelation(field.type)) {\n // For single relations, include only the ID field\n if (!field.isArray) {\n properties[field.connectionField] = {\n type: this.mapPrismaTypeToJsonSchema(\n model.fields.find(\n (_field) => _field.name === field.connectionField\n )?.type || \"String\"\n ),\n };\n\n // Check if relation ID is required\n if (!field.isOptional && field.defaultValue === undefined)\n required.push(field.name);\n }\n // Skip array relations in create schema\n continue;\n }\n\n const property = this.convertFieldToJsonSchema(field);\n properties[field.name] = property;\n\n // Field is required if not optional, no default, and not array\n if (\n !field.isOptional &&\n field.defaultValue === undefined &&\n !field.isArray\n ) {\n required.push(field.name);\n }\n }\n\n return {\n type: \"object\",\n properties,\n required,\n };\n }\n\n /**\n * Generate update schema (all fields optional, includes relation IDs only)\n */\n private generateUpdateSchema(\n model: PrismaModel,\n _: Record<string, any>\n ): JsonSchema {\n const properties: { [key: string]: JsonSchemaProperty } = {};\n const autoFillFields = [\"createdAt\", \"updatedAt\", \"deletedAt\", \"id\"];\n\n for (const field of model.fields) {\n // Skip ID fields\n if (field.isId || autoFillFields.includes(field.name)) continue;\n\n // Handle relations\n if (this.isModelRelation(field.type)) {\n // For single relations, include only the ID field\n if (!field.isArray)\n properties[field.connectionField] = {\n type: this.mapPrismaTypeToJsonSchema(\n model.fields.find(\n (_field) => _field.name === field.connectionField\n )?.type || \"String\"\n ),\n };\n\n // Skip array relations in update schema\n continue;\n }\n\n const property = this.convertFieldToJsonSchema(field);\n properties[field.name] = property;\n }\n\n return {\n type: \"object\",\n properties,\n required: [], // All fields are optional in update\n };\n }\n\n /**\n * Generate response schema (includes nested relations based on query options)\n */\n private generateResponseSchema(\n model: PrismaModel,\n options: Record<string, any>,\n _: \"findOne\" | \"findMany\"\n ): JsonSchema {\n const properties: { [key: string]: JsonSchemaProperty } = {};\n const required: string[] = [];\n\n // Get select and include options\n const selectFields = options?.select;\n const includeRelations = options?.include;\n\n for (const field of model.fields) {\n // Skip password fields\n if (field.name.toLowerCase().includes(\"password\")) continue;\n\n // If select is specified, only include selected fields\n if (selectFields && !selectFields[field.name]) continue;\n\n // Handle relations\n if (this.isModelRelation(field.type)) {\n // Include relation if specified in include option\n if (includeRelations?.[field.name]) {\n const relationModel = this.schema.models.find(\n (m) => m.name === field.type\n );\n if (relationModel) {\n const relationSchema = this.generateNestedRelationSchema(\n relationModel,\n includeRelations[field.name]\n );\n properties[field.name] = field.isArray\n ? { type: \"array\", items: relationSchema }\n : relationSchema;\n }\n }\n continue;\n }\n\n const property = this.convertFieldToJsonSchema(field);\n properties[field.name] = property;\n\n // Field is required if not optional (for response schemas, we include all by default)\n if (!field.isOptional) required.push(field.name);\n }\n\n return {\n type: \"object\",\n properties,\n required,\n };\n }\n\n /**\n * Generate nested relation schema\n */\n private generateNestedRelationSchema(\n model: PrismaModel,\n includeOptions: any\n ): JsonSchemaProperty {\n const properties: { [key: string]: JsonSchemaProperty } = {};\n const required: string[] = [];\n\n // Handle nested select\n const selectFields = includeOptions?.select;\n const nestedIncludes = includeOptions?.include;\n\n for (const field of model.fields) {\n // Skip password fields\n if (field.name.toLowerCase().includes(\"password\")) {\n continue;\n }\n\n if (selectFields && !selectFields[field.name]) {\n continue;\n }\n\n if (this.isModelRelation(field.type)) {\n if (nestedIncludes?.[field.name]) {\n const relationModel = this.schema.models.find(\n (m) => m.name === field.type\n );\n if (relationModel) {\n const nestedSchema = this.generateNestedRelationSchema(\n relationModel,\n nestedIncludes[field.name]\n );\n properties[field.name] = field.isArray\n ? { type: \"array\", items: nestedSchema }\n : nestedSchema;\n }\n }\n continue;\n }\n\n const property = this.convertFieldToJsonSchema(field);\n properties[field.name] = property;\n\n if (!field.isOptional) {\n required.push(field.name);\n }\n }\n\n return {\n type: \"object\",\n properties,\n required,\n };\n }\n\n /**\n * Auth-specific schema generators\n */\n private generateLoginSchema(arkosConfig?: ArkosConfig): JsonSchema {\n const userNameFields =\n arkosConfig?.authentication?.login?.allowedUsernames || [];\n\n // Helper function to get display name for nested fields\n const getDisplayName = (field: string) => {\n if (field.includes(\".\")) return field.split(\".\").pop() || field; // Get the part after the last dot\n return field;\n };\n\n // Base schema with password (always required)\n const baseSchema: JsonSchemaProperty = {\n type: \"object\",\n properties: {\n password: {\n type: \"string\",\n minLength: 8,\n },\n },\n required: [\"password\"],\n };\n\n // Add all username fields to properties\n userNameFields.forEach((field) => {\n const displayName = getDisplayName(field);\n baseSchema.properties![displayName] = {\n type: \"string\",\n format: \"string\",\n description: `Username field: ${field}`, // Optional: show original field path\n };\n });\n\n // At least one username field must be provided along with password\n if (userNameFields.length > 0) {\n const usernameDisplayNames = userNameFields.map(getDisplayName);\n\n return {\n ...baseSchema,\n anyOf: usernameDisplayNames.map(() => ({\n required: [...baseSchema.required!],\n })),\n };\n }\n\n return baseSchema;\n }\n private generateSignupSchema(\n model: PrismaModel,\n options?: Record<string, any>\n ): JsonSchema {\n // Similar to create but might have specific required fields\n const singupSchema = this.generateCreateSchema(model, options || {});\n\n const restrictedFields = [\n \"roles\",\n \"role\",\n \"isActive\",\n \"isStaff\",\n \"isSuperUser\",\n \"passwordChangedAt\",\n \"deletedSelfAccountAt\",\n \"lastLoginAt\",\n ];\n restrictedFields.forEach((field) => {\n delete singupSchema?.properties?.[field];\n });\n\n return singupSchema;\n }\n\n private generateUpdateMeSchema(\n model: PrismaModel,\n options?: Record<string, any>\n ): JsonSchema {\n // Similar to update but might exclude certain fields like role, etc.\n const updateSchema = this.generateUpdateSchema(model, options || {});\n\n // Remove sensitive fields that users shouldn't update themselves\n const restrictedFields = [\n \"roles\",\n \"role\",\n \"isActive\",\n \"isStaff\",\n \"isSuperUser\",\n \"passwordChangedAt\",\n \"deletedSelfAccountAt\",\n \"password\",\n \"lastLoginAt\",\n ];\n restrictedFields.forEach((field) => {\n delete updateSchema?.properties?.[field];\n });\n\n return updateSchema;\n }\n\n private generateUpdatePasswordSchema(\n _: PrismaModel,\n _1?: Record<string, any>\n ): JsonSchema {\n return {\n type: \"object\",\n properties: {\n currentPassword: { type: \"string\" },\n newPassword: { type: \"string\", minLength: 8 },\n },\n required: [\"currentPassword\", \"newPassword\"],\n };\n }\n\n /**\n * Utility methods\n */\n private resolvePrismaQueryOptions(\n prismaQueryOptions?: PrismaQueryOptions<any> | AuthPrismaQueryOptions<any>,\n action?: ValidationFileMappingKey\n ): Record<string, any> {\n if (!prismaQueryOptions || !action) {\n return {};\n }\n\n const options = prismaQueryOptions as any;\n const actionOptions = options[action] || {};\n\n // Start with deprecated queryOptions (for backward compatibility)\n let mergedOptions = options.queryOptions || {};\n\n // Apply global options (replaces queryOptions)\n if (options.global)\n mergedOptions = deepmerge(mergedOptions, options.global);\n\n // Apply general operation options based on action type\n const generalOptions = this.getGeneralOptionsForAction(options, action);\n if (generalOptions)\n mergedOptions = deepmerge(mergedOptions, generalOptions);\n\n // Finally apply specific action options (highest priority)\n if (actionOptions) mergedOptions = deepmerge(mergedOptions, actionOptions);\n\n return mergedOptions;\n }\n\n /**\n * Helps in remmaping those prisma query options that combines many operations for example find, save...\n */\n private getGeneralOptionsForAction(\n options: any,\n action: ValidationFileMappingKey\n ): Record<string, any> | null {\n const actionMap: { [key: string]: string[] } = {\n find: [\"findOne\", \"findMany\"],\n create: [\"createOne\", \"createMany\"],\n update: [\"updateOne\", \"updateMany\"],\n delete: [\"deleteOne\", \"deleteMany\"],\n save: [\"createOne\", \"createMany\", \"updateOne\", \"updateMany\"],\n saveOne: [\"createOne\", \"updateOne\"],\n saveMany: [\"createMany\", \"updateMany\"],\n };\n\n for (const [optionKey, actions] of Object.entries(actionMap)) {\n if (actions.includes(action) && options[optionKey]) {\n return options[optionKey];\n }\n }\n\n return null;\n }\n\n private isEndpointDisabled(\n endpoint: string,\n routerConfig?: RouterConfig\n ): boolean {\n if (!routerConfig?.disable) return false;\n\n if (typeof routerConfig.disable === \"boolean\") {\n return routerConfig.disable;\n }\n\n return (\n routerConfig.disable[endpoint as keyof typeof routerConfig.disable] ||\n false\n );\n }\n\n private isModelRelation(typeName: string): boolean {\n return this.schema.models.some((m) => m.name === typeName);\n }\n\n private convertFieldToJsonSchema(field: PrismaField): JsonSchemaProperty {\n // Reuse the existing method from the original generator\n const baseType = this.mapPrismaTypeToJsonSchema(field.type);\n const property: JsonSchemaProperty = { type: baseType };\n\n if (field.isArray) {\n property.type = \"array\";\n property.items = { type: this.mapPrismaTypeToJsonSchema(field.type) };\n }\n\n if (field.defaultValue !== undefined) {\n property.default = field.defaultValue;\n }\n\n if (field.type === \"DateTime\") {\n property.format = \"date-time\";\n }\n\n if (this.isEnum(field.type)) {\n const enumDef = this.schema.enums.find((e) => e.name === field.type);\n if (enumDef) {\n property.enum = enumDef.values;\n }\n }\n\n return property;\n }\n\n private mapPrismaTypeToJsonSchema(prismaType: string): string {\n const typeMap: { [key: string]: string } = {\n String: \"string\",\n Int: \"number\",\n Float: \"number\",\n Boolean: \"boolean\",\n DateTime: \"string\",\n Json: \"object\",\n Bytes: \"string\",\n };\n\n if (typeMap[prismaType]) return typeMap[prismaType];\n\n if (this.isEnum(prismaType)) return \"string\";\n\n if (this.isModelRelation(prismaType)) return \"object\";\n\n return \"string\";\n }\n\n private isEnum(typeName: string): boolean {\n return this.schema.enums.some((e) => e.name === typeName);\n }\n}\n\nconst enhancedPrismaJsonSchemaGenerator =\n new EnhancedPrismaJsonSchemaGenerator();\n\nexport default enhancedPrismaJsonSchemaGenerator;\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prisma-schema-parser.js","sourceRoot":"","sources":["../../../../src/utils/prisma/prisma-schema-parser.ts"],"names":[],"mappings":";;;AAAA,8DAAoE;AAkBpE,MAAa,kBAAkB;IAA/B;QAEU,UAAK,GAAiB,EAAE,CAAC;QAEzB,WAAM,GAAkB,EAAE,CAAC;IAgTrC,CAAC;IAzSC,KAAK;QACH,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;QACjC,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,aAAa,EAAE,CAAC;QAEnC,OAAO;YACL,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,KAAK,EAAE,IAAI,CAAC,KAAK;SAClB,CAAC;IACJ,CAAC;IAQO,YAAY;QAClB,MAAM,KAAK,GAAiB,EAAE,CAAC;QAC/B,MAAM,MAAM,GAAG,IAAA,wCAAuB,GAAE,IAAI,EAAE,CAAC;QAC/C,MAAM,UAAU,GAAG,MAAM,CAAC,KAAK,CAAC,yBAAyB,CAAC,IAAI,EAAE,CAAC;QAEjE,KAAK,MAAM,KAAK,IAAI,UAAU,EAAE,CAAC;YAC/B,MAAM,OAAO,GAAG,IAAI,CAAC,cAAc,CAAC,KAAK,CAAC,C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;QAGD,IAAI,UAAU,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;YAE7B,OAAO,SAAS,CAAC;QACnB,CAAC;QAED,OAAO,UAAU,CAAC;IACpB,CAAC;IAgBD,MAAM,CAAC,QAAgB;QACrB,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC;IACrD,CAAC;IAgBD,OAAO,CAAC,QAAgB;QACtB,OAAO,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC;IACtD,CAAC;CACF;AApTD,gDAoTC;AAED,MAAM,kBAAkB,GAAG,IAAI,kBAAkB,EAAE,CAAC;AAEpD,kBAAe,kBAAkB,CAAC","sourcesContent":["import { getPrismaSchemasContent } from \"../helpers/models.helpers\";\nimport { PrismaSchema, PrismaModel, PrismaEnum, PrismaField } from \"./types\";\n\n/**\n * A parser for Prisma schema files that extracts models, enums, and their properties.\n *\n * @example\n * ```typescript\n * const schemaContent = `\n * model User {\n * id Int @id @default(autoincrement())\n * email String @unique\n * }\n * `;\n * const parser = new PrismaSchemaParser();\n * const schema = parser.parse();\n * ```\n */\nexport class PrismaSchemaParser {\n /** Collection of parsed enum definitions */\n private enums: PrismaEnum[] = [];\n /** Collection of parsed model definitions */\n private models: PrismaModel[] = [];\n\n /**\n * Parses the Prisma schema and extracts all models and enums.\n *\n * @returns The parsed schema containing arrays of models and enums\n */\n parse(): PrismaSchema {\n this.enums = this.extractEnums();\n this.models = this.extractModels();\n\n return {\n models: this.models,\n enums: this.enums,\n };\n }\n\n /**\n * Extracts all enum definitions from the schema.\n *\n * @private\n * @returns Array of parsed enum objects\n */\n private extractEnums(): PrismaEnum[] {\n const enums: PrismaEnum[] = [];\n const schema = getPrismaSchemasContent() || \"\";\n const enumBlocks = schema.match(/enum\\s+\\w+\\s*\\{[^}]*\\}/g) || [];\n\n for (const block of enumBlocks) {\n const enumObj = this.parseEnumBlock(block);\n if (enumObj) {\n enums.push(enumObj);\n }\n }\n\n return enums;\n }\n\n /**\n * Parses a single enum block and extracts its name and values.\n *\n * @private\n * @param block - The enum block string (e.g., \"enum Status { ACTIVE INACTIVE }\")\n * @returns The parsed enum object or null if parsing fails\n */\n private parseEnumBlock(block: string): PrismaEnum | null {\n const nameMatch = block.match(/enum\\s+(\\w+)/);\n if (!nameMatch) return null;\n\n const name = nameMatch[1];\n const values = block\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(\n (line) =>\n line &&\n !line.startsWith(\"enum\") &&\n !line.startsWith(\"{\") &&\n !line.startsWith(\"}\")\n )\n .map((line) => line.replace(/,$/, \"\"));\n\n return { name, values };\n }\n\n /**\n * Extracts all model definitions from the schema.\n *\n * @private\n * @returns Array of parsed model objects\n */\n private extractModels(): PrismaModel[] {\n const models: PrismaModel[] = [];\n const modelBlocks = this.extractModelBlocks();\n\n for (const block of modelBlocks) {\n const model = this.parseModelBlock(block);\n if (model) {\n models.push(model);\n }\n }\n\n return models;\n }\n\n /**\n * Extracts raw model block strings from the schema using regex.\n *\n * @private\n * @returns Array of model block strings\n */\n private extractModelBlocks(): string[] {\n const modelRegex = /model\\s+\\w+\\s*\\{[^}]*\\}/g;\n const schema = getPrismaSchemasContent() || \"\";\n return schema.match(modelRegex) || [];\n }\n\n /**\n * Parses a single model block and extracts its name, fields, and metadata.\n *\n * @private\n * @param block - The model block string\n * @returns The parsed model object or null if parsing fails\n */\n private parseModelBlock(block: string): PrismaModel | null {\n const nameMatch = block.match(/model\\s+(\\w+)/);\n if (!nameMatch) return null;\n\n const name = nameMatch[1];\n const fields = this.parseFields(block);\n\n // Check for @@map directive\n const mapMatch = block.match(/@@map\\s*\\(\\s*\"([^\"]+)\"\\s*\\)/);\n const mapName = mapMatch ? mapMatch[1] : undefined;\n\n return { name, fields, mapName };\n }\n\n /**\n * Parses all field definitions within a model block.\n *\n * @private\n * @param block - The model block string containing field definitions\n * @returns Array of parsed field objects\n */\n private parseFields(block: string): PrismaField[] {\n const fields: PrismaField[] = [];\n const fieldLines = block\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(\n (line) =>\n line &&\n !line.startsWith(\"model\") &&\n !line.startsWith(\"{\") &&\n !line.startsWith(\"}\")\n );\n\n for (const line of fieldLines) {\n if (line.startsWith(\"//\") || line.startsWith(\"@@\")) continue;\n\n const field = this.parseFieldLine(line);\n if (field) {\n fields.push(field);\n }\n }\n\n return fields;\n }\n\n /**\n * Parses a single field line and extracts all field properties.\n *\n * @private\n * @param line - A single field definition line (e.g., \"id Int @id @default(autoincrement())\")\n * @returns The parsed field object or null if parsing fails\n *\n * @example\n * ```typescript\n * // Input: \"email String? @unique @default(\"user@example.com\")\"\n * // Output: {\n * // name: \"email\",\n * // type: \"String\",\n * // isOptional: true,\n * // isArray: false,\n * // defaultValue: \"user@example.com\",\n * // isId: false,\n * // isUnique: true,\n * // attributes: [\"@unique\", \"@default(\\\"user@example.com\\\")\"]\n * // }\n * ```\n */\n private parseFieldLine(line: string): PrismaField | null {\n const fieldMatch = line.match(/^(\\w+)\\s+(\\w+(?:\\[\\])?)\\??\\s*(.*)/);\n if (!fieldMatch) return null;\n\n const [, name, typeWithArray, attributesStr] = fieldMatch;\n const isArray = typeWithArray.endsWith(\"[]\");\n const type = isArray ? typeWithArray.slice(0, -2) : typeWithArray;\n const isOptional = line.includes(\"?\");\n\n const attributes = attributesStr\n .split(/\\s+/)\n .filter((attr) => attr.startsWith(\"@\"));\n\n // Extract default value\n let defaultValue: any = undefined;\n const defaultMatch = attributesStr.match(/@default\\(([^)]+)\\)/);\n if (defaultMatch) {\n defaultValue = this.parseDefaultValue(defaultMatch[1]);\n }\n\n // Extract connection field from @relation\n let connectionField = \"\";\n const relationMatch = attributesStr.match(\n /@relation\\([^)]*fields:\\s*\\[([^\\]]+)\\]/\n );\n if (relationMatch) {\n // Extract the field name and clean it up (remove quotes and whitespace)\n connectionField = relationMatch[1].trim().replace(/['\"]/g, \"\");\n }\n\n const isId = attributes.some((attr) => attr.startsWith(\"@id\"));\n const isUnique = attributes.some((attr) => attr.startsWith(\"@unique\"));\n\n return {\n name,\n type,\n isOptional,\n isArray,\n connectionField,\n defaultValue,\n isId,\n isUnique,\n attributes,\n };\n }\n\n /**\n * Parses a default value string and converts it to the appropriate JavaScript type.\n *\n * @private\n * @param defaultStr - The default value string from @default() attribute\n * @returns The parsed default value in appropriate JavaScript type, or undefined for functions\n *\n * @example\n * ```typescript\n * parseDefaultValue('\"hello\"') // returns \"hello\"\n * parseDefaultValue('true') // returns true\n * parseDefaultValue('42') // returns 42\n * parseDefaultValue('3.14') // returns 3.14\n * parseDefaultValue('ACTIVE') // returns \"ACTIVE\" (enum value)\n * parseDefaultValue('now()') // returns undefined (function)\n * ```\n */\n private parseDefaultValue(defaultStr: string): any {\n defaultStr = defaultStr.trim();\n\n // Handle string values\n if (defaultStr.startsWith('\"') && defaultStr.endsWith('\"')) {\n return defaultStr.slice(1, -1);\n }\n\n // Handle boolean values\n if (defaultStr === \"true\") return true;\n if (defaultStr === \"false\") return false;\n\n // Handle numeric values\n if (/^\\d+$/.test(defaultStr)) {\n return parseInt(defaultStr, 10);\n }\n if (/^\\d+\\.\\d+$/.test(defaultStr)) {\n return parseFloat(defaultStr);\n }\n\n // Handle enum values (no quotes, not a function)\n if (!defaultStr.includes(\"(\")) {\n return defaultStr;\n }\n\n // Handle functions (like now(), auto(), etc.)\n if (defaultStr.includes(\"(\")) {\n // For MongoDB, we'll skip function defaults as they're handled by the DB\n return undefined;\n }\n\n return defaultStr;\n }\n\n /**\n * Checks if a given type name corresponds to a defined enum.\n *\n * @param typeName - The type name to check\n * @returns True if the type is an enum, false otherwise\n *\n * @example\n * ```typescript\n * const parser = new PrismaSchemaParser(schemaWithStatusEnum);\n * parser.parse();\n * parser.isEnum('Status'); // true\n * parser.isEnum('String'); // false\n * ```\n */\n isEnum(typeName: string): boolean {\n return this.enums.some((e) => e.name === typeName);\n }\n\n /**\n * Checks if a given type name corresponds to a defined model.\n *\n * @param typeName - The type name to check\n * @returns True if the type is a model, false otherwise\n *\n * @example\n * ```typescript\n * const parser = new PrismaSchemaParser(schemaWithUserModel);\n * parser.parse();\n * parser.isModel('User'); // true\n * parser.isModel('String'); // false\n * ```\n */\n isModel(typeName: string): boolean {\n return this.models.some((m) => m.name === typeName);\n }\n}\n\nconst prismaSchemaParser = new PrismaSchemaParser();\n\nexport default prismaSchemaParser;\n"]}
|
|
1
|
+
{"version":3,"file":"prisma-schema-parser.js","sourceRoot":"","sources":["../../../../src/utils/prisma/prisma-schema-parser.ts"],"names":[],"mappings":";;;AAAA,8DAAoE;AAkBpE,MAAa,kBAAkB;IAA/B;QAEU,UAAK,GAAiB,EAAE,CAAC;QAEzB,WAAM,GAAkB,EAAE,CAAC;IAySrC,CAAC;IAlSC,KAAK;QACH,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;QACjC,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,aAAa,EAAE,CAAC;QAEnC,OAAO;YACL,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,KAAK,EAAE,IAAI,CAAC,KAAK;SAClB,CAAC;IACJ,CAAC;IAQO,YAAY;QAClB,MAAM,KAAK,GAAiB,EAAE,CAAC;QAC/B,MAAM,MAAM,GAAG,IAAA,wCAAuB,GAAE,IAAI,EAAE,CAAC;QAC/C,MAAM,UAAU,GAAG,MAAM,CAAC,KAAK,CAAC,yBAAyB,CAAC,IAAI,EAAE,CAAC;QAEjE,KAAK,MAAM,KAAK,IAAI,UAAU,EAAE,CAAC;YAC/B,MAAM,OAAO,GAAG,IAAI,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;YAC3C,IAAI,OAAO,EAAE,CAAC;gBACZ,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YACtB,CAAC;QACH,CAAC;QAED,OAA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,CAAC,CAAC,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC;IACrD,CAAC;IAgBD,OAAO,CAAC,QAAgB;QACtB,OAAO,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC;IACtD,CAAC;CACF;AA7SD,gDA6SC;AAED,MAAM,kBAAkB,GAAG,IAAI,kBAAkB,EAAE,CAAC;AAEpD,kBAAe,kBAAkB,CAAC","sourcesContent":["import { getPrismaSchemasContent } from \"../helpers/models.helpers\";\nimport { PrismaSchema, PrismaModel, PrismaEnum, PrismaField } from \"./types\";\n\n/**\n * A parser for Prisma schema files that extracts models, enums, and their properties.\n *\n * @example\n * ```typescript\n * const schemaContent = `\n * model User {\n * id Int @id @default(autoincrement())\n * email String @unique\n * }\n * `;\n * const parser = new PrismaSchemaParser();\n * const schema = parser.parse();\n * ```\n */\nexport class PrismaSchemaParser {\n /** Collection of parsed enum definitions */\n private enums: PrismaEnum[] = [];\n /** Collection of parsed model definitions */\n private models: PrismaModel[] = [];\n\n /**\n * Parses the Prisma schema and extracts all models and enums.\n *\n * @returns The parsed schema containing arrays of models and enums\n */\n parse(): PrismaSchema {\n this.enums = this.extractEnums();\n this.models = this.extractModels();\n\n return {\n models: this.models,\n enums: this.enums,\n };\n }\n\n /**\n * Extracts all enum definitions from the schema.\n *\n * @private\n * @returns Array of parsed enum objects\n */\n private extractEnums(): PrismaEnum[] {\n const enums: PrismaEnum[] = [];\n const schema = getPrismaSchemasContent() || \"\";\n const enumBlocks = schema.match(/enum\\s+\\w+\\s*\\{[^}]*\\}/g) || [];\n\n for (const block of enumBlocks) {\n const enumObj = this.parseEnumBlock(block);\n if (enumObj) {\n enums.push(enumObj);\n }\n }\n\n return enums;\n }\n\n /**\n * Parses a single enum block and extracts its name and values.\n *\n * @private\n * @param block - The enum block string (e.g., \"enum Status { ACTIVE INACTIVE }\")\n * @returns The parsed enum object or null if parsing fails\n */\n private parseEnumBlock(block: string): PrismaEnum | null {\n const nameMatch = block.match(/enum\\s+(\\w+)/);\n if (!nameMatch) return null;\n\n const name = nameMatch[1];\n const values = block\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(\n (line) =>\n line &&\n !line.startsWith(\"enum\") &&\n !line.startsWith(\"{\") &&\n !line.startsWith(\"}\")\n )\n .map((line) => line.replace(/,$/, \"\"));\n\n return { name, values };\n }\n\n /**\n * Extracts all model definitions from the schema.\n *\n * @private\n * @returns Array of parsed model objects\n */\n private extractModels(): PrismaModel[] {\n const models: PrismaModel[] = [];\n const modelBlocks = this.extractModelBlocks();\n\n for (const block of modelBlocks) {\n const model = this.parseModelBlock(block);\n if (model) {\n models.push(model);\n }\n }\n\n return models;\n }\n\n /**\n * Extracts raw model block strings from the schema using regex.\n *\n * @private\n * @returns Array of model block strings\n */\n private extractModelBlocks(): string[] {\n const modelRegex = /model\\s+\\w+\\s*\\{[^}]*\\}/g;\n const schema = getPrismaSchemasContent() || \"\";\n return schema.match(modelRegex) || [];\n }\n\n /**\n * Parses a single model block and extracts its name, fields, and metadata.\n *\n * @private\n * @param block - The model block string\n * @returns The parsed model object or null if parsing fails\n */\n private parseModelBlock(block: string): PrismaModel | null {\n const nameMatch = block.match(/model\\s+(\\w+)/);\n if (!nameMatch) return null;\n\n const name = nameMatch[1];\n const fields = this.parseFields(block);\n\n // Check for @@map directive\n const mapMatch = block.match(/@@map\\s*\\(\\s*\"([^\"]+)\"\\s*\\)/);\n const mapName = mapMatch ? mapMatch[1] : undefined;\n\n return { name, fields, mapName };\n }\n\n /**\n * Parses all field definitions within a model block.\n *\n * @private\n * @param block - The model block string containing field definitions\n * @returns Array of parsed field objects\n */\n private parseFields(block: string): PrismaField[] {\n const fields: PrismaField[] = [];\n const fieldLines = block\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(\n (line) =>\n line &&\n !line.startsWith(\"model\") &&\n !line.startsWith(\"{\") &&\n !line.startsWith(\"}\")\n );\n\n for (const line of fieldLines) {\n if (line.startsWith(\"//\") || line.startsWith(\"@@\")) continue;\n\n const field = this.parseFieldLine(line);\n if (field) {\n fields.push(field);\n }\n }\n\n return fields;\n }\n\n /**\n * Parses a single field line and extracts all field properties.\n *\n * @private\n * @param line - A single field definition line (e.g., \"id Int @id @default(autoincrement())\")\n * @returns The parsed field object or null if parsing fails\n *\n * @example\n * ```typescript\n * // Input: \"email String? @unique @default(\"user@example.com\")\"\n * // Output: {\n * // name: \"email\",\n * // type: \"String\",\n * // isOptional: true,\n * // isArray: false,\n * // defaultValue: \"user@example.com\",\n * // isId: false,\n * // isUnique: true,\n * // attributes: [\"@unique\", \"@default(\\\"user@example.com\\\")\"]\n * // }\n * ```\n */\n private parseFieldLine(line: string): PrismaField | null {\n const fieldMatch = line.match(/^(\\w+)\\s+(\\w+(?:\\[\\])?)\\??\\s*(.*)/);\n if (!fieldMatch) return null;\n\n const [, name, typeWithArray, attributesStr] = fieldMatch;\n const isArray = typeWithArray.endsWith(\"[]\");\n const type = isArray ? typeWithArray.slice(0, -2) : typeWithArray;\n const isOptional = line.includes(\"?\");\n\n const attributes = attributesStr\n .split(/\\s+/)\n .filter((attr) => attr.startsWith(\"@\"));\n\n // Extract default value\n let defaultValue: any = undefined;\n const defaultMatch = attributesStr.match(/@default\\(([^)]+)\\)/);\n if (defaultMatch) {\n defaultValue = this.parseDefaultValue(defaultMatch[1]);\n }\n\n // Extract connection field from @relation\n let connectionField = \"\";\n const relationMatch = attributesStr.match(\n /@relation\\([^)]*fields:\\s*\\[([^\\]]+)\\]/\n );\n if (relationMatch) {\n // Extract the field name and clean it up (remove quotes and whitespace)\n connectionField = relationMatch[1].trim().replace(/['\"]/g, \"\");\n }\n\n const isId = attributes.some((attr) => attr.startsWith(\"@id\"));\n const isUnique = attributes.some((attr) => attr.startsWith(\"@unique\"));\n\n return {\n name,\n type,\n isOptional,\n isArray,\n connectionField,\n defaultValue,\n isId,\n isUnique,\n attributes,\n };\n }\n\n /**\n * Parses a default value string and converts it to the appropriate JavaScript type.\n *\n * @private\n * @param defaultStr - The default value string from @default() attribute\n * @returns The parsed default value in appropriate JavaScript type, or undefined for functions\n *\n * @example\n * ```typescript\n * parseDefaultValue('\"hello\"') // returns \"hello\"\n * parseDefaultValue('true') // returns true\n * parseDefaultValue('42') // returns 42\n * parseDefaultValue('3.14') // returns 3.14\n * parseDefaultValue('ACTIVE') // returns \"ACTIVE\" (enum value)\n * parseDefaultValue('now()') // returns undefined (function)\n * ```\n */\n private parseDefaultValue(defaultStr: string): any {\n defaultStr = defaultStr.trim();\n\n // Handle string values\n if (defaultStr.startsWith('\"') && defaultStr.endsWith('\"'))\n return defaultStr.slice(1, -1);\n\n // Handle boolean values\n if (defaultStr === \"true\") return true;\n if (defaultStr === \"false\") return false;\n\n // Handle numeric values\n if (/^\\d+$/.test(defaultStr)) return parseInt(defaultStr, 10);\n\n if (/^\\d+\\.\\d+$/.test(defaultStr)) return parseFloat(defaultStr);\n\n // Handle enum values (no quotes, not a function)\n if (!defaultStr.includes(\"(\")) return defaultStr;\n\n // Handle functions (like now(), auto(), etc.)\n if (defaultStr.includes(\"(\"))\n // For MongoDB, we'll skip function defaults as they're handled by the DB\n return undefined;\n\n return defaultStr;\n }\n\n /**\n * Checks if a given type name corresponds to a defined enum.\n *\n * @param typeName - The type name to check\n * @returns True if the type is an enum, false otherwise\n *\n * @example\n * ```typescript\n * const parser = new PrismaSchemaParser(schemaWithStatusEnum);\n * parser.parse();\n * parser.isEnum('Status'); // true\n * parser.isEnum('String'); // false\n * ```\n */\n isEnum(typeName: string): boolean {\n return this.enums.some((e) => e.name === typeName);\n }\n\n /**\n * Checks if a given type name corresponds to a defined model.\n *\n * @param typeName - The type name to check\n * @returns True if the type is a model, false otherwise\n *\n * @example\n * ```typescript\n * const parser = new PrismaSchemaParser(schemaWithUserModel);\n * parser.parse();\n * parser.isModel('User'); // true\n * parser.isModel('String'); // false\n * ```\n */\n isModel(typeName: string): boolean {\n return this.models.some((m) => m.name === typeName);\n }\n}\n\nconst prismaSchemaParser = new PrismaSchemaParser();\n\nexport default prismaSchemaParser;\n"]}
|
package/dist/cjs/utils/sheu.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});class Sheu{getTimestamp(){return new Date().toTimeString().split(" ")[0]}formatText(t="",e={}){const r=e?.label?t?e?.label+" ":e?.label:"";let o=`${r}${t}`;if(e.timestamp){const m=this.getTimestamp();if(e.timestamp===!0)o=`${r}\x1B[90m${m}\x1B[0m ${t}`;else if(typeof e.timestamp=="string"){const x=this.getColorCode(e.timestamp);o=`${r}${x}${m}\x1B[0m ${t}`}}return e.bold&&(o=`\x1B[1m${o}\x1B[0m`),o}getColorCode(t){return{red:"\x1B[31m",blue:"\x1B[34m",green:"\x1B[32m",yellow:"\x1B[33m",cyan:"\x1B[36m",magenta:"\x1B[35m",white:"\x1B[37m",black:"\x1B[30m",gray:"\x1B[90m",orange:"\x1B[91m"}[t]||"\x1B[90m"}red(t,e){const r=`\x1B[31m${t}\x1B[0m`;return this.formatText(r,e||{})}blue(t,e){const r=`\x1B[34m${t}\x1B[0m`;return this.formatText(r,e||{})}green(t,e){const r=`\x1B[32m${t}\x1B[0m`;return this.formatText(r,e||{})}yellow(t,e){const r=`\x1B[33m${t}\x1B[0m`;return this.formatText(r,e||{})}cyan(t,e){const r=`\x1B[36m${t}\x1B[0m`;return this.formatText(r,e||{})}magenta(t,e){const r=`\x1B[35m${t}\x1B[0m`;return this.formatText(r,e||{})}white(t,e){const r=`\x1B[37m${t}\x1B[0m`;return this.formatText(r,e||{})}black(t,e){const r=`\x1B[30m${t}\x1B[0m`;return this.formatText(r,e||{})}gray(t,e){const r=`\x1B[90m${t}\x1B[0m`;return this.formatText(r,e||{})}orange(t,e){const r=`\x1B[91m${t}\x1B[0m`;return this.formatText(r,e||{})}bold(t,e){const r=`\x1B[1m${t}\x1B[0m`;return this.formatText(r,{...e,bold:!1})}info(t,e){const o=this.formatText(t,{...e,label:"[\x1B[
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});class Sheu{getTimestamp(){return new Date().toTimeString().split(" ")[0]}formatText(t="",e={}){const r=e?.label?t?e?.label+" ":e?.label:"";let o=`${r}${t}`;if(e.timestamp){const m=this.getTimestamp();if(e.timestamp===!0)o=`${r}\x1B[90m${m}\x1B[0m ${t}`;else if(typeof e.timestamp=="string"){const x=this.getColorCode(e.timestamp);o=`${r}${x}${m}\x1B[0m ${t}`}}return e.bold&&(o=`\x1B[1m${o}\x1B[0m`),o}getColorCode(t){return{red:"\x1B[31m",blue:"\x1B[34m",green:"\x1B[32m",yellow:"\x1B[33m",cyan:"\x1B[36m",magenta:"\x1B[35m",white:"\x1B[37m",black:"\x1B[30m",gray:"\x1B[90m",orange:"\x1B[91m"}[t]||"\x1B[90m"}red(t,e){const r=`\x1B[31m${t}\x1B[0m`;return this.formatText(r,e||{})}blue(t,e){const r=`\x1B[34m${t}\x1B[0m`;return this.formatText(r,e||{})}green(t,e){const r=`\x1B[32m${t}\x1B[0m`;return this.formatText(r,e||{})}yellow(t,e){const r=`\x1B[33m${t}\x1B[0m`;return this.formatText(r,e||{})}cyan(t,e){const r=`\x1B[36m${t}\x1B[0m`;return this.formatText(r,e||{})}magenta(t,e){const r=`\x1B[35m${t}\x1B[0m`;return this.formatText(r,e||{})}white(t,e){const r=`\x1B[37m${t}\x1B[0m`;return this.formatText(r,e||{})}black(t,e){const r=`\x1B[30m${t}\x1B[0m`;return this.formatText(r,e||{})}gray(t,e){const r=`\x1B[90m${t}\x1B[0m`;return this.formatText(r,e||{})}orange(t,e){const r=`\x1B[91m${t}\x1B[0m`;return this.formatText(r,e||{})}bold(t,e){const r=`\x1B[1m${t}\x1B[0m`;return this.formatText(r,{...e,bold:!1})}info(t,e){const o=this.formatText(t,{...e,label:"[\x1B[36mInfo\x1B[0m]"});return console.info(o),o}error(t,e){const o=this.formatText(t,{...e,label:"[\x1B[31mError\x1B[0m]"});return console.error(o),o}ready(t,e){const o=this.formatText(t,{...e,label:"[\x1B[32mReady\x1B[0m]"});return console.info(o),o}done(t,e){const o=this.formatText(t,{...e,label:"[\x1B[32mDone\x1B[0m]"});return console.info(o),o}warn(t,e){const o=this.formatText(t,{...e,label:"[\x1B[33mWarn\x1B[0m]"});return console.warn(o),o}}const sheu=new Sheu;exports.default=sheu;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sheu.js","sourceRoot":"","sources":["../../../src/utils/sheu.ts"],"names":[],"mappings":";;AAGA,MAAM,IAAI;IAIA,YAAY;QAClB,OAAO,IAAI,IAAI,EAAE,CAAC,YAAY,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IACjD,CAAC;IAKO,UAAU,CAChB,OAAe,EAAE,EACjB,UAII,EAAE;QAEN,MAAM,KAAK,GAAG,OAAO,EAAE,KAAK;YAC1B,CAAC,CAAC,IAAI;gBACJ,CAAC,CAAC,OAAO,EAAE,KAAK,GAAG,GAAG;gBACtB,CAAC,CAAC,OAAO,EAAE,KAAK;YAClB,CAAC,CAAC,EAAE,CAAC;QACP,IAAI,MAAM,GAAG,GAAG,KAAK,GAAG,IAAI,EAAE,CAAC;QAG/B,IAAI,OAAO,CAAC,SAAS,EAAE,CAAC;YACtB,MAAM,SAAS,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;YACtC,IAAI,OAAO,CAAC,SAAS,KAAK,IAAI;gBAC5B,MAAM,GAAG,GAAG,KAAK,WAAW,SAAS,WAAW,IAAI,EAAE,CAAC;iBACpD,IAAI,OAAO,OAAO,CAAC,SAAS,KAAK,QAAQ,EAAE,CAAC;gBAC/C,MAAM,SAAS,GAAG,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;gBACvD,MAAM,GAAG,GAAG,KAAK,GAAG,SAAS,GAAG,SAAS,WAAW,IAAI,EAAE,CAAC;YAC7D,CAAC;QACH,C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AK,EAAE,CAAC,CAAC;QAC/D,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACrB,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AAED,MAAM,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC;AAExB,kBAAe,IAAI,CAAC","sourcesContent":["/**\n * Sheu - Simplified terminal color utility for styling console output\n */\nclass Sheu {\n /**\n * Get current timestamp in HH:MM:SS format\n */\n private getTimestamp(): string {\n return new Date().toTimeString().split(\" \")[0];\n }\n\n /**\n * Apply timestamp and bold formatting if requested\n */\n private formatText(\n text: string = \"\",\n options: {\n timestamp?: boolean | string;\n bold?: boolean;\n label?: string;\n } = {}\n ): string {\n const label = options?.label\n ? text\n ? options?.label + \" \"\n : options?.label\n : \"\";\n let result = `${label}${text}`;\n\n // Apply timestamp if requested\n if (options.timestamp) {\n const timestamp = this.getTimestamp();\n if (options.timestamp === true)\n result = `${label}\\x1b[90m${timestamp}\\x1b[0m ${text}`;\n else if (typeof options.timestamp === \"string\") {\n const colorCode = this.getColorCode(options.timestamp);\n result = `${label}${colorCode}${timestamp}\\x1b[0m ${text}`;\n }\n }\n\n if (options.bold) result = `\\x1b[1m${result}\\x1b[0m`;\n\n return result;\n }\n\n /**\n * Get ANSI color code for color name\n */\n private getColorCode(color: string): string {\n const colorMap: { [key: string]: string } = {\n red: \"\\x1b[31m\",\n blue: \"\\x1b[34m\",\n green: \"\\x1b[32m\",\n yellow: \"\\x1b[33m\",\n cyan: \"\\x1b[36m\",\n magenta: \"\\x1b[35m\",\n white: \"\\x1b[37m\",\n black: \"\\x1b[30m\",\n gray: \"\\x1b[90m\",\n orange: \"\\x1b[91m\",\n };\n return colorMap[color] || \"\\x1b[90m\"; // Default to gray if color not found\n }\n\n /**\n * Red color\n */\n red(\n text: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const coloredText = `\\x1b[31m${text}\\x1b[0m`;\n return this.formatText(coloredText, options || {});\n }\n\n /**\n * Blue color\n */\n blue(\n text: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const coloredText = `\\x1b[34m${text}\\x1b[0m`;\n return this.formatText(coloredText, options || {});\n }\n\n /**\n * Green color\n */\n green(\n text: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const coloredText = `\\x1b[32m${text}\\x1b[0m`;\n return this.formatText(coloredText, options || {});\n }\n\n /**\n * Yellow color\n */\n yellow(\n text: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const coloredText = `\\x1b[33m${text}\\x1b[0m`;\n return this.formatText(coloredText, options || {});\n }\n\n /**\n * Cyan color\n */\n cyan(\n text: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const coloredText = `\\x1b[36m${text}\\x1b[0m`;\n return this.formatText(coloredText, options || {});\n }\n\n /**\n * Magenta color\n */\n magenta(\n text: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const coloredText = `\\x1b[35m${text}\\x1b[0m`;\n return this.formatText(coloredText, options || {});\n }\n\n /**\n * White color\n */\n white(\n text: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const coloredText = `\\x1b[37m${text}\\x1b[0m`;\n return this.formatText(coloredText, options || {});\n }\n\n /**\n * Black color\n */\n black(\n text: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const coloredText = `\\x1b[30m${text}\\x1b[0m`;\n return this.formatText(coloredText, options || {});\n }\n\n /**\n * Gray color\n */\n gray(\n text: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const coloredText = `\\x1b[90m${text}\\x1b[0m`;\n return this.formatText(coloredText, options || {});\n }\n\n /**\n * Orange color\n */\n orange(\n text: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const coloredText = `\\x1b[91m${text}\\x1b[0m`;\n return this.formatText(coloredText, options || {});\n }\n\n /**\n * Bold text formatting\n */\n bold(text: string, options?: { timestamp?: boolean | string }): string {\n const boldText = `\\x1b[1m${text}\\x1b[0m`;\n return this.formatText(boldText, { ...options, bold: false }); // Don't double-bold\n }\n\n /**\n * Info label with cyan color [INFO]\n */\n info(\n message: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const label = `[\\x1b[36mINFO\\x1b[0m]`;\n const result = this.formatText(message, { ...options, label });\n console.info(result);\n return result;\n }\n\n /**\n * Error label with red color [ERROR]\n */\n error(\n message: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const label = `[\\x1b[31mERROR\\x1b[0m]`;\n const result = this.formatText(message, { ...options, label });\n console.error(result);\n return result;\n }\n\n /**\n * Ready label with green color [READY]\n */\n ready(\n message: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const label = `[\\x1b[32mREADY\\x1b[0m]`;\n const result = this.formatText(message, { ...options, label });\n console.info(result);\n return result;\n }\n\n /**\n * Done label with green color [DONE]\n */\n done(\n message: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const label = `[\\x1b[32mDONE\\x1b[0m]`;\n const result = this.formatText(message, { ...options, label });\n console.info(result);\n return result;\n }\n\n /**\n * Warning label with yellow color [WARN]\n */\n warn(\n message: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const label = `[\\x1b[33mWARN\\x1b[0m]`;\n const result = this.formatText(message, { ...options, label });\n console.warn(result);\n return result;\n }\n}\n\nconst sheu = new Sheu();\n\nexport default sheu;\n"]}
|
|
1
|
+
{"version":3,"file":"sheu.js","sourceRoot":"","sources":["../../../src/utils/sheu.ts"],"names":[],"mappings":";;AAGA,MAAM,IAAI;IAIA,YAAY;QAClB,OAAO,IAAI,IAAI,EAAE,CAAC,YAAY,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IACjD,CAAC;IAKO,UAAU,CAChB,OAAe,EAAE,EACjB,UAII,EAAE;QAEN,MAAM,KAAK,GAAG,OAAO,EAAE,KAAK;YAC1B,CAA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G,wBAAwB,CAAC;QACvC,MAAM,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;QAC/D,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACrB,OAAO,MAAM,CAAC;IAChB,CAAC;IAKD,IAAI,CACF,OAAe,EACf,OAA0D;QAE1D,MAAM,KAAK,GAAG,uBAAuB,CAAC;QACtC,MAAM,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;QAC/D,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACrB,OAAO,MAAM,CAAC;IAChB,CAAC;IAKD,IAAI,CACF,OAAe,EACf,OAA0D;QAE1D,MAAM,KAAK,GAAG,uBAAuB,CAAC;QACtC,MAAM,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;QAC/D,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACrB,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AAED,MAAM,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC;AAExB,kBAAe,IAAI,CAAC","sourcesContent":["/**\n * Sheu - Simplified terminal color utility for styling console output\n */\nclass Sheu {\n /**\n * Get current timestamp in HH:MM:SS format\n */\n private getTimestamp(): string {\n return new Date().toTimeString().split(\" \")[0];\n }\n\n /**\n * Apply timestamp and bold formatting if requested\n */\n private formatText(\n text: string = \"\",\n options: {\n timestamp?: boolean | string;\n bold?: boolean;\n label?: string;\n } = {}\n ): string {\n const label = options?.label\n ? text\n ? options?.label + \" \"\n : options?.label\n : \"\";\n let result = `${label}${text}`;\n\n // Apply timestamp if requested\n if (options.timestamp) {\n const timestamp = this.getTimestamp();\n if (options.timestamp === true)\n result = `${label}\\x1b[90m${timestamp}\\x1b[0m ${text}`;\n else if (typeof options.timestamp === \"string\") {\n const colorCode = this.getColorCode(options.timestamp);\n result = `${label}${colorCode}${timestamp}\\x1b[0m ${text}`;\n }\n }\n\n if (options.bold) result = `\\x1b[1m${result}\\x1b[0m`;\n\n return result;\n }\n\n /**\n * Get ANSI color code for color name\n */\n private getColorCode(color: string): string {\n const colorMap: { [key: string]: string } = {\n red: \"\\x1b[31m\",\n blue: \"\\x1b[34m\",\n green: \"\\x1b[32m\",\n yellow: \"\\x1b[33m\",\n cyan: \"\\x1b[36m\",\n magenta: \"\\x1b[35m\",\n white: \"\\x1b[37m\",\n black: \"\\x1b[30m\",\n gray: \"\\x1b[90m\",\n orange: \"\\x1b[91m\",\n };\n return colorMap[color] || \"\\x1b[90m\"; // Default to gray if color not found\n }\n\n /**\n * Red color\n */\n red(\n text: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const coloredText = `\\x1b[31m${text}\\x1b[0m`;\n return this.formatText(coloredText, options || {});\n }\n\n /**\n * Blue color\n */\n blue(\n text: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const coloredText = `\\x1b[34m${text}\\x1b[0m`;\n return this.formatText(coloredText, options || {});\n }\n\n /**\n * Green color\n */\n green(\n text: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const coloredText = `\\x1b[32m${text}\\x1b[0m`;\n return this.formatText(coloredText, options || {});\n }\n\n /**\n * Yellow color\n */\n yellow(\n text: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const coloredText = `\\x1b[33m${text}\\x1b[0m`;\n return this.formatText(coloredText, options || {});\n }\n\n /**\n * Cyan color\n */\n cyan(\n text: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const coloredText = `\\x1b[36m${text}\\x1b[0m`;\n return this.formatText(coloredText, options || {});\n }\n\n /**\n * Magenta color\n */\n magenta(\n text: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const coloredText = `\\x1b[35m${text}\\x1b[0m`;\n return this.formatText(coloredText, options || {});\n }\n\n /**\n * White color\n */\n white(\n text: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const coloredText = `\\x1b[37m${text}\\x1b[0m`;\n return this.formatText(coloredText, options || {});\n }\n\n /**\n * Black color\n */\n black(\n text: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const coloredText = `\\x1b[30m${text}\\x1b[0m`;\n return this.formatText(coloredText, options || {});\n }\n\n /**\n * Gray color\n */\n gray(\n text: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const coloredText = `\\x1b[90m${text}\\x1b[0m`;\n return this.formatText(coloredText, options || {});\n }\n\n /**\n * Orange color\n */\n orange(\n text: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const coloredText = `\\x1b[91m${text}\\x1b[0m`;\n return this.formatText(coloredText, options || {});\n }\n\n /**\n * Bold text formatting\n */\n bold(text: string, options?: { timestamp?: boolean | string }): string {\n const boldText = `\\x1b[1m${text}\\x1b[0m`;\n return this.formatText(boldText, { ...options, bold: false }); // Don't double-bold\n }\n\n /**\n * Info label with cyan color [INFO]\n */\n info(\n message: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const label = `[\\x1b[36mInfo\\x1b[0m]`;\n const result = this.formatText(message, { ...options, label });\n console.info(result);\n return result;\n }\n\n /**\n * Error label with red color [ERROR]\n */\n error(\n message: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const label = `[\\x1b[31mError\\x1b[0m]`;\n const result = this.formatText(message, { ...options, label });\n console.error(result);\n return result;\n }\n\n /**\n * Ready label with green color [READY]\n */\n ready(\n message: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n // const label = `\\x1b[32m✓\\x1b[0m`;\n const label = `[\\x1b[32mReady\\x1b[0m]`;\n const result = this.formatText(message, { ...options, label });\n console.info(result);\n return result;\n }\n\n /**\n * Done label with green color [DONE]\n */\n done(\n message: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const label = `[\\x1b[32mDone\\x1b[0m]`;\n const result = this.formatText(message, { ...options, label });\n console.info(result);\n return result;\n }\n\n /**\n * Warning label with yellow color [WARN]\n */\n warn(\n message: string,\n options?: { timestamp?: boolean | string; bold?: boolean }\n ): string {\n const label = `[\\x1b[33mWarn\\x1b[0m]`;\n const result = this.formatText(message, { ...options, label });\n console.warn(result);\n return result;\n }\n}\n\nconst sheu = new Sheu();\n\nexport default sheu;\n"]}
|
package/dist/esm/app.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":"AAIA,OAAO,OAAO,MAAM,SAAS,CAAC;AAC9B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,YAAY,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EACL,qBAAqB,EACrB,oCAAoC,GACrC,MAAM,4BAA4B,CAAC;AACpC,OAAO,YAAY,MAAM,kDAAkD,CAAC;AAC5E,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,WAAW,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACpE,OAAO,EACL,uBAAuB,EACvB,gBAAgB,GACjB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,mBAAmB,EAAE,MAAM,0CAA0C,CAAC;AAE/E,OAAO,EAAE,WAAW,EAAE,MAAM,sCAAsC,CAAC;AACnE,OAAO,SAAS,MAAM,kCAAkC,CAAC;AACzD,OAAO,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AAEpE,MAAM,CAAC,MAAM,GAAG,GAAoB,OAAO,EAAE,CAAC;AAE9C,MAAM,CAAC,KAAK,UAAU,SAAS,CAC7B,WA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AG,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,gBAAgB,CAAC,WAAW,CAAC,CAAC,CAAC;IAGvD,IAAI,aAAa,EAAE,UAAU;QAC3B,aAAa,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;YAC1C,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAClB,CAAC,CAAC,CAAC;IAGL,IAAI,CAAC,mBAAmB,EAAE,QAAQ,EAAE,CAAC,sBAAsB,CAAC;QAC1D,GAAG,CAAC,GAAG,CAAC,mBAAmB,CAAC,kBAAkB,IAAI,YAAY,CAAC,CAAC;IAElE,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,EAAE;QACtB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,kBAAkB,EAAE,CAAC,CAAC;IACxD,CAAC,CAAC,CAAC;IAEH,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["// require(\"ts-node\").register({\n// esm: true,\n// experimentalSpecifierResolution: \"node\",\n// });\nimport express from \"express\";\nimport cors from \"cors\";\nimport cookieParser from \"cookie-parser\";\nimport { getAuthRouter } from \"./modules/auth/auth.router\";\nimport {\n getPrismaModelsRouter,\n getAvailableResourcesAndRoutesRouter,\n} from \"./modules/base/base.router\";\nimport errorHandler from \"./modules/error-handler/error-handler.controller\";\nimport { rateLimit } from \"express-rate-limit\";\nimport compression from \"compression\";\nimport { handleRequestLogs } from \"./modules/base/base.middlewares\";\nimport {\n checkDatabaseConnection,\n loadPrismaModule,\n} from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploadRouter } from \"./modules/file-upload/file-upload.router\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport { queryParser } from \"./utils/helpers/query-parser.helpers\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport { getSwaggerRouter } from \"./modules/swagger/swagger.router\";\n\nexport const app: express.Express = express();\n\nexport async function bootstrap(\n arkosConfig: ArkosConfig\n): Promise<express.Express> {\n await loadPrismaModule();\n\n if (arkosConfig?.configureApp) await arkosConfig.configureApp(app);\n\n const middlewaresConfig = arkosConfig?.middlewares;\n const disabledMiddlewares = middlewaresConfig?.disable || [];\n const replacedMiddlewares = middlewaresConfig?.replace || {};\n\n // Compression middleware\n if (!disabledMiddlewares?.includes?.(\"compression\"))\n app.use(\n replacedMiddlewares.compression ||\n compression(arkosConfig?.compressionOptions)\n );\n\n // Global rate limit middleware\n if (!disabledMiddlewares?.includes?.(\"global-rate-limit\"))\n app.use(\n replacedMiddlewares.globalRateLimit ||\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 500,\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 arkosConfig?.globalRequestRateLimitOptions || {}\n )\n )\n );\n\n // CORS middleware\n if (!disabledMiddlewares?.includes?.(\"cors\"))\n app.use(\n replacedMiddlewares.cors ||\n cors(\n arkosConfig?.cors?.customHandler\n ? arkosConfig.cors.customHandler\n : deepmerge(\n {\n origin: (\n origin: string,\n cb: (err: Error | null, allow?: boolean) => void\n ) => {\n const allowed = arkosConfig?.cors?.allowedOrigins;\n\n if (allowed === \"*\") {\n cb(null, true);\n } else if (Array.isArray(allowed)) {\n cb(null, !origin || allowed?.includes?.(origin));\n } else if (typeof allowed === \"string\") {\n cb(null, !origin || allowed === origin);\n } else {\n cb(null, false);\n }\n },\n methods: [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\n \"Content-Type\",\n \"Authorization\",\n \"Connection\",\n ],\n credentials: true,\n },\n arkosConfig?.cors?.options || {}\n )\n )\n );\n\n // JSON body parser middleware\n if (!disabledMiddlewares?.includes?.(\"express-json\"))\n app.use(\n replacedMiddlewares.expressJson ||\n express.json(arkosConfig?.jsonBodyParserOptions)\n );\n\n // Cookie parser middleware\n if (!disabledMiddlewares?.includes?.(\"cookie-parser\"))\n app.use(\n replacedMiddlewares.cookieParser ||\n cookieParser(...[...(arkosConfig?.cookieParserParameters || [])])\n );\n\n // Query parser middleware\n if (!disabledMiddlewares?.includes?.(\"query-parser\"))\n app.use(\n replacedMiddlewares.queryParser ||\n queryParser(\n deepmerge(\n {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n },\n arkosConfig?.queryParserOptions || {}\n )\n )\n );\n\n // Database connection check middleware\n if (!disabledMiddlewares?.includes?.(\"database-connection\"))\n app.use(replacedMiddlewares.databaseConnection || checkDatabaseConnection);\n\n // Request logger middleware\n if (!disabledMiddlewares?.includes?.(\"request-logger\"))\n app.use(replacedMiddlewares.requestLogger || handleRequestLogs);\n\n // Additional custom middlewares\n if (arkosConfig?.middlewares?.additional)\n arkosConfig.middlewares.additional.forEach((middleware) => {\n app.use(middleware);\n });\n\n // Configure routers\n const routersConfig = arkosConfig?.routers;\n const disabledRouters = routersConfig?.disable || [];\n const replacedRouters = routersConfig?.replace || {};\n\n // Welcome endpoint\n if (!disabledRouters?.includes?.(\"welcome-endpoint\"))\n app.get(\n \"/api\",\n replacedRouters.welcomeEndpoint ||\n ((_, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n })\n );\n\n // File upload router\n if (!disabledRouters?.includes?.(\"file-upload\")) {\n const fileUploadRouter = replacedRouters.fileUpload\n ? await replacedRouters.fileUpload(arkosConfig)\n : await getFileUploadRouter(arkosConfig);\n app.use(fileUploadRouter);\n }\n\n // Auth router\n if (\n !disabledRouters?.includes?.(\"auth-router\") &&\n arkosConfig.authentication\n ) {\n const authRouter = replacedRouters.authRouter\n ? await replacedRouters.authRouter(arkosConfig)\n : await getAuthRouter(arkosConfig);\n app.use(\"/api\", authRouter);\n }\n\n // Prisma models router\n if (!disabledRouters?.includes?.(\"prisma-models-router\")) {\n const modelsRouter = replacedRouters.prismaModelsRouter\n ? await replacedRouters.prismaModelsRouter(arkosConfig)\n : await getPrismaModelsRouter(arkosConfig);\n app.use(\"/api\", modelsRouter);\n }\n\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n if (\n arkosConfig.swagger &&\n (process.env.ARKOS_BUILD !== \"true\" ||\n arkosConfig.swagger.enableAfterBuild === true)\n )\n app.use(\"/api\", await getSwaggerRouter(arkosConfig));\n\n // Additional custom routers\n if (routersConfig?.additional)\n routersConfig.additional.forEach((router) => {\n app.use(router);\n });\n\n // Global error handler middleware (must be last)\n if (!disabledMiddlewares?.includes?.(\"global-error-handler\"))\n app.use(replacedMiddlewares.globalErrorHandler || errorHandler);\n\n app.use(\"*\", (_, res) => {\n res.status(404).json({ message: \"Route not found!\" });\n });\n\n return app;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"app.js","sourceRoot":"","sources":["../../src/app.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,SAAS,CAAC;AAC9B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,YAAY,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EACL,qBAAqB,EACrB,oCAAoC,GACrC,MAAM,4BAA4B,CAAC;AACpC,OAAO,YAAY,MAAM,kDAAkD,CAAC;AAC5E,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,WAAW,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACpE,OAAO,EACL,uBAAuB,EACvB,gBAAgB,GACjB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,mBAAmB,EAAE,MAAM,0CAA0C,CAAC;AAE/E,OAAO,EAAE,WAAW,EAAE,MAAM,sCAAsC,CAAC;AACnE,OAAO,SAAS,MAAM,kCAAkC,CAAC;AACzD,OAAO,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AAEpE,MAAM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,CAAC,WAAW,KAAK,MAAM;YACjC,WAAW,CAAC,OAAO,CAAC,gBAAgB,KAAK,IAAI,CAAC;QAEhD,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,gBAAgB,CAAC,WAAW,CAAC,CAAC,CAAC;IAGvD,IAAI,aAAa,EAAE,UAAU;QAC3B,aAAa,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;YAC1C,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAClB,CAAC,CAAC,CAAC;IAGL,IAAI,CAAC,mBAAmB,EAAE,QAAQ,EAAE,CAAC,sBAAsB,CAAC;QAC1D,GAAG,CAAC,GAAG,CAAC,mBAAmB,CAAC,kBAAkB,IAAI,YAAY,CAAC,CAAC;IAElE,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,EAAE;QACtB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,kBAAkB,EAAE,CAAC,CAAC;IACxD,CAAC,CAAC,CAAC;IAEH,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import express from \"express\";\nimport cors from \"cors\";\nimport cookieParser from \"cookie-parser\";\nimport { getAuthRouter } from \"./modules/auth/auth.router\";\nimport {\n getPrismaModelsRouter,\n getAvailableResourcesAndRoutesRouter,\n} from \"./modules/base/base.router\";\nimport errorHandler from \"./modules/error-handler/error-handler.controller\";\nimport { rateLimit } from \"express-rate-limit\";\nimport compression from \"compression\";\nimport { handleRequestLogs } from \"./modules/base/base.middlewares\";\nimport {\n checkDatabaseConnection,\n loadPrismaModule,\n} from \"./utils/helpers/prisma.helpers\";\nimport { getFileUploadRouter } from \"./modules/file-upload/file-upload.router\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport { queryParser } from \"./utils/helpers/query-parser.helpers\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport { getSwaggerRouter } from \"./modules/swagger/swagger.router\";\n\nexport const app: express.Express = express();\n\nexport async function bootstrap(\n arkosConfig: ArkosConfig\n): Promise<express.Express> {\n await loadPrismaModule();\n\n if (arkosConfig?.configureApp) await arkosConfig.configureApp(app);\n\n const middlewaresConfig = arkosConfig?.middlewares;\n const disabledMiddlewares = middlewaresConfig?.disable || [];\n const replacedMiddlewares = middlewaresConfig?.replace || {};\n\n // Compression middleware\n if (!disabledMiddlewares?.includes?.(\"compression\"))\n app.use(\n replacedMiddlewares.compression ||\n compression(arkosConfig?.compressionOptions)\n );\n\n // Global rate limit middleware\n if (!disabledMiddlewares?.includes?.(\"global-rate-limit\"))\n app.use(\n replacedMiddlewares.globalRateLimit ||\n rateLimit(\n deepmerge(\n {\n windowMs: 60 * 1000,\n limit: 500,\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 arkosConfig?.globalRequestRateLimitOptions || {}\n )\n )\n );\n\n // CORS middleware\n if (!disabledMiddlewares?.includes?.(\"cors\"))\n app.use(\n replacedMiddlewares.cors ||\n cors(\n arkosConfig?.cors?.customHandler\n ? arkosConfig.cors.customHandler\n : deepmerge(\n {\n origin: (\n origin: string,\n cb: (err: Error | null, allow?: boolean) => void\n ) => {\n const allowed = arkosConfig?.cors?.allowedOrigins;\n\n if (allowed === \"*\") {\n cb(null, true);\n } else if (Array.isArray(allowed)) {\n cb(null, !origin || allowed?.includes?.(origin));\n } else if (typeof allowed === \"string\") {\n cb(null, !origin || allowed === origin);\n } else {\n cb(null, false);\n }\n },\n methods: [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"],\n allowedHeaders: [\n \"Content-Type\",\n \"Authorization\",\n \"Connection\",\n ],\n credentials: true,\n },\n arkosConfig?.cors?.options || {}\n )\n )\n );\n\n // JSON body parser middleware\n if (!disabledMiddlewares?.includes?.(\"express-json\"))\n app.use(\n replacedMiddlewares.expressJson ||\n express.json(arkosConfig?.jsonBodyParserOptions)\n );\n\n // Cookie parser middleware\n if (!disabledMiddlewares?.includes?.(\"cookie-parser\"))\n app.use(\n replacedMiddlewares.cookieParser ||\n cookieParser(...[...(arkosConfig?.cookieParserParameters || [])])\n );\n\n // Query parser middleware\n if (!disabledMiddlewares?.includes?.(\"query-parser\"))\n app.use(\n replacedMiddlewares.queryParser ||\n queryParser(\n deepmerge(\n {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n },\n arkosConfig?.queryParserOptions || {}\n )\n )\n );\n\n // Database connection check middleware\n if (!disabledMiddlewares?.includes?.(\"database-connection\"))\n app.use(replacedMiddlewares.databaseConnection || checkDatabaseConnection);\n\n // Request logger middleware\n if (!disabledMiddlewares?.includes?.(\"request-logger\"))\n app.use(replacedMiddlewares.requestLogger || handleRequestLogs);\n\n // Additional custom middlewares\n if (arkosConfig?.middlewares?.additional)\n arkosConfig.middlewares.additional.forEach((middleware) => {\n app.use(middleware);\n });\n\n // Configure routers\n const routersConfig = arkosConfig?.routers;\n const disabledRouters = routersConfig?.disable || [];\n const replacedRouters = routersConfig?.replace || {};\n\n // Welcome endpoint\n if (!disabledRouters?.includes?.(\"welcome-endpoint\"))\n app.get(\n \"/api\",\n replacedRouters.welcomeEndpoint ||\n ((_, res) => {\n res.status(200).json({ message: arkosConfig.welcomeMessage });\n })\n );\n\n // File upload router\n if (!disabledRouters?.includes?.(\"file-upload\")) {\n const fileUploadRouter = replacedRouters.fileUpload\n ? await replacedRouters.fileUpload(arkosConfig)\n : await getFileUploadRouter(arkosConfig);\n app.use(fileUploadRouter);\n }\n\n // Auth router\n if (\n !disabledRouters?.includes?.(\"auth-router\") &&\n arkosConfig.authentication\n ) {\n const authRouter = replacedRouters.authRouter\n ? await replacedRouters.authRouter(arkosConfig)\n : await getAuthRouter(arkosConfig);\n app.use(\"/api\", authRouter);\n }\n\n // Prisma models router\n if (!disabledRouters?.includes?.(\"prisma-models-router\")) {\n const modelsRouter = replacedRouters.prismaModelsRouter\n ? await replacedRouters.prismaModelsRouter(arkosConfig)\n : await getPrismaModelsRouter(arkosConfig);\n app.use(\"/api\", modelsRouter);\n }\n\n app.use(\"/api\", getAvailableResourcesAndRoutesRouter());\n\n if (\n arkosConfig.swagger &&\n (process.env.ARKOS_BUILD !== \"true\" ||\n arkosConfig.swagger.enableAfterBuild === true)\n )\n app.use(\"/api\", await getSwaggerRouter(arkosConfig));\n\n // Additional custom routers\n if (routersConfig?.additional)\n routersConfig.additional.forEach((router) => {\n app.use(router);\n });\n\n // Global error handler middleware (must be last)\n if (!disabledMiddlewares?.includes?.(\"global-error-handler\"))\n app.use(replacedMiddlewares.globalErrorHandler || errorHandler);\n\n app.use(\"*\", (_, res) => {\n res.status(404).json({ message: \"Route not found!\" });\n });\n\n return app;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{getArkosConfig as m}from"../../server.js";import u from"../../utils/helpers/deepmerge.helper.js";import{catchAsync as l}from"../../exports/error-handler/index.js";import f from"../../utils/validate-dto.js";import x from"../../utils/validate-schema.js";import{resolvePrismaQueryOptions as c}from"./utils/helpers/base.middlewares.helpers.js";export function callNext(t,e,n){n()}export function sendResponse(t,e){Number(t?.responseStatus)===204?e.status(Number(t?.responseStatus)).send():t.responseData&&t?.responseStatus?e.status(Number(t?.responseStatus)).json(t.responseData):Number(t?.responseStatus)&&!t.responseData?e.status(Number(t?.responseStatus)).send():e.status(500).json({message:"No status or data attached to the response"})}export function addRouteMiddlwaresAndConfigs(){}export function addPrismaQueryOptionsToRequest(t,e){return(n,i,r)=>{const s=m(),o=c(t,e),a=s?.request?.parameters?.allowDangerousPrismaQueryOptions?JSON.parse(n.query?.prismaQueryOptions||"{}"):{};n.prismaQueryOptions=u(o,a),r()}}export function handleRequestLogs(t,e,n){const i=Date.now(),r={GET:"\x1B[36m",POST:"\x1B[32m",PUT:"\x1B[33m",PATCH:"\x1B[33m",DELETE:"\x1B[31m",HEAD:"\x1B[34m",OPTIONS:"\x1B[34m"},s=o=>o>=200&&o<300?"\x1B[32m":o>=300&&o<400||o>=400&&o<500?"\x1B[33m":o>=500?"\x1B[31m":"\x1B[0m";e.on("finish",()=>{const o=Date.now()-i,p=new Date().toTimeString().split(" ")[0],d=r[t.method]||"\x1B[0m",b=s(e.statusCode);console.info(`[\x1B[
|
|
1
|
+
"use strict";import{getArkosConfig as m}from"../../server.js";import u from"../../utils/helpers/deepmerge.helper.js";import{catchAsync as l}from"../../exports/error-handler/index.js";import f from"../../utils/validate-dto.js";import x from"../../utils/validate-schema.js";import{resolvePrismaQueryOptions as c}from"./utils/helpers/base.middlewares.helpers.js";export function callNext(t,e,n){n()}export function sendResponse(t,e){Number(t?.responseStatus)===204?e.status(Number(t?.responseStatus)).send():t.responseData&&t?.responseStatus?e.status(Number(t?.responseStatus)).json(t.responseData):Number(t?.responseStatus)&&!t.responseData?e.status(Number(t?.responseStatus)).send():e.status(500).json({message:"No status or data attached to the response"})}export function addRouteMiddlwaresAndConfigs(){}export function addPrismaQueryOptionsToRequest(t,e){return(n,i,r)=>{const s=m(),o=c(t,e),a=s?.request?.parameters?.allowDangerousPrismaQueryOptions?JSON.parse(n.query?.prismaQueryOptions||"{}"):{};n.prismaQueryOptions=u(o,a),r()}}export function handleRequestLogs(t,e,n){const i=Date.now(),r={GET:"\x1B[36m",POST:"\x1B[32m",PUT:"\x1B[33m",PATCH:"\x1B[33m",DELETE:"\x1B[31m",HEAD:"\x1B[34m",OPTIONS:"\x1B[34m"},s=o=>o>=200&&o<300?"\x1B[32m":o>=300&&o<400||o>=400&&o<500?"\x1B[33m":o>=500?"\x1B[31m":"\x1B[0m";e.on("finish",()=>{const o=Date.now()-i,p=new Date().toTimeString().split(" ")[0],d=r[t.method]||"\x1B[0m",b=s(e.statusCode);console.info(`[\x1B[36mInfo\x1B[0m] \x1B[90m${p}\x1B[0m ${d}${t.method}\x1B[0m ${decodeURIComponent(t.originalUrl)} ${b}${e.statusCode}\x1B[0m \x1B[35m${o}ms\x1B[0m`)}),n()}export function handleRequestBodyValidationAndTransformation(t,e){return l(async(n,i,r)=>{const s=m()?.validation;let o=n.body;s?.resolver==="class-validator"&&t?n.body=await f(t,o,u({whitelist:!0,...e},s?.validationOptions||{})):s?.resolver==="zod"&&t&&(n.body=await x(t,o)),r()})}
|
|
@@ -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,UAAU,EAAE,MAAM,6BAA6B,CAAC;AACzD,OAAO,WAAW,MAAM,0BAA0B,CAAC;AACnD,OAAO,cAAc,MAAM,6BAA6B,CAAC;AAIzD,OAAO,EAAE,yBAAyB,EAAE,MAAM,0CAA0C,CAAC;AAErF,MAAM,UAAU,QAAQ,CAAC,CAAU,EAAE,EAAY,EAAE,IAAkB;IACnE,IAAI,EAAE,CAAC;AACT,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,GAAiB,EAAE,GAAkB;IAChE,IAAI,MAAM,CAAC,GAAG,EAAE,cAAc,CAAC,KAAK,GAAG;QACrC,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;SAC5C,IAAI,GAAG,CAAC,YAAY,IAAI,GAAG,EAAE,cAAc;QAC9C,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;SAC5D,IAAI,MAAM,CAAC,GAAG,EAAE,cAAc,CAAC,IAAI,CAAC,GAAG,CAAC,YAAY;QACvD,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC,CAAC,IAAI,EAAE,C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AAuC,EACvC,IAAI,EACJ,SAAS,CACP;gBACE,SAAS,EAAE,IAAI;gBACf,GAAG,+BAA+B;aACnC,EACD,iBAAiB,EAAE,iBAAiB,IAAI,EAAE,CAC3C,CACF,CAAC;aACC,IAAI,iBAAiB,EAAE,QAAQ,KAAK,KAAK,IAAI,gBAAgB;YAChE,GAAG,CAAC,IAAI,GAAG,MAAM,cAAc,CAAC,gBAAgC,EAAE,IAAI,CAAC,CAAC;QAE1E,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 { 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\";\n\nexport function callNext(_: Request, _1: Response, next: NextFunction) {\n next();\n}\n\nexport function sendResponse(req: ArkosRequest, res: ArkosResponse) {\n if (Number(req?.responseStatus) === 204)\n res.status(Number(req?.responseStatus)).send();\n else if (req.responseData && req?.responseStatus)\n res.status(Number(req?.responseStatus)).json(req.responseData);\n else if (Number(req?.responseStatus) && !req.responseData)\n res.status(Number(req?.responseStatus)).send();\n else\n res\n .status(500)\n .json({ message: \"No status or data attached to the response\" });\n}\n\nexport function addRouteMiddlwaresAndConfigs() {}\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 // Resolve and merge all applicable options using the helper\n const resolvedOptions = resolvePrismaQueryOptions(\n prismaQueryOptions,\n action\n );\n\n // Parse and merge any dangerous query options from request if allowed\n const requestQueryOptions = configs?.request?.parameters\n ?.allowDangerousPrismaQueryOptions\n ? JSON.parse((req.query?.prismaQueryOptions as string) || \"{}\")\n : {};\n\n // Final merge with request options having the highest priority\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(); // Capture the start time\n\n // Define colors for each HTTP method\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 // Function to determine status code color\n const getStatusColor = (statusCode: number) => {\n if (statusCode >= 200 && statusCode < 300) return \"\\x1b[32m\"; // Green\n if (statusCode >= 300 && statusCode < 400) return \"\\x1b[33m\"; // Orange/Yellow\n if (statusCode >= 400 && statusCode < 500) return \"\\x1b[33m\"; // Red\n if (statusCode >= 500) return \"\\x1b[31m\"; // White on Red background\n return \"\\x1b[0m\"; // Default (no color)\n };\n\n res.on(\"finish\", () => {\n const duration = Date.now() - startTime; // Calculate the time taken to process the request\n\n // Get the current date and time\n const now = new Date();\n const time = now.toTimeString().split(\" \")[0]; // Format as HH:MM:SS\n\n const methodColor =\n methodColors[req.method as keyof typeof methodColors] || \"\\x1b[0m\"; // Default to no color\n const statusColor = getStatusColor(res.statusCode); // Get the color for the status code\n\n console.info(\n `[\\x1b[
|
|
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,UAAU,EAAE,MAAM,6BAA6B,CAAC;AACzD,OAAO,WAAW,MAAM,0BAA0B,CAAC;AACnD,OAAO,cAAc,MAAM,6BAA6B,CAAC;AAIzD,OAAO,EAAE,yBAAyB,EAAE,MAAM,0CAA0C,CAAC;AAErF,MAAM,UAAU,QAAQ,CAAC,CAAU,EAAE,EAAY,EAAE,IAAkB;IACnE,IAAI,EAAE,CAAC;AACT,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,GAAiB,EAAE,GAAkB;IAChE,IAAI,MAAM,CAAC,GAAG,EAAE,cAAc,CAAC,KAAK,GAAG;QACrC,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;SAC5C,IAAI,GAAG,CAAC,YAAY,IAAI,GAAG,EAAE,cAAc;QAC9C,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;SAC5D,IAAI,MAAM,CAAC,GAAG,EAAE,cAAc,CAAC,IAAI,CAAC,GAAG,CAAC,YAAY;QACvD,GAAG,CAAC,MAAM,CAAC,MAAM,CAA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YACvE,GAAG,CAAC,IAAI,GAAG,MAAM,WAAW,CAC1B,gBAAuC,EACvC,IAAI,EACJ,SAAS,CACP;gBACE,SAAS,EAAE,IAAI;gBACf,GAAG,+BAA+B;aACnC,EACD,iBAAiB,EAAE,iBAAiB,IAAI,EAAE,CAC3C,CACF,CAAC;aACC,IAAI,iBAAiB,EAAE,QAAQ,KAAK,KAAK,IAAI,gBAAgB;YAChE,GAAG,CAAC,IAAI,GAAG,MAAM,cAAc,CAAC,gBAAgC,EAAE,IAAI,CAAC,CAAC;QAE1E,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 { 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\";\n\nexport function callNext(_: Request, _1: Response, next: NextFunction) {\n next();\n}\n\nexport function sendResponse(req: ArkosRequest, res: ArkosResponse) {\n if (Number(req?.responseStatus) === 204)\n res.status(Number(req?.responseStatus)).send();\n else if (req.responseData && req?.responseStatus)\n res.status(Number(req?.responseStatus)).json(req.responseData);\n else if (Number(req?.responseStatus) && !req.responseData)\n res.status(Number(req?.responseStatus)).send();\n else\n res\n .status(500)\n .json({ message: \"No status or data attached to the response\" });\n}\n\nexport function addRouteMiddlwaresAndConfigs() {}\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 // Resolve and merge all applicable options using the helper\n const resolvedOptions = resolvePrismaQueryOptions(\n prismaQueryOptions,\n action\n );\n\n // Parse and merge any dangerous query options from request if allowed\n const requestQueryOptions = configs?.request?.parameters\n ?.allowDangerousPrismaQueryOptions\n ? JSON.parse((req.query?.prismaQueryOptions as string) || \"{}\")\n : {};\n\n // Final merge with request options having the highest priority\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(); // Capture the start time\n\n // Define colors for each HTTP method\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 // Function to determine status code color\n const getStatusColor = (statusCode: number) => {\n if (statusCode >= 200 && statusCode < 300) return \"\\x1b[32m\"; // Green\n if (statusCode >= 300 && statusCode < 400) return \"\\x1b[33m\"; // Orange/Yellow\n if (statusCode >= 400 && statusCode < 500) return \"\\x1b[33m\"; // Red\n if (statusCode >= 500) return \"\\x1b[31m\"; // White on Red background\n return \"\\x1b[0m\"; // Default (no color)\n };\n\n res.on(\"finish\", () => {\n const duration = Date.now() - startTime; // Calculate the time taken to process the request\n\n // Get the current date and time\n const now = new Date();\n const time = now.toTimeString().split(\" \")[0]; // Format as HH:MM:SS\n\n const methodColor =\n methodColors[req.method as keyof typeof methodColors] || \"\\x1b[0m\"; // Default to no color\n const statusColor = getStatusColor(res.statusCode); // Get the color for the status code\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(); // Pass control to the next middleware or route handler\n}\n\n// Overload for 'auth'\nexport function handleRequestBodyValidationAndTransformation<T extends object>(\n schemaOrDtoClass?: ClassConstructor<T>,\n classValidatorValidationOptions?: ValidatorOptions\n): ArkosRequestHandler;\n\n// Overload for other models\nexport function handleRequestBodyValidationAndTransformation<T extends object>(\n schemaOrDtoClass?: ZodSchema<T>\n): ArkosRequestHandler;\n\n// Implementation\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"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";import a from"./utils/app-error.js";import*as e from"./utils/error-handler.helpers.js";import{server as i}from"../../server.js";export default function d(o,s,n,
|
|
1
|
+
"use strict";import a from"./utils/app-error.js";import*as e from"./utils/error-handler.helpers.js";import{server as i}from"../../server.js";export default function d(o,s,n,c){if(console.error("[\x1B[31mError\x1B[0m]:",o),o.statusCode=o.statusCode||500,o.status=o.status||"error",process.env.NODE_ENV!=="production"){l(o,s,n);return}let t={...o,message:o.message};o.name==="JsonWebTokenError"&&(t=e.handleJWTError()),o.name==="TokenExpiredError"&&(t=e.handleJWTExpired()),o.name==="PrismaClientValidationError"&&(t=e.handlePrismaClientValidationError(o)),o.code==="P1000"&&(t=e.handleAuthenticationError(o)),o.code==="P1001"&&(t=e.handleServerNotReachableError(o)),o.code==="P1002"&&(t=e.handleConnectionTimeoutError(o)),o.code==="P1003"&&(t=e.handleDatabaseNotFoundError(o)),o.code==="P2000"&&(t=e.handleFieldValueTooLargeError(o)),o.code==="P2001"&&(t=e.handleRecordNotFoundError(o)),o.code==="P2002"&&(t=e.handleUniqueConstraintError(o)),o.code==="P2003"&&(t=e.handleForeignKeyConstraintError(o)),o.code==="P2004"&&(t=e.handleConstraintFailedError(o)),o.code==="P2025"&&(t=e.handleNonExistingRecord(o)),o.code==="P3000"&&(t=e.handleSchemaCreationFailedError(o)),o.code==="P3001"&&(t=e.handleMigrationAlreadyAppliedError(o)),o.code==="P3002"&&(t=e.handleMigrationScriptFailedError(o)),o.code==="P3003"&&(t=e.handleVersionMismatchError(o)),o.name==="NetworkError"&&(t=e.handleNetworkError(o)),t.isOperational||(t=new a("Something went wrong!",500)),r(t,s,n)}function l(o,s,n){s.originalUrl.startsWith("/api")?n.status(o.statusCode).json({...o,message:o.message.split(`
|
|
2
2
|
`)[o.message.split(`
|
|
3
3
|
`).length-1],stack:o.stack?.split(`
|
|
4
|
-
`)}):n.status(o.statusCode).json({title:"Something went wrong!",message:o.message})}function
|
|
4
|
+
`)}):n.status(o.statusCode).json({title:"Something went wrong!",message:o.message})}function r(o,s,n){if(s.originalUrl.startsWith("/api")){o.isOperational?n.status(o.statusCode).json({status:o.status,message:o.message,meta:o.meta||{},code:o.code||"unknown"}):n.status(500).json({status:"error",message:"Something went wrong!"});return}if(o.isOperational){n.status(o.statusCode).json({title:"Something went wrong!",message:o.message});return}n.status(o.statusCode).json({title:"Something went wrong!",message:"Please try again later."})}process.on("SIGTERM",()=>{process.env.NODE_ENV!=="production"&&process.env.NODE_ENV!=="staging"?process.exit():(console.error("SIGTERM RECEIVED in Production. Shutting down gracefully!"),i.close(()=>{console.error("Process terminated!!!"),process.exit()}))});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":"AACA,OAAO,QAAQ,MAAM,mBAAmB,CAAC;AACzC,OAAO,KAAK,qBAAqB,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAiBtC,MAAM,CAAC,OAAO,UAAU,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,IAAkB;IAElB,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;IAE9C,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,IAAI,GAAG,CAAC;IACvC,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,OAAO,CAAC;IAGnC,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY,EAAE,CAAC;QAC1C,oBAAoB,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;QACpC,OAAO;IACT,CAAC;IAGD,IAAI,KAAK,GAAG,EAAE,GAAG,GAAG,EAAE,OAAO,EAAE,GAAG,CAAC,OAAO,EAAE,CAAC;IAG7C,IAAI,GAAG,CAAC,IAAI,KAAK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,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY;QACrC,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,SAAS,EAClC,CAAC;QACD,OAAO,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,KAAK,CAAC,2DAA2D,CAAC,CAAC;QAE3E,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;YACvC,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} next - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n next: NextFunction\n): void {\n console.error(\"[\\x1b[31mERROR\\x1b[0m]:\", err);\n // Default error status\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n // If the environment is not production, send detailed error information\n if (process.env.NODE_ENV !== \"production\") {\n sendDevelopmentError(err, req, res);\n return;\n }\n\n // Prepare error object for response, copying the original error's properties\n let error = { ...err, message: err.message };\n\n // Handle specific error cases (JWT errors, Prisma validation errors, etc.)\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n // Handle specific Prisma client validation errors\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n\n // Handle Prisma database-specific error codes (P1000 to P3005)\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"P2025\")\n error = errorControllerHelper.handleNonExistingRecord(err);\n if (err.code === \"P3000\")\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n if (err.code === \"P3001\")\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n if (err.code === \"P3002\")\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n if (err.code === \"P3003\")\n error = errorControllerHelper.handleVersionMismatchError(err);\n\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n if (!error.isOperational) error = new AppError(\"Something went wrong!\", 500);\n\n // Send the error response for production environment\n sendProductionError(error, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(\n err: AppError,\n req: Request,\n res: Response\n): void {\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n ...err,\n message: err.message.split(\"\\n\")[err.message.split(\"\\n\").length - 1],\n stack: err.stack?.split(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\n message: err.message,\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Something went wrong!\",\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\n message: err.message,\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\n message: \"Please try again later.\",\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (\n process.env.NODE_ENV !== \"production\" &&\n process.env.NODE_ENV !== \"staging\"\n ) {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
|
|
1
|
+
{"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":"AACA,OAAO,QAAQ,MAAM,mBAAmB,CAAC;AACzC,OAAO,KAAK,qBAAqB,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAiBtC,MAAM,CAA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I,CAAC;gBACnB,MAAM,EAAE,OAAO;gBACf,OAAO,EAAE,uBAAuB;aACjC,CAAC,CAAC;QAEL,OAAO;IACT,CAAC;IAED,IAAI,GAAG,CAAC,aAAa,EAAE,CAAC;QACtB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;YAC9B,KAAK,EAAE,uBAAuB;YAC9B,OAAO,EAAE,GAAG,CAAC,OAAO;SACrB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;QAC9B,KAAK,EAAE,uBAAuB;QAC9B,OAAO,EAAE,yBAAyB;KACnC,CAAC,CAAC;AACL,CAAC;AAWD,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;IACzB,IACE,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY;QACrC,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,SAAS,EAClC,CAAC;QACD,OAAO,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,KAAK,CAAC,2DAA2D,CAAC,CAAC;QAE3E,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;YACvC,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} next - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n _: NextFunction\n): void {\n console.error(\"[\\x1b[31mError\\x1b[0m]:\", err);\n // Default error status\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n // If the environment is not production, send detailed error information\n if (process.env.NODE_ENV !== \"production\") {\n sendDevelopmentError(err, req, res);\n return;\n }\n\n // Prepare error object for response, copying the original error's properties\n let error = { ...err, message: err.message };\n\n // Handle specific error cases (JWT errors, Prisma validation errors, etc.)\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n // Handle specific Prisma client validation errors\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n\n // Handle Prisma database-specific error codes (P1000 to P3005)\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"P2025\")\n error = errorControllerHelper.handleNonExistingRecord(err);\n if (err.code === \"P3000\")\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n if (err.code === \"P3001\")\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n if (err.code === \"P3002\")\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n if (err.code === \"P3003\")\n error = errorControllerHelper.handleVersionMismatchError(err);\n\n if (err.name === \"NetworkError\")\n error = errorControllerHelper.handleNetworkError(err);\n if (!error.isOperational) error = new AppError(\"Something went wrong!\", 500);\n\n // Send the error response for production environment\n sendProductionError(error, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(\n err: AppError,\n req: Request,\n res: Response\n): void {\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n ...err,\n message: err.message.split(\"\\n\")[err.message.split(\"\\n\").length - 1],\n stack: err.stack?.split(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\n message: err.message,\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Something went wrong!\",\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\n message: err.message,\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Something went wrong!\",\n message: \"Please try again later.\",\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (\n process.env.NODE_ENV !== \"production\" &&\n process.env.NODE_ENV !== \"staging\"\n ) {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
|