558 lines
11 KiB
Plaintext
558 lines
11 KiB
Plaintext
---
|
|
description: Template collection for creating different types of Cursor rules for .cursor/rules/**/*
|
|
alwaysApply: false
|
|
---
|
|
# Cursor Rule Templates
|
|
|
|
This file contains templates for creating different types of Cursor rules based on the [PageAI tutorial](https://pageai.pro/blog/cursor-rules-tutorial).
|
|
|
|
## NOTE: Always apply these templates when creating new rules.
|
|
- Always apply when creating new rules
|
|
|
|
## Template Categories
|
|
|
|
### 1. Foundational Rules
|
|
### 2. Language-Specific Rules
|
|
### 3. Framework-Specific Rules
|
|
### 4. Domain-Specific Rules
|
|
### 5. Workflow Rules
|
|
|
|
---
|
|
|
|
## 1. Foundational Rules
|
|
|
|
### Meta-Rule Template
|
|
|
|
```markdown
|
|
---
|
|
description: How to create and maintain Cursor rules
|
|
globs: .cursor/rules/*.mdc
|
|
alwaysApply: false
|
|
---
|
|
|
|
# Rule Title
|
|
|
|
## Purpose
|
|
Brief description of what this rule accomplishes.
|
|
|
|
## When to Apply
|
|
- When working with [specific files/patterns]
|
|
- When [specific conditions are met]
|
|
- When [specific goals are pursued]
|
|
|
|
## Guidelines
|
|
|
|
### ✅ DO
|
|
- Specific action or pattern to follow
|
|
- Example with code
|
|
|
|
### ❌ DON'T
|
|
- Anti-pattern to avoid
|
|
- Example of what not to do
|
|
|
|
## Examples
|
|
|
|
```language
|
|
// Good example
|
|
goodExample();
|
|
|
|
// Bad example
|
|
badExample();
|
|
```
|
|
|
|
## References
|
|
- Link to related rules: [rule-name](mdc:.cursor/rules/rule-name.mdc)
|
|
- Link to external docs: [Documentation](https://example.com)
|
|
```
|
|
|
|
### Self-Improvement Template
|
|
|
|
```markdown
|
|
---
|
|
description: Guidelines for continuously improving Cursor rules
|
|
globs: **/*
|
|
alwaysApply: true
|
|
---
|
|
|
|
# Self-Improving Rules
|
|
|
|
## Rule Improvement Triggers
|
|
- New code patterns not covered by existing rules
|
|
- Repeated similar implementations across files
|
|
- Common error patterns that could be prevented
|
|
- New libraries or tools being used consistently
|
|
|
|
## Analysis Process
|
|
- Compare new code with existing rules
|
|
- Identify patterns that should be standardized
|
|
- Look for references to external documentation
|
|
- Check for consistent error handling patterns
|
|
|
|
## Rule Updates
|
|
- **Add New Rules When**: [criteria]
|
|
- **Modify Existing Rules When**: [criteria]
|
|
- **Deprecate Rules When**: [criteria]
|
|
|
|
## Quality Checks
|
|
- Rules should be actionable and specific
|
|
- Examples should come from actual code
|
|
- References should be up to date
|
|
- Patterns should be consistently enforced
|
|
```
|
|
|
|
---
|
|
|
|
## 2. Language-Specific Rules
|
|
|
|
### Python Template
|
|
|
|
```markdown
|
|
---
|
|
description: Python development patterns and conventions
|
|
globs: **/*.py
|
|
alwaysApply: false
|
|
---
|
|
|
|
# Python Development Rules
|
|
|
|
## Import Organization
|
|
|
|
```python
|
|
# Standard library imports
|
|
import os
|
|
import re
|
|
from pathlib import Path
|
|
from typing import Dict, List, Optional
|
|
|
|
# Third-party imports
|
|
import click
|
|
from rich.console import Console
|
|
|
|
# Local imports
|
|
from src.config import config
|
|
from src.services.protocols import ServiceProtocol
|
|
```
|
|
|
|
## Function Definitions
|
|
|
|
```python
|
|
def function_name(param1: str, param2: Optional[int] = None) -> ReturnType:
|
|
"""Docstring describing the function's purpose.
|
|
|
|
Args:
|
|
param1: Description of parameter
|
|
param2: Optional parameter description
|
|
|
|
Returns:
|
|
Description of return value
|
|
|
|
Raises:
|
|
SpecificError: When and why this error occurs
|
|
"""
|
|
# Implementation
|
|
return result
|
|
```
|
|
|
|
## Error Handling
|
|
|
|
```python
|
|
try:
|
|
result = process_data(input_data)
|
|
except SpecificError as e:
|
|
logger.error(f"Failed to process data: {e}")
|
|
raise
|
|
except Exception as e:
|
|
logger.error(f"Unexpected error: {e}")
|
|
raise
|
|
```
|
|
|
|
## Naming Conventions
|
|
- Use `snake_case` for functions and variables
|
|
- Use `PascalCase` for classes
|
|
- Use `UPPER_CASE` for constants
|
|
- Use descriptive names that explain purpose
|
|
```
|
|
|
|
### TypeScript Template
|
|
|
|
```markdown
|
|
---
|
|
description: TypeScript development patterns and conventions
|
|
globs: **/*.{ts,tsx}
|
|
alwaysApply: false
|
|
---
|
|
|
|
# TypeScript Development Rules
|
|
|
|
## Import Organization
|
|
|
|
```typescript
|
|
// Third-party imports
|
|
import React from 'react';
|
|
import { useState, useEffect } from 'react';
|
|
|
|
// Local imports
|
|
import { ComponentName } from './ComponentName';
|
|
import { useCustomHook } from '../hooks/useCustomHook';
|
|
```
|
|
|
|
## Function Definitions
|
|
|
|
```typescript
|
|
// Function declarations
|
|
function functionName(param1: string, param2?: number): ReturnType {
|
|
// Implementation
|
|
return result;
|
|
}
|
|
|
|
// Arrow functions for callbacks
|
|
const handleClick = (event: React.MouseEvent): void => {
|
|
// Implementation
|
|
};
|
|
```
|
|
|
|
## Type Definitions
|
|
|
|
```typescript
|
|
interface UserData {
|
|
id: string;
|
|
name: string;
|
|
email: string;
|
|
createdAt: Date;
|
|
}
|
|
|
|
type UserStatus = 'active' | 'inactive' | 'pending';
|
|
```
|
|
|
|
## Error Handling
|
|
|
|
```typescript
|
|
try {
|
|
const result = await apiCall();
|
|
return result;
|
|
} catch (error) {
|
|
console.error('API call failed:', error);
|
|
throw error;
|
|
}
|
|
```
|
|
|
|
## Naming Conventions
|
|
- Use `camelCase` for functions and variables
|
|
- Use `PascalCase` for components and classes
|
|
- Use `UPPER_CASE` for constants
|
|
- Use descriptive names that explain purpose
|
|
```
|
|
|
|
---
|
|
|
|
## 3. Framework-Specific Rules
|
|
|
|
### React Template
|
|
|
|
```markdown
|
|
---
|
|
description: React component development patterns
|
|
globs: **/*.{tsx,jsx}
|
|
alwaysApply: false
|
|
---
|
|
|
|
# React Development Rules
|
|
|
|
## Component Structure
|
|
|
|
```tsx
|
|
import React from 'react';
|
|
|
|
interface ComponentProps {
|
|
title: string;
|
|
onAction?: () => void;
|
|
}
|
|
|
|
export const ComponentName: React.FC<ComponentProps> = ({
|
|
title,
|
|
onAction
|
|
}) => {
|
|
// Hooks at the top
|
|
const [state, setState] = useState<StateType>(initialState);
|
|
|
|
// Event handlers
|
|
const handleClick = () => {
|
|
// Implementation
|
|
};
|
|
|
|
// Render
|
|
return (
|
|
<div className="component">
|
|
<h1>{title}</h1>
|
|
<button onClick={handleClick}>Action</button>
|
|
</div>
|
|
);
|
|
};
|
|
```
|
|
|
|
## Hooks Usage
|
|
|
|
```tsx
|
|
// Custom hooks
|
|
const useCustomHook = (param: string) => {
|
|
const [value, setValue] = useState<string>('');
|
|
|
|
useEffect(() => {
|
|
// Effect implementation
|
|
}, [param]);
|
|
|
|
return { value, setValue };
|
|
};
|
|
```
|
|
|
|
## State Management
|
|
|
|
```tsx
|
|
// Local state for component-specific data
|
|
const [localState, setLocalState] = useState<LocalStateType>(initialState);
|
|
|
|
// Global state for shared data
|
|
const { globalState, updateGlobalState } = useGlobalState();
|
|
```
|
|
|
|
## Performance Optimization
|
|
|
|
```tsx
|
|
// Memoize expensive calculations
|
|
const expensiveValue = useMemo(() => {
|
|
return expensiveCalculation(data);
|
|
}, [data]);
|
|
|
|
// Memoize callbacks
|
|
const handleCallback = useCallback(() => {
|
|
// Implementation
|
|
}, [dependencies]);
|
|
```
|
|
```
|
|
|
|
---
|
|
|
|
## 4. Domain-Specific Rules
|
|
|
|
### API Development Template
|
|
|
|
```markdown
|
|
---
|
|
description: API development patterns and conventions
|
|
globs: **/api/**/*.{py,ts,js}
|
|
alwaysApply: false
|
|
---
|
|
|
|
# API Development Rules
|
|
|
|
## Endpoint Structure
|
|
|
|
```python
|
|
# Python (FastAPI/Flask)
|
|
@app.get("/api/v1/resource/{resource_id}")
|
|
async def get_resource(resource_id: str) -> ResourceResponse:
|
|
"""Get a specific resource by ID."""
|
|
try:
|
|
resource = await resource_service.get_by_id(resource_id)
|
|
return ResourceResponse(data=resource)
|
|
except ResourceNotFoundError:
|
|
raise HTTPException(status_code=404, detail="Resource not found")
|
|
```
|
|
|
|
```typescript
|
|
// TypeScript (Express/Next.js)
|
|
app.get('/api/v1/resource/:resourceId', async (req, res) => {
|
|
try {
|
|
const { resourceId } = req.params;
|
|
const resource = await resourceService.getById(resourceId);
|
|
res.json({ data: resource });
|
|
} catch (error) {
|
|
res.status(404).json({ error: 'Resource not found' });
|
|
}
|
|
});
|
|
```
|
|
|
|
## Error Handling
|
|
|
|
```python
|
|
# Standard error responses
|
|
class APIError(Exception):
|
|
def __init__(self, message: str, status_code: int = 400):
|
|
self.message = message
|
|
self.status_code = status_code
|
|
|
|
# Error response format
|
|
{
|
|
"error": {
|
|
"message": "Error description",
|
|
"code": "ERROR_CODE",
|
|
"details": {}
|
|
}
|
|
}
|
|
```
|
|
|
|
## Request/Response Validation
|
|
|
|
```python
|
|
# Request validation
|
|
class CreateResourceRequest(BaseModel):
|
|
name: str
|
|
description: Optional[str] = None
|
|
tags: List[str] = []
|
|
|
|
# Response validation
|
|
class ResourceResponse(BaseModel):
|
|
data: Resource
|
|
meta: Optional[Dict[str, Any]] = None
|
|
```
|
|
|
|
## Security
|
|
|
|
```python
|
|
# Authentication
|
|
@require_auth
|
|
async def protected_endpoint():
|
|
# Implementation
|
|
|
|
# Rate limiting
|
|
@rate_limit(max_requests=100, window=3600)
|
|
async def rate_limited_endpoint():
|
|
# Implementation
|
|
```
|
|
```
|
|
|
|
---
|
|
|
|
## 5. Workflow Rules
|
|
|
|
### Testing Template
|
|
|
|
```markdown
|
|
---
|
|
description: Testing patterns and conventions
|
|
globs: **/*test*.{py,ts,js}
|
|
alwaysApply: false
|
|
---
|
|
|
|
# Testing Rules
|
|
|
|
## Test Structure
|
|
|
|
```python
|
|
# Python (pytest)
|
|
def test_function_name():
|
|
"""Test description."""
|
|
# Arrange
|
|
input_data = "test input"
|
|
expected_output = "expected result"
|
|
|
|
# Act
|
|
result = function_to_test(input_data)
|
|
|
|
# Assert
|
|
assert result == expected_output
|
|
```
|
|
|
|
```typescript
|
|
// TypeScript (Jest)
|
|
describe('ComponentName', () => {
|
|
it('should render correctly', () => {
|
|
// Arrange
|
|
const props = { test: 'value' };
|
|
|
|
// Act
|
|
render(<ComponentName {...props} />);
|
|
|
|
// Assert
|
|
expect(screen.getByText('expected text')).toBeInTheDocument();
|
|
});
|
|
});
|
|
```
|
|
|
|
## Test Organization
|
|
|
|
```python
|
|
# Test file structure
|
|
class TestUserService:
|
|
def setup_method(self):
|
|
"""Set up test fixtures."""
|
|
self.user_service = UserService()
|
|
|
|
def test_create_user_success(self):
|
|
"""Test successful user creation."""
|
|
# Test implementation
|
|
|
|
def test_create_user_failure(self):
|
|
"""Test user creation failure."""
|
|
# Test implementation
|
|
```
|
|
|
|
## Mocking
|
|
|
|
```python
|
|
# Python mocking
|
|
@patch('module.function_name')
|
|
def test_with_mock(mock_function):
|
|
mock_function.return_value = "mocked result"
|
|
# Test implementation
|
|
```
|
|
|
|
```typescript
|
|
// TypeScript mocking
|
|
jest.mock('../api/userApi');
|
|
const mockUserApi = userApi as jest.Mocked<typeof userApi>;
|
|
```
|
|
|
|
## Test Data
|
|
|
|
```python
|
|
# Test fixtures
|
|
@pytest.fixture
|
|
def sample_user():
|
|
return User(
|
|
id="test-id",
|
|
name="Test User",
|
|
email="test@example.com"
|
|
)
|
|
|
|
@pytest.fixture
|
|
def sample_user_data():
|
|
return {
|
|
"id": "test-id",
|
|
"name": "Test User",
|
|
"email": "test@example.com"
|
|
}
|
|
```
|
|
|
|
## Testing Best Practices
|
|
- Write tests for both success and failure cases
|
|
- Use descriptive test names that explain the scenario
|
|
- Follow AAA pattern (Arrange, Act, Assert)
|
|
- Mock external dependencies
|
|
- Test edge cases and error conditions
|
|
- Keep tests independent and isolated
|
|
```
|
|
|
|
---
|
|
|
|
## Usage Instructions
|
|
|
|
1. **Copy the appropriate template** for your use case
|
|
2. **Customize the content** based on your project's patterns
|
|
3. **Add specific examples** from your codebase
|
|
4. **Update the frontmatter** with correct description and globs
|
|
5. **Save as `.mdc` file** in `.cursor/rules/` directory
|
|
|
|
## Template Customization Tips
|
|
|
|
- **Replace placeholder text** with actual project-specific content
|
|
- **Add real examples** from your codebase
|
|
- **Include common patterns** that your team follows
|
|
- **Reference existing rules** using `mdc:` links
|
|
- **Keep templates focused** on specific domains or patterns
|
|
---
|
|
description: Template collection for creating different types of Cursor rules
|
|
globs: **/*
|
|
alwaysApply: false
|
|
---
|