arkos 1.2.13-test.2 → 1.2.14-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.
@@ -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,GAAG,eAAe,CAAC,QAAQ,CAAC,SAAS,CAAC,WAAW,EAAE,CAAC,CAAC;QAGvE,IAAI,WAAW,EAAE,OAAO,EAAE,MAAM,IAAI,WAAW,CAAC,OAAO,CAAC,IAAI,KAAK,QAAQ;YACvE,OAAO,EAAE,CAAC;QAGZ,IAAI,YAAY,EAAE,OAAO,KAAK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O,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)\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;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,gB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AC,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 +1 @@
1
- "use strict";import f from"../../../../utils/prisma/enhaced-prisma-json-schema-generator.js";class h{extractModelNameFromSchemaRef(e){const t=e.match(/#\/components\/schemas\/(?:Create|Update|UpdateMany|FindOne|FindMany|CreateMany)?(.+?)(?:ModelSchema|Schema)$/);if(t){let n=t[1];return n==="Auth"||n==="Login"||n==="Signup"||n==="GetMe"||n==="UpdateMe"||n==="UpdatePassword"?"Auth":n}return null}extractActionFromOperationId(e){return e.includes("createMany")?"createMany":e.includes("updateMany")?"updateMany":e.includes("deleteMany")?"deleteMany":e.startsWith("create")?"createOne":e.startsWith("update")?"updateOne":e.startsWith("delete")?"deleteOne":e.startsWith("find")&&(e.includes("ById")||e.includes("One"))?"findOne":e.startsWith("find")?"findMany":e.includes("login")||e==="login"?"login":e.includes("signup")||e==="signup"?"signup":e.includes("getMe")||e==="getMe"?"getMe":e.includes("updateMe")||e==="updateMe"?"updateMe":e.includes("updatePassword")||e==="updatePassword"?"updatePassword":null}extractModelNameFromOperationId(e){let t=e.replace(/^(create|update|delete|find)Many/i,"").replace(/^(create|update|delete|find)/i,"").replace(/ById$/i,"").replace(/s$/,"");return e.includes("login")||e.includes("signup")||e.includes("getMe")||e.includes("updateMe")||e.includes("updatePassword")?"Auth":t||null}extractSchemaRefsWithContext(e,t=new Map,n={}){return typeof e!="object"||e===null?t:Array.isArray(e)?(e.forEach(c=>this.extractSchemaRefsWithContext(c,t,n)),t):(e.operationId&&typeof e.operationId=="string"&&(n={...n,operationId:e.operationId}),e.$ref&&typeof e.$ref=="string"&&t.set(e.$ref,{...n}),Object.values(e).forEach(c=>{this.extractSchemaRefsWithContext(c,t,n)}),t)}extractPathSchemaRefs(e){const t=new Map;return Object.entries(e).forEach(([n,c])=>{c&&Object.entries(c).forEach(([m,u])=>{if(!u||typeof u!="object")return;const d={method:m,path:n,operationId:u.operationId};this.extractSchemaRefsWithContext(u,t,d)})}),t}getSchemaNameFromRef(e){const t=e.match(/#\/components\/schemas\/(.+)$/);return t?t[1]:null}async generateMissingJsonSchemas(e,t,n){const c={},m=this.extractPathSchemaRefs(e),u=new Map;for(const[d,l]of m){const i=this.getSchemaNameFromRef(d);if(!i||t[i]||!i.includes("ModelSchema")&&!i.includes("Schema"))continue;let s=null,a=null;l.operationId&&(s=this.extractModelNameFromOperationId(l.operationId),a=this.extractActionFromOperationId(l.operationId)),(!s||!a)&&(s=s||this.extractModelNameFromSchemaRef(d),a=a||this.extractActionFromSchemaRef(d)),s&&a&&(u.has(s)||u.set(s,new Set),u.get(s).add(a))}for(const[d,l]of u)try{const i=Array.from(l),s=await f.generateModelSchemas({modelName:d,arkosConfig:n,schemasToGenerate:i});Object.entries(s).forEach(([a,o])=>{let r=a;["auth","login","me","password","me"].includes(d.toLowerCase())?a==="LoginSchema"?r="LoginSchema":a==="SignupSchema"?r="SignupSchema":a==="GetMeSchema"?r="GetMeSchema":a==="UpdateMeSchema"?r="UpdateMeSchema":a==="UpdatePasswordSchema"&&(r="UpdatePasswordSchema"):a.includes("ModelSchema")?r=a:r=`${a}ModelSchema`,c[r]=o})}catch(i){console.warn(`Failed to generate schemas for model ${d}:`,i)}return c}extractActionFromSchemaRef(e){return e.includes("CreateMany")?"createMany":e.includes("Create")?"createOne":e.includes("UpdateMany")?"updateMany":e.includes("Update")&&!e.includes("UpdateMe")&&!e.includes("UpdatePassword")?"updateOne":e.includes("FindMany")?"findMany":e.includes("FindOne")?"findOne":e.includes("Login")?"login":e.includes("Signup")?"signup":e.includes("GetMe")?"getMe":e.includes("UpdateMe")?"updateMe":e.includes("UpdatePassword")?"updatePassword":null}analyzeMissingSchemas(e,t){const n=this.extractPathSchemaRefs(e),c=[],m=[],u=[],d=[];for(const[l,i]of n){const s={ref:l,context:i};c.push(s);const a=this.getSchemaNameFromRef(l);if(a)if(t[a])u.push(s);else{m.push(s);let o=null,r=null;i.operationId&&(o=this.extractModelNameFromOperationId(i.operationId),r=this.extractActionFromOperationId(i.operationId)),(!o||!r)&&(o=o||this.extractModelNameFromSchemaRef(l),r=r||this.extractActionFromSchemaRef(l)),o&&r&&d.push({model:o,action:r,ref:l,operationId:i.operationId})}}return{allRefs:c,missingRefs:m,existingRefs:u,modelActions:d}}}const M=new h;export default M;
1
+ "use strict";import m from"../../../../utils/prisma/enhaced-prisma-json-schema-generator.js";class h{extractModelNameFromSchemaRef(e){const t=e.match(/#\/components\/schemas\/(?:Create|Update|UpdateMany|FindOne|FindMany|CreateMany)?(.+?)(?:ModelSchema|Schema)$/);if(t){let n=t[1];return n==="Auth"||n==="Login"||n==="Signup"||n==="GetMe"||n==="UpdateMe"||n==="UpdatePassword"?"Auth":n}return null}extractActionFromOperationId(e){return e.includes("createMany")?"createMany":e.includes("updateMany")?"updateMany":e.includes("deleteMany")?"deleteMany":e.startsWith("create")?"createOne":e.startsWith("update")?"updateOne":e.startsWith("delete")?"deleteOne":e.startsWith("find")&&(e.includes("ById")||e.includes("One"))?"findOne":e.startsWith("find")?"findMany":e.includes("login")||e==="login"?"login":e.includes("signup")||e==="signup"?"signup":e.includes("getMe")||e==="getMe"?"getMe":e.includes("updateMe")||e==="updateMe"?"updateMe":e.includes("updatePassword")||e==="updatePassword"?"updatePassword":null}extractModelNameFromOperationId(e){let t=e.replace(/^(create|update|delete|find)Many/i,"").replace(/^(create|update|delete|find)/i,"").replace(/ById$/i,"").replace(/s$/,"");return e.includes("login")||e.includes("signup")||e.includes("getMe")||e.includes("updateMe")||e.includes("updatePassword")?"Auth":t||null}extractSchemaRefsWithContext(e,t=new Map,n={}){return typeof e!="object"||e===null?t:Array.isArray(e)?(e.forEach(c=>this.extractSchemaRefsWithContext(c,t,n)),t):(e.operationId&&typeof e.operationId=="string"&&(n={...n,operationId:e.operationId}),e.$ref&&typeof e.$ref=="string"&&t.set(e.$ref,{...n}),Object.values(e).forEach(c=>{this.extractSchemaRefsWithContext(c,t,n)}),t)}extractPathSchemaRefs(e){const t=new Map;return Object.entries(e).forEach(([n,c])=>{c&&Object.entries(c).forEach(([f,u])=>{if(!u||typeof u!="object")return;const d={method:f,path:n,operationId:u.operationId};this.extractSchemaRefsWithContext(u,t,d)})}),t}getSchemaNameFromRef(e){const t=e.match(/#\/components\/schemas\/(.+)$/);return t?t[1]:null}async generateMissingJsonSchemas(e,t,n){const c={},f=this.extractPathSchemaRefs(e),u=new Map;for(const[d,l]of f){const s=this.getSchemaNameFromRef(d);if(!s||t[s]||!s.includes("ModelSchema")&&!s.includes("Schema"))continue;let i=null,a=null;l.operationId&&(i=this.extractModelNameFromOperationId(l.operationId),a=this.extractActionFromOperationId(l.operationId)),(!i||!a)&&(i=i||this.extractModelNameFromSchemaRef(d),a=a||this.extractActionFromSchemaRef(d)),i&&a&&(u.has(i)||u.set(i,new Set),u.get(i).add(a))}for(const[d,l]of u)try{const s=Array.from(l),i=await m.generateModelSchemas({modelName:d,arkosConfig:n,schemasToGenerate:s});Object.entries(i).forEach(([a,o])=>{let r=a;["auth","login","me","password","me"].includes(d.toLowerCase())?a==="LoginSchema"?r="LoginSchema":a==="SignupSchema"?r="SignupSchema":a==="GetMeSchema"?r="GetMeSchema":a==="UpdateMeSchema"?r="UpdateMeSchema":a==="UpdatePasswordSchema"&&(r="UpdatePasswordSchema"):a.includes("ModelSchema")?r=a:r=`${a}ModelSchema`,c[r]=o})}catch{}return c}extractActionFromSchemaRef(e){return e.includes("CreateMany")?"createMany":e.includes("Create")?"createOne":e.includes("UpdateMany")?"updateMany":e.includes("Update")&&!e.includes("UpdateMe")&&!e.includes("UpdatePassword")?"updateOne":e.includes("FindMany")?"findMany":e.includes("FindOne")?"findOne":e.includes("Login")?"login":e.includes("Signup")?"signup":e.includes("GetMe")?"getMe":e.includes("UpdateMe")?"updateMe":e.includes("UpdatePassword")?"updatePassword":null}analyzeMissingSchemas(e,t){const n=this.extractPathSchemaRefs(e),c=[],f=[],u=[],d=[];for(const[l,s]of n){const i={ref:l,context:s};c.push(i);const a=this.getSchemaNameFromRef(l);if(a)if(t[a])u.push(i);else{f.push(i);let o=null,r=null;s.operationId&&(o=this.extractModelNameFromOperationId(s.operationId),r=this.extractActionFromOperationId(s.operationId)),(!o||!r)&&(o=o||this.extractModelNameFromSchemaRef(l),r=r||this.extractActionFromSchemaRef(l)),o&&r&&d.push({model:o,action:r,ref:l,operationId:s.operationId})}}return{allRefs:c,missingRefs:f,existingRefs:u,modelActions:d}}}const M=new h;export default M;
@@ -1 +1 @@
1
- {"version":3,"file":"missing-json-schemas-generator.js","sourceRoot":"","sources":["../../../../../../src/modules/swagger/utils/helpers/missing-json-schemas-generator.ts"],"names":[],"mappings":"AAEA,OAAO,iCAAiC,MAAM,+DAA+D,CAAC;AAK9G,MAAM,2BAA2B;IAOvB,6BAA6B,CAAC,SAAiB;QACrD,MAAM,KAAK,GAAG,SAAS,CAAC,KAAK,CAC3B,+GAA+G,CAChH,CAAC;QACF,IAAI,KAAK,EAAE,CAAC;YACV,IAAI,SAAS,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;YAEzB,IACE,SAAS,KAAK,MAAM;gBACpB,SAAS,KAAK,OAAO;gBACrB,SAAS,KAAK,QAAQ;gBACtB,SAAS,KAAK,OAAO;gBACrB,SAAS,KAAK,UAAU;gBACxB,SAAS,KAAK,gBAAgB,EAC9B,CAAC;gBACD,OAAO,MAAM,CAAC;YAChB,CAAC;YACD,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IASO,4BAA4B,CAAC,WAAmB;QAEtD,IAAI,WAAW,CAAC,QAAQ,CAAC,YAAY,CAAC;YAAE,OAAO,YAAY,CAAC;QAC5D,IAAI,WAAW,CAAC,Q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AChB,KAAK,EAAE,SAAS;wBAChB,MAAM;wBACN,GAAG;wBACH,WAAW,EAAE,OAAO,CAAC,WAAW;qBACjC,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;QACH,CAAC;QAED,OAAO;YACL,OAAO;YACP,WAAW;YACX,YAAY;YACZ,YAAY;SACb,CAAC;IACJ,CAAC;CACF;AAED,MAAM,0BAA0B,GAAG,IAAI,2BAA2B,EAAE,CAAC;AAErE,eAAe,0BAA0B,CAAC","sourcesContent":["import { OpenAPIV3 } from \"openapi-types\";\nimport { ArkosConfig } from \"../../../../exports\";\nimport enhancedPrismaJsonSchemaGenerator from \"../../../../utils/prisma/enhaced-prisma-json-schema-generator\";\n\n/**\n * Used to backfill missing json schema contained in paths in situation such as when using a `arkosConfig.swagger.mode` different from prisma and `strict` to false, in this situation the jsonSchemas paths are filled with $ref pointing to non existent jsonSchema components.\n */\nclass MissingJsonSchemasGenerator {\n /**\n * Extract model name from schema reference\n * @example\n * \"#/components/schemas/CreateUserModelSchema\" -> \"User\"\n * \"#/components/schemas/FindManyPostModelSchema\" -> \"Post\"\n */\n private extractModelNameFromSchemaRef(schemaRef: string): string | null {\n const match = schemaRef.match(\n /#\\/components\\/schemas\\/(?:Create|Update|UpdateMany|FindOne|FindMany|CreateMany)?(.+?)(?:ModelSchema|Schema)$/\n );\n if (match) {\n let modelName = match[1];\n // Handle special auth cases\n if (\n modelName === \"Auth\" ||\n modelName === \"Login\" ||\n modelName === \"Signup\" ||\n modelName === \"GetMe\" ||\n modelName === \"UpdateMe\" ||\n modelName === \"UpdatePassword\"\n ) {\n return \"Auth\";\n }\n return modelName;\n }\n return null;\n }\n\n /**\n * Extract action type from operationId\n * @example\n * \"createManyUser\" -> \"createMany\"\n * \"findUsers\" -> \"findMany\"\n * \"updateUser\" -> \"updateOne\"\n */\n private extractActionFromOperationId(operationId: string): string | null {\n // Handle bulk operations first (more specific patterns)\n if (operationId.includes(\"createMany\")) return \"createMany\";\n if (operationId.includes(\"updateMany\")) return \"updateMany\";\n if (operationId.includes(\"deleteMany\")) return \"deleteMany\";\n\n // Handle single operations\n if (operationId.startsWith(\"create\")) return \"createOne\";\n if (operationId.startsWith(\"update\")) return \"updateOne\";\n if (operationId.startsWith(\"delete\")) return \"deleteOne\";\n if (\n operationId.startsWith(\"find\") &&\n (operationId.includes(\"ById\") || operationId.includes(\"One\"))\n )\n return \"findOne\";\n if (operationId.startsWith(\"find\")) return \"findMany\";\n\n // Handle auth operations\n if (operationId.includes(\"login\") || operationId === \"login\")\n return \"login\";\n if (operationId.includes(\"signup\") || operationId === \"signup\")\n return \"signup\";\n if (operationId.includes(\"getMe\") || operationId === \"getMe\")\n return \"getMe\";\n if (operationId.includes(\"updateMe\") || operationId === \"updateMe\")\n return \"updateMe\";\n if (\n operationId.includes(\"updatePassword\") ||\n operationId === \"updatePassword\"\n )\n return \"updatePassword\";\n\n return null;\n }\n\n /**\n * Extract model name from operationId\n * @example\n * \"createManyUser\" -> \"User\"\n * \"findUsers\" -> \"User\"\n * \"updateUser\" -> \"User\"\n */\n private extractModelNameFromOperationId(operationId: string): string | null {\n // Remove common prefixes and suffixes to isolate model name\n let modelName = operationId\n .replace(/^(create|update|delete|find)Many/i, \"\")\n .replace(/^(create|update|delete|find)/i, \"\")\n .replace(/ById$/i, \"\")\n .replace(/s$/, \"\"); // Remove plural 's'\n\n // Handle auth operations\n if (\n operationId.includes(\"login\") ||\n operationId.includes(\"signup\") ||\n operationId.includes(\"getMe\") ||\n operationId.includes(\"updateMe\") ||\n operationId.includes(\"updatePassword\")\n ) {\n return \"Auth\";\n }\n\n return modelName || null;\n }\n\n /**\n * Recursively extract all $ref values from an object along with their context\n */\n private extractSchemaRefsWithContext(\n obj: any,\n refs: Map<\n string,\n { operationId?: string; method?: string; path?: string }\n > = new Map(),\n context: { operationId?: string; method?: string; path?: string } = {}\n ): Map<string, { operationId?: string; method?: string; path?: string }> {\n if (typeof obj !== \"object\" || obj === null) {\n return refs;\n }\n\n if (Array.isArray(obj)) {\n obj.forEach((item) =>\n this.extractSchemaRefsWithContext(item, refs, context)\n );\n return refs;\n }\n\n // Update context when we find operationId\n if (obj.operationId && typeof obj.operationId === \"string\") {\n context = { ...context, operationId: obj.operationId };\n }\n\n if (obj.$ref && typeof obj.$ref === \"string\") {\n refs.set(obj.$ref, { ...context });\n }\n\n Object.values(obj).forEach((value) => {\n this.extractSchemaRefsWithContext(value, refs, context);\n });\n\n return refs;\n }\n\n /**\n * Extract schema references from paths with context\n */\n private extractPathSchemaRefs(\n paths: OpenAPIV3.PathsObject\n ): Map<string, { operationId?: string; method?: string; path?: string }> {\n const refs = new Map<\n string,\n { operationId?: string; method?: string; path?: string }\n >();\n\n Object.entries(paths).forEach(([path, pathItem]) => {\n if (!pathItem) return;\n\n Object.entries(pathItem).forEach(([method, operation]) => {\n if (!operation || typeof operation !== \"object\") return;\n\n const context = {\n method,\n path,\n operationId: (operation as any).operationId,\n };\n\n this.extractSchemaRefsWithContext(operation, refs, context);\n });\n });\n\n return refs;\n }\n\n /**\n * Extract schema name from $ref\n * @example\n * \"#/components/schemas/CreateUserModelSchema\" -> \"CreateUserModelSchema\"\n */\n private getSchemaNameFromRef(ref: string): string | null {\n const match = ref.match(/#\\/components\\/schemas\\/(.+)$/);\n return match ? match[1] : null;\n }\n\n async generateMissingJsonSchemas(\n currentPaths: OpenAPIV3.PathsObject,\n currentJsonSchemas: Record<string, any>,\n arkosConfig: ArkosConfig\n ): Promise<Record<string, any>> {\n const missingSchemas: Record<string, any> = {};\n\n // Extract all schema references with their context (operationId, method, path)\n const schemaRefsWithContext = this.extractPathSchemaRefs(currentPaths);\n\n // Group missing schemas by model and collect required actions\n const modelActions = new Map<string, Set<string>>();\n\n for (const [ref, context] of schemaRefsWithContext) {\n const schemaName = this.getSchemaNameFromRef(ref);\n if (!schemaName) continue;\n\n // Check if schema already exists\n if (currentJsonSchemas[schemaName]) continue;\n\n // Only process ModelSchema references\n if (!schemaName.includes(\"ModelSchema\") && !schemaName.includes(\"Schema\"))\n continue;\n\n let modelName: string | null = null;\n let action: string | null = null;\n\n // First try to get model and action from operationId (more reliable)\n if (context.operationId) {\n modelName = this.extractModelNameFromOperationId(context.operationId);\n action = this.extractActionFromOperationId(context.operationId);\n }\n\n // Fallback to schema ref analysis if operationId didn't work\n if (!modelName || !action) {\n modelName = modelName || this.extractModelNameFromSchemaRef(ref);\n action = action || this.extractActionFromSchemaRef(ref);\n }\n\n if (modelName && action) {\n if (!modelActions.has(modelName))\n modelActions.set(modelName, new Set());\n\n modelActions.get(modelName)!.add(action);\n }\n }\n\n // Generate schemas for each model\n for (const [modelName, actions] of modelActions) {\n try {\n const actionsArray = Array.from(actions) as any[];\n\n const generatedSchemas =\n await enhancedPrismaJsonSchemaGenerator.generateModelSchemas({\n modelName,\n arkosConfig,\n schemasToGenerate: actionsArray,\n });\n\n // Map generated schemas to the expected naming convention\n Object.entries(generatedSchemas).forEach(([key, schema]) => {\n // The enhanced generator might use different naming conventions\n // We need to map them to match what's expected in the $refs\n let mappedKey = key;\n const authModuleModel = [\"auth\", \"login\", \"me\", \"password\", \"me\"];\n\n // Handle auth schemas\n if (authModuleModel.includes(modelName.toLowerCase())) {\n if (key === \"LoginSchema\") mappedKey = \"LoginSchema\";\n else if (key === \"SignupSchema\") mappedKey = \"SignupSchema\";\n else if (key === \"GetMeSchema\") mappedKey = \"GetMeSchema\";\n else if (key === \"UpdateMeSchema\") mappedKey = \"UpdateMeSchema\";\n else if (key === \"UpdatePasswordSchema\")\n mappedKey = \"UpdatePasswordSchema\";\n } else {\n // Handle model schemas - ensure they match the expected naming pattern\n if (key.includes(\"ModelSchema\")) {\n mappedKey = key;\n } else {\n // Add ModelSchema suffix if missing\n mappedKey = `${key}ModelSchema`;\n }\n }\n\n missingSchemas[mappedKey] = schema;\n });\n } catch (error) {\n console.warn(\n `Failed to generate schemas for model ${modelName}:`,\n error\n );\n }\n }\n\n return missingSchemas;\n }\n\n /**\n * Legacy method - extract action type from schema reference (kept for backward compatibility)\n */\n private extractActionFromSchemaRef(schemaRef: string): string | null {\n if (schemaRef.includes(\"CreateMany\")) return \"createMany\";\n if (schemaRef.includes(\"Create\")) return \"createOne\";\n if (schemaRef.includes(\"UpdateMany\")) return \"updateMany\";\n if (\n schemaRef.includes(\"Update\") &&\n !schemaRef.includes(\"UpdateMe\") &&\n !schemaRef.includes(\"UpdatePassword\")\n )\n return \"updateOne\";\n if (schemaRef.includes(\"FindMany\")) return \"findMany\";\n if (schemaRef.includes(\"FindOne\")) return \"findOne\";\n if (schemaRef.includes(\"Login\")) return \"login\";\n if (schemaRef.includes(\"Signup\")) return \"signup\";\n if (schemaRef.includes(\"GetMe\")) return \"getMe\";\n if (schemaRef.includes(\"UpdateMe\")) return \"updateMe\";\n if (schemaRef.includes(\"UpdatePassword\")) return \"updatePassword\";\n\n return null;\n }\n\n /**\n * Debug method to analyze what schemas are missing with enhanced context\n */\n analyzeMissingSchemas(\n currentPaths: OpenAPIV3.PathsObject,\n currentJsonSchemas: Record<string, any>\n ): {\n allRefs: Array<{ ref: string; context: any }>;\n missingRefs: Array<{ ref: string; context: any }>;\n existingRefs: Array<{ ref: string; context: any }>;\n modelActions: {\n model: string;\n action: string;\n ref: string;\n operationId?: string;\n }[];\n } {\n const schemaRefsWithContext = this.extractPathSchemaRefs(currentPaths);\n\n const allRefs: Array<{ ref: string; context: any }> = [];\n const missingRefs: Array<{ ref: string; context: any }> = [];\n const existingRefs: Array<{ ref: string; context: any }> = [];\n const modelActions: {\n model: string;\n action: string;\n ref: string;\n operationId?: string;\n }[] = [];\n\n for (const [ref, context] of schemaRefsWithContext) {\n const refWithContext = { ref, context };\n allRefs.push(refWithContext);\n\n const schemaName = this.getSchemaNameFromRef(ref);\n if (!schemaName) continue;\n\n if (currentJsonSchemas[schemaName]) {\n existingRefs.push(refWithContext);\n } else {\n missingRefs.push(refWithContext);\n\n let modelName: string | null = null;\n let action: string | null = null;\n\n // Try operationId first\n if (context.operationId) {\n modelName = this.extractModelNameFromOperationId(context.operationId);\n action = this.extractActionFromOperationId(context.operationId);\n }\n\n // Fallback to schema ref\n if (!modelName || !action) {\n modelName = modelName || this.extractModelNameFromSchemaRef(ref);\n action = action || this.extractActionFromSchemaRef(ref);\n }\n\n if (modelName && action) {\n modelActions.push({\n model: modelName,\n action,\n ref,\n operationId: context.operationId,\n });\n }\n }\n }\n\n return {\n allRefs,\n missingRefs,\n existingRefs,\n modelActions,\n };\n }\n}\n\nconst missingJsonSchemaGenerator = new MissingJsonSchemasGenerator();\n\nexport default missingJsonSchemaGenerator;\n"]}
1
+ {"version":3,"file":"missing-json-schemas-generator.js","sourceRoot":"","sources":["../../../../../../src/modules/swagger/utils/helpers/missing-json-schemas-generator.ts"],"names":[],"mappings":"AAEA,OAAO,iCAAiC,MAAM,+DAA+D,CAAC;AAK9G,MAAM,2BAA2B;IAOvB,6BAA6B,CAAC,SAAiB;QACrD,MAAM,KAAK,GAAG,SAAS,CAAC,KAAK,CAC3B,+GAA+G,CAChH,CAAC;QACF,IAAI,KAAK,EAAE,CAAC;YACV,IAAI,SAAS,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;YAEzB,IACE,SAAS,KAAK,MAAM;gBACpB,SAAS,KAAK,OAAO;gBACrB,SAAS,KAAK,QAAQ;gBACtB,SAAS,KAAK,OAAO;gBACrB,SAAS,KAAK,UAAU;gBACxB,SAAS,KAAK,gBAAgB,EAC9B,CAAC;gBACD,OAAO,MAAM,CAAC;YAChB,CAAC;YACD,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IASO,4BAA4B,CAAC,WAAmB;QAEtD,IAAI,WAAW,CAAC,QAAQ,CAAC,YAAY,CAAC;YAAE,OAAO,YAAY,CAAC;QAC5D,IAAI,WAAW,CAAC,QAAQ,CAAC,YAAY,CAAC;YAAE,OAAO,YAAY,CAAC;QAC5D,IAAI,WAAW,CAAC,QAAQ,CAAC,YAAY,CAAC;YAAE,OAAO,YAAY,CAAC;QAG5D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AC;IACJ,CAAC;CACF;AAED,MAAM,0BAA0B,GAAG,IAAI,2BAA2B,EAAE,CAAC;AAErE,eAAe,0BAA0B,CAAC","sourcesContent":["import { OpenAPIV3 } from \"openapi-types\";\nimport { ArkosConfig } from \"../../../../exports\";\nimport enhancedPrismaJsonSchemaGenerator from \"../../../../utils/prisma/enhaced-prisma-json-schema-generator\";\n\n/**\n * Used to backfill missing json schema contained in paths in situation such as when using a `arkosConfig.swagger.mode` different from prisma and `strict` to false, in this situation the jsonSchemas paths are filled with $ref pointing to non existent jsonSchema components.\n */\nclass MissingJsonSchemasGenerator {\n /**\n * Extract model name from schema reference\n * @example\n * \"#/components/schemas/CreateUserModelSchema\" -> \"User\"\n * \"#/components/schemas/FindManyPostModelSchema\" -> \"Post\"\n */\n private extractModelNameFromSchemaRef(schemaRef: string): string | null {\n const match = schemaRef.match(\n /#\\/components\\/schemas\\/(?:Create|Update|UpdateMany|FindOne|FindMany|CreateMany)?(.+?)(?:ModelSchema|Schema)$/\n );\n if (match) {\n let modelName = match[1];\n // Handle special auth cases\n if (\n modelName === \"Auth\" ||\n modelName === \"Login\" ||\n modelName === \"Signup\" ||\n modelName === \"GetMe\" ||\n modelName === \"UpdateMe\" ||\n modelName === \"UpdatePassword\"\n ) {\n return \"Auth\";\n }\n return modelName;\n }\n return null;\n }\n\n /**\n * Extract action type from operationId\n * @example\n * \"createManyUser\" -> \"createMany\"\n * \"findUsers\" -> \"findMany\"\n * \"updateUser\" -> \"updateOne\"\n */\n private extractActionFromOperationId(operationId: string): string | null {\n // Handle bulk operations first (more specific patterns)\n if (operationId.includes(\"createMany\")) return \"createMany\";\n if (operationId.includes(\"updateMany\")) return \"updateMany\";\n if (operationId.includes(\"deleteMany\")) return \"deleteMany\";\n\n // Handle single operations\n if (operationId.startsWith(\"create\")) return \"createOne\";\n if (operationId.startsWith(\"update\")) return \"updateOne\";\n if (operationId.startsWith(\"delete\")) return \"deleteOne\";\n if (\n operationId.startsWith(\"find\") &&\n (operationId.includes(\"ById\") || operationId.includes(\"One\"))\n )\n return \"findOne\";\n if (operationId.startsWith(\"find\")) return \"findMany\";\n\n // Handle auth operations\n if (operationId.includes(\"login\") || operationId === \"login\")\n return \"login\";\n if (operationId.includes(\"signup\") || operationId === \"signup\")\n return \"signup\";\n if (operationId.includes(\"getMe\") || operationId === \"getMe\")\n return \"getMe\";\n if (operationId.includes(\"updateMe\") || operationId === \"updateMe\")\n return \"updateMe\";\n if (\n operationId.includes(\"updatePassword\") ||\n operationId === \"updatePassword\"\n )\n return \"updatePassword\";\n\n return null;\n }\n\n /**\n * Extract model name from operationId\n * @example\n * \"createManyUser\" -> \"User\"\n * \"findUsers\" -> \"User\"\n * \"updateUser\" -> \"User\"\n */\n private extractModelNameFromOperationId(operationId: string): string | null {\n // Remove common prefixes and suffixes to isolate model name\n let modelName = operationId\n .replace(/^(create|update|delete|find)Many/i, \"\")\n .replace(/^(create|update|delete|find)/i, \"\")\n .replace(/ById$/i, \"\")\n .replace(/s$/, \"\"); // Remove plural 's'\n\n // Handle auth operations\n if (\n operationId.includes(\"login\") ||\n operationId.includes(\"signup\") ||\n operationId.includes(\"getMe\") ||\n operationId.includes(\"updateMe\") ||\n operationId.includes(\"updatePassword\")\n ) {\n return \"Auth\";\n }\n\n return modelName || null;\n }\n\n /**\n * Recursively extract all $ref values from an object along with their context\n */\n private extractSchemaRefsWithContext(\n obj: any,\n refs: Map<\n string,\n { operationId?: string; method?: string; path?: string }\n > = new Map(),\n context: { operationId?: string; method?: string; path?: string } = {}\n ): Map<string, { operationId?: string; method?: string; path?: string }> {\n if (typeof obj !== \"object\" || obj === null) {\n return refs;\n }\n\n if (Array.isArray(obj)) {\n obj.forEach((item) =>\n this.extractSchemaRefsWithContext(item, refs, context)\n );\n return refs;\n }\n\n // Update context when we find operationId\n if (obj.operationId && typeof obj.operationId === \"string\") {\n context = { ...context, operationId: obj.operationId };\n }\n\n if (obj.$ref && typeof obj.$ref === \"string\") {\n refs.set(obj.$ref, { ...context });\n }\n\n Object.values(obj).forEach((value) => {\n this.extractSchemaRefsWithContext(value, refs, context);\n });\n\n return refs;\n }\n\n /**\n * Extract schema references from paths with context\n */\n private extractPathSchemaRefs(\n paths: OpenAPIV3.PathsObject\n ): Map<string, { operationId?: string; method?: string; path?: string }> {\n const refs = new Map<\n string,\n { operationId?: string; method?: string; path?: string }\n >();\n\n Object.entries(paths).forEach(([path, pathItem]) => {\n if (!pathItem) return;\n\n Object.entries(pathItem).forEach(([method, operation]) => {\n if (!operation || typeof operation !== \"object\") return;\n\n const context = {\n method,\n path,\n operationId: (operation as any).operationId,\n };\n\n this.extractSchemaRefsWithContext(operation, refs, context);\n });\n });\n\n return refs;\n }\n\n /**\n * Extract schema name from $ref\n * @example\n * \"#/components/schemas/CreateUserModelSchema\" -> \"CreateUserModelSchema\"\n */\n private getSchemaNameFromRef(ref: string): string | null {\n const match = ref.match(/#\\/components\\/schemas\\/(.+)$/);\n return match ? match[1] : null;\n }\n\n async generateMissingJsonSchemas(\n currentPaths: OpenAPIV3.PathsObject,\n currentJsonSchemas: Record<string, any>,\n arkosConfig: ArkosConfig\n ): Promise<Record<string, any>> {\n const missingSchemas: Record<string, any> = {};\n\n // Extract all schema references with their context (operationId, method, path)\n const schemaRefsWithContext = this.extractPathSchemaRefs(currentPaths);\n\n // Group missing schemas by model and collect required actions\n const modelActions = new Map<string, Set<string>>();\n\n for (const [ref, context] of schemaRefsWithContext) {\n const schemaName = this.getSchemaNameFromRef(ref);\n if (!schemaName) continue;\n\n // Check if schema already exists\n if (currentJsonSchemas[schemaName]) continue;\n\n // Only process ModelSchema references\n if (!schemaName.includes(\"ModelSchema\") && !schemaName.includes(\"Schema\"))\n continue;\n\n let modelName: string | null = null;\n let action: string | null = null;\n\n // First try to get model and action from operationId (more reliable)\n if (context.operationId) {\n modelName = this.extractModelNameFromOperationId(context.operationId);\n action = this.extractActionFromOperationId(context.operationId);\n }\n\n // Fallback to schema ref analysis if operationId didn't work\n if (!modelName || !action) {\n modelName = modelName || this.extractModelNameFromSchemaRef(ref);\n action = action || this.extractActionFromSchemaRef(ref);\n }\n\n if (modelName && action) {\n if (!modelActions.has(modelName))\n modelActions.set(modelName, new Set());\n\n modelActions.get(modelName)!.add(action);\n }\n }\n\n // Generate schemas for each model\n for (const [modelName, actions] of modelActions) {\n try {\n const actionsArray = Array.from(actions) as any[];\n\n const generatedSchemas =\n await enhancedPrismaJsonSchemaGenerator.generateModelSchemas({\n modelName,\n arkosConfig,\n schemasToGenerate: actionsArray,\n });\n\n // Map generated schemas to the expected naming convention\n Object.entries(generatedSchemas).forEach(([key, schema]) => {\n // The enhanced generator might use different naming conventions\n // We need to map them to match what's expected in the $refs\n let mappedKey = key;\n const authModuleModel = [\"auth\", \"login\", \"me\", \"password\", \"me\"];\n\n // Handle auth schemas\n if (authModuleModel.includes(modelName.toLowerCase())) {\n if (key === \"LoginSchema\") mappedKey = \"LoginSchema\";\n else if (key === \"SignupSchema\") mappedKey = \"SignupSchema\";\n else if (key === \"GetMeSchema\") mappedKey = \"GetMeSchema\";\n else if (key === \"UpdateMeSchema\") mappedKey = \"UpdateMeSchema\";\n else if (key === \"UpdatePasswordSchema\")\n mappedKey = \"UpdatePasswordSchema\";\n } else {\n // Handle model schemas - ensure they match the expected naming pattern\n if (key.includes(\"ModelSchema\")) {\n mappedKey = key;\n } else {\n // Add ModelSchema suffix if missing\n mappedKey = `${key}ModelSchema`;\n }\n }\n\n missingSchemas[mappedKey] = schema;\n });\n } catch (error) {\n // FIXME: check if all models are being generarted if so simply keep the error ssilent\n // console.warn(\n // `Failed to generate schemas for model ${modelName}:`,\n // error\n // );\n }\n }\n\n return missingSchemas;\n }\n\n /**\n * Legacy method - extract action type from schema reference (kept for backward compatibility)\n */\n private extractActionFromSchemaRef(schemaRef: string): string | null {\n if (schemaRef.includes(\"CreateMany\")) return \"createMany\";\n if (schemaRef.includes(\"Create\")) return \"createOne\";\n if (schemaRef.includes(\"UpdateMany\")) return \"updateMany\";\n if (\n schemaRef.includes(\"Update\") &&\n !schemaRef.includes(\"UpdateMe\") &&\n !schemaRef.includes(\"UpdatePassword\")\n )\n return \"updateOne\";\n if (schemaRef.includes(\"FindMany\")) return \"findMany\";\n if (schemaRef.includes(\"FindOne\")) return \"findOne\";\n if (schemaRef.includes(\"Login\")) return \"login\";\n if (schemaRef.includes(\"Signup\")) return \"signup\";\n if (schemaRef.includes(\"GetMe\")) return \"getMe\";\n if (schemaRef.includes(\"UpdateMe\")) return \"updateMe\";\n if (schemaRef.includes(\"UpdatePassword\")) return \"updatePassword\";\n\n return null;\n }\n\n /**\n * Debug method to analyze what schemas are missing with enhanced context\n */\n analyzeMissingSchemas(\n currentPaths: OpenAPIV3.PathsObject,\n currentJsonSchemas: Record<string, any>\n ): {\n allRefs: Array<{ ref: string; context: any }>;\n missingRefs: Array<{ ref: string; context: any }>;\n existingRefs: Array<{ ref: string; context: any }>;\n modelActions: {\n model: string;\n action: string;\n ref: string;\n operationId?: string;\n }[];\n } {\n const schemaRefsWithContext = this.extractPathSchemaRefs(currentPaths);\n\n const allRefs: Array<{ ref: string; context: any }> = [];\n const missingRefs: Array<{ ref: string; context: any }> = [];\n const existingRefs: Array<{ ref: string; context: any }> = [];\n const modelActions: {\n model: string;\n action: string;\n ref: string;\n operationId?: string;\n }[] = [];\n\n for (const [ref, context] of schemaRefsWithContext) {\n const refWithContext = { ref, context };\n allRefs.push(refWithContext);\n\n const schemaName = this.getSchemaNameFromRef(ref);\n if (!schemaName) continue;\n\n if (currentJsonSchemas[schemaName]) {\n existingRefs.push(refWithContext);\n } else {\n missingRefs.push(refWithContext);\n\n let modelName: string | null = null;\n let action: string | null = null;\n\n // Try operationId first\n if (context.operationId) {\n modelName = this.extractModelNameFromOperationId(context.operationId);\n action = this.extractActionFromOperationId(context.operationId);\n }\n\n // Fallback to schema ref\n if (!modelName || !action) {\n modelName = modelName || this.extractModelNameFromSchemaRef(ref);\n action = action || this.extractActionFromSchemaRef(ref);\n }\n\n if (modelName && action) {\n modelActions.push({\n model: modelName,\n action,\n ref,\n operationId: context.operationId,\n });\n }\n }\n }\n\n return {\n allRefs,\n missingRefs,\n existingRefs,\n modelActions,\n };\n }\n}\n\nconst missingJsonSchemaGenerator = new MissingJsonSchemasGenerator();\n\nexport default missingJsonSchemaGenerator;\n"]}
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
@@ -1,5 +1,5 @@
1
- "use strict";import{bootstrap as p}from"./app.js";import i from"./utils/helpers/deepmerge.helper.js";import a from"http";import{initializePrismaModels as c}from"./utils/helpers/models.helpers.js";import o from"./utils/sheu.js";import{capitalize as l}from"./utils/helpers/text.helpers.js";process.on("uncaughtException",e=>{o.error(`
1
+ "use strict";import{bootstrap as i}from"./app.js";import p from"./utils/helpers/deepmerge.helper.js";import a from"http";import{initializePrismaModels as c}from"./utils/helpers/models.helpers.js";import o from"./utils/sheu.js";import{capitalize as l}from"./utils/helpers/text.helpers.js";process.on("uncaughtException",e=>{e.message.includes("EPIPE")||(o.error(`
2
2
  UNCAUGHT EXCEPTION! SHUTTING DOWN...
3
- `,{timestamp:!0,bold:!0}),console.error(e.name,e.message),console.error(e),process.exit(1)});let r,t;export let _arkosConfig={welcomeMessage:"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com",port:Number(process.env.CLI_PORT)||Number(process.env.PORT)||8e3,host:process.env.CLI_HOST||process.env.HOST||"localhost",fileUpload:{baseUploadDir:"uploads",baseRoute:"/api/uploads"},available:!1};async function m(e={}){c(),_arkosConfig.available=!0,_arkosConfig=i(_arkosConfig,e);const s=process.env.CLI_PORT||_arkosConfig.port||process.env.PORT||"port"in _arkosConfig?_arkosConfig.port:8e3;t=await p(_arkosConfig);const n=new Date().toTimeString().split(" ")[0];return s?(r=a.createServer(t),_arkosConfig?.configureServer&&await _arkosConfig.configureServer(r),r.listen(Number(s),_arkosConfig.host,()=>{o.ready(`${o.gray(n)} ${l(process.env.NODE_ENV||"development")} server waiting on http://${_arkosConfig.host||"localhost"}:${s}`)})):o.warn(`${o.gray(n)} port set to undefined, hence no internal http server was setup.`),t}process.on("unhandledRejection",e=>{o.error(`
3
+ `,{timestamp:!0,bold:!0}),console.error(e.name,e.message),console.error(e),process.exit(1))});let r,t;export let _arkosConfig={welcomeMessage:"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com",port:Number(process.env.CLI_PORT)||Number(process.env.PORT)||8e3,host:process.env.CLI_HOST||process.env.HOST||"localhost",fileUpload:{baseUploadDir:"uploads",baseRoute:"/api/uploads"},available:!1};async function m(e={}){c(),_arkosConfig.available=!0,_arkosConfig=p(_arkosConfig,e);const s=process.env.CLI_PORT||_arkosConfig.port||process.env.PORT||"port"in _arkosConfig?_arkosConfig.port:8e3;t=await i(_arkosConfig);const n=new Date().toTimeString().split(" ")[0];return s?(r=a.createServer(t),_arkosConfig?.configureServer&&await _arkosConfig.configureServer(r),r.listen(Number(s),_arkosConfig.host,()=>{o.ready(`${o.gray(n)} ${l(process.env.NODE_ENV||"development")} server waiting on http://${_arkosConfig.host||"localhost"}:${s}`)})):o.warn(`${o.gray(n)} port set to undefined, hence no internal http server was setup.`),t}process.on("unhandledRejection",e=>{o.error(`
4
4
  UNHANDLED REJECTION! SHUTTING DOWN...
5
5
  `,{timestamp:!0,bold:!0}),console.error(e.name,e.message),console.error(e),r?.close(()=>{process.exit(1)})});export function terminateApplicationRunningProcessAndServer(){r?.close(()=>{process.exit(1)})}export function getArkosConfig(){return _arkosConfig}export function getExpressApp(){return t}export{r as server,m as initApp};
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAElC,OAAO,SAAS,MAAM,kCAAkC,CAAC;AACzD,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AACxE,OAAO,IAAI,MAAM,cAAc,CA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CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAOH,MAAM,UAAU,2CAA2C;IACzD,MAAM,EAAE,KAAK,CAAC,GAAG,EAAE;QACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC;AAOD,MAAM,UAAU,cAAc;IAC5B,OAAO,YAAY,CAAC;AACtB,CAAC;AAED,MAAM,UAAU,aAAa;IAC3B,OAAO,IAAI,CAAC;AACd,CAAC;AAED,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC","sourcesContent":["import { IncomingMessage, Server, ServerResponse } from \"http\";\nimport AppError from \"./modules/error-handler/utils/app-error\";\nimport { Express } from \"express\";\nimport { bootstrap } from \"./app\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport http from \"http\";\nimport { initializePrismaModels } from \"./utils/helpers/models.helpers\";\nimport sheu from \"./utils/sheu\";\nimport { capitalize } from \"./utils/helpers/text.helpers\";\n\nprocess.on(\"uncaughtException\", (err) => {\n // if (err.message.includes(\"EPIPE\")) return;\n\n sheu.error(\"\\nUNCAUGHT EXCEPTION! SHUTTING DOWN...\\n\", {\n timestamp: true,\n bold: true,\n });\n console.error(err.name, err.message);\n console.error(err);\n process.exit(1);\n});\n\nlet server: Server<typeof IncomingMessage, typeof ServerResponse>;\nlet _app: Express;\n\nexport let _arkosConfig: ArkosConfig & { available?: boolean } = {\n welcomeMessage:\n \"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com\",\n port: Number(process.env.CLI_PORT) || Number(process.env.PORT) || 8000,\n host: process.env.CLI_HOST || process.env.HOST || \"localhost\",\n fileUpload: {\n baseUploadDir: \"uploads\",\n baseRoute: \"/api/uploads\",\n },\n available: false,\n};\n\n/**\n * Initializes the application server.\n *\n * This function starts the server by listening on a specified port.\n * The port is determined by the following order of precedence:\n * 1. The `port` argument passed to the function.\n * 2. Defaults to `8000` if neither is provided.\n *\n * @param {ArkosConfig} arkosConfig - initial configs for the api ( authentication, port).\n * @returns {Promise<Express>} This function returns the Express App after all middlewares configurations.\n * You can prevent it from listen py passing port as undefined\n *\n */\nasync function initApp(arkosConfig: ArkosConfig = {}): Promise<Express> {\n initializePrismaModels();\n _arkosConfig.available = true;\n _arkosConfig = deepmerge(_arkosConfig, arkosConfig);\n\n const port =\n process.env.CLI_PORT ||\n _arkosConfig.port ||\n process.env.PORT ||\n \"port\" in _arkosConfig\n ? _arkosConfig.port\n : 8000;\n\n _app = await bootstrap(_arkosConfig);\n const time = new Date().toTimeString().split(\" \")[0];\n\n if (port) {\n server = http.createServer(_app);\n\n if (_arkosConfig?.configureServer)\n await _arkosConfig.configureServer(server);\n\n server.listen(Number(port), _arkosConfig.host!, () => {\n sheu.ready(\n `${sheu.gray(time)} ${capitalize(process.env.NODE_ENV || \"development\")} server waiting on http://${_arkosConfig.host || \"localhost\"}:${port}`\n );\n });\n } else {\n sheu.warn(\n `${sheu.gray(time)} port set to undefined, hence no internal http server was setup.`\n );\n }\n\n return _app;\n}\n\nprocess.on(\"unhandledRejection\", (err: AppError) => {\n sheu.error(\"\\nUNHANDLED REJECTION! SHUTTING DOWN...\\n\", {\n timestamp: true,\n bold: true,\n });\n console.error(err.name, err.message);\n console.error(err);\n server?.close(() => {\n process.exit(1);\n });\n});\n\n/**\n * Terminates the current running express application, server and process.\n *\n * @returns {void}\n */\nexport function terminateApplicationRunningProcessAndServer(): void {\n server?.close(() => {\n process.exit(1);\n });\n}\n\n/**\n * Gives access to the underlying current configurations being used by **Arkos** by default and also passed through `arkos.init()`\n *\n * @returns {ArkosConfig}\n */\nexport function getArkosConfig(): ArkosConfig {\n return _arkosConfig;\n}\n\nexport function getExpressApp() {\n return _app;\n}\n\nexport { server, initApp };\n"]}
1
+ {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":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,CAAC,KAAK,CAAC,2CAA2C,EAAE;QACtD,SAAS,EAAE,IAAI;QACf,IAAI,EAAE,IAAI;KACX,CAAC,CAAC;IACH,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,MAAM,EAAE,KAAK,CAAC,GAAG,EAAE;QACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAOH,MAAM,UAAU,2CAA2C;IACzD,MAAM,EAAE,KAAK,CAAC,GAAG,EAAE;QACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC;AAOD,MAAM,UAAU,cAAc;IAC5B,OAAO,YAAY,CAAC;AACtB,CAAC;AAED,MAAM,UAAU,aAAa;IAC3B,OAAO,IAAI,CAAC;AACd,CAAC;AAED,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC","sourcesContent":["import { IncomingMessage, Server, ServerResponse } from \"http\";\nimport AppError from \"./modules/error-handler/utils/app-error\";\nimport { Express } from \"express\";\nimport { bootstrap } from \"./app\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport http from \"http\";\nimport { initializePrismaModels } from \"./utils/helpers/models.helpers\";\nimport sheu from \"./utils/sheu\";\nimport { capitalize } from \"./utils/helpers/text.helpers\";\n\nprocess.on(\"uncaughtException\", (err) => {\n if (err.message.includes(\"EPIPE\")) return;\n\n sheu.error(\"\\nUNCAUGHT EXCEPTION! SHUTTING DOWN...\\n\", {\n timestamp: true,\n bold: true,\n });\n console.error(err.name, err.message);\n console.error(err);\n process.exit(1);\n});\n\nlet server: Server<typeof IncomingMessage, typeof ServerResponse>;\nlet _app: Express;\n\nexport let _arkosConfig: ArkosConfig & { available?: boolean } = {\n welcomeMessage:\n \"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com\",\n port: Number(process.env.CLI_PORT) || Number(process.env.PORT) || 8000,\n host: process.env.CLI_HOST || process.env.HOST || \"localhost\",\n fileUpload: {\n baseUploadDir: \"uploads\",\n baseRoute: \"/api/uploads\",\n },\n available: false,\n};\n\n/**\n * Initializes the application server.\n *\n * This function starts the server by listening on a specified port.\n * The port is determined by the following order of precedence:\n * 1. The `port` argument passed to the function.\n * 2. Defaults to `8000` if neither is provided.\n *\n * @param {ArkosConfig} arkosConfig - initial configs for the api ( authentication, port).\n * @returns {Promise<Express>} This function returns the Express App after all middlewares configurations.\n * You can prevent it from listen py passing port as undefined\n *\n */\nasync function initApp(arkosConfig: ArkosConfig = {}): Promise<Express> {\n initializePrismaModels();\n _arkosConfig.available = true;\n _arkosConfig = deepmerge(_arkosConfig, arkosConfig);\n\n const port =\n process.env.CLI_PORT ||\n _arkosConfig.port ||\n process.env.PORT ||\n \"port\" in _arkosConfig\n ? _arkosConfig.port\n : 8000;\n\n _app = await bootstrap(_arkosConfig);\n const time = new Date().toTimeString().split(\" \")[0];\n\n if (port) {\n server = http.createServer(_app);\n\n if (_arkosConfig?.configureServer)\n await _arkosConfig.configureServer(server);\n\n server.listen(Number(port), _arkosConfig.host!, () => {\n sheu.ready(\n `${sheu.gray(time)} ${capitalize(process.env.NODE_ENV || \"development\")} server waiting on http://${_arkosConfig.host || \"localhost\"}:${port}`\n );\n });\n } else {\n sheu.warn(\n `${sheu.gray(time)} port set to undefined, hence no internal http server was setup.`\n );\n }\n\n return _app;\n}\n\nprocess.on(\"unhandledRejection\", (err: AppError) => {\n sheu.error(\"\\nUNHANDLED REJECTION! SHUTTING DOWN...\\n\", {\n timestamp: true,\n bold: true,\n });\n console.error(err.name, err.message);\n console.error(err);\n server?.close(() => {\n process.exit(1);\n });\n});\n\n/**\n * Terminates the current running express application, server and process.\n *\n * @returns {void}\n */\nexport function terminateApplicationRunningProcessAndServer(): void {\n server?.close(() => {\n process.exit(1);\n });\n}\n\n/**\n * Gives access to the underlying current configurations being used by **Arkos** by default and also passed through `arkos.init()`\n *\n * @returns {ArkosConfig}\n */\nexport function getArkosConfig(): ArkosConfig {\n return _arkosConfig;\n}\n\nexport function getExpressApp() {\n return _app;\n}\n\nexport { server, initApp };\n"]}
@@ -1,4 +1,4 @@
1
- "use strict";import{spawn as x}from"child_process";import{watch as T}from"chokidar";import{fullCleanCwd as s,getUserFileExtension as S}from"../helpers/fs.helpers.js";import{getVersion as b}from"./utils/cli.helpers.js";import{loadEnvironmentVariables as E}from"../dotenv.helpers.js";import{importModule as y}from"../helpers/global.helpers.js";import O from"fs";import _ from"path";import j from"../sheu.js";let o=null,i;export async function devCommand($={}){process.env.NODE_ENV="development",i=E(),o=null;let r=null;try{const{port:l,host:u}=$;let h=!1;const g=S(),c=_.resolve(process.cwd(),`src/app.${g}`);O.existsSync(c)||(console.error(`Could not find application entry point at ${c}`),process.exit(1));const a=()=>({NODE_ENV:"development",...process.env,...l&&{CLI_PORT:l},...u&&{CLI_HOST:u}}),d=()=>{o&&(o.kill(),o=null);const e=a();g==="ts"?o=x("npx",["ts-node-dev","--respawn","--notify=false","--ignore-watch","node_modules","--ignore-watch","dist","--ignore-watch","build","--ignore-watch",".dist","--ignore-watch",".build","--watch","src",c],{stdio:"inherit",env:e,shell:!0}):o=x("npx",["node-dev","--respawn","--notify=false","--ignore","node_modules","--ignore","dist","--ignore","build","--ignore",".dist","--ignore",".build","--watch","src",c],{stdio:"inherit",env:e,shell:!0}),o&&(o.on("error",n=>{console.error("Failed to start server:",n)}),o.on("exit",(n,t)=>{!h&&t!=="SIGTERM"&&t!=="SIGINT"&&(console.info(`Server exited with code ${n}, restarting...`),d())}))},f=e=>{r&&clearTimeout(r);const t=new Date().toTimeString().split(" ")[0];j.info(`\x1B[90m${t}\x1B[0m Restarting: ${e.toLowerCase()}`),h=!0,o&&(o.kill(),o=null),r=setTimeout(()=>{d(),r=null},1e3)},k=()=>{const e=T(s(i?.join(",")||"").replaceAll("/","").split(",")||[],{ignoreInitial:!0,persistent:!0});return e.on("all",(n,t)=>{try{i=E(),f("Environments files changed")}catch(m){console.error(`Error reloading ${t}:`,m)}}),e},I=()=>{const e=T(["src","package.json","tsconfig.json","jsconfig.json","arkos.config.ts","arkos.config.js"],{ignoreInitial:!0,ignored:[/node_modules/,/\.git/,/\.dist/,/\.build/,/dist/,/build/,/\.env.*/],awaitWriteFinish:{stabilityThreshold:3e3}});return e.on("add",n=>{f(`${s(n)} has been created`)}),e.on("unlink",n=>{f(`${s(n)} has been deleted`)}),e};d();const v=k(),w=I(),C=async()=>{try{const{getArkosConfig:e}=await y("../../server"),n=e();if(n&&n.available){const t=a();return console.info(`
1
+ "use strict";import{spawn as x}from"child_process";import{watch as T}from"chokidar";import{fullCleanCwd as s,getUserFileExtension as S}from"../helpers/fs.helpers.js";import{getVersion as b}from"./utils/cli.helpers.js";import{loadEnvironmentVariables as E}from"../dotenv.helpers.js";import{importModule as y}from"../helpers/global.helpers.js";import O from"fs";import _ from"path";import j from"../sheu.js";let o=null,i;export async function devCommand($={}){process.env.NODE_ENV="development",i=E(),o=null;let r=null;try{const{port:l,host:u}=$;let h=!1;const g=S(),c=_.resolve(process.cwd(),`src/app.${g}`);O.existsSync(c)||(console.error(`Could not find application entry point at ${c}`),process.exit(1));const a=()=>({NODE_ENV:"development",...process.env,...l&&{CLI_PORT:l},...u&&{CLI_HOST:u}}),d=()=>{o&&(o.kill(),o=null);const e=a();g==="ts"?o=x("npx",["ts-node-dev","--respawn","--notify=false","--ignore-watch","node_modules","--ignore-watch","dist","--ignore-watch","build","--ignore-watch",".dist","--ignore-watch",".build","--watch","src",c],{stdio:"inherit",env:e,shell:!0}):o=x("npx",["node-dev","--respawn","--notify=false","--ignore","node_modules","--ignore","dist","--ignore","build","--ignore",".dist","--ignore",".build",c],{stdio:"inherit",env:e,shell:!0}),o&&(o.on("error",n=>{console.error("Failed to start server:",n)}),o.on("exit",(n,t)=>{!h&&t!=="SIGTERM"&&t!=="SIGINT"&&(console.info(`Server exited with code ${n}, restarting...`),d())}))},f=e=>{r&&clearTimeout(r);const t=new Date().toTimeString().split(" ")[0];j.info(`\x1B[90m${t}\x1B[0m Restarting: ${e.toLowerCase()}`),h=!0,o&&(o.kill(),o=null),r=setTimeout(()=>{d(),r=null},1e3)},k=()=>{const e=T(s(i?.join(",")||"").replaceAll("/","").split(",")||[],{ignoreInitial:!0,persistent:!0});return e.on("all",(n,t)=>{try{i=E(),f("Environments files changed")}catch(m){console.error(`Error reloading ${t}:`,m)}}),e},I=()=>{const e=T(["src","package.json","tsconfig.json","jsconfig.json","arkos.config.ts","arkos.config.js"],{ignoreInitial:!0,ignored:[/node_modules/,/\.git/,/\.dist/,/\.build/,/dist/,/build/,/\.env.*/],awaitWriteFinish:{stabilityThreshold:3e3}});return e.on("add",n=>{f(`${s(n)} has been created`)}),e.on("unlink",n=>{f(`${s(n)} has been deleted`)}),e};d();const v=k(),w=I(),C=async()=>{try{const{getArkosConfig:e}=await y("../../server"),n=e();if(n&&n.available){const t=a();return console.info(`
2
2
  `),console.info(` \x1B[1m\x1B[36m Arkos.js ${b()}\x1B[0m`),console.info(` - Local: http://${t.CLI_HOST||n.host||t.HOST||"localhost"}:${t.CLI_PORT||n.port||t.PORT||"8000"}`),console.info(` - Environments: ${s(i?.join(", ")||"").replaceAll(`${process.cwd()}/`,"").replaceAll("/","")}`),console.info(`
3
3
  `),!0}return!1}catch(e){const n=e?.message;return!n.includes("../../server")&&!n.includes("cjs/server")&&console.info(e),!1}};(async()=>{let e=0;const n=15;for(;e<n&&!await C();)await new Promise(m=>setTimeout(m,150)),e++;if(e>=n){const t=a();console.info(`
4
4
  `),console.info(` \x1B[1m\x1B[36m Arkos.js ${b()}\x1B[0m`),console.info(` - Local: http://${t.CLI_HOST||t.HOST||"localhost"}:${t.CLI_PORT||t.PORT||"8000"}`),console.info(` - Environments: ${s(i?.join(", ")||"").replaceA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O,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC;AAKD,MAAM,UAAU,iCAAiC;IAC9C,KAAsB,EAAE,IAAI,EAAE,EAAE,CAAC;IAClC,KAAK,GAAG,IAAI,CAAC;AACf,CAAC","sourcesContent":["import { spawn, ChildProcess } from \"child_process\";\nimport { watch } from \"chokidar\";\nimport { fullCleanCwd, getUserFileExtension } from \"../helpers/fs.helpers\";\nimport { getVersion } from \"./utils/cli.helpers\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\nimport { importModule } from \"../helpers/global.helpers\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport sheu from \"../sheu\";\n\ninterface DevOptions {\n port?: string;\n host?: string;\n}\n\nlet child: ChildProcess | null = null;\nlet envFiles: string[] | undefined;\n\n/**\n * Dev server command for the arkos CLI\n */\nexport async function devCommand(options: DevOptions = {}) {\n process.env.NODE_ENV = \"development\";\n envFiles = loadEnvironmentVariables();\n child = null;\n let restartTimeout: NodeJS.Timeout | null = null;\n\n try {\n const { port, host } = options;\n let isRestarting = false;\n // Detect if project uses TypeScript or JavaScript\n const fileExt = getUserFileExtension();\n\n // Find the application entry point\n const entryPoint = path.resolve(process.cwd(), `src/app.${fileExt}`);\n\n if (!fs.existsSync(entryPoint)) {\n console.error(`Could not find application entry point at ${entryPoint}`);\n process.exit(1);\n }\n\n // Set environment variables\n const getEnv = () =>\n ({\n NODE_ENV: \"development\",\n ...process.env,\n ...(port && { CLI_PORT: port }),\n ...(host && { CLI_HOST: host }),\n }) as { [x: string]: string };\n\n // Function to start the child process\n const startServer = () => {\n if (child) {\n child.kill();\n child = null;\n }\n\n const env = getEnv();\n\n if (fileExt === \"ts\") {\n // Enhanced ts-node-dev configuration\n child = spawn(\n \"npx\",\n [\n \"ts-node-dev\",\n \"--respawn\",\n \"--notify=false\", // Disable desktop notifications\n \"--ignore-watch\",\n \"node_modules\",\n \"--ignore-watch\",\n \"dist\",\n \"--ignore-watch\",\n \"build\",\n \"--ignore-watch\",\n \".dist\",\n \"--ignore-watch\",\n \".build\",\n \"--watch\",\n \"src\", // Explicitly watch src directory\n entryPoint,\n ],\n {\n stdio: \"inherit\",\n env,\n shell: true,\n }\n );\n } else {\n // Enhanced nodemon configuration\n\n child = spawn(\n \"npx\",\n [\n \"node-dev\",\n \"--respawn\",\n \"--notify=false\",\n \"--ignore\",\n \"node_modules\",\n \"--ignore\",\n \"dist\",\n \"--ignore\",\n \"build\",\n \"--ignore\",\n \".dist\",\n \"--ignore\",\n \".build\",\n \"--watch\",\n \"src\",\n entryPoint,\n ],\n {\n stdio: \"inherit\",\n env,\n shell: true,\n }\n );\n }\n\n if (child) {\n child.on(\"error\", (error) => {\n console.error(\"Failed to start server:\", error);\n });\n\n child.on(\"exit\", (code, signal) => {\n if (!isRestarting && signal !== \"SIGTERM\" && signal !== \"SIGINT\") {\n console.info(`Server exited with code ${code}, restarting...`);\n startServer();\n }\n });\n }\n };\n\n // Function to handle server restart with debouncing\n const scheduleRestart = (reason: string) => {\n if (restartTimeout) clearTimeout(restartTimeout);\n const now = new Date();\n const time = now.toTimeString().split(\" \")[0];\n\n sheu.info(`\\x1b[90m${time}\\x1b[0m Restarting: ${reason.toLowerCase()}`);\n\n isRestarting = true;\n if (child) {\n child.kill();\n child = null;\n }\n restartTimeout = setTimeout(() => {\n startServer();\n restartTimeout = null;\n }, 1000);\n };\n\n // Setup environment file watching\n const setupEnvWatcher = () => {\n const envWatcher = watch(\n fullCleanCwd(envFiles?.join(\",\") || \"\")\n .replaceAll(\"/\", \"\")\n .split(\",\") || [],\n {\n ignoreInitial: true,\n persistent: true,\n }\n );\n\n envWatcher.on(\"all\", (_, filePath) => {\n try {\n envFiles = loadEnvironmentVariables();\n\n // Restart server to pick up new env vars\n scheduleRestart(\"Environments files changed\");\n } catch (error) {\n console.error(`Error reloading ${filePath}:`, error);\n }\n });\n\n return envWatcher;\n };\n\n // Setup additional file watching for better new file detection\n const setupAdditionalWatcher = () => {\n const additionalWatcher = watch(\n [\n \"src\",\n \"package.json\",\n \"tsconfig.json\",\n \"jsconfig.json\",\n \"arkos.config.ts\",\n \"arkos.config.js\",\n ],\n {\n ignoreInitial: true,\n ignored: [\n /node_modules/,\n /\\.git/,\n /\\.dist/,\n /\\.build/,\n /dist/,\n /build/,\n /\\.env.*/,\n ],\n awaitWriteFinish: {\n stabilityThreshold: 3000,\n },\n }\n );\n\n additionalWatcher.on(\"add\", (filePath) => {\n scheduleRestart(`${fullCleanCwd(filePath)} has been created`);\n });\n\n additionalWatcher.on(\"unlink\", (filePath) => {\n scheduleRestart(`${fullCleanCwd(filePath)} has been deleted`);\n });\n\n return additionalWatcher;\n };\n\n // Start the server\n startServer();\n\n // Setup watchers if enabled\n const envWatcher = setupEnvWatcher();\n const additionalWatcher = setupAdditionalWatcher();\n\n const checkConfig = async () => {\n try {\n // Import the config getter\n const { getArkosConfig } = await importModule(\"../../server\");\n const config = getArkosConfig();\n if (config && config.available) {\n // Config is ready, display the info with actual values\n const env = getEnv();\n console.info(\"\\n\");\n console.info(` \\x1b[1m\\x1b[36m Arkos.js ${getVersion()}\\x1b[0m`);\n console.info(\n ` - Local: http://${\n env.CLI_HOST || config.host || env.HOST || \"localhost\"\n }:${env.CLI_PORT || config.port || env.PORT || \"8000\"}`\n );\n console.info(\n ` - Environments: ${fullCleanCwd(envFiles?.join(\", \") || \"\")\n .replaceAll(`${process.cwd()}/`, \"\")\n .replaceAll(\"/\", \"\")}`\n );\n console.info(\"\\n\");\n return true;\n }\n return false;\n } catch (err: any) {\n const message = err?.message;\n if (\n !message.includes(\"../../server\") &&\n !message.includes(\"cjs/server\")\n )\n console.info(err);\n return false;\n }\n };\n\n // Try to get config periodically\n const waitForConfig = async () => {\n let attempts = 0;\n const maxAttempts = 15;\n while (attempts < maxAttempts) {\n const ready = await checkConfig();\n if (ready) break;\n await new Promise((resolve) => setTimeout(resolve, 150));\n attempts++;\n }\n\n // Fall back to defaults if config never became available\n if (attempts >= maxAttempts) {\n const env = getEnv();\n console.info(\"\\n\");\n console.info(` \\x1b[1m\\x1b[36m Arkos.js ${getVersion()}\\x1b[0m`);\n console.info(\n ` - Local: http://${\n env.CLI_HOST || env.HOST || \"localhost\"\n }:${env.CLI_PORT || env.PORT || \"8000\"}`\n );\n console.info(\n ` - Environments: ${fullCleanCwd(envFiles?.join(\", \") || \"\")\n .replaceAll(`${process.cwd()}/`, \"\")\n .replaceAll(\"/\", \"\")}`\n );\n console.info(\"\\n\");\n }\n };\n\n waitForConfig();\n\n // Enhanced cleanup function\n const cleanup = () => {\n if (restartTimeout) clearTimeout(restartTimeout);\n\n if (envWatcher) envWatcher.close();\n\n if (additionalWatcher) additionalWatcher.close();\n\n if (child) {\n child.kill(\"SIGTERM\");\n\n // Force kill after 5 seconds if still running\n setTimeout(() => {\n if (child && !child.killed) child.kill(\"SIGKILL\");\n }, 5000);\n }\n\n process.exit(0);\n };\n\n // Handle process exit\n process.on(\"SIGINT\", cleanup);\n process.on(\"SIGTERM\", cleanup);\n\n // Handle uncaught exceptions\n process.on(\"uncaughtException\", (error) => {\n console.error(\"Uncaught Exception:\", error);\n cleanup();\n });\n } catch (error) {\n console.error(\"Development server failed to start:\", error);\n\n if (child) {\n (child as ChildProcess)?.kill?.();\n child = null;\n }\n\n process.exit(1);\n }\n}\n\n/**\n * Help function to help other processes to terminate the development server child process\n */\nexport function killDevelopmentServerChildProcess() {\n (child as ChildProcess)?.kill?.();\n child = null;\n}\n"]}
1
+ {"version":3,"file":"dev.js","sourceRoot":"","sources":["../../../../src/utils/cli/dev.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAgB,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,KAAK,EAAE,MAAM,UAAU,CAAC;AACjC,OAAO,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC3E,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAE,wBAAwB,EAAE,MA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AE,CAAC;gBACV,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;gBAGtB,UAAU,CAAC,GAAG,EAAE;oBACd,IAAI,KAAK,IAAI,CAAC,KAAK,CAAC,MAAM;wBAAE,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;gBACpD,CAAC,EAAE,IAAI,CAAC,CAAC;YACX,CAAC;YAED,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAClB,CAAC,CAAC;QAGF,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;QAC9B,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QAG/B,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,KAAK,EAAE,EAAE;YACxC,OAAO,CAAC,KAAK,CAAC,qBAAqB,EAAE,KAAK,CAAC,CAAC;YAC5C,OAAO,EAAE,CAAC;QACZ,CAAC,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CAAC,qCAAqC,EAAE,KAAK,CAAC,CAAC;QAE5D,IAAI,KAAK,EAAE,CAAC;YACT,KAAsB,EAAE,IAAI,EAAE,EAAE,CAAC;YAClC,KAAK,GAAG,IAAI,CAAC;QACf,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC;AAKD,MAAM,UAAU,iCAAiC;IAC9C,KAAsB,EAAE,IAAI,EAAE,EAAE,CAAC;IAClC,KAAK,GAAG,IAAI,CAAC;AACf,CAAC","sourcesContent":["import { spawn, ChildProcess } from \"child_process\";\nimport { watch } from \"chokidar\";\nimport { fullCleanCwd, getUserFileExtension } from \"../helpers/fs.helpers\";\nimport { getVersion } from \"./utils/cli.helpers\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\nimport { importModule } from \"../helpers/global.helpers\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport sheu from \"../sheu\";\n\ninterface DevOptions {\n port?: string;\n host?: string;\n}\n\nlet child: ChildProcess | null = null;\nlet envFiles: string[] | undefined;\n\n/**\n * Dev server command for the arkos CLI\n */\nexport async function devCommand(options: DevOptions = {}) {\n process.env.NODE_ENV = \"development\";\n envFiles = loadEnvironmentVariables();\n child = null;\n let restartTimeout: NodeJS.Timeout | null = null;\n\n try {\n const { port, host } = options;\n let isRestarting = false;\n // Detect if project uses TypeScript or JavaScript\n const fileExt = getUserFileExtension();\n\n // Find the application entry point\n const entryPoint = path.resolve(process.cwd(), `src/app.${fileExt}`);\n\n if (!fs.existsSync(entryPoint)) {\n console.error(`Could not find application entry point at ${entryPoint}`);\n process.exit(1);\n }\n\n // Set environment variables\n const getEnv = () =>\n ({\n NODE_ENV: \"development\",\n ...process.env,\n ...(port && { CLI_PORT: port }),\n ...(host && { CLI_HOST: host }),\n }) as { [x: string]: string };\n\n // Function to start the child process\n const startServer = () => {\n if (child) {\n child.kill();\n child = null;\n }\n\n const env = getEnv();\n\n if (fileExt === \"ts\") {\n // Enhanced ts-node-dev configuration\n child = spawn(\n \"npx\",\n [\n \"ts-node-dev\",\n \"--respawn\",\n \"--notify=false\", // Disable desktop notifications\n \"--ignore-watch\",\n \"node_modules\",\n \"--ignore-watch\",\n \"dist\",\n \"--ignore-watch\",\n \"build\",\n \"--ignore-watch\",\n \".dist\",\n \"--ignore-watch\",\n \".build\",\n \"--watch\",\n \"src\", // Explicitly watch src directory\n entryPoint,\n ],\n {\n stdio: \"inherit\",\n env,\n shell: true,\n }\n );\n } else {\n // Enhanced nodemon configuration\n\n child = spawn(\n \"npx\",\n [\n \"node-dev\",\n \"--respawn\",\n \"--notify=false\",\n \"--ignore\",\n \"node_modules\",\n \"--ignore\",\n \"dist\",\n \"--ignore\",\n \"build\",\n \"--ignore\",\n \".dist\",\n \"--ignore\",\n \".build\",\n entryPoint,\n ],\n {\n stdio: \"inherit\",\n env,\n shell: true,\n }\n );\n }\n\n if (child) {\n child.on(\"error\", (error) => {\n console.error(\"Failed to start server:\", error);\n });\n\n child.on(\"exit\", (code, signal) => {\n if (!isRestarting && signal !== \"SIGTERM\" && signal !== \"SIGINT\") {\n console.info(`Server exited with code ${code}, restarting...`);\n startServer();\n }\n });\n }\n };\n\n // Function to handle server restart with debouncing\n const scheduleRestart = (reason: string) => {\n if (restartTimeout) clearTimeout(restartTimeout);\n const now = new Date();\n const time = now.toTimeString().split(\" \")[0];\n\n sheu.info(`\\x1b[90m${time}\\x1b[0m Restarting: ${reason.toLowerCase()}`);\n\n isRestarting = true;\n if (child) {\n child.kill();\n child = null;\n }\n restartTimeout = setTimeout(() => {\n startServer();\n restartTimeout = null;\n }, 1000);\n };\n\n // Setup environment file watching\n const setupEnvWatcher = () => {\n const envWatcher = watch(\n fullCleanCwd(envFiles?.join(\",\") || \"\")\n .replaceAll(\"/\", \"\")\n .split(\",\") || [],\n {\n ignoreInitial: true,\n persistent: true,\n }\n );\n\n envWatcher.on(\"all\", (_, filePath) => {\n try {\n envFiles = loadEnvironmentVariables();\n\n // Restart server to pick up new env vars\n scheduleRestart(\"Environments files changed\");\n } catch (error) {\n console.error(`Error reloading ${filePath}:`, error);\n }\n });\n\n return envWatcher;\n };\n\n // Setup additional file watching for better new file detection\n const setupAdditionalWatcher = () => {\n const additionalWatcher = watch(\n [\n \"src\",\n \"package.json\",\n \"tsconfig.json\",\n \"jsconfig.json\",\n \"arkos.config.ts\",\n \"arkos.config.js\",\n ],\n {\n ignoreInitial: true,\n ignored: [\n /node_modules/,\n /\\.git/,\n /\\.dist/,\n /\\.build/,\n /dist/,\n /build/,\n /\\.env.*/,\n ],\n awaitWriteFinish: {\n stabilityThreshold: 3000,\n },\n }\n );\n\n additionalWatcher.on(\"add\", (filePath) => {\n scheduleRestart(`${fullCleanCwd(filePath)} has been created`);\n });\n\n additionalWatcher.on(\"unlink\", (filePath) => {\n scheduleRestart(`${fullCleanCwd(filePath)} has been deleted`);\n });\n\n return additionalWatcher;\n };\n\n // Start the server\n startServer();\n\n // Setup watchers if enabled\n const envWatcher = setupEnvWatcher();\n const additionalWatcher = setupAdditionalWatcher();\n\n const checkConfig = async () => {\n try {\n // Import the config getter\n const { getArkosConfig } = await importModule(\"../../server\");\n const config = getArkosConfig();\n if (config && config.available) {\n // Config is ready, display the info with actual values\n const env = getEnv();\n console.info(\"\\n\");\n console.info(` \\x1b[1m\\x1b[36m Arkos.js ${getVersion()}\\x1b[0m`);\n console.info(\n ` - Local: http://${\n env.CLI_HOST || config.host || env.HOST || \"localhost\"\n }:${env.CLI_PORT || config.port || env.PORT || \"8000\"}`\n );\n console.info(\n ` - Environments: ${fullCleanCwd(envFiles?.join(\", \") || \"\")\n .replaceAll(`${process.cwd()}/`, \"\")\n .replaceAll(\"/\", \"\")}`\n );\n console.info(\"\\n\");\n return true;\n }\n return false;\n } catch (err: any) {\n const message = err?.message;\n if (\n !message.includes(\"../../server\") &&\n !message.includes(\"cjs/server\")\n )\n console.info(err);\n return false;\n }\n };\n\n // Try to get config periodically\n const waitForConfig = async () => {\n let attempts = 0;\n const maxAttempts = 15;\n while (attempts < maxAttempts) {\n const ready = await checkConfig();\n if (ready) break;\n await new Promise((resolve) => setTimeout(resolve, 150));\n attempts++;\n }\n\n // Fall back to defaults if config never became available\n if (attempts >= maxAttempts) {\n const env = getEnv();\n console.info(\"\\n\");\n console.info(` \\x1b[1m\\x1b[36m Arkos.js ${getVersion()}\\x1b[0m`);\n console.info(\n ` - Local: http://${\n env.CLI_HOST || env.HOST || \"localhost\"\n }:${env.CLI_PORT || env.PORT || \"8000\"}`\n );\n console.info(\n ` - Environments: ${fullCleanCwd(envFiles?.join(\", \") || \"\")\n .replaceAll(`${process.cwd()}/`, \"\")\n .replaceAll(\"/\", \"\")}`\n );\n console.info(\"\\n\");\n }\n };\n\n waitForConfig();\n\n // Enhanced cleanup function\n const cleanup = () => {\n if (restartTimeout) clearTimeout(restartTimeout);\n\n if (envWatcher) envWatcher.close();\n\n if (additionalWatcher) additionalWatcher.close();\n\n if (child) {\n child.kill(\"SIGTERM\");\n\n // Force kill after 5 seconds if still running\n setTimeout(() => {\n if (child && !child.killed) child.kill(\"SIGKILL\");\n }, 5000);\n }\n\n process.exit(0);\n };\n\n // Handle process exit\n process.on(\"SIGINT\", cleanup);\n process.on(\"SIGTERM\", cleanup);\n\n // Handle uncaught exceptions\n process.on(\"uncaughtException\", (error) => {\n console.error(\"Uncaught Exception:\", error);\n cleanup();\n });\n } catch (error) {\n console.error(\"Development server failed to start:\", error);\n\n if (child) {\n (child as ChildProcess)?.kill?.();\n child = null;\n }\n\n process.exit(1);\n }\n}\n\n/**\n * Help function to help other processes to terminate the development server child process\n */\nexport function killDevelopmentServerChildProcess() {\n (child as ChildProcess)?.kill?.();\n child = null;\n}\n"]}
@@ -1 +1 @@
1
- "use strict";import e from"fs";import{killDevelopmentServerChildProcess as o}from"../dev.js";import{killProductionServerChildProcess as i}from"../start.js";export function ensureDirectoryExists(r){e.existsSync(r)||e.mkdirSync(r,{recursive:!0})}export function killServerChildProcess(){o(),i()}export function getVersion(){return"1.2.13-test.2"}
1
+ "use strict";import e from"fs";import{killDevelopmentServerChildProcess as o}from"../dev.js";import{killProductionServerChildProcess as i}from"../start.js";export function ensureDirectoryExists(r){e.existsSync(r)||e.mkdirSync(r,{recursive:!0})}export function killServerChildProcess(){o(),i()}export function getVersion(){return"1.2.14-beta"}
@@ -1 +1 @@
1
- "use strict";import h from"../helpers/deepmerge.helper.js";import{importPrismaModelModules as f,localValidatorFileExists as p}from"../helpers/models.helpers.js";import y from"./prisma-schema-parser.js";export class EnhancedPrismaJsonSchemaGenerator{constructor(){this.schema=y.parse()}async generateModelSchemas(t){const{modelName:a,arkosConfig:e,schemasToGenerate:i=["model","login","signup","getMe","updateMe","updatePassword","create","createOne","createMany","update","updateOne","updateMany","query","findOne","findMany"]}=t,n=await f(a,e),s=n?.router?.config||{},r=n?.prismaQueryOptions||{},d=["auth","me","password","signup","login"].includes(a.toLowerCase());if(e?.swagger?.strict&&e.swagger.mode!=="prisma")return{};if(s?.disable===!0)return{};const c=this.schema.models.find(u=>u.name.toLowerCase()===a.toLowerCase());if(!c&&!d)throw new Error(`Model ${a} not found in schema`);const l={};return d?await this.generateAuthSchemas(this.schema.models.find(u=>u.name.toLowerCase()==="user"),l,e,i,r):c&&await this.generateCrudSchemas(c,l,e,i,r,s),{...l}}async generateAuthSchemas(t,a,e,i,n,s){const r="Auth";if(!e?.authentication)return a;i.includes("login")&&!this.isEndpointDisabled("login",s)&&!await p("login",r,e)&&(a.LoginSchema=this.generateLoginSchema(e)),i.includes("signup")&&!this.isEndpointDisabled("signup",s)&&!await p("signup",r,e)&&(a.SignupSchema=this.generateSignupSchema(t,n?.signup)),i.includes("updateMe")&&!this.isEndpointDisabled("updateMe",s)&&!await p("updateMe",r,e)&&(a.UpdateMeSchema=this.generateUpdateMeSchema(t,n?.updateMe)),i.includes("updatePassword")&&!this.isEndpointDisabled("updatePassword",s)&&!await p("updatePassword",r,e)&&(a.UpdatePasswordSchema=this.generateUpdatePasswordSchema(t,n?.updatePassword)),i.includes("getMe")&&!this.isEndpointDisabled("getMe",s)&&!await p("getMe",r,e)&&(a.GetMeSchema=this.generateResponseSchema(t,n?.getMe||{},"findOne"))}async generateCrudSchemas(t,a,e,i,n,s){const r=t.name,o=async(d,c)=>{const l=e.validation?.resolver==="zod"?"Schema":"Dto";if(await p(d==="Create"?"createOne":"updateOne",c,e))return`${d}${c}${l}`;{const m=`${d}${c}ModelSchema`;return a[m]||(d==="Create"?a[m]=this.generateCreateSchema(t,this.resolvePrismaQueryOptions(n,"createOne")):d==="Update"&&(a[m]=this.generateUpdateSchema(t,this.resolvePrismaQueryOptions(n,"updateOne")))),m}};if(i.includes("createOne")&&!this.isEndpointDisabled("createOne",s)&&!await p("createOne",r,e)&&(a[`Create${r}ModelSchema`]=this.generateCreateSchema(t,this.resolvePrismaQueryOptions(n,"createOne"))),i.includes("createMany")&&!this.isEndpointDisabled("createMany",s)&&!await p("createMany",r,e)){const d=await o("Create",r);a[`CreateMany${r}ModelSchema`]={type:"array",items:{$ref:`#/components/schemas/${d}`}}}if(i.includes("updateOne")&&!this.isEndpointDisabled("updateOne",s)&&!await p("updateOne",r,e)&&(a[`Update${r}ModelSchema`]=this.generateUpdateSchema(t,this.resolvePrismaQueryOptions(n,"updateOne"))),i.includes("updateMany")&&!this.isEndpointDisabled("updateMany",s)&&!await p("updateMany",r,e)){const d=await o("Update",r);a[`UpdateMany${r}ModelSchema`]={type:"object",properties:{data:{type:"object",$ref:`#/components/schemas/${d}`},where:{type:"object"}},required:["data"]}}i.includes("findOne")&&!this.isEndpointDisabled("findOne",s)&&!await p("findOne",r,e)&&(a[`FindOne${r}ModelSchema`]=this.generateResponseSchema(t,this.resolvePrismaQueryOptions(n,"findOne"),"findOne")),i.includes("findMany")&&!this.isEndpointDisabled("findMany",s)&&!await p("findMany",r,e)&&(a[`FindMany${r}ModelSchema`]={type:"array",items:this.generateResponseSchema(t,this.resolvePrismaQueryOptions(n,"findMany"),"findMany")})}generateCreateSchema(t,a){const e={},i=[],n=["createdAt","updatedAt","deletedAt","id"];t.name.toLowerCase()==="auth"&&n.push("roles","role","isActive","isStaff","isSuperUser","passwordChangedAt","deletedSelfAccountAt","lastLoginAt");for(const s of t.fields){if(s.isId||n.includes(s.name))continue;if(this.isModelRelation(s.type)){s.isArray||(e[s.connectionField]={type:this.mapPrismaTypeToJsonSchema(t.fields.find(o=>o.name===s.connectionField)?.type||"String")},!s.isOptional&&s.defaultValue===void 0&&i.push(s.name));continue}const r=this.convertFieldToJsonSchema(s);e[s.name]=r,!s.isOptional&&s.defaultValue===void 0&&!s.isArray&&i.push(s.name)}return{type:"object",properties:e,required:i}}generateUpdateSchema(t,a){const e={},i=["createdAt","updatedAt","deletedAt","id"];for(const n of t.fields){if(n.isId||i.includes(n.name))continue;if(this.isModelRelation(n.type)){n.isArray||(e[n.connectionField]={type:this.mapPrismaTypeToJsonSchema(t.fields.find(r=>r.name===n.connectionField)?.type||"String")});continue}const s=this.convertFieldToJsonSchema(n);e[n.name]=s}return{type:"object",properties:e,required:[]}}generateResponseSchema(t,a,e){const i={},n=[],s=a?.select,r=a?.include;for(const o of t.fields){if(o.name.toLowerCase().includes("password")||s&&!s[o.name])continue;if(this.isModelRelation(o.type)){if(r?.[o.name]){const c=this.schema.models.find(l=>l.name===o.type);if(c){const l=this.generateNestedRelationSchema(c,r[o.name]);i[o.name]=o.isArray?{type:"array",items:l}:l}}continue}const d=this.convertFieldToJsonSchema(o);i[o.name]=d,o.isOptional||n.push(o.name)}return{type:"object",properties:i,required:n}}generateNestedRelationSchema(t,a){const e={},i=[],n=a?.select,s=a?.include;for(const r of t.fields){if(r.name.toLowerCase().includes("password")||n&&!n[r.name])continue;if(this.isModelRelation(r.type)){if(s?.[r.name]){const d=this.schema.models.find(c=>c.name===r.type);if(d){const c=this.generateNestedRelationSchema(d,s[r.name]);e[r.name]=r.isArray?{type:"array",items:c}:c}}continue}const o=this.convertFieldToJsonSchema(r);e[r.name]=o,r.isOptional||i.push(r.name)}return{type:"object",properties:e,required:i}}generateLoginSchema(t){const a=t?.authentication?.login?.allowedUsernames||[],e=n=>n.includes(".")&&n.split(".").pop()||n,i={type:"object",properties:{password:{type:"string",minLength:8}},required:["password"]};if(a.forEach(n=>{const s=e(n);i.properties[s]={type:"string",format:"string",description:`Username field: ${n}`}}),a.length>0){const n=a.map(e);return{...i,anyOf:n.map(()=>({required:[...i.required]}))}}return i}generateSignupSchema(t,a){const e=this.generateCreateSchema(t,a||{});return["roles","role","isActive","isStaff","isSuperUser","passwordChangedAt","deletedSelfAccountAt","lastLoginAt"].forEach(n=>{delete e?.properties?.[n]}),e}generateUpdateMeSchema(t,a){const e=this.generateUpdateSchema(t,a||{});return["roles","role","isActive","isStaff","isSuperUser","passwordChangedAt","deletedSelfAccountAt","password","lastLoginAt"].forEach(n=>{delete e?.properties?.[n]}),e}generateUpdatePasswordSchema(t,a){return{type:"object",properties:{currentPassword:{type:"string"},newPassword:{type:"string",minLength:8}},required:["currentPassword","newPassword"]}}resolvePrismaQueryOptions(t,a){if(!t||!a)return{};const e=t,i=e[a]||{};let n=e.queryOptions||{};e.global&&(n=h(n,e.global));const s=this.getGeneralOptionsForAction(e,a);return s&&(n=h(n,s)),i&&(n=h(n,i)),n}getGeneralOptionsForAction(t,a){const e={find:["findOne","findMany"],create:["createOne","createMany"],update:["updateOne","updateMany"],delete:["deleteOne","deleteMany"],save:["createOne","createMany","updateOne","updateMany"],saveOne:["createOne","updateOne"],saveMany:["createMany","updateMany"]};for(const[i,n]of Object.entries(e))if(n.includes(a)&&t[i])return t[i];return null}isEndpointDisabled(t,a){return a?.disable?typeof a.disable=="boolean"?a.disable:a.disable[t]||!1:!1}isModelRelation(t){return this.schema.models.some(a=>a.name===t)}convertFieldToJsonSchema(t){const e={type:this.mapPrismaTypeToJsonSchema(t.type)};if(t.isArray&&(e.type="array",e.items={type:this.mapPrismaTypeToJsonSchema(t.type)}),t.defaultValue!==void 0&&(e.default=t.defaultValue),t.type==="DateTime"&&(e.format="date-time"),this.isEnum(t.type)){const i=this.schema.enums.find(n=>n.name===t.type);i&&(e.enum=i.values)}return e}mapPrismaTypeToJsonSchema(t){const a={String:"string",Int:"number",Float:"number",Boolean:"boolean",DateTime:"string",Json:"object",Bytes:"string"};return a[t]?a[t]:this.isEnum(t)?"string":this.isModelRelation(t)?"object":"string"}isEnum(t){return this.schema.enums.some(a=>a.name===t)}}const S=new EnhancedPrismaJsonSchemaGenerator;export default S;
1
+ "use strict";import h from"../helpers/deepmerge.helper.js";import{importPrismaModelModules as f,localValidatorFileExists as p}from"../helpers/models.helpers.js";import y from"./prisma-schema-parser.js";export class EnhancedPrismaJsonSchemaGenerator{constructor(){this.schema=y.parse()}async generateModelSchemas(t){const{modelName:a,arkosConfig:e,schemasToGenerate:i=["model","login","signup","getMe","updateMe","updatePassword","create","createOne","createMany","update","updateOne","updateMany","query","findOne","findMany"]}=t,n=await f(a,e),s=n?.router?.config||{},r=n?.prismaQueryOptions||{},d=["auth","me","password","signup","login"].includes(a.toLowerCase());if(e?.swagger?.strict&&e.swagger.mode!=="prisma")return{};if(s?.disable===!0)return{};const c=this.schema.models.find(u=>u.name.toLowerCase()===a.toLowerCase());if(!c&&!d)return{};const l={};return d?await this.generateAuthSchemas(this.schema.models.find(u=>u.name.toLowerCase()==="user"),l,e,i,r):c&&await this.generateCrudSchemas(c,l,e,i,r,s),{...l}}async generateAuthSchemas(t,a,e,i,n,s){const r="Auth";if(!e?.authentication)return a;i.includes("login")&&!this.isEndpointDisabled("login",s)&&!await p("login",r,e)&&(a.LoginSchema=this.generateLoginSchema(e)),i.includes("signup")&&!this.isEndpointDisabled("signup",s)&&!await p("signup",r,e)&&(a.SignupSchema=this.generateSignupSchema(t,n?.signup)),i.includes("updateMe")&&!this.isEndpointDisabled("updateMe",s)&&!await p("updateMe",r,e)&&(a.UpdateMeSchema=this.generateUpdateMeSchema(t,n?.updateMe)),i.includes("updatePassword")&&!this.isEndpointDisabled("updatePassword",s)&&!await p("updatePassword",r,e)&&(a.UpdatePasswordSchema=this.generateUpdatePasswordSchema(t,n?.updatePassword)),i.includes("getMe")&&!this.isEndpointDisabled("getMe",s)&&!await p("getMe",r,e)&&(a.GetMeSchema=this.generateResponseSchema(t,n?.getMe||{},"findOne"))}async generateCrudSchemas(t,a,e,i,n,s){const r=t.name,o=async(d,c)=>{const l=e.validation?.resolver==="zod"?"Schema":"Dto";if(await p(d==="Create"?"createOne":"updateOne",c,e))return`${d}${c}${l}`;{const m=`${d}${c}ModelSchema`;return a[m]||(d==="Create"?a[m]=this.generateCreateSchema(t,this.resolvePrismaQueryOptions(n,"createOne")):d==="Update"&&(a[m]=this.generateUpdateSchema(t,this.resolvePrismaQueryOptions(n,"updateOne")))),m}};if(i.includes("createOne")&&!this.isEndpointDisabled("createOne",s)&&!await p("createOne",r,e)&&(a[`Create${r}ModelSchema`]=this.generateCreateSchema(t,this.resolvePrismaQueryOptions(n,"createOne"))),i.includes("createMany")&&!this.isEndpointDisabled("createMany",s)&&!await p("createMany",r,e)){const d=await o("Create",r);a[`CreateMany${r}ModelSchema`]={type:"array",items:{$ref:`#/components/schemas/${d}`}}}if(i.includes("updateOne")&&!this.isEndpointDisabled("updateOne",s)&&!await p("updateOne",r,e)&&(a[`Update${r}ModelSchema`]=this.generateUpdateSchema(t,this.resolvePrismaQueryOptions(n,"updateOne"))),i.includes("updateMany")&&!this.isEndpointDisabled("updateMany",s)&&!await p("updateMany",r,e)){const d=await o("Update",r);a[`UpdateMany${r}ModelSchema`]={type:"object",properties:{data:{type:"object",$ref:`#/components/schemas/${d}`},where:{type:"object"}},required:["data"]}}i.includes("findOne")&&!this.isEndpointDisabled("findOne",s)&&!await p("findOne",r,e)&&(a[`FindOne${r}ModelSchema`]=this.generateResponseSchema(t,this.resolvePrismaQueryOptions(n,"findOne"),"findOne")),i.includes("findMany")&&!this.isEndpointDisabled("findMany",s)&&!await p("findMany",r,e)&&(a[`FindMany${r}ModelSchema`]={type:"array",items:this.generateResponseSchema(t,this.resolvePrismaQueryOptions(n,"findMany"),"findMany")})}generateCreateSchema(t,a){const e={},i=[],n=["createdAt","updatedAt","deletedAt","id"];t.name.toLowerCase()==="auth"&&n.push("roles","role","isActive","isStaff","isSuperUser","passwordChangedAt","deletedSelfAccountAt","lastLoginAt");for(const s of t.fields){if(s.isId||n.includes(s.name))continue;if(this.isModelRelation(s.type)){s.isArray||(e[s.connectionField]={type:this.mapPrismaTypeToJsonSchema(t.fields.find(o=>o.name===s.connectionField)?.type||"String")},!s.isOptional&&s.defaultValue===void 0&&i.push(s.name));continue}const r=this.convertFieldToJsonSchema(s);e[s.name]=r,!s.isOptional&&s.defaultValue===void 0&&!s.isArray&&i.push(s.name)}return{type:"object",properties:e,required:i}}generateUpdateSchema(t,a){const e={},i=["createdAt","updatedAt","deletedAt","id"];for(const n of t.fields){if(n.isId||i.includes(n.name))continue;if(this.isModelRelation(n.type)){n.isArray||(e[n.connectionField]={type:this.mapPrismaTypeToJsonSchema(t.fields.find(r=>r.name===n.connectionField)?.type||"String")});continue}const s=this.convertFieldToJsonSchema(n);e[n.name]=s}return{type:"object",properties:e,required:[]}}generateResponseSchema(t,a,e){const i={},n=[],s=a?.select,r=a?.include;for(const o of t.fields){if(o.name.toLowerCase().includes("password")||s&&!s[o.name])continue;if(this.isModelRelation(o.type)){if(r?.[o.name]){const c=this.schema.models.find(l=>l.name===o.type);if(c){const l=this.generateNestedRelationSchema(c,r[o.name]);i[o.name]=o.isArray?{type:"array",items:l}:l}}continue}const d=this.convertFieldToJsonSchema(o);i[o.name]=d,o.isOptional||n.push(o.name)}return{type:"object",properties:i,required:n}}generateNestedRelationSchema(t,a){const e={},i=[],n=a?.select,s=a?.include;for(const r of t.fields){if(r.name.toLowerCase().includes("password")||n&&!n[r.name])continue;if(this.isModelRelation(r.type)){if(s?.[r.name]){const d=this.schema.models.find(c=>c.name===r.type);if(d){const c=this.generateNestedRelationSchema(d,s[r.name]);e[r.name]=r.isArray?{type:"array",items:c}:c}}continue}const o=this.convertFieldToJsonSchema(r);e[r.name]=o,r.isOptional||i.push(r.name)}return{type:"object",properties:e,required:i}}generateLoginSchema(t){const a=t?.authentication?.login?.allowedUsernames||[],e=n=>n.includes(".")&&n.split(".").pop()||n,i={type:"object",properties:{password:{type:"string",minLength:8}},required:["password"]};if(a.forEach(n=>{const s=e(n);i.properties[s]={type:"string",format:"string",description:`Username field: ${n}`}}),a.length>0){const n=a.map(e);return{...i,anyOf:n.map(()=>({required:[...i.required]}))}}return i}generateSignupSchema(t,a){const e=this.generateCreateSchema(t,a||{});return["roles","role","isActive","isStaff","isSuperUser","passwordChangedAt","deletedSelfAccountAt","lastLoginAt"].forEach(n=>{delete e?.properties?.[n]}),e}generateUpdateMeSchema(t,a){const e=this.generateUpdateSchema(t,a||{});return["roles","role","isActive","isStaff","isSuperUser","passwordChangedAt","deletedSelfAccountAt","password","lastLoginAt"].forEach(n=>{delete e?.properties?.[n]}),e}generateUpdatePasswordSchema(t,a){return{type:"object",properties:{currentPassword:{type:"string"},newPassword:{type:"string",minLength:8}},required:["currentPassword","newPassword"]}}resolvePrismaQueryOptions(t,a){if(!t||!a)return{};const e=t,i=e[a]||{};let n=e.queryOptions||{};e.global&&(n=h(n,e.global));const s=this.getGeneralOptionsForAction(e,a);return s&&(n=h(n,s)),i&&(n=h(n,i)),n}getGeneralOptionsForAction(t,a){const e={find:["findOne","findMany"],create:["createOne","createMany"],update:["updateOne","updateMany"],delete:["deleteOne","deleteMany"],save:["createOne","createMany","updateOne","updateMany"],saveOne:["createOne","updateOne"],saveMany:["createMany","updateMany"]};for(const[i,n]of Object.entries(e))if(n.includes(a)&&t[i])return t[i];return null}isEndpointDisabled(t,a){return a?.disable?typeof a.disable=="boolean"?a.disable:a.disable[t]||!1:!1}isModelRelation(t){return this.schema.models.some(a=>a.name===t)}convertFieldToJsonSchema(t){const e={type:this.mapPrismaTypeToJsonSchema(t.type)};if(t.isArray&&(e.type="array",e.items={type:this.mapPrismaTypeToJsonSchema(t.type)}),t.defaultValue!==void 0&&(e.default=t.defaultValue),t.type==="DateTime"&&(e.format="date-time"),this.isEnum(t.type)){const i=this.schema.enums.find(n=>n.name===t.type);i&&(e.enum=i.values)}return e}mapPrismaTypeToJsonSchema(t){const a={String:"string",Int:"number",Float:"number",Boolean:"boolean",DateTime:"string",Json:"object",Bytes:"string"};return a[t]?a[t]:this.isEnum(t)?"string":this.isModelRelation(t)?"object":"string"}isEnum(t){return this.schema.enums.some(a=>a.name===t)}}const S=new EnhancedPrismaJsonSchemaGenerator;export default S;