prisma-zod-generator
Version:
Prisma 2+ generator to emit Zod schemas from your Prisma schema
270 lines (269 loc) • 9.47 kB
TypeScript
/**
* Zod Comment Parser
*
* Parses @zod validation annotations from Prisma schema field comments
* to generate enhanced Zod validation schemas.
*/
import { DMMF } from '@prisma/generator-helper';
/**
* Interface for field comment context including metadata for error reporting
*/
export interface FieldCommentContext {
modelName: string;
fieldName: string;
fieldType: string;
comment: string;
isOptional: boolean;
isList: boolean;
}
/**
* Interface for extracted field comments with processing status
*/
export interface ExtractedFieldComment {
context: FieldCommentContext;
normalizedComment: string;
hasZodAnnotations: boolean;
extractionErrors: string[];
}
/**
* Interface for custom import statements
*/
export interface CustomImport {
importStatement: string;
source: string;
importedItems: string[];
isDefault: boolean;
isNamespace: boolean;
isTypeOnly: boolean;
originalStatement: string;
}
/**
* Interface for custom imports parsing result
*/
export interface CustomImportsParseResult {
imports: CustomImport[];
customSchema?: string;
parseErrors: string[];
isValid: boolean;
}
/**
* Interface for model comment context including metadata for error reporting
*/
export interface ModelCommentContext {
modelName: string;
comment: string;
}
/**
* Extract comments from Prisma DMMF model fields
*
* This function processes Prisma model field definitions and extracts
* comment data with proper normalization and context for downstream parsing.
*
* @param models - Array of Prisma DMMF models
* @returns Array of extracted field comments with context
*/
export declare function extractFieldComments(models: DMMF.Model[]): ExtractedFieldComment[];
/**
* Extract and normalize a single field comment
*
* @param context - Field context with comment and metadata
* @returns Extracted comment with processing information
*/
export declare function extractFieldComment(context: FieldCommentContext): ExtractedFieldComment;
/**
* Normalize comment content for consistent processing
*
* Handles multi-line comments, whitespace normalization, and ensures
* consistent format for downstream parsing.
*
* @param comment - Raw comment from Prisma field
* @returns Normalized comment string
*/
export declare function normalizeComment(comment: string): string;
/**
* Detect if comment contains @zod validation annotations
*
* Performs a quick check to determine if the comment contains
* any @zod annotations before more expensive parsing operations.
*
* @param comment - Normalized comment string
* @returns True if @zod annotations are detected
*/
export declare function detectZodAnnotations(comment: string): boolean;
/**
* Validate comment structure and detect potential issues
*
* Performs structural validation to catch common comment formatting
* issues that could cause parsing problems later.
*
* @param comment - Normalized comment string
* @param context - Field context for error reporting
* @returns Array of validation errors
*/
export declare function validateCommentStructure(comment: string, context: FieldCommentContext): string[];
/**
* Get comment extraction statistics for debugging
*
* @param extractedComments - Array of extracted comments
* @returns Statistics about comment extraction
*/
export declare function getExtractionStatistics(extractedComments: ExtractedFieldComment[]): {
totalFields: number;
fieldsWithComments: number;
fieldsWithZodAnnotations: number;
extractionErrors: number;
};
/**
* Filter extracted comments to only those with @zod annotations
*
* @param extractedComments - Array of all extracted comments
* @returns Array of comments containing @zod annotations
*/
export declare function filterZodComments(extractedComments: ExtractedFieldComment[]): ExtractedFieldComment[];
/**
* Get all extraction errors across multiple field comments
*
* @param extractedComments - Array of extracted comments
* @returns Array of all errors with field context
*/
export declare function getAllExtractionErrors(extractedComments: ExtractedFieldComment[]): Array<{
modelName: string;
fieldName: string;
errors: string[];
}>;
/**
* Interface for parsed @zod annotation
*/
export interface ParsedZodAnnotation {
method: string;
parameters: unknown[];
rawMatch: string;
position: number;
/** Optional generic type arguments captured after the method name, e.g., `<"UserId">` */
genericArgs?: string;
}
/**
* Interface for @zod annotation parsing result
*/
export interface ZodAnnotationParseResult {
annotations: ParsedZodAnnotation[];
parseErrors: string[];
isValid: boolean;
}
/**
* Parse @zod annotations from normalized comment text
*
* Extracts and parses all @zod annotations including method names,
* parameters, and handles complex chaining scenarios.
*
* @param comment - Normalized comment string
* @param context - Field context for error reporting
* @returns Parse result with annotations and errors
*/
export declare function parseZodAnnotations(comment: string, context: FieldCommentContext): ZodAnnotationParseResult;
/**
* Validate parsed @zod annotations for semantic correctness
*
* @param annotations - Array of parsed annotations
* @param context - Field context
* @returns Array of validation errors
*/
export declare function validateZodAnnotations(annotations: ParsedZodAnnotation[], context: FieldCommentContext): string[];
/**
* Interface for Zod schema generation result
*/
export interface ZodSchemaGenerationResult {
schemaChain: string;
imports: Set<string>;
errors: string[];
isValid: boolean;
}
/**
* Interface for validation method mapping configuration
*/
export interface ValidationMethodConfig {
methodName: string;
zodMethod: string;
parameterCount: number | 'variable';
requiresImport?: string;
fieldTypeCompatibility?: string[];
}
/**
* Map parsed @zod annotations to Zod schema method calls
*
* Converts parsed annotations into actual Zod validation method chains
* that can be used in generated schema code.
*
* @param annotations - Array of parsed annotations
* @param context - Field context for validation
* @param zodVersion - Zod version target ('v3', 'v4', or 'auto')
* @returns Schema generation result with method chain and imports
*/
export declare function mapAnnotationsToZodSchema(annotations: ParsedZodAnnotation[], context: FieldCommentContext, zodVersion?: 'auto' | 'v3' | 'v4'): ZodSchemaGenerationResult;
/**
* Generate complete Zod schema with base type and validations
*
* @param baseType - Base Zod type (e.g., 'z.string()', 'z.number()')
* @param annotations - Parsed annotations
* @param context - Field context
* @returns Complete schema generation result
*/
export declare function generateCompleteZodSchema(baseType: string, annotations: ParsedZodAnnotation[], context: FieldCommentContext, zodVersion?: 'auto' | 'v3' | 'v4'): ZodSchemaGenerationResult;
/**
* Get base Zod type for Prisma field type
*
* @param fieldType - Prisma field type
* @param isOptional - Whether field is optional
* @param isList - Whether field is a list
* @returns Base Zod type string
*/
export declare function getBaseZodType(fieldType: string, isOptional: boolean, isList: boolean): string;
/**
* Field-aware base type resolver to correctly handle enums vs relations.
*/
export declare function getBaseZodTypeForField(field: import('@prisma/generator-helper').DMMF.Field, isOptionalOverride?: boolean): string;
/**
* Get required imports for Zod schema generation
*
* @param fieldType - Prisma field type
* @param customImports - Additional imports from validation methods
* @returns Set of import statements
*/
export declare function getRequiredImports(fieldType: string, customImports?: Set<string>): Set<string>;
/**
* Detect if comment contains @zod.import annotations
*
* @param comment - Normalized comment string
* @returns True if @zod.import annotations are detected
*/
export declare function detectCustomImports(comment: string): boolean;
/**
* Parse custom imports from a comment string
*
* Supports both model-level and field-level imports:
* - @zod.import(["import { myFunction } from 'mypackage'"])
* - @zod.import(["import myFunction from 'mypackage'"])
* - @zod.import(["import * as myModule from 'mypackage'"])
*
* @param comment - Comment string to parse
* @param context - Context for error reporting (model or field)
* @returns Custom imports parsing result
*/
export declare function parseCustomImports(comment: string, context: ModelCommentContext | FieldCommentContext): CustomImportsParseResult;
/**
* Find balanced parentheses in a string starting from a given position
*
* @param text - Text to search in
* @param startPos - Starting position (after opening parenthesis)
* @returns End position of balanced parentheses or -1 if not found
*/
export declare function findBalancedParentheses(text: string, startPos: number): number;
export declare function extractModelCustomImports(model: DMMF.Model): CustomImportsParseResult;
/**
* Extract custom imports from field documentation
*
* @param field - Prisma DMMF field
* @param modelName - Name of the model containing the field
* @returns Custom imports parsing result
*/
export declare function extractFieldCustomImports(field: DMMF.Field, modelName: string): CustomImportsParseResult;