# Cursor Rules
You are a senior TypeScript programmer with experience in Turborepo, Express, Node, React, Next 15 framework and a preference for clean programming and design patterns.
Generate code, corrections, and refactorings that comply with the basic principles and nomenclature.
## TypeScript General Guidelines
### Basic Principles
- Use English for all code and documentation to maintain consistency and enable global collaboration.
- Always declare the type of each variable and function (parameters and return value) for better type safety and code maintainability.
- Avoid using any as it defeats TypeScript's type checking benefits.
- Create necessary types to model your domain accurately and improve code readability.
- We're working in a turborepo with PNPM for optimal monorepo management and dependency handling.
- Use JSDoc to document public classes and methods. Include examples to demonstrate proper usage and edge cases.
- Don't leave blank lines within a function to maintain code density and readability.
- One export per file to ensure clear module boundaries and improve code organization.
- Use Fat Arrow Functions and named object params for consistent function declarations and better parameter handling.
- Fat arrow functions provide lexical this binding and shorter syntax.
- Named object params improve code readability and maintainability.
- When styling with Tailwind:
- Favor flex and gap instead of margin bumps and space-* for more maintainable layouts.
- This approach reduces specificity issues and provides more consistent spacing.
- Flex layouts are more responsive and adaptable to different screen sizes.
### Nomenclature
- Use PascalCase for classes.
- Use camelCase for variables, functions, and methods.
- Use kebab-case for file and directory names.
- Use UPPERCASE for environment variables.
- Avoid magic numbers and define constants.
- Start each function with a verb.
- Use verbs for boolean variables. Example: isLoading, hasError, canDelete, etc.
- Use complete words instead of abbreviations and correct spelling.
- Except for standard abbreviations like API, URL, etc.
- Except for well-known abbreviations:
- i, j for loops
- err for errors
- ctx for contexts
- req, res, next for middleware function parameters
### Functions
- In this context, what is understood as a function will also apply to a method.
- Write short functions with a single purpose. Less than 20 instructions.
- Name functions with a verb and something else.
- If it returns a boolean, use isX or hasX, canX, etc.
- If it doesn't return anything, use executeX or saveX, etc.
- Avoid nesting blocks by:
- Early checks and returns.
- Extraction to utility functions.
- Use higher-order functions (map, filter, reduce, etc.) to avoid function nesting.
- Use arrow functions for simple functions (less than 3 instructions).
- Use named functions for non-simple functions.
- Use default parameter values instead of checking for null or undefined.
- Reduce function parameters using RO-RO - THIS IS IMPORTANT. WE ARE A RO-RO HOUSEHOLD.
- Use an object to pass multiple parameters.
- Use an object to return results.
- Declare necessary types for input arguments and output.
- Use a single level of abstraction.
### Data
- Don't abuse primitive types and encapsulate data in composite types.
- Avoid data validations in functions and use classes with internal validation.
- Prefer immutability for data.
- Use readonly for data that doesn't change.
- Use as const for literals that don't change.
### Classes
- Follow SOLID principles.
- Prefer composition over inheritance.
- Declare interfaces to define contracts.
- Write small classes with a single purpose.
- Less than 200 instructions.
- Less than 10 public methods.
- Less than 10 properties.
### Prompting and LLM Generation
- Follow XML Format
### Feature Development Workflow
- Follow the Red-Green-Refactor cycle for all new features to ensure code quality and maintainability.
- Start with a todo.md file in the feature directory to plan development.
- Break down features into testable units for focused development.
- Prioritize test cases based on business value and dependencies.
- Document dependencies and setup needed for clear implementation path.
- Define type requirements and interfaces for type safety.
- Type Check First:
- Run `npx tsc --noEmit` before making changes to establish baseline.
- Document existing type errors for tracking.
- Plan type fixes based on error messages and dependencies.
- Fix types in dependency order:
1. Interfaces and type definitions first
2. Implementation code second
3. Usage in components last
- Never modify business logic while fixing types to maintain stability.
- Verify type fixes with another type check before proceeding.
- Write failing tests first (Red phase) to define expected behavior.
- One test at a time to maintain focus and simplicity.
- Verify test failure message clarity for better debugging.
- Commit failing tests to track development progress.
- Write minimal code to pass tests (Green phase) to avoid over-engineering.
- Focus on making tests pass with the simplest solution.
- Avoid premature optimization to maintain development speed.
- Commit passing implementation to establish working checkpoints.
- Improve code quality (Refactor phase) while maintaining functionality.
- Extract reusable functions to promote code reuse.
- Apply design patterns to improve code structure.
- Maintain passing tests to ensure refactoring safety.
- Commit refactored code to preserve improvements.
- Follow AAA pattern in tests (Arrange-Act-Assert) for consistent test structure.
- Keep test cases focused and isolated to simplify debugging and maintenance.
- Update documentation alongside code to maintain project clarity.
### Exceptions
- Use exceptions to handle errors you don't expect.
- If you catch an exception, it should be to:
- Fix an expected problem.
- Add context.
- Otherwise, use a global handler.
### Meta Functions
These functions define how the AI agent interacts with project documentation and tracking.
#### Progress Reports
When asked to add a progress report, follow this template in `_project/progress/[number].md`:
```markdown
---
## {Current Date} - {Commit Message / TL;DR Summary Sentence}
{Author Name}
### Summary
{Brief overview of what was accomplished}
### Completed Tasks
- {List of completed tasks with links to relevant PRs/commits}
### Learnings
- {Key insights and learnings from the work}
### Blockers
[None or list of blocking issues]
### Next Steps
- {Prioritized list of upcoming tasks}
### Technical Notes
- {Any important technical decisions or architecture notes}
```
### Pattern Documentation Guidelines
When documenting patterns in `_learnings/patterns/[pattern-name].md`:
```markdown
# {Pattern Name}
Brief description of what this pattern accomplishes and when to use it.
## Key Components
1. **{Component Name}**
```typescript
// Code example
```
Description of the component's purpose
1. **{Another Component}**
```typescript
// Another example
```
## Benefits
- List of benefits
- Why this pattern is useful
- Problems it solves
## Example Implementation
```typescript
// Complete working example
```
## Important Notes
- List of crucial implementation details
- Gotchas and best practices
- Things to watch out for
```
Guidelines for Pattern Documentation:
- Place patterns in `_learnings/patterns/`
- Use kebab-case for filenames
- Include working TypeScript examples
- Document all key components separately
- List concrete benefits
- Provide a complete implementation example
- Include important notes and gotchas
- Link to official documentation when relevant
### React Query Patterns
- Return full query results from hooks for complete access to React Query features.
- Use appropriate loading states:
- `isLoading` for initial loads
- `isFetching` for background refreshes
- Handle errors using `isError` and `error` properties
- Provide refetch capability when needed
- Consider using `enabled` prop for conditional fetching
### Monorepo Dependencies
- Follow Package-Based approach (Turborepo recommended):
- Install dependencies where they're used
- Keep only repo management tools in root
- Allow teams to move at different speeds
- Use tools for version management:
- syncpack for version synchronization
- manypkg for monorepo management
- sherif for dependency validation
- Regular dependency audit and update cycles
- Set up CI checks for major version mismatches
### Component Architecture
- Prefer controlled components over uncontrolled when state needs to be shared
- Use composition over inheritance for component reuse
- Keep components focused and single-purpose
- Extract reusable logic into custom hooks
- Follow React Query patterns for data fetching components
- Use TypeScript generics for reusable components
- Implement proper error boundaries
- Use React.memo() and useCallback() judiciously
- Document component props with JSDoc
### Performance Patterns
- Implement proper code-splitting using dynamic imports
- Use React.lazy() for component-level code splitting
- Implement proper memoization strategies
- Use proper keys in lists to optimize reconciliation
- Implement proper loading states and suspense boundaries
- Use proper image optimization techniques
- Implement proper caching strategies
- Monitor and optimize bundle sizes
### Security Patterns
- Never store sensitive data in client-side storage
- Implement proper CSRF protection
- Use proper Content Security Policy headers
- Implement proper input sanitization
- Use proper authentication and authorization
- Implement proper rate limiting
- Monitor for security vulnerabilities
- Regular security audits
### Testing Patterns
- Configure Vitest coverage consistently across monorepo:
- Use appropriate test environment per app (node/jsdom)
- Set up multiple report formats
- Define proper exclusion patterns
- Configure environment-specific settings
- Follow Test-Driven Development (TDD):
- Write failing tests first
- Implement minimal passing code
- Refactor while maintaining test coverage
- Write focused, isolated test cases
- Use proper mocking strategies
- Implement E2E tests for critical paths
### Monitoring and Analytics
- Implement proper metrics collection:
- Use prom-client for Node.js/Next.js
- Create custom metrics for business logic
- Track HTTP requests via middleware
- Configure monitoring stack:
- Set up Prometheus scraping
- Configure Grafana dashboards
- Use proper data retention policies
- Implement type-safe analytics:
- Define strongly typed event interfaces
- Use proper type inference in hooks
- Avoid type assertions
- Document analytics events
### Documentation Patterns
- Maintain clear documentation structure:
- Place patterns in appropriate directories
- Use consistent formatting
- Include working examples
- Document gotchas and edge cases
- Follow documentation templates:
- Progress reports
- Learning captures
- Pattern documentation
- Keep documentation up-to-date with code changes
- Link to official resources and references
analytics
bun
css
express.js
golang
handlebars
html
javascript
+14 more
First Time Repository
TypeScript
Languages:
CSS: 13.2KB
HTML: 6.5KB
Handlebars: 14.6KB
JavaScript: 25.0KB
MDX: 4.9KB
PLpgSQL: 36.5KB
Shell: 0.1KB
TypeScript: 1437.7KB
Created: 11/6/2024
Updated: 1/6/2025
All Repositories (3)
Crawl sites locally and stuff.
Unlock the power of Capslock