mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 23:04:59 +08:00
Regenerate all MDC rules with fresh Exa data and December 2025 best practices
- Refreshed all 241 library rules with current best practices - Updated Exa search results for all libraries with 2025 content - Fixed --regenerate-all flag logic to properly process all libraries - Removed duplicate astro entry in rules.json (merged tags) - Added missing docker.mdc and vim.mdc files - All rules now include modern patterns and anti-patterns - Updated with framework-specific recommendations for 2025 Technical improvements: - Fixed retry_failed_only logic in generate_mdc_files.py - Improved progress tracking for regeneration scenarios - Ensured proper handling of --refresh-exa flag
This commit is contained in:
+253
-129
@@ -1,145 +1,269 @@
|
||||
---
|
||||
description: This rule provides comprehensive guidelines for using the Zod library effectively, covering code organization, performance, security, and testing to ensure robust and maintainable type validation.
|
||||
globs: *.ts?(x)
|
||||
description: This guide outlines definitive best practices for using Zod in TypeScript projects, ensuring robust runtime validation, superior type safety, and maintainable schemas.
|
||||
globs: **/*.{ts,tsx}
|
||||
---
|
||||
- **Organize Zod schemas logically for readability and maintainability.** Group related schemas together and structure your Zod code for improved clarity, especially in larger projects.
|
||||
- **Compose and reuse related schemas to avoid repetition.** Use Zod's composition features (e.g., `z.intersection`, `z.union`, `z.extend`) to create reusable schema components and reduce redundancy.
|
||||
- **Implement schema versioning for better management.** As your application evolves, version your schemas to handle data migrations and maintain compatibility with older data formats.
|
||||
- **Use Zod for type-safe data validation and transformation.** Leverage Zod's capabilities for both validating and transforming data to ensure data integrity throughout your application.
|
||||
# Zod Best Practices
|
||||
|
||||
### 1. Code Organization and Structure:
|
||||
Zod is the definitive TypeScript-first schema validation library. It provides static type inference directly from runtime schemas, catching data-shape errors at both compile time and runtime. Adhere to these guidelines to build resilient, type-safe applications with Zod 4.
|
||||
|
||||
- **Directory Structure Best Practices:**
|
||||
- Consider grouping Zod schemas within dedicated directories (e.g., `schemas/`, `models/schemas/`).
|
||||
- Organize schemas by domain, feature, or data model.
|
||||
- Use subdirectories for complex schemas or schema families.
|
||||
- **File Naming Conventions:**
|
||||
- Name schema files descriptively (e.g., `user.schema.ts`, `product.schema.ts`).
|
||||
- Use a consistent naming pattern throughout the project.
|
||||
- Consider including the data model name or the schema's purpose in the filename.
|
||||
- **Module Organization:**
|
||||
- Export schemas as named exports from each module.
|
||||
- Create index files (e.g., `index.ts`) to re-export schemas from subdirectories for easier access.
|
||||
- Use clear and concise module names.
|
||||
- **Component Architecture:**
|
||||
- If you are building React components, consider creating a `components/schemas/` directory where you house your schema related to specific components.
|
||||
- Use Zod to validate the props passed to React components using `z.infer` and `z.ZodType<Props>`
|
||||
- You can create a custom hook that handles validation with Zod and stores the parsed result in React state.
|
||||
- **Code Splitting Strategies:**
|
||||
- For large schema definitions, split them into smaller, more manageable files.
|
||||
- Use Zod's composition features to combine these smaller schemas into larger, more complex schemas as needed.
|
||||
## Core Setup & Principles
|
||||
|
||||
### 2. Common Patterns and Anti-patterns:
|
||||
### 1. Enable Strict TypeScript
|
||||
|
||||
- **Design Patterns Specific to Zod:**
|
||||
- **Schema Composition:** Use `z.intersection`, `z.union`, `z.extend`, and `z.optional` to combine and modify existing schemas.
|
||||
- **Schema Transformation:** Use `.transform` to modify data during validation.
|
||||
- **Custom Validation:** Use `.refine` and `.superRefine` for custom validation logic.
|
||||
- **Default Values:** Use `.default` to assign default values to schema properties.
|
||||
- **Recommended Approaches for Common Tasks:**
|
||||
- **Form Validation:** Use Zod to validate form input data and display errors.
|
||||
- **API Request Validation:** Use Zod to validate incoming API request bodies.
|
||||
- **Data Serialization/Deserialization:** Use Zod to validate and transform data when serializing or deserializing.
|
||||
- **Anti-patterns and Code Smells to Avoid:**
|
||||
- **Overly Complex Schemas:** Avoid creating schemas that are too complex or difficult to understand. Break them down into smaller, more manageable schemas.
|
||||
- **Ignoring Validation Errors:** Always handle validation errors and provide informative feedback to the user.
|
||||
- **Duplicated Schema Definitions:** Avoid duplicating schema definitions. Use schema composition to reuse existing schemas.
|
||||
- **State Management Best Practices:**
|
||||
- When using Zod with state management libraries (e.g., Redux, Zustand), validate the state data using Zod schemas.
|
||||
- Use Zod to validate state updates before applying them to the state.
|
||||
- **Error Handling Patterns:**
|
||||
- Use Zod's `.safeParse` method to handle validation errors gracefully.
|
||||
- Provide informative error messages to the user.
|
||||
- Log validation errors for debugging purposes.
|
||||
Zod's type inference relies on `strict: true` in your `tsconfig.json`. This is non-negotiable for reliable type safety.
|
||||
|
||||
### 3. Performance Considerations:
|
||||
```json
|
||||
// tsconfig.json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"strict": true, // ✅ ALWAYS enable strict mode
|
||||
// ...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- **Optimization Techniques:**
|
||||
- **Schema Caching:** Cache frequently used schemas to avoid re-parsing them.
|
||||
- **Pre-compilation:** If possible, pre-compile schemas during build time to improve performance.
|
||||
- **Minimize Schema Complexity:** Keep schemas as simple as possible to reduce validation overhead.
|
||||
- **Memory Management:**
|
||||
- Be mindful of the memory usage of large schemas, especially when dealing with large datasets.
|
||||
- Release unused schemas when they are no longer needed.
|
||||
- **Bundle Size Optimization:**
|
||||
- Remove unused schemas and code from the bundle.
|
||||
- Use tree shaking to eliminate dead code.
|
||||
- **Lazy Loading Strategies:**
|
||||
- Lazily load schemas that are not immediately needed.
|
||||
- Use code splitting to load schemas on demand.
|
||||
### 2. Standardize Zod 4 Adoption
|
||||
|
||||
### 4. Security Best Practices:
|
||||
Ensure your project and any Zod-dependent libraries use the modern Zod 4 core.
|
||||
|
||||
- **Common Vulnerabilities and How to Prevent Them:**
|
||||
- **Injection Attacks:** Prevent injection attacks by validating and sanitizing user input data.
|
||||
- **Cross-Site Scripting (XSS):** Prevent XSS attacks by encoding user input data before displaying it in the UI.
|
||||
- **Denial of Service (DoS):** Prevent DoS attacks by limiting the size and complexity of input data.
|
||||
- **Input Validation:**
|
||||
- Validate all user input data using Zod schemas.
|
||||
- Enforce strict validation rules to prevent invalid or malicious data from entering the system.
|
||||
- **Authentication and Authorization Patterns:**
|
||||
- Use Zod to validate user credentials during authentication.
|
||||
- Use Zod to validate authorization tokens and permissions.
|
||||
- **Data Protection Strategies:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use secure storage mechanisms to protect data from unauthorized access.
|
||||
- **Secure API Communication:**
|
||||
- Use HTTPS to encrypt API communication.
|
||||
- Validate API request and response data using Zod schemas.
|
||||
```json
|
||||
// package.json
|
||||
{
|
||||
"dependencies": {
|
||||
"zod": "^3.25.0 || ^4.0.0" // ✅ Use this peer dependency range
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 5. Testing Approaches:
|
||||
### 3. Leverage Type Inference (`z.infer`)
|
||||
|
||||
- **Unit Testing Strategies:**
|
||||
- Write unit tests for individual schemas to ensure they validate data correctly.
|
||||
- Test different input scenarios, including valid and invalid data.
|
||||
- Use mocking and stubbing to isolate schemas from external dependencies.
|
||||
- **Integration Testing:**
|
||||
- Write integration tests to ensure that schemas work correctly with other parts of the application.
|
||||
- Test the interaction between schemas and data sources (e.g., databases, APIs).
|
||||
- **End-to-End Testing:**
|
||||
- Write end-to-end tests to ensure that the entire application works correctly with Zod schemas.
|
||||
- Test the user interface and the data flow through the application.
|
||||
- **Test Organization:**
|
||||
- Organize tests into separate directories based on the type of test (e.g., unit, integration, end-to-end).
|
||||
- Use descriptive test names to indicate the purpose of each test.
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking and stubbing to isolate schemas from external dependencies during testing.
|
||||
- Mock data sources and APIs to control the test environment.
|
||||
Always infer types from your schemas. This eliminates duplication and keeps types synchronized with validation logic.
|
||||
|
||||
### 6. Common Pitfalls and Gotchas:
|
||||
```typescript
|
||||
import { z } from 'zod';
|
||||
|
||||
- **Frequent Mistakes Developers Make:**
|
||||
- **Incorrect Schema Definitions:** Ensure that schema definitions accurately reflect the expected data format.
|
||||
- **Ignoring Validation Errors:** Always handle validation errors and provide informative feedback to the user.
|
||||
- **Overly Complex Schemas:** Avoid creating schemas that are too complex or difficult to understand.
|
||||
- **Edge Cases to Be Aware Of:**
|
||||
- **Null and Undefined Values:** Handle null and undefined values correctly in schemas.
|
||||
- **Empty Strings and Arrays:** Handle empty strings and arrays appropriately.
|
||||
- **Date and Time Formats:** Use consistent date and time formats throughout the application.
|
||||
- **Version-Specific Issues:**
|
||||
- Be aware of any version-specific issues or breaking changes in Zod.
|
||||
- Refer to the Zod documentation and release notes for information on compatibility and migration.
|
||||
- **Compatibility Concerns:**
|
||||
- Ensure that Zod schemas are compatible with the data formats used by other systems or libraries.
|
||||
- Consider using a data serialization format (e.g., JSON, YAML) that is widely supported.
|
||||
- **Debugging Strategies:**
|
||||
- Use Zod's `.safeParse` method to log validation errors for debugging purposes.
|
||||
- Use a debugger to step through the validation process and identify issues.
|
||||
const userSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
name: z.string().min(1),
|
||||
email: z.string().email(),
|
||||
});
|
||||
|
||||
### 7. Tooling and Environment:
|
||||
// ❌ BAD: Manually defining types
|
||||
interface User {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
- **Recommended Development Tools:**
|
||||
- **TypeScript:** Use TypeScript to provide static typing for Zod schemas and data.
|
||||
- **VS Code:** Use VS Code with the Zod extension for improved code completion and validation.
|
||||
- **Build Configuration:**
|
||||
- Configure the build process to transpile TypeScript code and bundle JavaScript code.
|
||||
- Use a module bundler (e.g., Webpack, Parcel, Rollup) to optimize the bundle size.
|
||||
- **Linting and Formatting:**
|
||||
- Use a linter (e.g., ESLint) to enforce code style and best practices.
|
||||
- Use a code formatter (e.g., Prettier) to automatically format code.
|
||||
- **Deployment Best Practices:**
|
||||
- Deploy the application to a production environment with appropriate security measures in place.
|
||||
- Monitor the application for errors and performance issues.
|
||||
- **CI/CD Integration:**
|
||||
- Integrate Zod schemas into the CI/CD pipeline to automate validation and testing.
|
||||
- Run unit tests, integration tests, and end-to-end tests as part of the CI/CD process.
|
||||
// ✅ GOOD: Infer types directly from the schema
|
||||
type User = z.infer<typeof userSchema>;
|
||||
|
||||
function processUser(user: User) {
|
||||
console.log(user.email);
|
||||
}
|
||||
```
|
||||
|
||||
## Data Validation & Error Handling
|
||||
|
||||
### 4. Always Parse Untrusted Data
|
||||
|
||||
Never trust external data. Use `schema.parse()` or `schema.safeParse()` immediately upon receiving data from APIs, forms, or environment variables.
|
||||
|
||||
```typescript
|
||||
import { z } from 'zod';
|
||||
|
||||
const idSchema = z.string().uuid();
|
||||
|
||||
// ❌ BAD: Assuming data is valid
|
||||
function processId(id: string) {
|
||||
// This 'id' could be anything if not validated
|
||||
console.log(id.toUpperCase());
|
||||
}
|
||||
|
||||
// ✅ GOOD: Use safeParse for external/untrusted data
|
||||
function handleRequest(rawId: unknown) {
|
||||
const result = idSchema.safeParse(rawId);
|
||||
if (!result.success) {
|
||||
console.error('Invalid ID received:', result.error.issues);
|
||||
return { status: 400, message: 'Invalid ID' };
|
||||
}
|
||||
// Data is now type-safe and validated
|
||||
processId(result.data);
|
||||
return { status: 200, message: 'ID processed' };
|
||||
}
|
||||
|
||||
// ✅ GOOD: Use parse for trusted data or when immediate error throwing is desired
|
||||
function loadConfig(envVar: unknown) {
|
||||
try {
|
||||
const config = z.object({ API_KEY: z.string().min(1) }).parse(envVar);
|
||||
console.log('Config loaded:', config.API_KEY);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
console.error('Invalid environment config:', error.issues);
|
||||
process.exit(1); // Critical error, exit application
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 5. Customize Error Messages for UX
|
||||
|
||||
Provide clear, user-friendly error messages directly within your schemas.
|
||||
|
||||
```typescript
|
||||
import { z } from 'zod';
|
||||
|
||||
const loginSchema = z.object({
|
||||
email: z.string().email({ message: 'Invalid email address.' }), // ✅ Custom message
|
||||
password: z.string().min(8, { message: 'Password must be at least 8 characters.' }), // ✅ Custom message
|
||||
});
|
||||
|
||||
// Integrate with form libraries (e.g., React Hook Form)
|
||||
// const { register, handleSubmit, formState: { errors } } = useForm({
|
||||
// resolver: zodResolver(loginSchema),
|
||||
// });
|
||||
```
|
||||
|
||||
## Schema Design & Organization
|
||||
|
||||
### 6. Keep Schemas Modular & Domain-Specific
|
||||
|
||||
Organize schemas into small, focused files based on their domain. Avoid monolithic schema files.
|
||||
|
||||
```
|
||||
// ❌ BAD: monolithic schemas.ts
|
||||
// schemas.ts
|
||||
export const userSchema = z.object({ /* ... */ });
|
||||
export const productSchema = z.object({ /* ... */ });
|
||||
export const orderSchema = z.object({ /* ... */ });
|
||||
|
||||
// ✅ GOOD: modular, domain-specific files
|
||||
// schemas/user.schema.ts
|
||||
export const userSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
name: z.string().min(1),
|
||||
email: z.string().email(),
|
||||
});
|
||||
|
||||
// schemas/product.schema.ts
|
||||
export const productSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
name: z.string().min(3),
|
||||
price: z.number().positive(),
|
||||
});
|
||||
|
||||
// schemas/index.ts (optional re-export)
|
||||
export * from './user.schema';
|
||||
export * from './product.schema';
|
||||
```
|
||||
|
||||
### 7. Use Transforms and Refinements for Data Normalization
|
||||
|
||||
Normalize and sanitize data as part of validation.
|
||||
|
||||
```typescript
|
||||
import { z } from 'zod';
|
||||
|
||||
// ❌ BAD: Manual post-validation processing
|
||||
const emailInputSchemaBad = z.string().email();
|
||||
const processEmailBad = (email: string) => email.toLowerCase().trim();
|
||||
|
||||
// ✅ GOOD: Integrate transforms directly into the schema
|
||||
const emailInputSchema = z
|
||||
.string()
|
||||
.trim() // ✅ Trim whitespace
|
||||
.toLowerCase() // ✅ Convert to lowercase
|
||||
.email({ message: 'Invalid email address' });
|
||||
|
||||
const postIdSchema = z.string().uuid().transform((val) => `post-${val}`); // ✅ Transform data type or format
|
||||
|
||||
const passwordSchema = z.string()
|
||||
.min(8)
|
||||
.refine(val => /[A-Z]/.test(val), { message: 'Password must contain an uppercase letter' }); // ✅ Refine with custom logic
|
||||
```
|
||||
|
||||
### 8. Prefer `z.coerce` for Type Coercion
|
||||
|
||||
Use `z.coerce` for explicit type conversion of known string inputs (e.g., from query parameters, environment variables).
|
||||
|
||||
```typescript
|
||||
import { z } from 'zod';
|
||||
|
||||
// ❌ BAD: Manual parsing or loose validation
|
||||
const pageParamBad = z.string(); // Will be '1' not 1
|
||||
const pageNumberBad = parseInt(pageParamBad.parse('10'));
|
||||
|
||||
// ✅ GOOD: Coerce directly in the schema
|
||||
const querySchema = z.object({
|
||||
page: z.coerce.number().int().positive().default(1), // ✅ Coerces '10' to 10
|
||||
isActive: z.coerce.boolean().default(false), // ✅ Coerces 'true'/'false' to boolean
|
||||
});
|
||||
|
||||
const { page, isActive } = querySchema.parse({ page: '5', isActive: 'true' });
|
||||
console.log(page, typeof page); // 5, 'number'
|
||||
console.log(isActive, typeof isActive); // true, 'boolean'
|
||||
```
|
||||
|
||||
### 9. Differentiate `optional()`, `nullable()`, and `default()`
|
||||
|
||||
Understand the nuances for robust schema design.
|
||||
|
||||
```typescript
|
||||
import { z } from 'zod';
|
||||
|
||||
const userProfileSchema = z.object({
|
||||
username: z.string(),
|
||||
// ✅ optional(): field can be present or absent (undefined)
|
||||
bio: z.string().optional(),
|
||||
// ✅ nullable(): field can be present with a value or null
|
||||
website: z.string().url().nullable(),
|
||||
// ✅ default(): provides a fallback value if field is undefined
|
||||
status: z.enum(['active', 'inactive']).default('active'),
|
||||
});
|
||||
|
||||
type UserProfile = z.infer<typeof userProfileSchema>;
|
||||
/*
|
||||
{
|
||||
username: string;
|
||||
bio?: string | undefined;
|
||||
website: string | null;
|
||||
status: "active" | "inactive";
|
||||
}
|
||||
*/
|
||||
```
|
||||
|
||||
## Testing & Maintenance
|
||||
|
||||
### 10. Write Schema-Focused Unit Tests
|
||||
|
||||
Thoroughly test your Zod schemas with both valid and invalid data to prevent regressions.
|
||||
|
||||
```typescript
|
||||
// tests/schemas/user.schema.test.ts
|
||||
import { userSchema } from '../../schemas/user.schema';
|
||||
|
||||
describe('userSchema', () => {
|
||||
it('should validate a valid user object', () => {
|
||||
const validUser = {
|
||||
id: 'a1b2c3d4-e5f6-7890-1234-567890abcdef',
|
||||
name: 'John Doe',
|
||||
email: 'john.doe@example.com',
|
||||
};
|
||||
expect(() => userSchema.parse(validUser)).not.toThrow(); // ✅ Validates successfully
|
||||
});
|
||||
|
||||
it('should invalidate an invalid email', () => {
|
||||
const invalidUser = {
|
||||
id: 'a1b2c3d4-e5f6-7890-1234-567890abcdef',
|
||||
name: 'John Doe',
|
||||
email: 'invalid-email',
|
||||
};
|
||||
const result = userSchema.safeParse(invalidUser);
|
||||
expect(result.success).toBe(false); // ✅ Fails validation
|
||||
if (!result.success) {
|
||||
expect(result.error.issues[0].message).toBe('Invalid email'); // ✅ Specific error message
|
||||
}
|
||||
});
|
||||
});
|
||||
```
|
||||
Reference in New Issue
Block a user