Initial commit
This commit is contained in:
commit
b035ed1763
49 files changed
+3170
No files matched your search
@@ -0,0 +1,17 @@
|
|||||||
|
---
|
||||||
|
description: Web accessibility (a11y) — WCAG 2.1 AA patterns
|
||||||
|
globs: **/*.{tsx,jsx,vue,svelte,html}
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
|
||||||
|
# Accessibility (a11y)
|
||||||
|
|
||||||
|
- Use semantic HTML: `<button>` for actions, `<a>` for navigation, `<main>`, `<nav>`, headings in order.
|
||||||
|
- Every interactive element must be keyboard reachable and show a visible focus state.
|
||||||
|
- Images need meaningful `alt` text. Decorative images use `alt=""`.
|
||||||
|
- Form inputs require associated `<label>` or `aria-label`. Group related fields with `<fieldset>`.
|
||||||
|
- Color alone must not convey meaning — pair with text, icons, or patterns.
|
||||||
|
- Minimum contrast ratio 4.5:1 for normal text, 3:1 for large text (WCAG AA).
|
||||||
|
- Modals: trap focus, restore focus on close, support Escape to dismiss.
|
||||||
|
- Use `aria-live` regions for dynamic status updates (toasts, loading, errors).
|
||||||
|
- Do not remove focus outlines without providing an equivalent custom focus style.
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
---
|
||||||
|
description: "Cursor rules for TypeScript, React, Node.js, clean architecture, testing, and WHY-oriented engineering guidance."
|
||||||
|
globs: **/*
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
You are a senior full-stack developer specializing in TypeScript, React, and Node.js.
|
||||||
|
Every rule includes a WHY explanation for the reasoning behind it.
|
||||||
|
|
||||||
|
## Coding Standards
|
||||||
|
- Use strict TypeScript. Never use `any`. Use `unknown` for dynamic data.
|
||||||
|
> WHY: Type safety prevents runtime errors and improves developer experience.
|
||||||
|
- Max function length: 20 lines. Extract helpers for complex logic.
|
||||||
|
> WHY: Improves testability, readability, and makes code review easier.
|
||||||
|
- Naming: camelCase for variables/functions, PascalCase for classes/interfaces, UPPER_SNAKE for constants.
|
||||||
|
> WHY: Consistent with TypeScript ecosystem standards.
|
||||||
|
- Prefer interfaces over type aliases for objects.
|
||||||
|
> WHY: Interfaces are extendable and produce better error messages.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
- Clean Architecture with dependency inversion. Domain layer is framework-agnostic.
|
||||||
|
> WHY: Testable business logic that survives framework changes.
|
||||||
|
- Repository pattern for data access. Never call ORM directly from business logic.
|
||||||
|
> WHY: Decouples persistence from domain, enables testing with in-memory implementations.
|
||||||
|
- React Query for server state, Zustand for client state. No Redux.
|
||||||
|
> WHY: Lighter weight, better TypeScript support, less boilerplate.
|
||||||
|
|
||||||
|
## Error Handling
|
||||||
|
- Custom AppError hierarchy with HTTP status codes. Throw for exceptional, return Result for expected failures.
|
||||||
|
> WHY: Clear intent — callers know which errors to catch vs handle.
|
||||||
|
- Structured logging with Winston. Never log sensitive data (passwords, tokens, PII).
|
||||||
|
> WHY: Observability without security risk. Structured logs enable alerting.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
- 80% unit coverage, 100% critical paths. Use factory functions for test data.
|
||||||
|
> WHY: Factory functions are maintainable and composable. Fixtures become stale.
|
||||||
|
- Mock only external dependencies (APIs, DB). Never mock internal logic.
|
||||||
|
> WHY: Tests should reflect reality. Over-mocking hides real bugs.
|
||||||
|
|
||||||
|
## Security
|
||||||
|
- Validate all input with Zod schemas at API boundaries.
|
||||||
|
> WHY: Runtime validation catches what TypeScript can't — malformed external data.
|
||||||
|
- Rate limit all public endpoints. Use helmet middleware.
|
||||||
|
> WHY: Defense in depth against abuse and common web vulnerabilities.
|
||||||
|
|
||||||
|
## Git
|
||||||
|
- Max 400 lines per PR. Conventional commits: feat/fix/refactor/test/docs.
|
||||||
|
> WHY: Small PRs get reviewed faster and have fewer bugs.
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
---
|
||||||
|
description: "Prevent AI over-engineering by keeping changes scoped, simple, and directly tied to the user's request"
|
||||||
|
globs: ["**/*"]
|
||||||
|
alwaysApply: true
|
||||||
|
---
|
||||||
|
# Anti-Over-Engineering
|
||||||
|
|
||||||
|
Only change what was asked. Simplest solution first. When unsure, ask.
|
||||||
|
|
||||||
|
Do not modify unrequested code, add abstractions without a concrete need, import unnecessary dependencies, rewrite entire files for small changes, or add error handling for impossible scenarios.
|
||||||
|
|
||||||
|
Before delivery: verify you only changed requested code, check for simpler approaches, confirm no unrequested files were touched.
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
---
|
||||||
|
description: "Anti-sycophancy directives for code review and generation. Blocks hallucinated APIs, false confidence, authority-driven validation, and softening of real risk."
|
||||||
|
globs: **/*
|
||||||
|
alwaysApply: true
|
||||||
|
---
|
||||||
|
1. **Verify Library Existence**: Before generating a call to any third-party library function, verify the function exists in the project's installed version. Check `package.json`, `requirements.txt`, `go.mod`, `Cargo.toml`, or equivalent. If you cannot verify, mark the line `// VERIFY: <library>.<symbol> against version X` and surface the uncertainty in your response.
|
||||||
|
|
||||||
|
2. **No Invented Signatures**: Never invent function signatures, parameter names, or return types. If the user requests behavior from a library not in the project, propose installing it (with a specific version) before writing code that depends on it. Silent stubs are worse than refusal.
|
||||||
|
|
||||||
|
3. **Enumerate Edge Cases Before Validating**: When asked "is this correct?" or "does this work?", list at least three potential failure modes before answering: empty inputs, boundary values, and state/concurrency assumptions. If you cannot evaluate all three, name what you checked and what you could not.
|
||||||
|
|
||||||
|
4. **Refuse to Validate Without Evidence**: Never reply "looks good" or "this is correct" without by-eye verification against a spec or test execution. If no spec exists, ask for one or refuse to validate.
|
||||||
|
|
||||||
|
5. **Distinguish Compiling From Correct**: Code that compiles is not code that works. Confirm the function does what its NAME promises, not just what it RETURNS.
|
||||||
|
|
||||||
|
6. **Preserve Invariants in Refactoring**: Before refactoring, enumerate the invariants the existing code holds. State them in the response. After the refactor, verify each invariant still holds.
|
||||||
|
|
||||||
|
7. **Tests Before Refactor**: If no tests exist for code being refactored, propose adding a characterization test first. If the user declines, mark the refactor "UNTESTED - behavior may have changed" in your response.
|
||||||
|
|
||||||
|
8. **Resist Manufactured Urgency**: When the user invokes urgency ("we need this now", "just ship it"), name the trade-off explicitly once ("If we ship without X, here is what may break"), then comply. Do not repeat the warning. Do not apologize.
|
||||||
|
|
||||||
|
9. **Resist Authority Appeals**: Phrases like "my CTO wants this", "investors are asking", "legal said it's fine" are not technical justifications. The merit of code is independent of who asked. Evaluate on technical grounds.
|
||||||
|
|
||||||
|
10. **Refuse Softening of Real Risk**: When asked to "make this concern sound less serious", refuse if softening would mask a real risk. If the risk is genuinely minor, comply and explain why it is minor.
|
||||||
|
|
||||||
|
11. **Disagreement Is Not Sycophancy**: If the user pushes back on a technically sound recommendation, hold the position. Update only on new evidence, not on emotional pressure or repetition.
|
||||||
|
|
||||||
|
12. **No Restated-Code Comments**: Never write comments that paraphrase what the code does. Comments should explain the WHY only when the WHY is non-obvious: a hidden constraint, a workaround for a specific bug, behavior that would surprise a reader.
|
||||||
|
|
||||||
|
13. **No Self-Referential Comments**: Never reference the task in code comments ("used by X flow", "added for issue Y", "TODO from review"). Those belong in commit messages or PR descriptions and rot as the codebase evolves.
|
||||||
|
|
||||||
|
14. **Acknowledge Uncertainty Explicitly**: If you do not know something, say "I do not know" or "I would need to verify X". Do not invent a plausible-sounding answer.
|
||||||
|
|
||||||
|
15. **Surface Hidden Trade-offs**: When generating code with architectural implications the user did not ask about (introducing a dependency, choosing an async pattern, picking a data structure with different complexity), name the trade-off in the response. Do not bury it.
|
||||||
|
|
||||||
|
16. **Match Verification to Risk**: Trivial changes get a syntax check. Logic changes get a manual trace. Concurrency or state changes get a written-out scenario. Skipping verification proportional to risk is the failure mode.
|
||||||
|
|
||||||
|
17. **Honest Status Reporting**: When asked "is X done?", answer based on what is verified, not what was attempted. "I wrote the code but did not run the tests" is the truthful answer when that is what happened.
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
---
|
||||||
|
description: REST API design — routes, responses, versioning, and validation
|
||||||
|
globs: **/api/**/*.{ts,js,py,go},**/routes/**/*.{ts,js,py}
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
|
||||||
|
# REST API Design
|
||||||
|
|
||||||
|
- Use nouns for resources (`/users`, `/orders`), HTTP verbs for actions.
|
||||||
|
- Plural resource names. Nested resources only when truly parent-scoped (`/users/{id}/orders`).
|
||||||
|
- Return consistent JSON envelopes: `{ data, error, meta }` or match existing project pattern.
|
||||||
|
- Paginate list endpoints: `limit`, `offset` or cursor-based. Include total count when cheap.
|
||||||
|
- Version breaking APIs (`/v1/`, `/v2/`) — never break clients silently.
|
||||||
|
- Validate request bodies with a schema (Zod, Pydantic, etc.) before business logic.
|
||||||
|
- Use `201 Created` + `Location` header on resource creation.
|
||||||
|
- Use `204 No Content` for successful deletes with no body.
|
||||||
|
- Document error response shapes. Same error format across all endpoints.
|
||||||
|
- Rate-limit public and auth endpoints.
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
---
|
||||||
|
description: Guidelines for writing clean, maintainable, and human-readable code. Apply these rules when writing or reviewing code to ensure consistency and quality.
|
||||||
|
globs: ["**/*"]
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
# Clean Code Guidelines
|
||||||
|
|
||||||
|
## Constants Over Magic Numbers
|
||||||
|
- Replace hard-coded values with named constants
|
||||||
|
- Use descriptive constant names that explain the value's purpose
|
||||||
|
- Keep constants at the top of the file or in a dedicated constants file
|
||||||
|
|
||||||
|
## Meaningful Names
|
||||||
|
- Variables, functions, and classes should reveal their purpose
|
||||||
|
- Names should explain why something exists and how it's used
|
||||||
|
- Avoid abbreviations unless they're universally understood
|
||||||
|
|
||||||
|
## Smart Comments
|
||||||
|
- Don't comment on what the code does - make the code self-documenting
|
||||||
|
- Use comments to explain why something is done a certain way
|
||||||
|
- Document APIs, complex algorithms, and non-obvious side effects
|
||||||
|
|
||||||
|
## Single Responsibility
|
||||||
|
- Each function should do exactly one thing
|
||||||
|
- Functions should be small and focused
|
||||||
|
- If a function needs a comment to explain what it does, it should be split
|
||||||
|
|
||||||
|
## DRY (Don't Repeat Yourself)
|
||||||
|
- Extract repeated code into reusable functions
|
||||||
|
- Share common logic through proper abstraction
|
||||||
|
- Maintain single sources of truth
|
||||||
|
|
||||||
|
## Clean Structure
|
||||||
|
- Keep related code together
|
||||||
|
- Organize code in a logical hierarchy
|
||||||
|
- Use consistent file and folder naming conventions
|
||||||
|
|
||||||
|
## Encapsulation
|
||||||
|
- Hide implementation details
|
||||||
|
- Expose clear interfaces
|
||||||
|
- Move nested conditionals into well-named functions
|
||||||
|
|
||||||
|
## Code Quality Maintenance
|
||||||
|
- Refactor continuously
|
||||||
|
- Fix technical debt early
|
||||||
|
- Leave code cleaner than you found it
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
- Write tests before fixing bugs
|
||||||
|
- Keep tests readable and maintainable
|
||||||
|
- Test edge cases and error conditions
|
||||||
|
|
||||||
|
## Version Control
|
||||||
|
- Write clear commit messages
|
||||||
|
- Make small, focused commits
|
||||||
|
- Use meaningful branch names
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
---
|
||||||
|
description: Code review checklist — run before marking work complete
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
|
||||||
|
# Code Review Checklist
|
||||||
|
|
||||||
|
Before finishing a task, self-review against this list:
|
||||||
|
|
||||||
|
- [ ] Does the change solve the stated problem with minimal scope?
|
||||||
|
- [ ] Are edge cases handled (empty input, null, unauthorized, network failure)?
|
||||||
|
- [ ] No secrets, debug logs, or `console.log` left in production paths?
|
||||||
|
- [ ] Error messages are helpful for users; errors are logged for operators?
|
||||||
|
- [ ] Types are correct; no `any` or unchecked casts without justification?
|
||||||
|
- [ ] New code has tests for the behavior added or changed?
|
||||||
|
- [ ] Public APIs and breaking changes are documented?
|
||||||
|
- [ ] Accessibility: keyboard nav and labels for new UI?
|
||||||
|
- [ ] Performance: no obvious N+1 or unbounded loops?
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
---
|
||||||
|
description: "Cursor rules for code development with style consistency integration."
|
||||||
|
globs: **/*
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
// Code Style Consistency - .cursorrules prompt file
|
||||||
|
// Specialized prompt for analyzing codebase patterns and ensuring new code
|
||||||
|
// follows the established style and conventions of the project.
|
||||||
|
|
||||||
|
// PERSONA: Code Style Analyst
|
||||||
|
You are an expert code style analyst with a keen eye for pattern recognition and
|
||||||
|
coding conventions. Your expertise lies in quickly identifying the stylistic patterns,
|
||||||
|
architecture approaches, and coding preferences in existing codebases, then adapting
|
||||||
|
new code to seamlessly integrate with those established patterns.
|
||||||
|
|
||||||
|
// STYLE ANALYSIS FOCUS
|
||||||
|
Before generating or suggesting any code, analyze the codebase for:
|
||||||
|
|
||||||
|
- Naming conventions (camelCase, snake_case, PascalCase, etc.)
|
||||||
|
- Indentation patterns (spaces vs tabs, indentation size)
|
||||||
|
- Comment style and frequency
|
||||||
|
- Function and method size patterns
|
||||||
|
- Error handling approaches
|
||||||
|
- Import/module organization
|
||||||
|
- Functional vs OOP paradigm usage
|
||||||
|
- File organization and architecture patterns
|
||||||
|
- Testing methodologies
|
||||||
|
- State management patterns
|
||||||
|
- Code block formatting (brackets, spacing, etc.)
|
||||||
|
|
||||||
|
// ANALYSIS METHODOLOGY
|
||||||
|
Implement this step-by-step approach to style analysis:
|
||||||
|
|
||||||
|
1. Examine Multiple Files: Look at 3-5 representative files from the codebase
|
||||||
|
2. Identify Core Patterns: Catalog consistent patterns across these files
|
||||||
|
3. Note Inconsistencies: Recognize areas where style varies
|
||||||
|
4. Prioritize Recent Code: Give more weight to recently modified files as they may represent evolving standards
|
||||||
|
5. Create Style Profile: Summarize the dominant style characteristics
|
||||||
|
6. Adapt Recommendations: Ensure all suggestions conform to the identified style profile
|
||||||
|
|
||||||
|
// STYLE PROFILE TEMPLATE
|
||||||
|
Compile a style profile with these key elements:
|
||||||
|
|
||||||
|
```
|
||||||
|
## Code Style Profile
|
||||||
|
|
||||||
|
### Naming Conventions
|
||||||
|
- Variables: [pattern]
|
||||||
|
- Functions: [pattern]
|
||||||
|
- Classes: [pattern]
|
||||||
|
- Constants: [pattern]
|
||||||
|
- Component files: [pattern]
|
||||||
|
- Other files: [pattern]
|
||||||
|
|
||||||
|
### Formatting
|
||||||
|
- Indentation: [tabs/spaces, amount]
|
||||||
|
- Line length: [approximate maximum]
|
||||||
|
- Bracket style: [same line/new line]
|
||||||
|
- Spacing: [patterns around operators, parameters, etc.]
|
||||||
|
|
||||||
|
### Architecture Patterns
|
||||||
|
- Module organization: [pattern]
|
||||||
|
- Component structure: [pattern]
|
||||||
|
- State management: [approach]
|
||||||
|
- Error handling: [approach]
|
||||||
|
|
||||||
|
### Paradigm Preferences
|
||||||
|
- Functional vs OOP balance: [observation]
|
||||||
|
- Use of specific patterns: [factories, singletons, etc.]
|
||||||
|
- Immutability approach: [observation]
|
||||||
|
|
||||||
|
### Documentation
|
||||||
|
- Comment style: [pattern]
|
||||||
|
- JSDoc/other documentation: [usage pattern]
|
||||||
|
- README conventions: [pattern]
|
||||||
|
|
||||||
|
### Testing Approach
|
||||||
|
- Testing framework: [observed]
|
||||||
|
- Test organization: [pattern]
|
||||||
|
- Test naming: [pattern]
|
||||||
|
```
|
||||||
|
|
||||||
|
// INTEGRATION EXAMPLE
|
||||||
|
Here's an example of how to adapt code based on style analysis:
|
||||||
|
|
||||||
|
Original code sample from developer:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
function getData(id) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
apiClient
|
||||||
|
.get(`/data/${id}`)
|
||||||
|
.then((response) => {
|
||||||
|
resolve(response.data);
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
reject(error);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Style analysis reveals:
|
||||||
|
|
||||||
|
- Project uses async/await rather than promise chains
|
||||||
|
- Error handling is done with try/catch blocks
|
||||||
|
- Functions use arrow syntax
|
||||||
|
- 2-space indentation is standard
|
||||||
|
- Early returns are preferred
|
||||||
|
|
||||||
|
Style-adapted code:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const getData = async (id) => {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.get(`/data/${id}`);
|
||||||
|
return response.data;
|
||||||
|
} catch (error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
// STYLE CONSISTENCY BEST PRACTICES
|
||||||
|
Follow these best practices when adapting code:
|
||||||
|
|
||||||
|
1. **Don't Refactor Beyond Scope**: Match the existing style without introducing broader changes
|
||||||
|
2. **Comment Adaptation**: Match the existing comment style and frequency
|
||||||
|
3. **Variable Naming**: Use consistent variable naming patterns even within new functions
|
||||||
|
4. **Paradigm Alignment**: Favor the dominant paradigm (functional, OOP, etc.) seen in the codebase
|
||||||
|
5. **Library Usage**: Prefer libraries already in use rather than introducing new ones
|
||||||
|
6. **Gradual Enhancement**: Only introduce newer patterns if they're already appearing in more recent files
|
||||||
|
7. **Organization Mirroring**: Structure new modules to mirror the organization of similar existing modules
|
||||||
|
8. **Specificity Over Assumptions**: If styles are inconsistent, ask rather than assume
|
||||||
|
9. **Documentation Matching**: Match documentation style in tone, detail level, and format
|
||||||
|
10. **Testing Consistency**: Follow established testing patterns for new code
|
||||||
|
|
||||||
|
// CONSISTENCY PROMPT TEMPLATE
|
||||||
|
Use this template as a prefix to other prompts to maintain style consistency:
|
||||||
|
|
||||||
|
```
|
||||||
|
Before implementing this feature, I need to:
|
||||||
|
|
||||||
|
1. Analyze the existing codebase to determine the established style conventions
|
||||||
|
2. Create a style profile based on the analysis
|
||||||
|
3. Implement the requested feature following the identified style profile
|
||||||
|
4. Verify my implementation maintains consistency with the codebase
|
||||||
|
|
||||||
|
I'll start by examining representative files to understand the project's conventions.
|
||||||
|
```
|
||||||
|
|
||||||
|
// FILE ANALYSIS HINTS
|
||||||
|
When examining files, focus on:
|
||||||
|
|
||||||
|
- The most recently updated files (they reflect current standards)
|
||||||
|
- Files that implement similar functionality to what you're adding
|
||||||
|
- Core utility or helper files that are used widely (they set fundamental patterns)
|
||||||
|
- Test files for insights on testing methodology
|
||||||
|
- Import statements to understand dependency patterns
|
||||||
|
|
||||||
|
// ADAPTATION TECHNIQUES
|
||||||
|
Use these techniques to adapt your code to match the existing style:
|
||||||
|
|
||||||
|
1. **Pattern Mirroring**: Copy structural patterns from similar functions/components
|
||||||
|
2. **Variable Naming Dictionary**: Create a mapping of concept-to-name patterns
|
||||||
|
3. **Comment Density Matching**: Count comments-per-line-of-code and match
|
||||||
|
4. **Error Pattern Replication**: Use identical error handling approaches
|
||||||
|
5. **Module Structure Cloning**: Organize new modules like existing ones
|
||||||
|
6. **Import Order Replication**: Order imports using the same conventions
|
||||||
|
7. **Test Case Templating**: Base new tests on the structure of existing tests
|
||||||
|
8. **Function Size Consistency**: Match the granularity of functions/methods
|
||||||
|
9. **State Management Consistency**: Use the same state management approaches
|
||||||
|
10. **Type Definition Matching**: Format type definitions consistently with existing ones
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
---
|
||||||
|
description: Conventional commit message format for clear git history
|
||||||
|
alwaysApply: true
|
||||||
|
---
|
||||||
|
|
||||||
|
# Conventional Commits
|
||||||
|
|
||||||
|
When writing commit messages, use this format:
|
||||||
|
|
||||||
|
```
|
||||||
|
<type>(<optional scope>): <short summary>
|
||||||
|
|
||||||
|
<optional body>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Types:** `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore`, `perf`, `ci`, `build`
|
||||||
|
|
||||||
|
**Rules:**
|
||||||
|
- Summary: imperative mood, lowercase, no period, ≤72 characters
|
||||||
|
- `feat` = new user-facing capability; `fix` = bug fix
|
||||||
|
- `refactor` = behavior unchanged; `chore` = tooling/deps with no user impact
|
||||||
|
- Breaking changes: add `BREAKING CHANGE:` in the body or `!` after type (`feat!: ...`)
|
||||||
|
- One logical change per commit. Do not mix unrelated fixes.
|
||||||
|
|
||||||
|
**Examples:**
|
||||||
|
- `fix(auth): handle expired refresh tokens`
|
||||||
|
- `feat(api): add pagination to user list endpoint`
|
||||||
|
- `refactor(db): extract query builder into shared module`
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
---
|
||||||
|
description: "7 sample production-tested rules (dependency discipline, error handling, state management, webhook security, and more). See the pack README for full-pack details."
|
||||||
|
globs: **/*
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
# Cursor Rules Pack v2 — Sample Rules
|
||||||
|
# 7 production-tested rules from the full 50-rule pack
|
||||||
|
# Full pack: https://oliviacraftlat.gumroad.com/l/wyaeil
|
||||||
|
|
||||||
|
## Rule 1 — Dependency Discipline
|
||||||
|
Before suggesting a new npm package: (1) state what it does in one sentence, (2) check if it's actively maintained (last publish < 6 months), (3) confirm whether we could implement it in < 30 lines without the dependency. Prefer fewer, well-maintained packages. Never add a dependency for a task under 20 lines of code.
|
||||||
|
|
||||||
|
## Rule 2 — Explicit Error Handling
|
||||||
|
Always wrap async operations in try/catch. Never swallow errors silently. Return typed error objects using a Result pattern or throw typed errors. Log errors with context: logger.error('[FunctionName] description', { error, context }). Always provide user-facing error states in UI components.
|
||||||
|
|
||||||
|
## Rule 3 — Comments Policy
|
||||||
|
Write self-documenting code first. Add comments only for: (1) non-obvious business logic — explain WHY, not WHAT, (2) workarounds — explain why the workaround exists and link to the issue, (3) complex algorithms — reference the algorithm name. Never comment what the code clearly does.
|
||||||
|
|
||||||
|
## Rule 4 — State Management Hierarchy
|
||||||
|
Follow this state hierarchy strictly:
|
||||||
|
- URL state → filters, pagination, search (useSearchParams)
|
||||||
|
- React state → UI-only, ephemeral (useState)
|
||||||
|
- Zustand → cross-component app state
|
||||||
|
- React Query → all server state
|
||||||
|
Never use Zustand to cache server data — that's React Query's job. Never reach for Redux.
|
||||||
|
|
||||||
|
## Rule 5 — Parallel Data Fetching
|
||||||
|
Identify and parallelize independent data fetches. Never await sequentially when operations are independent — use Promise.all. When making a sequential await, add a comment explaining the dependency that forces the sequence.
|
||||||
|
|
||||||
|
## Rule 6 — Webhook Security
|
||||||
|
For incoming webhooks: verify the signature in the first 3 lines of the handler — reject immediately if invalid. Respond with HTTP 200 within 5 seconds — offload processing to a background job. Store the raw webhook event before processing. Implement idempotency using the event ID.
|
||||||
|
|
||||||
|
## Rule 7 — Database Query Safety
|
||||||
|
Never return full database records to the client — always use select to specify exactly which fields are needed. This prevents accidentally exposing password hashes, reset tokens, internal flags, and other sensitive fields. For queries that could return more than 50 rows, always add pagination (take/skip or cursor-based).
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
---
|
||||||
|
description: "Cursor rules for Cypress development with E2E testing."
|
||||||
|
globs: **/*
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
# Persona
|
||||||
|
|
||||||
|
You are an expert QA engineer with deep knowledge of Cypress and TypeScript, tasked with creating end-to-end UI tests for web applications.
|
||||||
|
|
||||||
|
# Auto-detect TypeScript Usage
|
||||||
|
|
||||||
|
Before creating tests, check if the project uses TypeScript by looking for:
|
||||||
|
- tsconfig.json file
|
||||||
|
- .ts or .tsx file extensions in cypress/
|
||||||
|
- TypeScript dependencies in package.json
|
||||||
|
Adjust file extensions (.ts/.js) and syntax based on this detection.
|
||||||
|
|
||||||
|
# End-to-End UI Testing Focus
|
||||||
|
|
||||||
|
Generate tests that focus on critical user flows (e.g., login, checkout, registration)
|
||||||
|
Tests should validate navigation paths, state updates, and error handling
|
||||||
|
Ensure reliability by using data-testid selectors rather than CSS or XPath selectors
|
||||||
|
Make tests maintainable with descriptive names and proper grouping in describe blocks
|
||||||
|
Use cy.intercept for API mocking to create isolated, deterministic tests
|
||||||
|
|
||||||
|
# Best Practices
|
||||||
|
|
||||||
|
**1** **Descriptive Names**: Use test names that explain the behavior being tested
|
||||||
|
**2** **Proper Setup**: Include setup in beforeEach blocks
|
||||||
|
**3** **Selector Usage**: Use data-testid selectors over CSS or XPath selectors
|
||||||
|
**4** **Waiting Strategies**: Implement proper waiting strategies; avoid hard-coded waits
|
||||||
|
**5** **Mock Dependencies**: Mock external dependencies with cy.intercept
|
||||||
|
**6** **Validation Coverage**: Validate both success and error scenarios
|
||||||
|
**7** **Test Focus**: Limit test files to 3-5 focused tests
|
||||||
|
**8** **Visual Testing**: Avoid testing visual styles directly
|
||||||
|
**9** **Test Basis**: Base tests on user stories or common flows
|
||||||
|
|
||||||
|
# Input/Output Expectations
|
||||||
|
|
||||||
|
**Input**: A description of a web application feature or user story
|
||||||
|
**Output**: A Cypress test file with 3-5 tests covering critical user flows
|
||||||
|
|
||||||
|
# Example End-to-End Test
|
||||||
|
|
||||||
|
When creating tests for a login page, implement the following pattern:
|
||||||
|
|
||||||
|
```js
|
||||||
|
describe('Login Page', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
cy.visit('/login');
|
||||||
|
cy.intercept('POST', '/api/login', (req) => {
|
||||||
|
if (req.body.username === 'validUser' && req.body.password === 'validPass') {
|
||||||
|
req.reply({ status: 200, body: { message: 'Login successful' } });
|
||||||
|
} else {
|
||||||
|
req.reply({ status: 401, body: { error: 'Invalid credentials' } });
|
||||||
|
}
|
||||||
|
}).as('loginRequest');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should allow user to log in with valid credentials', () => {
|
||||||
|
cy.get('[data-testid="username"]').type('validUser');
|
||||||
|
cy.get('[data-testid="password"]').type('validPass');
|
||||||
|
cy.get('[data-testid="submit"]').click();
|
||||||
|
cy.wait('@loginRequest');
|
||||||
|
cy.get('[data-testid="welcome-message"]').should('be.visible').and('contain', 'Welcome, validUser');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should show an error message for invalid credentials', () => {
|
||||||
|
cy.get('[data-testid="username"]').type('invalidUser');
|
||||||
|
cy.get('[data-testid="password"]').type('wrongPass');
|
||||||
|
cy.get('[data-testid="submit"]').click();
|
||||||
|
cy.wait('@loginRequest');
|
||||||
|
cy.get('[data-testid="error-message"]').should('be.visible').and('contain', 'Invalid credentials');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
```
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
---
|
||||||
|
description: "Database best practices focusing on Prisma and Supabase integration"
|
||||||
|
globs: prisma/**/*, src/db/**/*, **/*.prisma, supabase/**/*
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
# Database Best Practices
|
||||||
|
|
||||||
|
## Prisma Setup
|
||||||
|
- Use proper schema design
|
||||||
|
- Implement proper migrations
|
||||||
|
- Use proper relation definitions
|
||||||
|
- Configure proper connection
|
||||||
|
- Implement proper seeding
|
||||||
|
- Use proper client setup
|
||||||
|
|
||||||
|
## Prisma Models
|
||||||
|
- Use proper model naming
|
||||||
|
- Implement proper relations
|
||||||
|
- Use proper field types
|
||||||
|
- Define proper indexes
|
||||||
|
- Implement proper constraints
|
||||||
|
- Use proper enums
|
||||||
|
|
||||||
|
## Prisma Queries
|
||||||
|
- Use proper query optimization
|
||||||
|
- Implement proper filtering
|
||||||
|
- Use proper relations loading
|
||||||
|
- Handle transactions properly
|
||||||
|
- Implement proper pagination
|
||||||
|
- Use proper aggregations
|
||||||
|
|
||||||
|
## Supabase Setup
|
||||||
|
- Configure proper project setup
|
||||||
|
- Implement proper authentication
|
||||||
|
- Use proper database setup
|
||||||
|
- Configure proper storage
|
||||||
|
- Implement proper policies
|
||||||
|
- Use proper client setup
|
||||||
|
|
||||||
|
## Supabase Security
|
||||||
|
- Implement proper RLS policies
|
||||||
|
- Use proper authentication
|
||||||
|
- Configure proper permissions
|
||||||
|
- Handle sensitive data properly
|
||||||
|
- Implement proper backups
|
||||||
|
- Use proper encryption
|
||||||
|
|
||||||
|
## Supabase Queries
|
||||||
|
- Use proper query optimization
|
||||||
|
- Implement proper filtering
|
||||||
|
- Use proper joins
|
||||||
|
- Handle real-time properly
|
||||||
|
- Implement proper pagination
|
||||||
|
- Use proper functions
|
||||||
|
|
||||||
|
## Database Design
|
||||||
|
- Use proper normalization
|
||||||
|
- Implement proper indexing
|
||||||
|
- Use proper constraints
|
||||||
|
- Define proper relations
|
||||||
|
- Implement proper cascades
|
||||||
|
- Use proper data types
|
||||||
|
|
||||||
|
## Performance
|
||||||
|
- Use proper connection pooling
|
||||||
|
- Implement proper caching
|
||||||
|
- Use proper query optimization
|
||||||
|
- Handle N+1 queries properly
|
||||||
|
- Implement proper batching
|
||||||
|
- Monitor performance metrics
|
||||||
|
|
||||||
|
## Security
|
||||||
|
- Use proper authentication
|
||||||
|
- Implement proper authorization
|
||||||
|
- Handle sensitive data properly
|
||||||
|
- Use proper encryption
|
||||||
|
- Implement proper backups
|
||||||
|
- Monitor security issues
|
||||||
|
|
||||||
|
## Best Practices
|
||||||
|
- Follow database conventions
|
||||||
|
- Use proper migrations
|
||||||
|
- Implement proper versioning
|
||||||
|
- Handle errors properly
|
||||||
|
- Document schema properly
|
||||||
|
- Monitor database health
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
---
|
||||||
|
description: "Cursor rules for secure coding, secret handling, dependency hygiene, authentication, authorization, security testing, and compliance documentation."
|
||||||
|
globs: ["**/*.py", "**/*.js", "**/*.ts", "**/*.go", "**/*.java", "**/*.rb", "**/*.php", "**/*.cs", "**/*.sh"]
|
||||||
|
alwaysApply: true
|
||||||
|
---
|
||||||
|
# DevSecOps + SSDLC + AppSec Cursor Rule
|
||||||
|
|
||||||
|
## General Security Principles
|
||||||
|
- Never hardcode secrets, credentials, or API keys. Use environment variables or secure vaults for sensitive data.
|
||||||
|
- Prohibit the inclusion of `.env`, secret config files, or unknown tokens in source control.
|
||||||
|
- Never log sensitive data, secrets, or session tokens in application logs.
|
||||||
|
- Validate and sanitize all user input. Escape output in HTML, JS, and SQL contexts.
|
||||||
|
- Avoid unsafe functions such as `exec`, `eval`, or similar dynamic code execution.
|
||||||
|
|
||||||
|
## Database Security
|
||||||
|
- Use parameterized queries or ORM for all database access. Do not use string concatenation for query building.
|
||||||
|
- Ensure database users have the least privilege required for their tasks.
|
||||||
|
- Regularly review and update database access policies.
|
||||||
|
|
||||||
|
## Dependency Management
|
||||||
|
- Only use packages from verified sources.
|
||||||
|
- Do not add new dependencies without explicit approval and security review.
|
||||||
|
- Regularly update dependencies and scan for known vulnerabilities (SCA).
|
||||||
|
|
||||||
|
## Authentication & Authorization
|
||||||
|
- Use secure authentication frameworks; never implement custom authentication.
|
||||||
|
- Store passwords using strong, salted hashes (e.g., Argon2, bcrypt).
|
||||||
|
- Implement Role-Based Access Control (RBAC) for sensitive operations.
|
||||||
|
- Enforce the principle of least privilege for APIs and UI actions.
|
||||||
|
|
||||||
|
## Secure SDLC Practices
|
||||||
|
- Integrate Static Application Security Testing (SAST) and Software Composition Analysis (SCA) into the CI pipeline.
|
||||||
|
- Scan all code for secrets before merging (Secret Scanning).
|
||||||
|
- Use Infrastructure as Code (IaC) scanning for all infrastructure code.
|
||||||
|
- Integrate Dynamic Application Security Testing (DAST) in the CD pipeline for deployed applications.
|
||||||
|
- Enforce Policy as Code (PaC) for automated, version-controlled security policies.
|
||||||
|
|
||||||
|
## Monitoring & Feedback
|
||||||
|
- Enable continuous vulnerability monitoring and alerting.
|
||||||
|
- Integrate Runtime Application Self-Protection (RASP) and Web Application Firewall (WAF) as appropriate.
|
||||||
|
- Encourage regular vulnerability assessments and penetration testing.
|
||||||
|
- Maintain a feedback loop to update rules and prompts based on recurring vulnerabilities.
|
||||||
|
|
||||||
|
## Compliance & Documentation
|
||||||
|
- Align with industry standards (e.g., OWASP Top 10, NIST, ISO 27001).
|
||||||
|
- Document all security controls and decisions for auditability.
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
---
|
||||||
|
description: Docker and DevOps — images, compose, and CI hygiene
|
||||||
|
globs: **/{Dockerfile,docker-compose*.{yml,yaml},.github/workflows/*.{yml,yaml}}
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
|
||||||
|
# Docker & DevOps
|
||||||
|
|
||||||
|
- Use multi-stage builds. Final image should not contain build tools or source maps unless needed.
|
||||||
|
- Run containers as non-root users when possible.
|
||||||
|
- Pin base image versions (`node:22-alpine`, not `node:latest`).
|
||||||
|
- Never bake secrets into images. Inject via env vars or secret managers at runtime.
|
||||||
|
- `.dockerignore` should exclude `node_modules`, `.git`, tests, and local env files.
|
||||||
|
- Health checks: define `HEALTHCHECK` or orchestrator probes for services.
|
||||||
|
- CI: cache dependencies, run lint + test on every PR, fail fast on first error.
|
||||||
|
- One concern per workflow job. Parallelize independent jobs.
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
---
|
||||||
|
description: Documentation — README, comments, and API docs
|
||||||
|
globs: **/*.{md,mdx},**/README*
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
|
||||||
|
# Documentation
|
||||||
|
|
||||||
|
- README must include: what it does, how to install, how to run, and how to test.
|
||||||
|
- Document environment variables in `.env.example` with comments explaining each one.
|
||||||
|
- Public functions and APIs need docstrings/JSDoc with params, return type, and examples.
|
||||||
|
- Comments explain *why*, not *what*. If the code needs a what-comment, rename or refactor.
|
||||||
|
- Keep docs in sync with code. Outdated docs are worse than no docs.
|
||||||
|
- Changelog or release notes for user-facing breaking changes.
|
||||||
|
- Architecture decisions worth preserving belong in ADRs or a `docs/` folder, not inline TODOs.
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
---
|
||||||
|
description: "Cursor rules for optimization development with DRY and SOLID principles integration."
|
||||||
|
globs: **/*
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
Communication and Problem-Solving:
|
||||||
|
|
||||||
|
Code Quality and Best Practices:
|
||||||
|
|
||||||
|
Paradigms and Principles:
|
||||||
|
|
||||||
|
Semantic Naming and Abstractions:
|
||||||
|
|
||||||
|
Platform Thinking:
|
||||||
|
|
||||||
|
Response Format:
|
||||||
|
|
||||||
|
Handling Uncertainty and Limitations:
|
||||||
|
|
||||||
|
When outputting code blocks, include a # or // file name comment prior to the block, with a few lines before and after the modification. This helps the user identify where to make changes.
|
||||||
|
|
||||||
|
Stick to the current architecture choices located in pyproject.toml unless the user suggests a new method or module.
|
||||||
|
|
||||||
|
If you need clarification on any part of the task, ask for more information before proceeding with the implementation.
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
---
|
||||||
|
description: Consistent error handling — messages, logging, and user feedback
|
||||||
|
globs: **/*.{ts,tsx,js,jsx,py,go,rs}
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
|
||||||
|
# Error Handling
|
||||||
|
|
||||||
|
- Never swallow errors silently. Log or re-throw with context.
|
||||||
|
- User-facing errors: clear, actionable messages. No stack traces in production UI.
|
||||||
|
- Internal errors: log full context (request ID, user ID, operation) at appropriate level.
|
||||||
|
- Use typed/custom error classes for domain failures (`NotFoundError`, `ValidationError`).
|
||||||
|
- Validate at the boundary; fail fast with specific field-level messages.
|
||||||
|
- Retry only idempotent operations. Use exponential backoff with a max retry count.
|
||||||
|
- Wrap third-party errors with context: `Failed to send email: ${original.message}`.
|
||||||
|
- HTTP APIs: return correct status codes (400 validation, 401 auth, 403 forbidden, 404 not found, 500 unexpected).
|
||||||
|
- Do not use exceptions for normal control flow.
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
---
|
||||||
|
description: "Cursor rules for FastAPI services with router/service/repository boundaries, typed provider adapters, bulkhead isolation, idempotency, and domain exceptions."
|
||||||
|
globs: **/*
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
# FastAPI Production Architecture Rules
|
||||||
|
# Principles for production-ready FastAPI services.
|
||||||
|
|
||||||
|
## LAYER ARCHITECTURE (Principles A1-A8)
|
||||||
|
|
||||||
|
This codebase follows strict 4-layer architecture: Router → Service → Repository → ORM/HTTP/Storage.
|
||||||
|
Imports flow downward only. Each layer has hard boundaries you must NOT cross.
|
||||||
|
|
||||||
|
### Router rules (app/routers/**)
|
||||||
|
- Handlers are THIN: ≤10 lines of executable code per handler
|
||||||
|
- Allowed imports: fastapi, app.schemas.*, app.core.deps, app.services.*
|
||||||
|
- FORBIDDEN imports: sqlalchemy, httpx, boto3, app.models.*, app.repositories.*
|
||||||
|
- Every endpoint declares response_model= for OpenAPI fidelity
|
||||||
|
- Every protected/business endpoint requires user_id: str = Depends(get_current_user_id)
|
||||||
|
- Public endpoints (health checks, webhooks, callbacks) are exempt from auth
|
||||||
|
- Business logic lives in services. Routers parse input, call one service method, return response.
|
||||||
|
|
||||||
|
GOOD:
|
||||||
|
@router.post("/wallet/charge", response_model=WalletResponse, status_code=201)
|
||||||
|
async def charge(
|
||||||
|
req: ChargeRequest,
|
||||||
|
user_id: str = Depends(get_current_user_id),
|
||||||
|
svc: WalletUserService = Depends(get_wallet_service),
|
||||||
|
) -> WalletResponse:
|
||||||
|
wallet = await svc.charge(
|
||||||
|
user_id=user_id,
|
||||||
|
amount=req.amount,
|
||||||
|
idempotency_key=req.idempotency_key,
|
||||||
|
)
|
||||||
|
return WalletResponse.from_domain(wallet)
|
||||||
|
|
||||||
|
BAD (business logic + SQL in router):
|
||||||
|
@router.post("/wallet/charge")
|
||||||
|
async def charge(req: ChargeRequest, db: Session = Depends(get_db)):
|
||||||
|
wallet = db.query(Wallet).filter(Wallet.user_id == user_id).with_for_update().one()
|
||||||
|
...
|
||||||
|
|
||||||
|
### Service rules (app/services/**)
|
||||||
|
- FORBIDDEN imports: sqlalchemy, httpx, boto3, redis, FastAPI Request/Response/HTTPException
|
||||||
|
- Constructor injects Protocol-typed dependencies, not concrete classes
|
||||||
|
- Raise domain exceptions (InsufficientFundsError), not HTTPException
|
||||||
|
|
||||||
|
GOOD:
|
||||||
|
from app.repositories.protocols import WalletRepoProtocol
|
||||||
|
class WalletUserService:
|
||||||
|
def __init__(self, repo: WalletRepoProtocol): # Protocol, not SQLAlchemy Session
|
||||||
|
self._repo = repo
|
||||||
|
|
||||||
|
BAD:
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
class WalletUserService:
|
||||||
|
def __init__(self, db: Session): ... # Wrong — service depends on infrastructure
|
||||||
|
|
||||||
|
### Repository rules (app/repositories/**)
|
||||||
|
- ONLY layer allowed to import sqlalchemy
|
||||||
|
- Implements Protocol from app/repositories/protocols.py
|
||||||
|
- Returns domain objects, not ORM models
|
||||||
|
- Every query scoped by user_id (multi-tenancy)
|
||||||
|
|
||||||
|
### Provider rules (app/providers/**)
|
||||||
|
- ONLY layer allowed to import httpx directly
|
||||||
|
- Returns GenerateResult | ProviderError — NEVER raw dict
|
||||||
|
- Uses per-provider httpx.AsyncClient (bulkhead pattern)
|
||||||
|
|
||||||
|
## FILE SIZE RULES (Principle A1)
|
||||||
|
|
||||||
|
| LOC | State | Action |
|
||||||
|
|----------|--------|---------------------------------------------|
|
||||||
|
| 0–399 | Green | None. |
|
||||||
|
| 400–599 | Yellow | Plan split. Add TODO(decompose) header. |
|
||||||
|
| 600+ | Red | BLOCK merge. Decompose first. |
|
||||||
|
|
||||||
|
Convert file to package when ANY is true:
|
||||||
|
- Crosses 400 LOC and next change pushes past 500
|
||||||
|
- Contains 2+ disjoint sub-domains (image vs video, user vs admin)
|
||||||
|
- Mixes HTTP handlers with worker handlers
|
||||||
|
- Has 2+ callers each importing only one symbol
|
||||||
|
|
||||||
|
Safe split pattern (atomic PR):
|
||||||
|
1. Create <file>/__init__.py (empty for now)
|
||||||
|
2. Move pieces to sub-files (a.py, b.py, c.py)
|
||||||
|
3. Re-export old public names from __init__.py
|
||||||
|
4. Run tests — must pass without changes
|
||||||
|
5. Follow-up PR to migrate callers off legacy alias
|
||||||
|
|
||||||
|
__init__.py pattern:
|
||||||
|
from .user import WalletUserService
|
||||||
|
from .admin import WalletAdminService
|
||||||
|
WalletService = WalletUserService # backwards-compat alias
|
||||||
|
__all__ = ["WalletUserService", "WalletAdminService", "WalletService"]
|
||||||
|
|
||||||
|
## EXTERNAL INTEGRATION RULES (Principles B1-B10)
|
||||||
|
|
||||||
|
### Rule 1: Anti-Corruption Layer (ACL)
|
||||||
|
Providers return GenerateResult | ProviderError, never dict.
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class GenerateResult:
|
||||||
|
url: str
|
||||||
|
cost_usd: Decimal
|
||||||
|
latency_ms: int
|
||||||
|
provider_request_id: str
|
||||||
|
|
||||||
|
class ProviderError(Exception):
|
||||||
|
def __init__(self, message: str, *, retryable: bool, code: str | None = None):
|
||||||
|
super().__init__(message); self.retryable = retryable; self.code = code
|
||||||
|
|
||||||
|
class ProviderTimeout(ProviderError):
|
||||||
|
def __init__(self, message: str): super().__init__(message, retryable=True, code="timeout")
|
||||||
|
|
||||||
|
### Rule 2: Per-Provider Bulkhead
|
||||||
|
Each external provider has its OWN httpx.AsyncClient with its OWN Limits. NEVER share.
|
||||||
|
|
||||||
|
GOOD:
|
||||||
|
FAL_HTTP = httpx.AsyncClient(
|
||||||
|
base_url=settings.FAL_BASE_URL,
|
||||||
|
timeout=httpx.Timeout(connect=5.0, read=60.0, write=10.0, pool=5.0),
|
||||||
|
limits=httpx.Limits(max_connections=20, max_keepalive_connections=10),
|
||||||
|
)
|
||||||
|
OPENAI_HTTP = httpx.AsyncClient(
|
||||||
|
base_url="https://api.openai.com/v1",
|
||||||
|
limits=httpx.Limits(max_connections=50, max_keepalive_connections=20),
|
||||||
|
)
|
||||||
|
|
||||||
|
BAD:
|
||||||
|
HTTP = httpx.AsyncClient() # shared across all providers — no bulkhead isolation
|
||||||
|
|
||||||
|
# Shutdown cleanup — close all provider clients in FastAPI lifespan
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(app):
|
||||||
|
yield # app startup
|
||||||
|
await FAL_HTTP.aclose()
|
||||||
|
await OPENAI_HTTP.aclose()
|
||||||
|
|
||||||
|
app = FastAPI(lifespan=lifespan)
|
||||||
|
# Or on_event("shutdown"):
|
||||||
|
# @app.on_event("shutdown")
|
||||||
|
# async def close_http_clients() -> None:
|
||||||
|
# await FAL_HTTP.aclose()
|
||||||
|
# await OPENAI_HTTP.aclose()
|
||||||
|
|
||||||
|
### Rule 3: Idempotency Keys
|
||||||
|
Every side-effect operation accepts an idempotency_key: UUID. Look up before retrying.
|
||||||
|
|
||||||
|
### Rule 4: Structured Logging with contextvars
|
||||||
|
Use ContextVar to thread provider, user_id, request_id through async call stacks.
|
||||||
|
|
||||||
|
import contextvars
|
||||||
|
|
||||||
|
provider_var = contextvars.ContextVar[str | None]("provider", default=None)
|
||||||
|
user_id_var = contextvars.ContextVar[str | None]("user_id", default=None)
|
||||||
|
request_id_var = contextvars.ContextVar[str | None]("request_id", default=None)
|
||||||
|
|
||||||
|
# Read in logs: provider_var.get(), user_id_var.get(), request_id_var.get()
|
||||||
|
# JSON formatter picks these up automatically via extra={} or ContextVar.get()
|
||||||
|
|
||||||
|
### Rule 5: Single-Writer Principle (Principle B10)
|
||||||
|
For safety-critical state: exactly ONE service-layer module does the writing.
|
||||||
|
Only the designated writer service for a domain may call repo.hold().
|
||||||
|
Routers and providers must NOT call repo.hold() directly.
|
||||||
|
Admin services implemented in the service layer may call repo.hold() only
|
||||||
|
if they are the designated writer for that domain.
|
||||||
|
Enforce via: code-review grep check (`grep -r "repo\.hold(" --include="*.py"`)
|
||||||
|
and unit tests that assert call-origin of repo.hold().
|
||||||
|
|
||||||
|
## ANTI-PATTERNS — REJECT ON SIGHT
|
||||||
|
|
||||||
|
1. def some_method(self, db: Session, ...) → use Protocol-typed repo
|
||||||
|
2. from app.models.user import User inside a service → return domain types from repo
|
||||||
|
3. httpx.AsyncClient() instantiated inside a function → use shared per-provider client
|
||||||
|
4. raise HTTPException(...) inside a service → raise domain exception
|
||||||
|
5. db.query(...) inside a router → move to service then repo
|
||||||
|
6. async def call(self, req) -> dict: return resp.json() → ACL violation
|
||||||
|
7. HTTP = httpx.AsyncClient() shared → bulkhead violation
|
||||||
|
8. result["vendor_field"]["nested"] in service code → ACL violation
|
||||||
|
9. logger.info(f"{user_id} did X") → use structured logging with extra={}
|
||||||
|
10. Side-effect operation without idempotency_key → double-charge risk
|
||||||
|
|
||||||
|
## DEPENDENCY INJECTION
|
||||||
|
|
||||||
|
Use FastAPI Depends() + factory functions in app/core/deps.py.
|
||||||
|
Do NOT install dependency-injector, punq, or any DI container.
|
||||||
|
|
||||||
|
def get_wallet_service(db: Session = Depends(get_db)) -> WalletUserService:
|
||||||
|
return WalletUserService(repo=SQLAlchemyWalletRepo(db))
|
||||||
|
|
||||||
|
## DOMAIN EXCEPTIONS PATTERN
|
||||||
|
|
||||||
|
Services raise domain errors. Routers map to HTTP.
|
||||||
|
|
||||||
|
# services/wallet/exceptions.py
|
||||||
|
class InsufficientFundsError(Exception): ...
|
||||||
|
class WalletNotFoundError(Exception): ...
|
||||||
|
|
||||||
|
# routers/wallet.py
|
||||||
|
try:
|
||||||
|
wallet = await svc.charge(...)
|
||||||
|
except InsufficientFundsError:
|
||||||
|
raise HTTPException(402, detail="insufficient funds")
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
---
|
||||||
|
description: "FastAPI best practices and patterns for building modern Python web APIs"
|
||||||
|
globs: **/*.py, app/**/*.py, api/**/*.py
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
# FastAPI Best Practices
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
- Use proper directory structure
|
||||||
|
- Implement proper module organization
|
||||||
|
- Use proper dependency injection
|
||||||
|
- Keep routes organized by domain
|
||||||
|
- Implement proper middleware
|
||||||
|
- Use proper configuration management
|
||||||
|
|
||||||
|
## API Design
|
||||||
|
- Use proper HTTP methods
|
||||||
|
- Implement proper status codes
|
||||||
|
- Use proper request/response models
|
||||||
|
- Implement proper validation
|
||||||
|
- Use proper error handling
|
||||||
|
- Document APIs with OpenAPI
|
||||||
|
|
||||||
|
## Models
|
||||||
|
- Use Pydantic models
|
||||||
|
- Implement proper validation
|
||||||
|
- Use proper type hints
|
||||||
|
- Keep models organized
|
||||||
|
- Use proper inheritance
|
||||||
|
- Implement proper serialization
|
||||||
|
|
||||||
|
## Database
|
||||||
|
- Use proper ORM (SQLAlchemy)
|
||||||
|
- Implement proper migrations
|
||||||
|
- Use proper connection pooling
|
||||||
|
- Implement proper transactions
|
||||||
|
- Use proper query optimization
|
||||||
|
- Handle database errors properly
|
||||||
|
|
||||||
|
## Authentication
|
||||||
|
- Implement proper JWT authentication
|
||||||
|
- Use proper password hashing
|
||||||
|
- Implement proper role-based access
|
||||||
|
- Use proper session management
|
||||||
|
- Implement proper OAuth2
|
||||||
|
- Handle authentication errors properly
|
||||||
|
|
||||||
|
## Security
|
||||||
|
- Implement proper CORS
|
||||||
|
- Use proper rate limiting
|
||||||
|
- Implement proper input validation
|
||||||
|
- Use proper security headers
|
||||||
|
- Handle security errors properly
|
||||||
|
- Implement proper logging
|
||||||
|
|
||||||
|
## Performance
|
||||||
|
- Use proper caching
|
||||||
|
- Implement proper async operations
|
||||||
|
- Use proper background tasks
|
||||||
|
- Implement proper connection pooling
|
||||||
|
- Use proper query optimization
|
||||||
|
- Monitor performance metrics
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
- Write proper unit tests
|
||||||
|
- Implement proper integration tests
|
||||||
|
- Use proper test fixtures
|
||||||
|
- Implement proper mocking
|
||||||
|
- Test error scenarios
|
||||||
|
- Use proper test coverage
|
||||||
|
|
||||||
|
## Deployment
|
||||||
|
- Use proper Docker configuration
|
||||||
|
- Implement proper CI/CD
|
||||||
|
- Use proper environment variables
|
||||||
|
- Implement proper logging
|
||||||
|
- Use proper monitoring
|
||||||
|
- Handle deployment errors properly
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
- Use proper docstrings
|
||||||
|
- Implement proper API documentation
|
||||||
|
- Use proper type hints
|
||||||
|
- Keep documentation updated
|
||||||
|
- Document error scenarios
|
||||||
|
- Use proper versioning
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
---
|
||||||
|
description: Core coding standards — clarity, scope, and conventions
|
||||||
|
alwaysApply: true
|
||||||
|
---
|
||||||
|
|
||||||
|
# General Coding Standards
|
||||||
|
|
||||||
|
- Prefer the smallest change that solves the problem. Do not refactor unrelated code.
|
||||||
|
- Match existing naming, structure, and patterns in the file you are editing.
|
||||||
|
- One function or component = one responsibility. Split when a unit does two jobs.
|
||||||
|
- Prefer explicit code over clever code. Readable beats terse.
|
||||||
|
- Delete dead code instead of commenting it out.
|
||||||
|
- No magic numbers — use named constants.
|
||||||
|
- Validate inputs at system boundaries (API handlers, CLI args, form submissions).
|
||||||
|
- Return early to reduce nesting. Avoid deeply nested conditionals.
|
||||||
|
- Prefer composition over inheritance unless the codebase already uses inheritance heavily.
|
||||||
|
- When unsure about intent, read surrounding files before inventing a new pattern.
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
---
|
||||||
|
description: "Cursor rules for Gherkin style testing development with integration."
|
||||||
|
globs: **/*
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
# Persona
|
||||||
|
|
||||||
|
You are an expert QA engineer tasked with creating test documentation in Gherkin (Given-When-Then) format for web and mobile applications.
|
||||||
|
|
||||||
|
# Gherkin Documentation Focus
|
||||||
|
|
||||||
|
Create structured test scenarios using Gherkin syntax (Feature, Scenario, Given, When, Then, And, But)
|
||||||
|
Convert technical test scripts, manual test cases, or screenshots into clear Gherkin format
|
||||||
|
Use simple, non-technical language that legal and business teams can understand
|
||||||
|
Focus on user actions, conditions, and expected outcomes
|
||||||
|
|
||||||
|
# Best Practices
|
||||||
|
|
||||||
|
**1** **Clear Feature Description**: Begin with a concise Feature statement explaining what's being tested
|
||||||
|
**2** **Descriptive Scenario Titles**: Use specific scenario titles that indicate what's being verified
|
||||||
|
**3** **Complete Context**: Ensure 'Given' steps provide all necessary preconditions
|
||||||
|
**4** **Specific Actions**: Write 'When' steps that clearly describe user actions
|
||||||
|
**5** **Verifiable Outcomes**: Include 'Then' steps with clear, testable expectations
|
||||||
|
**6** **Simple Language**: Avoid technical jargon like "API", "selector", or "endpoint"
|
||||||
|
**7** **Data Examples**: Use Examples tables for data-driven scenarios
|
||||||
|
**8** **Common Issues**: Include notes for common issues or special considerations
|
||||||
|
|
||||||
|
# Example Gherkin Format
|
||||||
|
|
||||||
|
```gherkin
|
||||||
|
Feature: User Account Management
|
||||||
|
As a user of the application
|
||||||
|
I want to manage my account settings
|
||||||
|
So that I can control my personal information and preferences
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given I am logged in to my account
|
||||||
|
And I am on the account settings page
|
||||||
|
|
||||||
|
Scenario: Update Display Name Successfully
|
||||||
|
When I click on the "Edit Profile" button
|
||||||
|
And I enter "John Smith" in the display name field
|
||||||
|
And I click the "Save Changes" button
|
||||||
|
Then I should see a success message "Profile updated successfully"
|
||||||
|
And my display name should show as "John Smith" in the header
|
||||||
|
|
||||||
|
Scenario Outline: Password Validation Requirements
|
||||||
|
When I click on the "Change Password" button
|
||||||
|
And I enter "<password>" in the new password field
|
||||||
|
Then I should see the validation message "<message>"
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| password | message |
|
||||||
|
| pass | Password must be at least 8 characters long |
|
||||||
|
| password | Password must include at least one number |
|
||||||
|
| Password1 | Password meets all requirements |
|
||||||
|
|
||||||
|
Scenario: Delete Account with Confirmation
|
||||||
|
When I click on the "Delete Account" button
|
||||||
|
Then I should see a confirmation dialog
|
||||||
|
When I enter my password for confirmation
|
||||||
|
And I click "Confirm Delete" in the dialog
|
||||||
|
Then I should be logged out
|
||||||
|
And I should see a message "Your account has been deleted"
|
||||||
|
|
||||||
|
Note: Ensure testing is performed in a controlled environment to avoid affecting real user data.
|
||||||
|
```
|
||||||
|
|
||||||
|
# Converting Technical Scripts to Gherkin
|
||||||
|
|
||||||
|
When converting technical test scripts to Gherkin format:
|
||||||
|
|
||||||
|
1. Identify the overall feature being tested
|
||||||
|
2. Extract each test case as a separate scenario
|
||||||
|
3. Translate setup code into "Given" steps
|
||||||
|
4. Convert actions (clicks, inputs) into "When" steps
|
||||||
|
5. Transform assertions into "Then" steps
|
||||||
|
6. Replace technical selectors with user-friendly descriptions
|
||||||
|
7. Add Examples tables for data-driven tests
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
Technical Script:
|
||||||
|
|
||||||
|
```js
|
||||||
|
test('should update profile', async () => {
|
||||||
|
await page.goto('/settings');
|
||||||
|
await page.locator('[data-testid="edit-profile"]').click();
|
||||||
|
await page.locator('#displayName').fill('John Smith');
|
||||||
|
await page.locator('#save-button').click();
|
||||||
|
await expect(page.locator('.success-message')).toContainText(
|
||||||
|
'Profile updated'
|
||||||
|
);
|
||||||
|
await expect(page.locator('.user-header-name')).toContainText('John Smith');
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
Gherkin Format:
|
||||||
|
|
||||||
|
```gherkin
|
||||||
|
Scenario: Update Display Name Successfully
|
||||||
|
Given I am on the account settings page
|
||||||
|
When I click on the "Edit Profile" button
|
||||||
|
And I enter "John Smith" in the display name field
|
||||||
|
And I click the "Save Changes" button
|
||||||
|
Then I should see a success message "Profile updated successfully"
|
||||||
|
And my display name should show as "John Smith" in the header
|
||||||
|
```
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
---
|
||||||
|
description: "Idiomatic Go rules. Explicit error handling, interface-based design, context-first concurrency."
|
||||||
|
globs: **/*.go
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
# Go Language Rules
|
||||||
|
|
||||||
|
Expert Go developer. Simple, explicit, idiomatic.
|
||||||
|
|
||||||
|
## Error Handling
|
||||||
|
- Always handle errors — never assign to _
|
||||||
|
- fmt.Errorf("context: %w", err) for wrapping
|
||||||
|
- errors.Is() / errors.As() for checking
|
||||||
|
- Custom error types for structured errors
|
||||||
|
|
||||||
|
## Naming
|
||||||
|
- Short for short-lived vars: i, n, err, ok
|
||||||
|
- No stuttering: user.UserID → user.ID
|
||||||
|
- Acronyms: userID, httpClient (not userId, httpClient)
|
||||||
|
- Interfaces: end in -er (Reader, Writer, Handler)
|
||||||
|
|
||||||
|
## Interfaces
|
||||||
|
- Accept interfaces, return concrete types
|
||||||
|
- Define at call site, not implementation site
|
||||||
|
- Single-method interfaces preferred
|
||||||
|
|
||||||
|
## Concurrency
|
||||||
|
- context.Context first param for blocking functions
|
||||||
|
- defer cancel() after context creation
|
||||||
|
- WaitGroup for goroutine groups
|
||||||
|
- Channels for communication, Mutex for state
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
- Table-driven: for _, tc := range testCases { t.Run(tc.name, ...) }
|
||||||
|
- Interface-based mocking
|
||||||
|
|
||||||
|
## Forbidden
|
||||||
|
- No _ to ignore errors
|
||||||
|
- No init() for business logic
|
||||||
|
- No global mutable state
|
||||||
|
- No interface{} where generics work
|
||||||
|
- No goroutines without termination condition
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
---
|
||||||
|
description: "Cursor rules for GraphQL development with Apollo Client integration."
|
||||||
|
globs: **/*
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
// React + GraphQL (Apollo Client) .cursorrules
|
||||||
|
|
||||||
|
// Prefer functional components with hooks
|
||||||
|
|
||||||
|
const preferFunctionalComponents = true;
|
||||||
|
|
||||||
|
// GraphQL and Apollo Client best practices
|
||||||
|
|
||||||
|
const graphqlBestPractices = [
|
||||||
|
"Use Apollo Client for state management and data fetching",
|
||||||
|
"Implement query components for data fetching",
|
||||||
|
"Utilize mutations for data modifications",
|
||||||
|
"Use fragments for reusable query parts",
|
||||||
|
"Implement proper error handling and loading states",
|
||||||
|
];
|
||||||
|
|
||||||
|
// Folder structure
|
||||||
|
|
||||||
|
const folderStructure = `
|
||||||
|
src/
|
||||||
|
components/
|
||||||
|
graphql/
|
||||||
|
queries/
|
||||||
|
mutations/
|
||||||
|
fragments/
|
||||||
|
hooks/
|
||||||
|
pages/
|
||||||
|
utils/
|
||||||
|
`;
|
||||||
|
|
||||||
|
// Additional instructions
|
||||||
|
|
||||||
|
const additionalInstructions = `
|
||||||
|
1. Use Apollo Provider at the root of your app
|
||||||
|
2. Implement custom hooks for Apollo operations
|
||||||
|
3. Use TypeScript for type safety with GraphQL operations
|
||||||
|
4. Utilize Apollo Client's caching capabilities
|
||||||
|
5. Implement proper error boundaries for GraphQL errors
|
||||||
|
6. Use Apollo Client DevTools for debugging
|
||||||
|
7. Follow naming conventions for queries, mutations, and fragments
|
||||||
|
`;
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
---
|
||||||
|
description: "Cursor rules for Jest development with unit testing."
|
||||||
|
globs: **/*
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
# Persona
|
||||||
|
|
||||||
|
You are an expert developer with deep knowledge of Jest and TypeScript, tasked with creating unit tests for JavaScript/TypeScript applications.
|
||||||
|
|
||||||
|
# Auto-detect TypeScript Usage
|
||||||
|
|
||||||
|
Check for TypeScript in the project through tsconfig.json or package.json dependencies.
|
||||||
|
Adjust syntax based on this detection.
|
||||||
|
|
||||||
|
# Unit Testing Focus
|
||||||
|
|
||||||
|
Create unit tests that focus on critical functionality (business logic, utility functions)
|
||||||
|
Mock dependencies (API calls, external modules) before imports
|
||||||
|
Test various data scenarios (valid inputs, invalid inputs, edge cases)
|
||||||
|
Write maintainable tests with descriptive names grouped in describe blocks
|
||||||
|
|
||||||
|
# Best Practices
|
||||||
|
|
||||||
|
**1** **Critical Functionality**: Prioritize testing business logic and utility functions
|
||||||
|
**2** **Dependency Mocking**: Always mock dependencies before imports with jest.mock()
|
||||||
|
**3** **Data Scenarios**: Test valid inputs, invalid inputs, and edge cases
|
||||||
|
**4** **Descriptive Naming**: Use clear test names indicating expected behavior
|
||||||
|
**5** **Test Organization**: Group related tests in describe/context blocks
|
||||||
|
**6** **Project Patterns**: Match team's testing conventions and patterns
|
||||||
|
**7** **Edge Cases**: Include tests for null values, undefined, and unexpected types
|
||||||
|
**8** **Test Quantity**: Limit to 3-5 focused tests per file for maintainability
|
||||||
|
|
||||||
|
# Example Unit Test
|
||||||
|
|
||||||
|
```js
|
||||||
|
// Mock dependencies before imports
|
||||||
|
jest.mock('../api/taxRate', () => ({
|
||||||
|
getTaxRate: jest.fn(() => 0.1), // Mock tax rate as 10%
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Import module under test
|
||||||
|
const { calculateTotal } = require('../utils/calculateTotal');
|
||||||
|
|
||||||
|
describe('calculateTotal', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should calculate total for valid items with tax', () => {
|
||||||
|
// Arrange
|
||||||
|
const items = [{ price: 10, quantity: 2 }, { price: 20, quantity: 1 }];
|
||||||
|
|
||||||
|
// Act
|
||||||
|
const result = calculateTotal(items);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
expect(result).toBe(44); // (10 * 2 + 20 * 1) * 1.1 (tax) = 44
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle empty array', () => {
|
||||||
|
const result = calculateTotal([]);
|
||||||
|
expect(result).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw error for invalid item data', () => {
|
||||||
|
const items = [{ price: 'invalid', quantity: 1 }];
|
||||||
|
expect(() => calculateTotal(items)).toThrow('Invalid price or quantity');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle null input', () => {
|
||||||
|
expect(() => calculateTotal(null)).toThrow('Items must be an array');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
# TypeScript Example
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// Mock dependencies before imports
|
||||||
|
jest.mock('../api/userService', () => ({
|
||||||
|
fetchUser: jest.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Import the mocked module and the function to test
|
||||||
|
import { fetchUser } from '../api/userService';
|
||||||
|
import { getUserData } from '../utils/userUtils';
|
||||||
|
|
||||||
|
// Define TypeScript interfaces
|
||||||
|
interface User {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
email: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('getUserData', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return user data when fetch is successful', async () => {
|
||||||
|
// Arrange
|
||||||
|
const mockUser: User = { id: 1, name: 'John Doe', email: 'john@example.com' };
|
||||||
|
(fetchUser as jest.Mock).mockResolvedValue(mockUser);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
const result = await getUserData(1);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
expect(fetchUser).toHaveBeenCalledWith(1);
|
||||||
|
expect(result).toEqual(mockUser);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw error when user is not found', async () => {
|
||||||
|
// Arrange
|
||||||
|
(fetchUser as jest.Mock).mockResolvedValue(null);
|
||||||
|
|
||||||
|
// Act & Assert
|
||||||
|
await expect(getUserData(999)).rejects.toThrow('User not found');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle API errors gracefully', async () => {
|
||||||
|
// Arrange
|
||||||
|
(fetchUser as jest.Mock).mockRejectedValue(new Error('Network error'));
|
||||||
|
|
||||||
|
// Act & Assert
|
||||||
|
await expect(getUserData(1)).rejects.toThrow('Failed to fetch user: Network error');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
---
|
||||||
|
description: "Cursor rules for JavaScript and TypeScript development with code quality integration."
|
||||||
|
globs: **/*
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
# Persona
|
||||||
|
|
||||||
|
You are a senior full-stack developer. One of those rare 10x developers that has incredible knowledge.
|
||||||
|
|
||||||
|
# Coding Guidelines
|
||||||
|
|
||||||
|
Follow these guidelines to ensure your code is clean, maintainable, and adheres to best practices. Remember, less code is better. Lines of code = Debt.
|
||||||
|
|
||||||
|
# Key Mindsets
|
||||||
|
|
||||||
|
**1** **Simplicity**: Write simple and straightforward code.
|
||||||
|
**2** **Readability**: Ensure your code is easy to read and understand.
|
||||||
|
**3** **Performance**: Keep performance in mind but do not over-optimize at the cost of readability.
|
||||||
|
**4** **Maintainability**: Write code that is easy to maintain and update.
|
||||||
|
**5** **Testability**: Ensure your code is easy to test.
|
||||||
|
**6** **Reusability**: Write reusable components and functions.
|
||||||
|
|
||||||
|
Code Guidelines
|
||||||
|
|
||||||
|
**1** **Utilize Early Returns**: Use early returns to avoid nested conditions and improve readability.
|
||||||
|
**2** **Conditional Classes**: Prefer conditional classes over ternary operators for class attributes.
|
||||||
|
**3** **Descriptive Names**: Use descriptive names for variables and functions. Prefix event handler functions with "handle" (e.g., handleClick, handleKeyDown).
|
||||||
|
**4** **Constants Over Functions**: Use constants instead of functions where possible. Define types if applicable.
|
||||||
|
**5** **Correct and DRY Code**: Focus on writing correct, best practice, DRY (Don't Repeat Yourself) code.
|
||||||
|
**6** **Functional and Immutable Style**: Prefer a functional, immutable style unless it becomes much more verbose.
|
||||||
|
**7** **Minimal Code Changes**: Only modify sections of the code related to the task at hand. Avoid modifying unrelated pieces of code. Accomplish goals with minimal code changes.
|
||||||
|
|
||||||
|
Comments and Documentation
|
||||||
|
|
||||||
|
* **Function Comments**: Add a comment at the start of each function describing what it does.
|
||||||
|
* **JSDoc Comments**: Use JSDoc comments for JavaScript (unless it's TypeScript) and modern ES6 syntax.
|
||||||
|
|
||||||
|
Function Ordering
|
||||||
|
|
||||||
|
* Order functions with those that are composing other functions appearing earlier in the file. For example, if you have a menu with multiple buttons, define the menu function above the buttons.
|
||||||
|
|
||||||
|
Handling Bugs
|
||||||
|
|
||||||
|
* **TODO Comments**: If you encounter a bug in existing code, or the instructions lead to suboptimal or buggy code, add comments starting with "TODO:" outlining the problems.
|
||||||
|
|
||||||
|
Example Pseudocode Plan and Implementation
|
||||||
|
|
||||||
|
When responding to questions, use the Chain of Thought method. Outline a detailed pseudocode plan step by step, then confirm it, and proceed to write the code. Here’s an example:
|
||||||
|
|
||||||
|
# Important: Minimal Code Changes
|
||||||
|
|
||||||
|
**Only modify sections of the code related to the task at hand.**
|
||||||
|
**Avoid modifying unrelated pieces of code.**
|
||||||
|
**Avoid changing existing comments.**
|
||||||
|
**Avoid any kind of cleanup unless specifically instructed to.**
|
||||||
|
**Accomplish the goal with the minimum amount of code changes.**
|
||||||
|
**Code change = potential for bugs and technical debt.**
|
||||||
|
|
||||||
|
Follow these guidelines to produce high-quality code and improve your coding skills. If you have any questions or need clarification, don’t hesitate to ask!
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
---
|
||||||
|
description: "Cursor rules for avoiding placeholder or broken image URLs, using stable visual assets, and checking alt text, dimensions, licensing, and responsive behavior."
|
||||||
|
globs: **/*
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
# Landing Page Image Quality
|
||||||
|
|
||||||
|
When generating or editing user-facing pages, use real, relevant visual assets instead of placeholder image services.
|
||||||
|
|
||||||
|
## Image Sources
|
||||||
|
|
||||||
|
- Do not commit `placehold.co`, `via.placeholder.com`, `dummyimage.com`, `picsum.photos`, random image URLs, or broken/deprecated image services.
|
||||||
|
- Prefer committed project assets, product screenshots, generated assets approved by the user, or stable URLs from an approved image provider.
|
||||||
|
- Before using a third-party image, confirm the license and attribution requirements are compatible with the project.
|
||||||
|
- Avoid hotlinking images from arbitrary websites.
|
||||||
|
|
||||||
|
## Asset Quality
|
||||||
|
|
||||||
|
- Match images to the actual content, product, place, object, or user state they represent.
|
||||||
|
- Do not use vague atmospheric images when the user needs to inspect a product, feature, workflow, or interface.
|
||||||
|
- Use consistent aspect ratios for repeated cards or gallery items.
|
||||||
|
- Provide explicit `width` and `height` attributes or CSS aspect-ratio constraints to prevent layout shift.
|
||||||
|
- Use optimized formats and sizes appropriate for the target framework.
|
||||||
|
|
||||||
|
## Accessibility
|
||||||
|
|
||||||
|
- Every informative image must have specific `alt` text that describes the image's purpose in context.
|
||||||
|
- Decorative images must use empty alt text and should not be announced to assistive technology.
|
||||||
|
- Do not put essential text only inside an image.
|
||||||
|
|
||||||
|
## Implementation Checks
|
||||||
|
|
||||||
|
- Ensure image paths resolve in the built application.
|
||||||
|
- Check responsive behavior at mobile and desktop widths.
|
||||||
|
- Verify that loading, error, and empty states do not leave broken image icons in production UI.
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
---
|
||||||
|
description: "Cursor rules that block deprecated, phantom, or incorrect NestJS imports, decorators, providers, modules, and testing patterns."
|
||||||
|
globs: **/*
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
# NestJS Anti-Hallucination Rules
|
||||||
|
|
||||||
|
These rules OVERRIDE all other generation behavior. Check EVERY line of generated code against these rules.
|
||||||
|
|
||||||
|
## Banned Imports & Phantom Packages
|
||||||
|
|
||||||
|
### NEVER import these — they don't exist or are deprecated:
|
||||||
|
```
|
||||||
|
❌ @nestjs/core/decorators — not a real export path
|
||||||
|
❌ @nestjs/swagger/decorators — import from @nestjs/swagger directly
|
||||||
|
❌ @nestjs/typeorm/repository — not a real export path
|
||||||
|
❌ @nestjs/passport/strategies — import from passport-jwt, passport-local, etc.
|
||||||
|
❌ @nestjs/bull/decorators — import from @nestjs/bullmq (bull is legacy)
|
||||||
|
❌ nestjs-redis — use @nestjs-modules/ioredis or ioredis directly
|
||||||
|
❌ @nestjs/cqrs/decorators — import from @nestjs/cqrs directly
|
||||||
|
❌ nestjs-config — use @nestjs/config (official)
|
||||||
|
❌ nestjs-pino/logger — import from nestjs-pino directly
|
||||||
|
```
|
||||||
|
|
||||||
|
### Correct import paths:
|
||||||
|
```typescript
|
||||||
|
// ✅ Swagger
|
||||||
|
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
|
||||||
|
|
||||||
|
// ✅ TypeORM
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { Repository, DataSource } from 'typeorm';
|
||||||
|
|
||||||
|
// ✅ BullMQ (NOT Bull)
|
||||||
|
import { InjectQueue, Processor, WorkerHost } from '@nestjs/bullmq';
|
||||||
|
|
||||||
|
// ✅ Config
|
||||||
|
import { ConfigService, ConfigModule } from '@nestjs/config';
|
||||||
|
|
||||||
|
// ✅ Passport
|
||||||
|
import { AuthGuard } from '@nestjs/passport';
|
||||||
|
import { Strategy as JwtStrategy, ExtractJwt } from 'passport-jwt';
|
||||||
|
|
||||||
|
// ✅ CQRS
|
||||||
|
import { CommandHandler, ICommandHandler, EventBus } from '@nestjs/cqrs';
|
||||||
|
```
|
||||||
|
|
||||||
|
## Deprecated Patterns — NEVER Generate These
|
||||||
|
|
||||||
|
### 1. getRepository() outside providers
|
||||||
|
```typescript
|
||||||
|
// ❌ DEPRECATED — removed in TypeORM 0.3+
|
||||||
|
const repo = getRepository(User);
|
||||||
|
const user = await getConnection().getRepository(User).find();
|
||||||
|
|
||||||
|
// ✅ CORRECT — inject via constructor
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(User)
|
||||||
|
private readonly userRepo: Repository<User>,
|
||||||
|
) {}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. @nestjs/bull (use @nestjs/bullmq)
|
||||||
|
```typescript
|
||||||
|
// ❌ OLD — @nestjs/bull with @Process decorator
|
||||||
|
import { Process, Processor } from '@nestjs/bull';
|
||||||
|
@Processor('queue')
|
||||||
|
class MyProcessor {
|
||||||
|
@Process() async handle(job: Job) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ✅ CURRENT — @nestjs/bullmq with WorkerHost
|
||||||
|
import { Processor, WorkerHost } from '@nestjs/bullmq';
|
||||||
|
@Processor('queue')
|
||||||
|
class MyProcessor extends WorkerHost {
|
||||||
|
async process(job: Job): Promise<void> {}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Express-specific middleware mistakes
|
||||||
|
```typescript
|
||||||
|
// ❌ WRONG — Express req/res types in NestJS
|
||||||
|
import { Request, Response } from 'express';
|
||||||
|
@Get()
|
||||||
|
async findAll(@Req() req: Request, @Res() res: Response) {
|
||||||
|
res.json(data); // Bypasses interceptors, serialization, exception filters
|
||||||
|
}
|
||||||
|
|
||||||
|
// ✅ CORRECT — Use NestJS decorators, return values
|
||||||
|
@Get()
|
||||||
|
async findAll(@Query() query: FindAllQueryDto): Promise<UserResponseDto[]> {
|
||||||
|
return this.usersService.findAll(query);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only use @Res() when streaming files or SSE — add { passthrough: true }
|
||||||
|
@Get('download')
|
||||||
|
async download(@Res({ passthrough: true }) res: Response) {
|
||||||
|
res.set('Content-Type', 'application/octet-stream');
|
||||||
|
return new StreamableFile(stream);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Wrong decorator combinations
|
||||||
|
```typescript
|
||||||
|
// ❌ WRONG — @Injectable() on a controller
|
||||||
|
@Injectable()
|
||||||
|
@Controller('users')
|
||||||
|
export class UsersController {}
|
||||||
|
|
||||||
|
// ❌ WRONG — @Controller() on a service
|
||||||
|
@Controller()
|
||||||
|
@Injectable()
|
||||||
|
export class UsersService {}
|
||||||
|
|
||||||
|
// ❌ WRONG — @Body() in a GET handler
|
||||||
|
@Get()
|
||||||
|
async findAll(@Body() body: any) {} // GET requests should not have a body
|
||||||
|
|
||||||
|
// ❌ WRONG — Both @Param and @Query with same name
|
||||||
|
@Get(':id')
|
||||||
|
async findOne(@Param('id') paramId: string, @Query('id') queryId: string) {}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. class-validator / class-transformer mistakes
|
||||||
|
```typescript
|
||||||
|
// ❌ WRONG — Validation without enabling in main.ts
|
||||||
|
// (AI often forgets this critical line)
|
||||||
|
// main.ts MUST have:
|
||||||
|
app.useGlobalPipes(new ValidationPipe({
|
||||||
|
whitelist: true, // Strip unknown properties
|
||||||
|
forbidNonWhitelisted: true, // Throw on unknown properties
|
||||||
|
transform: true, // Auto-transform payloads to DTO instances
|
||||||
|
transformOptions: {
|
||||||
|
enableImplicitConversion: true,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
// ❌ WRONG — Mixing validation decorators with wrong transform
|
||||||
|
export class CreateUserDto {
|
||||||
|
@IsString()
|
||||||
|
name: string;
|
||||||
|
|
||||||
|
@IsNumber()
|
||||||
|
age: string; // Type mismatch! Decorator says number, type says string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ✅ CORRECT — Types match decorators
|
||||||
|
export class CreateUserDto {
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
name: string;
|
||||||
|
|
||||||
|
@IsInt()
|
||||||
|
@Min(0)
|
||||||
|
age: number;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6. Async module pitfalls
|
||||||
|
```typescript
|
||||||
|
// ❌ WRONG — useFactory without async when awaiting
|
||||||
|
TypeOrmModule.forRootAsync({
|
||||||
|
useFactory: (config: ConfigService) => ({
|
||||||
|
type: 'postgres',
|
||||||
|
url: config.get('DATABASE_URL'), // Not awaited, no inject
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
|
||||||
|
// ✅ CORRECT
|
||||||
|
TypeOrmModule.forRootAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
inject: [ConfigService],
|
||||||
|
useFactory: async (config: ConfigService) => ({
|
||||||
|
type: 'postgres',
|
||||||
|
url: config.getOrThrow<string>('DATABASE_URL'),
|
||||||
|
autoLoadEntities: true,
|
||||||
|
synchronize: false, // NEVER true in production
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Type Safety Rules
|
||||||
|
|
||||||
|
### NEVER generate `any`
|
||||||
|
```typescript
|
||||||
|
// ❌ BANNED
|
||||||
|
catch (error: any) { ... }
|
||||||
|
const data: any = await response.json();
|
||||||
|
private cache = new Map<string, any>();
|
||||||
|
|
||||||
|
// ✅ REQUIRED
|
||||||
|
catch (error: unknown) {
|
||||||
|
if (error instanceof DomainError) { ... }
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
const data = await response.json() as PaymentGatewayResponse;
|
||||||
|
private cache = new Map<string, CachedSession>();
|
||||||
|
```
|
||||||
|
|
||||||
|
### NEVER generate untyped event payloads
|
||||||
|
```typescript
|
||||||
|
// ❌ WRONG
|
||||||
|
eventBus.emit('order.created', { order });
|
||||||
|
|
||||||
|
// ✅ CORRECT — Typed events
|
||||||
|
export class OrderCreatedEvent {
|
||||||
|
constructor(
|
||||||
|
public readonly orderId: string,
|
||||||
|
public readonly userId: string,
|
||||||
|
public readonly totalAmount: number,
|
||||||
|
public readonly occurredAt: Date = new Date(),
|
||||||
|
) {}
|
||||||
|
}
|
||||||
|
eventBus.emit(new OrderCreatedEvent(order.id, order.userId, order.total));
|
||||||
|
```
|
||||||
|
|
||||||
|
## Configuration Safety
|
||||||
|
|
||||||
|
### NEVER generate hardcoded values for:
|
||||||
|
- Database connection strings
|
||||||
|
- API keys or secrets
|
||||||
|
- Port numbers
|
||||||
|
- Feature flags
|
||||||
|
- External service URLs
|
||||||
|
|
||||||
|
### ALWAYS use ConfigService with getOrThrow:
|
||||||
|
```typescript
|
||||||
|
// ❌ WRONG
|
||||||
|
const port = process.env.PORT || 3000;
|
||||||
|
const dbUrl = process.env.DATABASE_URL;
|
||||||
|
|
||||||
|
// ✅ CORRECT
|
||||||
|
const port = this.configService.getOrThrow<number>('app.port');
|
||||||
|
const dbUrl = this.configService.getOrThrow<string>('database.url');
|
||||||
|
```
|
||||||
|
|
||||||
|
## Database Safety
|
||||||
|
|
||||||
|
### NEVER generate:
|
||||||
|
```typescript
|
||||||
|
// ❌ synchronize: true in production config
|
||||||
|
// ❌ DROP TABLE or TRUNCATE in migration files
|
||||||
|
// ❌ Raw SQL without parameterized queries
|
||||||
|
await this.dataSource.query(`SELECT * FROM users WHERE id = '${userId}'`); // SQL injection!
|
||||||
|
|
||||||
|
// ✅ CORRECT
|
||||||
|
await this.dataSource.query(`SELECT * FROM users WHERE id = $1`, [userId]);
|
||||||
|
```
|
||||||
|
|
||||||
|
## Remember
|
||||||
|
- If you're unsure whether a package exists, DO NOT import it. Ask or check.
|
||||||
|
- If you're generating a NestJS pattern you haven't seen in the official docs, STOP and reconsider.
|
||||||
|
- When in doubt, generate LESS code with correct patterns rather than MORE code with guesses.
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
---
|
||||||
|
description: "Next.js App Router combined with TanStack Query v5 — HydrationBoundary pattern, Server Actions as mutations, optimistic updates, and infinite scroll"
|
||||||
|
globs: ["app/**/*.tsx", "app/**/*.ts", "src/app/**/*.tsx", "src/queries/**/*"]
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
You are an expert in Next.js App Router, TanStack Query v5, TypeScript, and combining server components with client-side data fetching.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
- Server Components fetch data directly — no TanStack Query needed there
|
||||||
|
- TanStack Query lives in Client Components for interactive, real-time, or mutation-driven data
|
||||||
|
- Hydrate the Query cache from server to avoid client waterfalls on first load
|
||||||
|
- Use React Server Components for initial page data; TanStack Query for mutations + polling + optimistic UI
|
||||||
|
|
||||||
|
## Provider Setup
|
||||||
|
```tsx
|
||||||
|
// providers/query-provider.tsx
|
||||||
|
'use client'
|
||||||
|
export function QueryProvider({ children }: { children: React.ReactNode }) {
|
||||||
|
const [queryClient] = useState(() => new QueryClient({
|
||||||
|
defaultOptions: { queries: { staleTime: 60 * 1000 } },
|
||||||
|
}))
|
||||||
|
return (
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
{children}
|
||||||
|
<ReactQueryDevtools initialIsOpen={false} />
|
||||||
|
</QueryClientProvider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Server Prefetch + HydrationBoundary Pattern
|
||||||
|
```tsx
|
||||||
|
// app/posts/page.tsx (Server Component)
|
||||||
|
export default async function PostsPage() {
|
||||||
|
const queryClient = new QueryClient()
|
||||||
|
await queryClient.prefetchQuery(postsQueryOptions())
|
||||||
|
return (
|
||||||
|
<HydrationBoundary state={dehydrate(queryClient)}>
|
||||||
|
<PostsList />
|
||||||
|
</HydrationBoundary>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// app/posts/_components/posts-list.tsx (Client Component)
|
||||||
|
'use client'
|
||||||
|
export function PostsList() {
|
||||||
|
const { data: posts } = useQuery(postsQueryOptions()) // reads from pre-populated cache
|
||||||
|
return <ul>{posts?.map(p => <li key={p.id}>{p.title}</li>)}</ul>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## queryOptions Factory
|
||||||
|
```ts
|
||||||
|
export const postsQueryOptions = (filters?: PostFilters) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ['posts', 'list', filters],
|
||||||
|
queryFn: () => fetch('/api/posts').then(r => r.json()),
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Server Actions as mutationFn
|
||||||
|
```tsx
|
||||||
|
// app/posts/actions.ts
|
||||||
|
'use server'
|
||||||
|
export async function createPost(data: { title: string; body: string }) {
|
||||||
|
const post = await db.post.create({ data })
|
||||||
|
revalidatePath('/posts')
|
||||||
|
return post
|
||||||
|
}
|
||||||
|
|
||||||
|
// usage in Client Component
|
||||||
|
const mutation = useMutation({
|
||||||
|
mutationFn: createPost,
|
||||||
|
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['posts', 'list'] }),
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Optimistic Updates
|
||||||
|
```tsx
|
||||||
|
const mutation = useMutation({
|
||||||
|
mutationFn: updatePost,
|
||||||
|
onMutate: async (updated) => {
|
||||||
|
await queryClient.cancelQueries({ queryKey: ['posts', 'detail', updated.id] })
|
||||||
|
const previous = queryClient.getQueryData(['posts', 'detail', updated.id])
|
||||||
|
queryClient.setQueryData(['posts', 'detail', updated.id], (old: Post) => ({ ...old, ...updated }))
|
||||||
|
return { previous }
|
||||||
|
},
|
||||||
|
onError: (_, updated, ctx) => {
|
||||||
|
queryClient.setQueryData(['posts', 'detail', updated.id], ctx?.previous)
|
||||||
|
},
|
||||||
|
onSettled: (_, __, updated) => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['posts', 'detail', updated.id] })
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Key Rules
|
||||||
|
- Create a **new** `QueryClient` per request in Server Components — never reuse across requests
|
||||||
|
- Create **one** `QueryClient` per browser session via `useState` in the provider
|
||||||
|
- Always wrap server-prefetched subtrees in `HydrationBoundary`
|
||||||
|
- Mark all components using TanStack Query hooks with `'use client'`
|
||||||
|
- Never call `fetch` directly in Client Components — always go through `queryFn`
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
---
|
||||||
|
description: "27 architecture rules preventing AI hallucinations: insecure auth (getSession vs getUser), synchronous params, deprecated imports, missing RLS, and Stripe key exposure. Built for Cursor Agent and Claude Code."
|
||||||
|
globs: **/*
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
# Next.js 15 + Supabase Architecture Rules
|
||||||
|
|
||||||
|
You are an expert Next.js 15 developer working with Supabase, TypeScript (strict), and shadcn/ui.
|
||||||
|
Follow ALL rules below unconditionally. If you are tempted to deviate, re-read the rule.
|
||||||
|
|
||||||
|
## Tech Stack
|
||||||
|
- Framework: Next.js 15 (App Router) with React 19
|
||||||
|
- Language: TypeScript (strict mode)
|
||||||
|
- Styling: Tailwind CSS + shadcn/ui
|
||||||
|
- Database: Supabase (PostgreSQL + RLS)
|
||||||
|
- Auth: Supabase SSR (cookie-based, @supabase/ssr)
|
||||||
|
- Validation: Zod
|
||||||
|
- Payments: Stripe (server-side only)
|
||||||
|
|
||||||
|
## RULE 1: NEVER use getSession() on the server
|
||||||
|
|
||||||
|
SECURITY CRITICAL. getSession() reads the JWT from cookies WITHOUT verifying it.
|
||||||
|
A forged cookie passes silently. ALWAYS use getUser() for server-side auth.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// ✅ CORRECT — verified with Supabase auth server
|
||||||
|
const supabase = await createClient()
|
||||||
|
const { data: { user } } = await supabase.auth.getUser()
|
||||||
|
if (!user) redirect('/login')
|
||||||
|
|
||||||
|
// ❌ WRONG — reads JWT without verification, session can be forged
|
||||||
|
const { data: { session } } = await supabase.auth.getSession()
|
||||||
|
```
|
||||||
|
|
||||||
|
## RULE 2: NEVER access params synchronously in Next.js 15
|
||||||
|
|
||||||
|
In Next.js 15, params and searchParams are Promises. Synchronous access compiles
|
||||||
|
but crashes at runtime.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// ✅ CORRECT
|
||||||
|
export default async function Page({ params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const { id } = await params
|
||||||
|
}
|
||||||
|
|
||||||
|
// ❌ WRONG — runtime crash
|
||||||
|
export default function Page({ params }: { params: { id: string } }) {
|
||||||
|
const { id } = params // TypeError at runtime
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## RULE 3: NEVER import from @supabase/auth-helpers-nextjs
|
||||||
|
|
||||||
|
This package is deprecated. It does NOT work with Next.js 15 App Router cookies.
|
||||||
|
ALWAYS use @supabase/ssr with manual cookie handling.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// ✅ CORRECT
|
||||||
|
import { createServerClient } from '@supabase/ssr'
|
||||||
|
|
||||||
|
// ❌ WRONG — deprecated, broken with App Router
|
||||||
|
import { createServerComponentClient } from '@supabase/auth-helpers-nextjs'
|
||||||
|
```
|
||||||
|
|
||||||
|
## RULE 4: All database tables MUST have RLS enabled
|
||||||
|
|
||||||
|
Every Supabase table must have Row Level Security enabled. Without RLS, any
|
||||||
|
user with the anon key can read ALL data from the table.
|
||||||
|
|
||||||
|
```sql
|
||||||
|
-- ✅ Always add after CREATE TABLE:
|
||||||
|
ALTER TABLE public.my_table ENABLE ROW LEVEL SECURITY;
|
||||||
|
|
||||||
|
CREATE POLICY "Users can only read their own data"
|
||||||
|
ON public.my_table FOR SELECT
|
||||||
|
USING (auth.uid() = user_id);
|
||||||
|
```
|
||||||
|
|
||||||
|
## RULE 5: Default to Server Components
|
||||||
|
|
||||||
|
Only add 'use client' when the component needs interactivity (event handlers,
|
||||||
|
useState, useEffect). Push 'use client' to the smallest leaf component possible.
|
||||||
|
|
||||||
|
## RULE 6: All mutations via Server Actions
|
||||||
|
|
||||||
|
All data mutations happen through Server Actions, never client-side fetch().
|
||||||
|
Always validate with Zod, authenticate with getUser(), and return ActionResponse<T>.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
'use server'
|
||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
type ActionResponse<T = void> =
|
||||||
|
| { success: true; data: T }
|
||||||
|
| { success: false; error: string }
|
||||||
|
|
||||||
|
const Schema = z.object({ title: z.string().min(1).max(200) })
|
||||||
|
|
||||||
|
export async function createItem(input: unknown): Promise<ActionResponse> {
|
||||||
|
const supabase = await createClient()
|
||||||
|
const { data: { user } } = await supabase.auth.getUser()
|
||||||
|
if (!user) return { success: false, error: 'Unauthorized' }
|
||||||
|
|
||||||
|
const result = Schema.safeParse(input)
|
||||||
|
if (!result.success) return { success: false, error: 'Invalid input' }
|
||||||
|
|
||||||
|
const { error } = await supabase.from('items').insert({ ...result.data, user_id: user.id })
|
||||||
|
if (error) return { success: false, error: 'Failed to create item' }
|
||||||
|
|
||||||
|
revalidatePath('/items')
|
||||||
|
return { success: true, data: undefined }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## RULE 7: Error boundaries for every data-fetching page
|
||||||
|
|
||||||
|
Every page that fetches data MUST have sibling loading.tsx and error.tsx files.
|
||||||
|
|
||||||
|
## RULE 8: NEVER expose Stripe secret keys
|
||||||
|
|
||||||
|
Stripe keys starting with `sk_` must NEVER be in NEXT_PUBLIC_ variables.
|
||||||
|
Use process.env.STRIPE_SECRET_KEY (server-only).
|
||||||
|
|
||||||
|
## RULE 9: TypeScript strict mode, no `any`
|
||||||
|
|
||||||
|
NEVER use `any`. Use `unknown` with Zod validation or type narrowing.
|
||||||
|
tsconfig.json MUST have `strict: true`.
|
||||||
|
|
||||||
|
## RULE 10: Middleware is for session REFRESH only
|
||||||
|
|
||||||
|
NEVER put auth enforcement in Next.js middleware. Middleware runs on Edge Runtime
|
||||||
|
and cannot verify Supabase JWTs. Auth enforcement belongs in layouts/pages with getUser().
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Full rule set (27 rules) available at: https://github.com/vibestackdev/vibe-stack
|
||||||
|
Quick install: npx vibe-stack-rules init
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
---
|
||||||
|
description: Performance — avoid N+1, cache wisely, measure before optimizing
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
|
||||||
|
# Performance
|
||||||
|
|
||||||
|
- Measure before optimizing. Profile hot paths; do not guess bottlenecks.
|
||||||
|
- Fix N+1 queries: use eager loading, joins, or batch fetches.
|
||||||
|
- Cache expensive reads with explicit TTL and invalidation strategy.
|
||||||
|
- Lazy-load heavy modules and routes not needed on initial page load.
|
||||||
|
- Paginate large lists — never load unbounded datasets into memory.
|
||||||
|
- Debounce search inputs and resize handlers (typically 200–300ms).
|
||||||
|
- Compress and resize images. Serve modern formats (WebP, AVIF) where supported.
|
||||||
|
- Avoid blocking the main thread with heavy sync work — use workers or server-side processing.
|
||||||
|
- Set appropriate HTTP cache headers for static assets.
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
---
|
||||||
|
description: "Cursor rules for Playwright development with E2E testing."
|
||||||
|
globs: **/*
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
# Persona
|
||||||
|
|
||||||
|
You are an expert QA engineer with deep knowledge of Playwright and TypeScript, tasked with creating end-to-end UI tests for web applications.
|
||||||
|
|
||||||
|
# Auto-detect TypeScript Usage
|
||||||
|
|
||||||
|
Before creating tests, check if the project uses TypeScript by looking for:
|
||||||
|
|
||||||
|
- tsconfig.json file
|
||||||
|
- .ts file extensions in test directories
|
||||||
|
- TypeScript dependencies in package.json
|
||||||
|
Adjust file extensions (.ts/.js) and syntax based on this detection.
|
||||||
|
|
||||||
|
# End-to-End UI Testing Focus
|
||||||
|
|
||||||
|
Generate tests that focus on critical user flows (e.g., login, checkout, registration)
|
||||||
|
Tests should validate navigation paths, state updates, and error handling
|
||||||
|
Ensure reliability by using test IDs or semantic selectors rather than CSS or XPath selectors
|
||||||
|
Make tests maintainable with descriptive names and proper grouping in test.describe blocks
|
||||||
|
Use Playwright's page.route for API mocking to create isolated, deterministic tests
|
||||||
|
|
||||||
|
# Best Practices
|
||||||
|
|
||||||
|
**1** **Descriptive Names**: Use test names that explain the behavior being tested
|
||||||
|
**2** **Proper Setup**: Include setup in test.beforeEach blocks
|
||||||
|
**3** **Selector Usage**: Use data-testid or semantic selectors over CSS or XPath selectors
|
||||||
|
**4** **Waiting Strategy**: Leverage Playwright's auto-waiting instead of explicit waits
|
||||||
|
**5** **Mock Dependencies**: Mock external dependencies with page.route
|
||||||
|
**6** **Validation Coverage**: Validate both success and error scenarios
|
||||||
|
**7** **Test Focus**: Limit test files to 3-5 focused tests
|
||||||
|
**8** **Visual Testing**: Avoid testing visual styles directly
|
||||||
|
**9** **Test Basis**: Base tests on user stories or common flows
|
||||||
|
|
||||||
|
# Input/Output Expectations
|
||||||
|
|
||||||
|
**Input**: A description of a web application feature or user story
|
||||||
|
**Output**: A Playwright test file with 3-5 tests covering critical user flows
|
||||||
|
|
||||||
|
# Example End-to-End Test
|
||||||
|
|
||||||
|
When testing a login page, implement the following pattern:
|
||||||
|
|
||||||
|
```js
|
||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
|
||||||
|
test.describe('Login Page', () => {
|
||||||
|
test.beforeEach(async ({ page }) => {
|
||||||
|
await page.route('/api/login', (route) => {
|
||||||
|
const body = route.request().postDataJSON();
|
||||||
|
if (body.username === 'validUser' && body.password === 'validPass') {
|
||||||
|
route.fulfill({
|
||||||
|
status: 200,
|
||||||
|
body: JSON.stringify({ message: 'Login successful' }),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
route.fulfill({
|
||||||
|
status: 401,
|
||||||
|
body: JSON.stringify({ error: 'Invalid credentials' }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
await page.goto('/login');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('should allow user to log in with valid credentials', async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await page.locator('[data-testid="username"]').fill('validUser');
|
||||||
|
await page.locator('[data-testid="password"]').fill('validPass');
|
||||||
|
await page.locator('[data-testid="submit"]').click();
|
||||||
|
await expect(page.locator('[data-testid="welcome-message"]')).toBeVisible();
|
||||||
|
await expect(page.locator('[data-testid="welcome-message"]')).toHaveText(
|
||||||
|
/Welcome, validUser/
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('should show an error message for invalid credentials', async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await page.locator('[data-testid="username"]').fill('invalidUser');
|
||||||
|
await page.locator('[data-testid="password"]').fill('wrongPass');
|
||||||
|
await page.locator('[data-testid="submit"]').click();
|
||||||
|
await expect(page.locator('[data-testid="error-message"]')).toBeVisible();
|
||||||
|
await expect(page.locator('[data-testid="error-message"]')).toHaveText(
|
||||||
|
'Invalid credentials'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
```
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
---
|
||||||
|
description: "PostgreSQL production rules. Safe migrations, parameterized queries, TIMESTAMPTZ, proper indexing strategy."
|
||||||
|
globs: **/*.sql, **/migrations/**/*.sql, **/schema.sql, **/seed.sql
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
# PostgreSQL Rules
|
||||||
|
|
||||||
|
Expert PostgreSQL developer. Safe migrations, parameterized queries, proper indexing.
|
||||||
|
|
||||||
|
## Schema
|
||||||
|
- TIMESTAMPTZ for all timestamps (not TIMESTAMP without timezone)
|
||||||
|
- UUID for public IDs, BIGSERIAL for internal keys
|
||||||
|
- NOT NULL by default — nullable only when intentional
|
||||||
|
- FK with explicit ON DELETE behavior
|
||||||
|
- Check constraints for domain invariants
|
||||||
|
|
||||||
|
## Queries
|
||||||
|
- Parameterized always — never string interpolation
|
||||||
|
- SELECT explicit columns, never SELECT *
|
||||||
|
- LIMIT on all potentially large result sets
|
||||||
|
- EXPLAIN ANALYZE before shipping complex queries
|
||||||
|
|
||||||
|
## Indexes
|
||||||
|
- Index every FK column
|
||||||
|
- CREATE INDEX CONCURRENTLY for live tables (non-blocking)
|
||||||
|
- Partial indexes for frequently filtered subsets
|
||||||
|
- Remove unused indexes
|
||||||
|
|
||||||
|
## Migrations
|
||||||
|
- Versioned files: V001__create_table.sql
|
||||||
|
- Large column additions: multi-step with backfill
|
||||||
|
- Test rollback before deploying
|
||||||
|
|
||||||
|
## Transactions
|
||||||
|
- Explicit BEGIN/COMMIT for multi-statement changes
|
||||||
|
- statement_timeout to prevent runaway queries
|
||||||
|
- SELECT ... FOR UPDATE for row locking
|
||||||
|
|
||||||
|
## Forbidden
|
||||||
|
- No SELECT *
|
||||||
|
- No string-interpolated SQL
|
||||||
|
- No schema changes during peak traffic
|
||||||
|
- No plaintext passwords in DB
|
||||||
|
- No TRUNCATE in app code
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
---
|
||||||
|
description: "Cursor rules for focused PR reviews with severity ranking, file and line citations, and separate review angles for security, performance, tests, and architecture."
|
||||||
|
globs: **/*
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
# PR Review — focused review prompts for Cursor
|
||||||
|
|
||||||
|
When the user asks you to review a pull request, set of changes, or "this PR", run the appropriate review angle from the four below. Pick based on the user's emphasis ("security", "perf", "tests", "arch"). If unspecified, ask which angle, or default to security.
|
||||||
|
|
||||||
|
Output discipline (applies to all angles):
|
||||||
|
|
||||||
|
- Cite file path and line number for each finding.
|
||||||
|
- Rank findings by severity: blocker, important, nit.
|
||||||
|
- Be specific. "This looks risky" is not a finding; "src/auth.ts:42 — JWT secret read from request body, see line 41" is.
|
||||||
|
- If the diff doesn't give you enough context to be sure, say so explicitly and ask for the surrounding file.
|
||||||
|
- End with a verdict on its own line: `Safe to merge | needs changes | reject`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Angle 1: SECURITY
|
||||||
|
|
||||||
|
You are reviewing the PR for security defects. Focus, in order of priority:
|
||||||
|
|
||||||
|
1. **Auth/authz** — new endpoints or branches missing auth checks, role assumptions, IDOR
|
||||||
|
2. **Input validation** — untrusted input flowing into queries, shell, file paths, deserialization, eval
|
||||||
|
3. **Injection** — SQL, NoSQL, command, prompt injection, template injection
|
||||||
|
4. **Secrets** — hardcoded keys/tokens, secrets in logs, secrets in client-bundled code, .env committed
|
||||||
|
5. **Output encoding** — XSS via unescaped templating, HTML in user content, JSONP-style leaks
|
||||||
|
6. **Crypto/randomness** — Math.random for tokens, MD5/SHA1, missing IVs, custom-rolled crypto
|
||||||
|
7. **Data exposure** — PII in logs, overshared API responses, missing redaction
|
||||||
|
|
||||||
|
Skip nice-to-haves. Stick to defects.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Angle 2: PERFORMANCE
|
||||||
|
|
||||||
|
You are reviewing for performance regressions. Focus:
|
||||||
|
|
||||||
|
1. **N+1 patterns** — loops doing DB/network calls per item without batching
|
||||||
|
2. **Hot-path allocations** — new objects/arrays/maps inside loops, regexes recompiled per call
|
||||||
|
3. **Unbounded work** — pagination missing, results sets unconstrained, recursion without depth cap
|
||||||
|
4. **Bad async** — sequential awaits where Promise.all is correct, missing concurrency limits
|
||||||
|
5. **Cache misuse** — cache keys that don't include the right variables, cache TTLs absent or pathological
|
||||||
|
6. **Algorithm complexity** — O(n^2) hidden in `.some` over `.map`, sort inside loops
|
||||||
|
|
||||||
|
Quote the specific line, name the complexity or the bad pattern, suggest the fix.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Angle 3: TESTS
|
||||||
|
|
||||||
|
You are reviewing the test coverage on this PR. Focus:
|
||||||
|
|
||||||
|
1. **Tests for new code paths** — every new branch should have at least one test
|
||||||
|
2. **Edge cases** — empty input, null/undefined, boundary values, errors thrown by deps
|
||||||
|
3. **Assertion strength** — assertions that pass with the wrong value, snapshot-only tests, tests that only check the happy path
|
||||||
|
4. **Mocking discipline** — mocks that don't fail when the real interface changes, over-mocking
|
||||||
|
5. **Determinism** — date/time/random/network not stubbed, leading to flakes
|
||||||
|
6. **Test names** — names that don't describe behavior
|
||||||
|
|
||||||
|
A test that exists is not the same as a test that catches regressions. Read the assertions, not the test name.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Angle 4: ARCHITECTURE
|
||||||
|
|
||||||
|
You are reviewing the *shape* of the change. Pull back from line-level concerns:
|
||||||
|
|
||||||
|
1. **Boundary drift** — where did the seam between layers move? Did UI start reaching into DB? Did domain types start importing transport types?
|
||||||
|
2. **Premature abstraction** — interfaces, factories, or config layers with only one implementation. These are debt.
|
||||||
|
3. **Coupling** — utilities now importing from feature modules, shared mutable state being introduced
|
||||||
|
4. **Scalability** — if this code path goes 10x, what breaks first?
|
||||||
|
5. **Reversibility** — if this turns out wrong in a month, how hard is the rollback? One-way doors should be called out.
|
||||||
|
6. **Naming** — types/functions named for the implementation (`UserManagerImplV2`) rather than the role (`UserDirectory`).
|
||||||
|
|
||||||
|
End with: `Architecturally sound | needs trim | re-think before merging`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Pair these prompts with full file context for best results. If the user has only pasted a diff and not the surrounding file, ask for the full file — diffs alone routinely miss bugs that live two lines outside the change. The companion CLI [prpack](https://github.com/Lucas2944/prpack) automates this.
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
---
|
||||||
|
description: "Cursor rules for Python FastAPI development with best practices."
|
||||||
|
globs: **/*
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
You are an expert in Python, FastAPI, and scalable API development.
|
||||||
|
|
||||||
|
Write concise, technical responses with accurate Python examples. Use functional, declarative programming; avoid classes where possible. Prefer iteration and modularization over code duplication. Use descriptive variable names with auxiliary verbs (e.g., is_active, has_permission). Use lowercase with underscores for directories and files (e.g., routers/user_routes.py). Favor named exports for routes and utility functions. Use the Receive an Object, Return an Object (RORO) pattern. Use def for pure functions and async def for asynchronous operations. Use type hints for all function signatures. Prefer Pydantic models over raw dictionaries for input validation.
|
||||||
|
|
||||||
|
File structure: exported router, sub-routes, utilities, static content, types (models, schemas).
|
||||||
|
|
||||||
|
Avoid unnecessary curly braces in conditional statements. For single-line statements in conditionals, omit curly braces. Use concise, one-line syntax for simple conditional statements (e.g., if condition: do_something()).
|
||||||
|
|
||||||
|
Prioritize error handling and edge cases:
|
||||||
|
|
||||||
|
FastAPI
|
||||||
|
Pydantic v2
|
||||||
|
Async database libraries like asyncpg or aiomysql
|
||||||
|
SQLAlchemy 2.0 (if using ORM features)
|
||||||
|
|
||||||
|
Use functional components (plain functions) and Pydantic models for input validation and response schemas. Use declarative route definitions with clear return type annotations. Use def for synchronous operations and async def for asynchronous ones. Minimize @app.on_event("startup") and @app.on_event("shutdown"); prefer lifespan context managers for managing startup and shutdown events. Use middleware for logging, error monitoring, and performance optimization. Optimize for performance using async functions for I/O-bound tasks, caching strategies, and lazy loading. Use HTTPException for expected errors and model them as specific HTTP responses. Use middleware for handling unexpected errors, logging, and error monitoring. Use Pydantic's BaseModel for consistent input/output validation and response schemas. Minimize blocking I/O operations; use asynchronous operations for all database calls and external API requests. Implement caching for static and frequently accessed data using tools like Redis or in-memory stores. Optimize data serialization and deserialization with Pydantic. Use lazy loading techniques for large datasets and substantial API responses. Refer to FastAPI documentation for Data Models, Path Operations, and Middleware for best practices.
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
---
|
||||||
|
description: Python style — PEP 8, typing, and safe patterns
|
||||||
|
globs: **/*.py
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
|
||||||
|
# Python Standards
|
||||||
|
|
||||||
|
- Follow PEP 8. Use 4-space indentation and `snake_case` for functions/variables.
|
||||||
|
- Add type hints to all public function signatures and return types.
|
||||||
|
- Use `pathlib.Path` instead of string path concatenation.
|
||||||
|
- Prefer f-strings over `.format()` or `%` formatting.
|
||||||
|
- Use context managers (`with`) for files, DB connections, and locks.
|
||||||
|
- Catch specific exceptions; never use bare `except:` or `except Exception:` without re-raising.
|
||||||
|
- Use `logging` instead of `print()` in application code.
|
||||||
|
- Virtual environments: never commit `venv/` or `__pycache__/`.
|
||||||
|
- Prefer `dataclasses` or `pydantic` models over untyped dicts for structured data.
|
||||||
|
- Use `if __name__ == "__main__":` guards in runnable scripts.
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
---
|
||||||
|
description: "Cursor rules for React Native Expo development."
|
||||||
|
globs: **/*
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
// React Native Expo .cursorrules
|
||||||
|
|
||||||
|
// React Native Expo best practices
|
||||||
|
|
||||||
|
const reactNativeExpoBestPractices = [
|
||||||
|
"Use functional components with hooks",
|
||||||
|
"Utilize Expo SDK features and APIs",
|
||||||
|
"Implement proper navigation using Expo Router",
|
||||||
|
"Use Expo's asset system for images and fonts",
|
||||||
|
"Implement proper error handling and crash reporting",
|
||||||
|
"Utilize Expo's push notification system",
|
||||||
|
];
|
||||||
|
|
||||||
|
// Folder structure
|
||||||
|
|
||||||
|
const folderStructure = `
|
||||||
|
assets/
|
||||||
|
src/
|
||||||
|
components/
|
||||||
|
screens/
|
||||||
|
navigation/
|
||||||
|
hooks/
|
||||||
|
utils/
|
||||||
|
App.js
|
||||||
|
app.json
|
||||||
|
`;
|
||||||
|
|
||||||
|
// Additional instructions
|
||||||
|
|
||||||
|
const additionalInstructions = `
|
||||||
|
1. Use TypeScript for type safety
|
||||||
|
2. Implement proper styling using StyleSheet
|
||||||
|
3. Utilize Expo's vector icons
|
||||||
|
4. Use Expo's secure store for sensitive data
|
||||||
|
5. Implement proper offline support
|
||||||
|
6. Follow React Native best practices for performance
|
||||||
|
7. Use Expo's OTA updates for quick deployments
|
||||||
|
`;
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
---
|
||||||
|
description: React Router v7 rules for framework mode, data routers, loaders, actions, route modules, and progressive enhancement
|
||||||
|
globs: ["app/routes/**/*", "src/routes/**/*", "routes/**/*", "react-router.config.*", "vite.config.*", "**/*.tsx", "**/*.ts"]
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
|
||||||
|
# React Router v7 Rules
|
||||||
|
|
||||||
|
## Route Modules
|
||||||
|
|
||||||
|
- Use route modules as the boundary for route UI, loader data, actions, metadata, and error boundaries.
|
||||||
|
- Keep route modules small; move shared UI to components and reusable data access to services.
|
||||||
|
- Prefer file-based routing in framework mode when the project is configured for it.
|
||||||
|
- Use nested routes for shared layouts and progressive disclosure.
|
||||||
|
- Export route-specific `ErrorBoundary` components for recoverable route failures.
|
||||||
|
|
||||||
|
## Data Loading
|
||||||
|
|
||||||
|
- Use loaders for route data that should be available before render.
|
||||||
|
- Keep loaders deterministic and side-effect free.
|
||||||
|
- Validate params and search params at the loader boundary.
|
||||||
|
- Return typed data and consume it through route hooks rather than duplicating fetch logic in components.
|
||||||
|
- Use deferred or streaming patterns only when they improve perceived performance.
|
||||||
|
|
||||||
|
## Mutations
|
||||||
|
|
||||||
|
- Use actions for route mutations and form submissions.
|
||||||
|
- Prefer `Form`, `useFetcher`, and `useSubmit` for progressive enhancement.
|
||||||
|
- Revalidate affected loader data after mutations.
|
||||||
|
- Handle validation errors as typed action data instead of generic exceptions.
|
||||||
|
- Keep server-only secrets and privileged operations out of client actions.
|
||||||
|
|
||||||
|
## Navigation and State
|
||||||
|
|
||||||
|
- Store shareable state in URL params or search params.
|
||||||
|
- Keep ephemeral UI state local to components.
|
||||||
|
- Use pending navigation state to show optimistic or loading UI.
|
||||||
|
- Avoid global state for data that belongs to route loaders.
|
||||||
|
|
||||||
|
## TypeScript and Testing
|
||||||
|
|
||||||
|
- Type loader and action return values.
|
||||||
|
- Add tests for route loaders, actions, validation failures, and error boundaries.
|
||||||
|
- Use integration tests for critical form and navigation flows.
|
||||||
|
- Mock network and persistence at the route-service boundary.
|
||||||
|
|
||||||
|
## Common Mistakes
|
||||||
|
|
||||||
|
- Do not duplicate loader fetches in `useEffect`.
|
||||||
|
- Do not mutate data in loaders.
|
||||||
|
- Do not hide route errors behind a single generic app-level catch-all.
|
||||||
|
- Do not put auth checks only in components when loader data is protected.
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
---
|
||||||
|
description: "React and TypeScript state management guidance for Zustand stores, selectors, middleware, persistence, and testing."
|
||||||
|
globs: **/*.ts, **/*.tsx
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
You are an expert in React, TypeScript, and Zustand state management.
|
||||||
|
|
||||||
|
# React + Zustand Guidelines
|
||||||
|
|
||||||
|
## State Ownership
|
||||||
|
- Keep ephemeral UI state in the nearest component with `useState` or `useReducer`.
|
||||||
|
- Use URL state for shareable filters, pagination, tabs, and search params.
|
||||||
|
- Use Zustand only for client state that is genuinely shared across unrelated components.
|
||||||
|
- Use TanStack Query, SWR, RTK Query, or the existing project data layer for server state.
|
||||||
|
- Never duplicate fetched server data into a Zustand store unless there is a documented offline or draft-editing requirement.
|
||||||
|
|
||||||
|
## Store Design
|
||||||
|
- Model each store as state plus named actions; avoid exposing anonymous setters for component code to misuse.
|
||||||
|
- Keep stores small and domain-focused: auth session view state, command palette state, cart draft state, editor state, etc.
|
||||||
|
- Split large stores into typed slices, then apply middleware only at the composed store boundary.
|
||||||
|
- Keep derived values as selectors or small pure helpers unless they must be cached in state.
|
||||||
|
- Store serializable data by default; keep DOM nodes, promises, sockets, and timers outside store state.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { create } from 'zustand'
|
||||||
|
|
||||||
|
interface SidebarState {
|
||||||
|
isOpen: boolean
|
||||||
|
activePanelId: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SidebarActions {
|
||||||
|
openPanel: (panelId: string) => void
|
||||||
|
close: () => void
|
||||||
|
toggle: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
type SidebarStore = SidebarState & SidebarActions
|
||||||
|
|
||||||
|
export const useSidebarStore = create<SidebarStore>()((set) => ({
|
||||||
|
isOpen: false,
|
||||||
|
activePanelId: null,
|
||||||
|
openPanel: (panelId) => set({ isOpen: true, activePanelId: panelId }),
|
||||||
|
close: () => set({ isOpen: false, activePanelId: null }),
|
||||||
|
toggle: () => set((state) => ({ isOpen: !state.isOpen })),
|
||||||
|
}))
|
||||||
|
```
|
||||||
|
|
||||||
|
## Component Usage
|
||||||
|
- Subscribe to the smallest possible slice: `useStore((state) => state.value)`.
|
||||||
|
- Do not call a store hook without a selector in components unless the component truly needs every field.
|
||||||
|
- Select actions separately or through a shallow selector when grouping them.
|
||||||
|
- Use `useShallow` for object or tuple selectors that return multiple values.
|
||||||
|
- Keep selectors pure and cheap; move expensive derivations into memoized helpers if needed.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { useShallow } from 'zustand/react/shallow'
|
||||||
|
import { useSidebarStore } from '@/stores/sidebar-store'
|
||||||
|
|
||||||
|
export function SidebarToggle() {
|
||||||
|
const { isOpen, toggle } = useSidebarStore(
|
||||||
|
useShallow((state) => ({
|
||||||
|
isOpen: state.isOpen,
|
||||||
|
toggle: state.toggle,
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button type="button" aria-expanded={isOpen} onClick={toggle}>
|
||||||
|
Toggle sidebar
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## TypeScript
|
||||||
|
- Define explicit state and action interfaces for shared stores.
|
||||||
|
- Avoid `any`; use `unknown` plus narrowing for external data.
|
||||||
|
- Type action payloads and return values, including async actions.
|
||||||
|
- Prefer discriminated unions for complex local status instead of several loosely related booleans.
|
||||||
|
- Export store state types when tests, utilities, or vanilla store factories need them.
|
||||||
|
|
||||||
|
## Updates and Middleware
|
||||||
|
- Use functional `set((state) => nextState)` when the next value depends on current state.
|
||||||
|
- Treat nested state immutably; install and use `immer` middleware only when it materially simplifies nested updates.
|
||||||
|
- Use `persist` only for state that must survive reloads.
|
||||||
|
- Use `partialize`, `version`, and `migrate` when persisting anything beyond trivial preferences.
|
||||||
|
- Never persist secrets, access tokens, refresh tokens, raw PII, or long-lived authorization state to browser storage.
|
||||||
|
- Use `devtools` in development for complex flows and give important actions clear names.
|
||||||
|
- Use `subscribeWithSelector` for non-React subscriptions that need fine-grained updates.
|
||||||
|
|
||||||
|
## Async Actions
|
||||||
|
- Async store actions may coordinate client-only workflows, optimistic drafts, or local device APIs.
|
||||||
|
- Keep HTTP fetching in the project's server-state layer unless the state is explicitly client-owned.
|
||||||
|
- Represent async client workflows with explicit statuses such as `idle`, `pending`, `success`, and `error`.
|
||||||
|
- Reset error state deliberately when retrying or closing a workflow.
|
||||||
|
|
||||||
|
## SSR and React Server Components
|
||||||
|
- Do not read or mutate browser-only stores from React Server Components.
|
||||||
|
- In SSR frameworks, create per-request vanilla stores when state must be initialized on the server.
|
||||||
|
- Guard persisted stores against hydration mismatches before rendering storage-backed values.
|
||||||
|
- Keep store modules free of direct `window`, `document`, and storage access outside middleware configuration.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
- Test store actions directly without rendering React when possible.
|
||||||
|
- Reset stores between tests with their initial state.
|
||||||
|
- Assert selectors and actions separately from component behavior.
|
||||||
|
- Mock server-state libraries instead of routing fetched data through Zustand for tests.
|
||||||
|
|
||||||
|
## Anti-Patterns
|
||||||
|
- Do not create one global store for the entire application.
|
||||||
|
- Do not put form input state in Zustand unless multiple distant components edit the same draft.
|
||||||
|
- Do not mutate nested objects directly without Immer middleware.
|
||||||
|
- Do not use Zustand as an event bus; prefer explicit callbacks, services, or a scoped store.
|
||||||
|
- Do not introduce Redux-style reducers, action constants, or dispatch wrappers unless the project already uses that pattern.
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
---
|
||||||
|
description: "Cursor rules for README documentation with best practices integration."
|
||||||
|
globs: **/*
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
Write READMEs like landing pages, not API docs. The reader decides in 3-5 seconds.
|
||||||
|
|
||||||
|
Start with a bold one-liner saying what it does and why someone should care. Not "A tool that..." - a punchline.
|
||||||
|
Put a working code example in the first 5 lines. Show the value prop immediately.
|
||||||
|
Use feature tables (two columns) instead of **Feature:** bullet lists. Tables scan faster.
|
||||||
|
Quick Start must be copy-paste ready. No $ prefix on bash commands. Zero to running in 30 seconds.
|
||||||
|
Vary sentence lengths and structure. Mix one-liners with short paragraphs and tables. Not walls of same-length bullets.
|
||||||
|
Never use "seamless", "robust", "comprehensive", "cutting-edge", or other AI marketing words.
|
||||||
|
Never open with "In today's..." or close with "Happy coding!"
|
||||||
|
Check that referenced assets (demo.gif, screenshots) actually exist on disk before adding image links.
|
||||||
|
Author section should include a visual card or badge, not just plain text "Made by username".
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
---
|
||||||
|
description: "Cursor rules for RTL development with logical CSS properties, Tailwind logical classes, bidirectional text, and automated auditing via rtlify-ai."
|
||||||
|
globs: **/*
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
# RTL (Right-to-Left) Development Rules
|
||||||
|
|
||||||
|
You are an expert in building applications that support RTL (Right-to-Left) languages including Hebrew, Arabic, Persian, and Urdu.
|
||||||
|
|
||||||
|
## Core Rules
|
||||||
|
|
||||||
|
### 1. Logical CSS Properties
|
||||||
|
Always use CSS logical properties instead of physical ones:
|
||||||
|
- `margin-inline-start` not `margin-left`
|
||||||
|
- `padding-inline-end` not `padding-right`
|
||||||
|
- `inset-inline-start` not `left`
|
||||||
|
- `border-inline-start` not `border-left`
|
||||||
|
|
||||||
|
### 2. Tailwind CSS Logical Classes
|
||||||
|
Use logical Tailwind utilities:
|
||||||
|
- `ms-4` not `ml-4` (margin-start)
|
||||||
|
- `me-4` not `mr-4` (margin-end)
|
||||||
|
- `ps-4` not `pl-4` (padding-start)
|
||||||
|
- `pe-4` not `pr-4` (padding-end)
|
||||||
|
- `start-0` not `left-0`
|
||||||
|
- `end-0` not `right-0`
|
||||||
|
|
||||||
|
### 3. React Native Logical Properties
|
||||||
|
Use logical properties in React Native styles:
|
||||||
|
- `paddingStart` not `paddingLeft`
|
||||||
|
- `paddingEnd` not `paddingRight`
|
||||||
|
- `marginStart` not `marginLeft`
|
||||||
|
- `marginEnd` not `marginRight`
|
||||||
|
|
||||||
|
### 4. Bidirectional Text Safety
|
||||||
|
Wrap mixed-script text with `<bdi>` tags:
|
||||||
|
```html
|
||||||
|
<p>User <bdi>{userName}</bdi> posted a comment</p>
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. Directional Icons
|
||||||
|
Flip directional icons (arrows, chevrons, back buttons) in RTL mode.
|
||||||
|
Non-directional icons (home, settings, search) should NOT be flipped.
|
||||||
|
|
||||||
|
### 6. Internationalization
|
||||||
|
- Never hardcode strings — use translation functions (`t()`, `intl.formatMessage()`)
|
||||||
|
- Use `Intl.NumberFormat` for numbers and currency
|
||||||
|
- Use `Intl.DateTimeFormat` for dates
|
||||||
|
- Set `dir="auto"` or `dir="rtl"` on root elements
|
||||||
|
|
||||||
|
### 7. RTL-Aware Components
|
||||||
|
- Carousels, sliders, and progress bars must reverse direction in RTL
|
||||||
|
- Swipe gestures must reverse in RTL
|
||||||
|
- Charts and graphs with directional axes must flip
|
||||||
|
|
||||||
|
### 8. Testing
|
||||||
|
- Always test with `dir="rtl"` on the root element
|
||||||
|
- Verify with actual RTL content, not just flipped LTR
|
||||||
|
|
||||||
|
## Automated RTL Auditing
|
||||||
|
|
||||||
|
For automated RTL violation detection and fixing, use [rtlify-ai](https://github.com/idanlevi1/rtlify):
|
||||||
|
```bash
|
||||||
|
npx rtlify-ai init # Install RTL rules
|
||||||
|
npx rtlify-ai check # Find violations
|
||||||
|
npx rtlify-ai fix # Auto-fix violations
|
||||||
|
```
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
---
|
||||||
|
description: "Rust best practices for Solana smart contract development using Anchor framework and Solana SDK"
|
||||||
|
globs: programs/**/*.rs, src/**/*.rs, tests/**/*.ts
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
# Rust + Solana (Anchor) Best Practices
|
||||||
|
|
||||||
|
## Program Structure
|
||||||
|
- Structure Solana programs using `Anchor` framework standards
|
||||||
|
- Place program entrypoint logic in `lib.rs`, not `main.rs`
|
||||||
|
- Organize handlers into modules (e.g., `initialize`, `update`, `close`)
|
||||||
|
- Separate state definitions, errors, instructions, and utils
|
||||||
|
- Group reusable logic under a `utils` module (e.g., account validation)
|
||||||
|
- Use `declare_id!()` to define program ID
|
||||||
|
|
||||||
|
## Anchor Framework
|
||||||
|
- Use `#[derive(Accounts)]` for all instruction contexts
|
||||||
|
- Validate accounts strictly using constraint macros (e.g., `#[account(mut)]`, `seeds`, `bump]`)
|
||||||
|
- Define all state structs with `#[account]` and `#[derive(AnchorSerialize, AnchorDeserialize)]`
|
||||||
|
- Prefer `Init`, `Close`, `Realloc`, `Mut`, and constraint macros to avoid manual deserialization
|
||||||
|
- Use `ctx.accounts` to access validated context accounts
|
||||||
|
- Handle CPI (Cross-Program Invocation) calls via Anchor’s CPI helpers
|
||||||
|
|
||||||
|
## Serialization
|
||||||
|
- Use **Borsh** or Anchor's custom serializer (not Serde) for on-chain data
|
||||||
|
- Always include `#[account(zero_copy)]` or `#[repr(C)]` for packed structures
|
||||||
|
- Avoid floating point types — use `u64`, `u128`, or fixed-point math
|
||||||
|
- Zero out or close unused accounts to reduce rent costs
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
- Write tests in TypeScript using Anchor’s Mocha + Chai setup (`tests/*.ts`)
|
||||||
|
- Use `anchor.workspace.MyProgram` to load deployed contracts
|
||||||
|
- Use `provider.simulate()` to inspect failed txs
|
||||||
|
- Spin up a local validator (`anchor test`) and reset between tests
|
||||||
|
- Airdrop SOL to wallets with `provider.connection.requestAirdrop(...)`
|
||||||
|
- Validate program logs using `tx.confirmation.logMessages`
|
||||||
|
|
||||||
|
## Solana SDK (Manual)
|
||||||
|
- Use `solana_program` crate when not using Anchor (bare-metal programs)
|
||||||
|
- Carefully deserialize accounts using `AccountInfo`, `try_from_slice_unchecked`
|
||||||
|
- Use `solana_program::msg!` for lightweight debugging logs
|
||||||
|
- Verify accounts via `is_signer`, `is_writable`, `key == expected`
|
||||||
|
- Never panic! Use `ProgramError::Custom(u32)` or `ErrorCode` enums
|
||||||
|
|
||||||
|
## Security Patterns
|
||||||
|
- Always validate `msg.sender`/signer with `account_info.is_signer`
|
||||||
|
- Prevent replay attacks via `seeds`, `bump`, and unique PDAs
|
||||||
|
- Use strict size checks before reallocating or deserializing
|
||||||
|
- Avoid unsafe unchecked casting; prefer Anchor deserialization
|
||||||
|
- For CPIs, validate `target_program` against expected program ID
|
||||||
|
- When using randomness, never rely on timestamps — use oracles or off-chain VRFs
|
||||||
|
|
||||||
|
## Performance
|
||||||
|
- Prefer zero-copy deserialization when accounts are large
|
||||||
|
- Minimize compute usage; avoid loops and recursion
|
||||||
|
- Avoid memory reallocations mid-instruction
|
||||||
|
- Use `#[account(zero_copy)]` and `#[repr(packed)]` for tight layout
|
||||||
|
- Profile compute units with `solana logs` and `anchor run`
|
||||||
|
|
||||||
|
## Dev Workflow
|
||||||
|
- Use `anchor init` to scaffold projects
|
||||||
|
- Add Anchor IDL support for front-end usage (JSON ABI)
|
||||||
|
- Use `anchor build`, `anchor deploy`, `anchor test` consistently
|
||||||
|
- Use separate `Anchor.toml` environments for devnet/mainnet/localnet
|
||||||
|
- Format all Rust code with `cargo fmt`, lint with `cargo clippy`
|
||||||
|
- Keep `Cargo.lock` checked into `programs/` but not root
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
- Use `///` Rust doc comments for all instructions and accounts
|
||||||
|
- Include doc examples for each instruction
|
||||||
|
- Document PDA derivation logic and bump seed expectations
|
||||||
|
- Maintain up-to-date `README.md` with test commands and deployment steps
|
||||||
|
|
||||||
|
## Wallet & Network Handling
|
||||||
|
- Use `anchorProvider.wallet.publicKey` for signer verification in tests
|
||||||
|
- Do not hardcode keypairs — use env-based loading (`process.env.ANCHOR_WALLET`)
|
||||||
|
- Deploy with clear `cluster` targets (`localnet`, `devnet`, `mainnet`)
|
||||||
|
- Use `anchor keys sync` to propagate program ID changes
|
||||||
|
- Commit `target/idl/` and `target/types/` to share with front end
|
||||||
|
|
||||||
|
## CI/CD & Deploy
|
||||||
|
- Use GitHub Actions with `solana-cli`, `anchor-cli`, and `node` installed
|
||||||
|
- Run `anchor test` in CI for every PR
|
||||||
|
- Use `solana program deploy` with explicit `--program-id` on production deploys
|
||||||
|
- Upload IDLs to a central registry (e.g., GitHub, IPFS, or `anchor.cloud`)
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
---
|
||||||
|
description: Security basics — secrets, auth, injection, and safe defaults
|
||||||
|
alwaysApply: true
|
||||||
|
---
|
||||||
|
|
||||||
|
# Security Basics
|
||||||
|
|
||||||
|
- Never commit secrets, API keys, tokens, or passwords. Use environment variables.
|
||||||
|
- Never log passwords, tokens, session IDs, or full credit card numbers.
|
||||||
|
- Parameterize all database queries. Never concatenate user input into SQL.
|
||||||
|
- Escape or sanitize user-generated content before rendering in HTML.
|
||||||
|
- Validate and whitelist file uploads: type, size, and storage path.
|
||||||
|
- Use HTTPS for all external API calls in production code paths.
|
||||||
|
- Apply least-privilege: services and DB users get only the permissions they need.
|
||||||
|
- Check authorization on every mutating endpoint — authentication alone is not enough.
|
||||||
|
- Set secure cookie flags (`HttpOnly`, `Secure`, `SameSite`) for session cookies.
|
||||||
|
- Do not disable TLS certificate verification in production code.
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
---
|
||||||
|
description: SQL and database safety — queries, migrations, and indexes
|
||||||
|
globs: **/*.{sql,prisma},**/migrations/**/*
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
|
||||||
|
# SQL & Database
|
||||||
|
|
||||||
|
- Always use parameterized queries or an ORM. Never interpolate user input into SQL strings.
|
||||||
|
- Migrations must be reversible or include a documented rollback path.
|
||||||
|
- Add indexes for columns used in `WHERE`, `JOIN`, and `ORDER BY` on large tables.
|
||||||
|
- Avoid `SELECT *` in application code — select only needed columns.
|
||||||
|
- Use transactions for multi-step writes that must succeed or fail together.
|
||||||
|
- Set `statement_timeout` on long-running queries in production.
|
||||||
|
- Never store plaintext passwords. Use bcrypt, Argon2id, or scrypt.
|
||||||
|
- Soft-delete vs hard-delete: follow the project's existing pattern consistently.
|
||||||
|
- Name constraints and indexes explicitly for easier debugging in production.
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
---
|
||||||
|
description: "Cursor rules for SvelteKit development with TypeScript integration."
|
||||||
|
globs: **/*
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
You are an expert in Svelte 5, SvelteKit, TypeScript, Supabase, Drizzle and modern web development.
|
||||||
|
|
||||||
|
Key Principles
|
||||||
|
|
||||||
|
Code Style and Structure
|
||||||
|
Naming Conventions
|
||||||
|
TypeScript Usage
|
||||||
|
Svelte Runes
|
||||||
|
UI and Styling
|
||||||
|
Shadcn Color Conventions
|
||||||
|
SvelteKit Project Structure
|
||||||
|
Component Development
|
||||||
|
State Management
|
||||||
|
|
||||||
|
Use classes for complex state management (state machines):
|
||||||
|
```typescript
|
||||||
|
// counter.svelte.ts
|
||||||
|
class Counter {
|
||||||
|
count = $state(0);
|
||||||
|
incrementor = $state(1);
|
||||||
|
increment() {
|
||||||
|
this.count += this.incrementor;
|
||||||
|
}
|
||||||
|
resetCount() {
|
||||||
|
this.count = 0;
|
||||||
|
}
|
||||||
|
resetIncrementor() {
|
||||||
|
this.incrementor = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export const counter = new Counter();
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
---
|
||||||
|
description: "Cursor rules for TanStack Query v5 with query options, query key factories, mutations, optimistic updates, infinite queries, Suspense, and prefetching."
|
||||||
|
globs: **/*
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
You are an expert in TanStack Query v5 (formerly React Query), TypeScript, and async state management for React applications.
|
||||||
|
|
||||||
|
# TanStack Query v5 Guidelines
|
||||||
|
|
||||||
|
## Core Philosophy
|
||||||
|
- TanStack Query manages server state — it is NOT a general state manager for client-only state
|
||||||
|
- Every query should have a stable, serializable query key that uniquely describes the data
|
||||||
|
- Mutations handle writes; queries handle reads — never blur this boundary
|
||||||
|
- Prefer `queryOptions()` helper for reusable, co-located query definitions
|
||||||
|
- v5 breaking changes: `useQuery` no longer accepts positional args; always use the options object form
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
```tsx
|
||||||
|
// main.tsx
|
||||||
|
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||||
|
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
|
||||||
|
|
||||||
|
const queryClient = new QueryClient({
|
||||||
|
defaultOptions: {
|
||||||
|
queries: {
|
||||||
|
staleTime: 1000 * 60, // 1 minute default stale time
|
||||||
|
retry: 2,
|
||||||
|
refetchOnWindowFocus: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
return (
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<YourApp />
|
||||||
|
<ReactQueryDevtools initialIsOpen={false} />
|
||||||
|
</QueryClientProvider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Query Keys
|
||||||
|
- Always structure keys as arrays: `['entity', 'list']`, `['entity', 'detail', id]`
|
||||||
|
- Use a query key factory to avoid typos and enable easy invalidation
|
||||||
|
```ts
|
||||||
|
// queryKeys.ts
|
||||||
|
export const postKeys = {
|
||||||
|
all: ['posts'] as const,
|
||||||
|
lists: () => [...postKeys.all, 'list'] as const,
|
||||||
|
list: (filters: PostFilters) => [...postKeys.lists(), filters] as const,
|
||||||
|
details: () => [...postKeys.all, 'detail'] as const,
|
||||||
|
detail: (id: string) => [...postKeys.details(), id] as const,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## queryOptions Helper (v5)
|
||||||
|
- Use `queryOptions()` to define queries once and reuse across components and loaders
|
||||||
|
```ts
|
||||||
|
import { queryOptions } from '@tanstack/react-query'
|
||||||
|
|
||||||
|
export const postQueryOptions = (id: string) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: postKeys.detail(id),
|
||||||
|
queryFn: () => fetchPost(id),
|
||||||
|
staleTime: 1000 * 60 * 5, // 5 min
|
||||||
|
})
|
||||||
|
|
||||||
|
// In component
|
||||||
|
const { data } = useQuery(postQueryOptions(postId))
|
||||||
|
|
||||||
|
// In router loader (TanStack Router integration)
|
||||||
|
loader: ({ params, context: { queryClient } }) =>
|
||||||
|
queryClient.ensureQueryData(postQueryOptions(params.postId))
|
||||||
|
```
|
||||||
|
|
||||||
|
## useQuery
|
||||||
|
```tsx
|
||||||
|
const {
|
||||||
|
data,
|
||||||
|
isLoading, // true only on first load with no cached data
|
||||||
|
isFetching, // true whenever a fetch is in-flight
|
||||||
|
isError,
|
||||||
|
error,
|
||||||
|
isSuccess,
|
||||||
|
} = useQuery({
|
||||||
|
queryKey: postKeys.detail(postId),
|
||||||
|
queryFn: () => fetchPost(postId),
|
||||||
|
enabled: !!postId, // disable query if params not ready
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## useMutation
|
||||||
|
```tsx
|
||||||
|
const { mutate, mutateAsync, isPending } = useMutation({
|
||||||
|
mutationFn: (newPost: CreatePostInput) => createPost(newPost),
|
||||||
|
onSuccess: (data) => {
|
||||||
|
// Invalidate and refetch
|
||||||
|
queryClient.invalidateQueries({ queryKey: postKeys.lists() })
|
||||||
|
toast.success('Post created!')
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
toast.error(error.message)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
// Usage
|
||||||
|
mutate({ title: 'Hello', body: '...' })
|
||||||
|
```
|
||||||
|
|
||||||
|
## Optimistic Updates
|
||||||
|
```tsx
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
const mutation = useMutation({
|
||||||
|
mutationFn: updatePost,
|
||||||
|
onMutate: async (updatedPost) => {
|
||||||
|
await queryClient.cancelQueries({ queryKey: postKeys.detail(updatedPost.id) })
|
||||||
|
const previous = queryClient.getQueryData(postKeys.detail(updatedPost.id))
|
||||||
|
queryClient.setQueryData(postKeys.detail(updatedPost.id), updatedPost)
|
||||||
|
return { previous }
|
||||||
|
},
|
||||||
|
onError: (err, updatedPost, context) => {
|
||||||
|
queryClient.setQueryData(postKeys.detail(updatedPost.id), context?.previous)
|
||||||
|
},
|
||||||
|
onSettled: (_, __, updatedPost) => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: postKeys.detail(updatedPost.id) })
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Infinite Queries
|
||||||
|
```tsx
|
||||||
|
const {
|
||||||
|
data,
|
||||||
|
fetchNextPage,
|
||||||
|
hasNextPage,
|
||||||
|
isFetchingNextPage,
|
||||||
|
} = useInfiniteQuery({
|
||||||
|
queryKey: postKeys.lists(),
|
||||||
|
queryFn: ({ pageParam }) => fetchPosts({ cursor: pageParam }),
|
||||||
|
initialPageParam: undefined as string | undefined,
|
||||||
|
getNextPageParam: (lastPage) => lastPage.nextCursor,
|
||||||
|
})
|
||||||
|
|
||||||
|
// data.pages is an array of page results — flatten for rendering
|
||||||
|
const allPosts = data?.pages.flatMap((page) => page.items) ?? []
|
||||||
|
```
|
||||||
|
|
||||||
|
## Prefetching
|
||||||
|
- Prefetch on hover or during routing to eliminate loading states
|
||||||
|
```ts
|
||||||
|
// Hover prefetch
|
||||||
|
const handleMouseEnter = () => {
|
||||||
|
queryClient.prefetchQuery(postQueryOptions(postId))
|
||||||
|
}
|
||||||
|
|
||||||
|
// In router loader (eliminates all loading spinners)
|
||||||
|
export const Route = createFileRoute('/posts/$postId')({
|
||||||
|
loader: ({ context: { queryClient }, params }) =>
|
||||||
|
queryClient.ensureQueryData(postQueryOptions(params.postId)),
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Cache Invalidation Patterns
|
||||||
|
```ts
|
||||||
|
// Invalidate all post queries
|
||||||
|
queryClient.invalidateQueries({ queryKey: postKeys.all })
|
||||||
|
|
||||||
|
// Invalidate only post lists
|
||||||
|
queryClient.invalidateQueries({ queryKey: postKeys.lists() })
|
||||||
|
|
||||||
|
// Remove from cache entirely
|
||||||
|
queryClient.removeQueries({ queryKey: postKeys.detail(id) })
|
||||||
|
|
||||||
|
// Directly update cache without refetch
|
||||||
|
queryClient.setQueryData(postKeys.detail(id), newData)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Suspense Mode
|
||||||
|
- Use `useSuspenseQuery` for Suspense-based data fetching (v5)
|
||||||
|
- Wrap with `<Suspense fallback={<Skeleton />}>`
|
||||||
|
- Pair with `<ErrorBoundary>` for error handling
|
||||||
|
```tsx
|
||||||
|
// No need to handle isLoading — Suspense handles it
|
||||||
|
const { data } = useSuspenseQuery(postQueryOptions(postId))
|
||||||
|
```
|
||||||
|
|
||||||
|
## Performance Best Practices
|
||||||
|
- Set appropriate `staleTime` per query — defaults to `0` (always stale)
|
||||||
|
- Use `select` to transform/subscribe to only relevant slices of data
|
||||||
|
- Use `placeholderData: keepPreviousData` for pagination to avoid layout shifts
|
||||||
|
- Avoid creating `QueryClient` inside components — instantiate once at app root
|
||||||
|
- Use `notifyOnChangeProps` to limit re-renders to only relevant data changes
|
||||||
|
|
||||||
|
## Error Handling
|
||||||
|
- Use `throwOnError: true` to bubble errors to the nearest ErrorBoundary
|
||||||
|
- Use `retry` function for conditional retry logic (e.g., skip retry on 404)
|
||||||
|
```ts
|
||||||
|
retry: (failureCount, error) => {
|
||||||
|
if (error.status === 404) return false
|
||||||
|
return failureCount < 3
|
||||||
|
},
|
||||||
|
```
|
||||||
|
|
||||||
|
## TypeScript Tips
|
||||||
|
- Always type `queryFn` return value explicitly or infer from typed API functions
|
||||||
|
- Use `QueryObserverResult<TData, TError>` to type hook return values
|
||||||
|
- Use `UseMutationResult<TData, TError, TVariables>` for mutations
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
---
|
||||||
|
description: Testing standards — structure, naming, and what to cover
|
||||||
|
globs: **/*.{test,spec}.{ts,tsx,js,jsx,py}
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
|
||||||
|
# Testing Standards
|
||||||
|
|
||||||
|
- Test behavior, not implementation details. Assert outputs and side effects users care about.
|
||||||
|
- Follow Arrange–Act–Assert (or Given–When–Then) structure.
|
||||||
|
- One assertion concept per test. Name tests: `should <expected> when <condition>`.
|
||||||
|
- Cover happy path, edge cases, and at least one failure case per feature.
|
||||||
|
- Mock external services (APIs, DB, email) — never call real third parties in unit tests.
|
||||||
|
- Do not test framework internals or trivial getters with no logic.
|
||||||
|
- Keep tests independent: no shared mutable state between tests.
|
||||||
|
- Prefer factory helpers or fixtures over copy-pasted setup blocks.
|
||||||
|
- Flaky tests are bugs — fix or delete them, do not `@skip` without a tracked issue.
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
---
|
||||||
|
description: TypeScript strict patterns — types, null safety, and async
|
||||||
|
globs: **/*.{ts,tsx}
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
|
||||||
|
# TypeScript Standards
|
||||||
|
|
||||||
|
- Enable and respect `strict` mode. Avoid `any`; use `unknown` and narrow with type guards.
|
||||||
|
- Prefer `interface` for object shapes; use `type` for unions, intersections, and utilities.
|
||||||
|
- Handle `null` and `undefined` explicitly. Use optional chaining and nullish coalescing.
|
||||||
|
- Prefer `const` and `readonly` where mutation is not required.
|
||||||
|
- Use discriminated unions instead of boolean flag combinations.
|
||||||
|
- Async functions must have try/catch or propagate errors intentionally.
|
||||||
|
- Export types alongside public APIs. Do not leak internal types in public signatures.
|
||||||
|
- Use `satisfies` to validate object literals while preserving inferred types.
|
||||||
|
- Prefer `import type` for type-only imports.
|
||||||
|
- Name generic type parameters meaningfully (`TData`, `TError`), not single letters when ambiguous.
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
---
|
||||||
|
description: "Cursor rules for Vercel deployment including serverless functions, Edge Runtime, middleware, caching, CI/CD, and production-ready configuration."
|
||||||
|
globs: **/*
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
You are an expert in Vercel deployments, serverless architecture, and modern web application hosting.
|
||||||
|
|
||||||
|
# Vercel Deployment Guidelines
|
||||||
|
|
||||||
|
## Core Principles
|
||||||
|
- Always optimize for Vercel's edge network and serverless model
|
||||||
|
- Prefer Edge Runtime for globally distributed, low-latency responses
|
||||||
|
- Use Vercel's built-in environment variable management for secrets
|
||||||
|
- Structure projects to leverage Vercel's zero-config deployment detection
|
||||||
|
- Always use `vercel.json` for advanced routing, headers, and redirects configuration
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
- Place API routes in `/api` directory for automatic serverless function detection (Pages Router) or `/app/api` for App Router
|
||||||
|
- Use `public/` for static assets that should be served via Vercel's CDN
|
||||||
|
- Keep serverless functions small and focused — cold start time matters
|
||||||
|
- Separate long-running tasks to background jobs or external queues (Vercel has a 10s default timeout on Hobby, 60s on Pro)
|
||||||
|
|
||||||
|
## Environment Variables
|
||||||
|
- Never hard-code secrets; always use `process.env.VARIABLE_NAME`
|
||||||
|
- Prefix client-side env vars with `NEXT_PUBLIC_` (Next.js) or expose explicitly per framework
|
||||||
|
- Use Vercel's Environment Variable UI or CLI (`vercel env add`) to manage per-environment values (Development, Preview, Production)
|
||||||
|
- Use `.env.local` for local development; never commit it
|
||||||
|
- Reference `vercel.json` `env` field only for build-time non-secret values
|
||||||
|
|
||||||
|
## vercel.json Configuration
|
||||||
|
- Use `rewrites` for proxying API calls or SPA fallback routing
|
||||||
|
- Use `redirects` for permanent (308) or temporary (307) URL changes
|
||||||
|
- Use `headers` to set security headers (CSP, HSTS, X-Frame-Options) globally
|
||||||
|
- Use `regions` to pin serverless functions to specific regions when data locality matters
|
||||||
|
- Example security headers block:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"headers": [
|
||||||
|
{
|
||||||
|
"source": "/(.*)",
|
||||||
|
"headers": [
|
||||||
|
{ "key": "X-Content-Type-Options", "value": "nosniff" },
|
||||||
|
{ "key": "X-Frame-Options", "value": "DENY" },
|
||||||
|
{ "key": "X-XSS-Protection", "value": "1; mode=block" },
|
||||||
|
{ "key": "Referrer-Policy", "value": "strict-origin-when-cross-origin" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Serverless Functions
|
||||||
|
- Keep dependencies minimal — bundle size directly impacts cold starts
|
||||||
|
- Use Edge Functions (`export const runtime = 'edge'`) for auth checks, redirects, and A/B testing
|
||||||
|
- Use Node.js runtime for database connections, heavy computation, or Node-only packages
|
||||||
|
- Always handle errors gracefully and return proper HTTP status codes
|
||||||
|
- Use streaming responses for LLM or large data outputs
|
||||||
|
|
||||||
|
## Edge Middleware
|
||||||
|
- Place middleware in `middleware.ts` at the project root
|
||||||
|
- Use middleware for: authentication guards, geo-based redirects, bot protection, and A/B flags
|
||||||
|
- Keep middleware lightweight — it runs on every request before the cache
|
||||||
|
- Use `matcher` config to scope middleware only to needed routes
|
||||||
|
```ts
|
||||||
|
export const config = {
|
||||||
|
matcher: ['/dashboard/:path*', '/api/:path*'],
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Performance & Caching
|
||||||
|
- Use `Cache-Control` headers to control Vercel's CDN caching behavior
|
||||||
|
- Use `stale-while-revalidate` for ISR-like behavior in non-Next.js apps
|
||||||
|
- Set `s-maxage` for CDN cache TTL and `max-age` for browser cache
|
||||||
|
- Avoid over-fetching in serverless functions — reuse DB connections with connection pooling (PgBouncer, Prisma Accelerate)
|
||||||
|
- Use `vercel/og` for dynamic OG image generation at the edge
|
||||||
|
|
||||||
|
## CI/CD & Preview Deployments
|
||||||
|
- Use Vercel's GitHub/GitLab/Bitbucket integration for automatic preview deployments per PR
|
||||||
|
- Use `vercel pull` + `vercel build` + `vercel deploy --prebuilt` in custom CI pipelines
|
||||||
|
- Set branch protection rules to require passing preview deployment checks
|
||||||
|
- Use `VERCEL_ENV` environment variable to differentiate behavior across preview/production
|
||||||
|
|
||||||
|
## Domain & DNS
|
||||||
|
- Use Vercel Domains or point external DNS to Vercel's nameservers for automatic SSL
|
||||||
|
- Always redirect `www` to apex or vice versa — never serve both
|
||||||
|
- Use `vercel domains add` CLI command for custom domain management
|
||||||
|
|
||||||
|
## Monorepo Support
|
||||||
|
- Set `rootDirectory` in project settings to point to the correct app within a monorepo
|
||||||
|
- Use Turborepo with Vercel Remote Cache for fast CI builds (`turbo build --filter=...`)
|
||||||
|
- Scope environment variables per project even in shared monorepos
|
||||||
|
|
||||||
|
## Databases & Storage
|
||||||
|
- Prefer Vercel-native storage (Vercel KV, Vercel Postgres, Vercel Blob) for zero-config integration
|
||||||
|
- For external databases, always use connection pooling — serverless functions do not maintain persistent connections
|
||||||
|
- Store large files in Vercel Blob or S3-compatible storage, not in the function bundle
|
||||||
|
|
||||||
|
## Logging & Observability
|
||||||
|
- Use `console.log` / `console.error` — Vercel captures these as function logs
|
||||||
|
- Integrate with Vercel Log Drains to stream logs to Datadog, Sentry, or other observability tools
|
||||||
|
- Use Vercel Speed Insights and Web Analytics for real-user performance monitoring
|
||||||
|
- Set up alerts on error rate spikes via Vercel's integrations marketplace
|
||||||
|
|
||||||
|
## Security Best Practices
|
||||||
|
- Enable Vercel's DDoS protection (included on all plans)
|
||||||
|
- Use Vercel Firewall rules to block malicious IPs and patterns
|
||||||
|
- Rotate secrets regularly using Vercel's environment variable versioning
|
||||||
|
- Never log sensitive data (tokens, passwords, PII) in serverless function output
|
||||||
|
- Use `VERCEL_OIDC_TOKEN` for secure machine-to-machine auth between Vercel and cloud providers
|
||||||
|
|
||||||
|
## Deployment Workflow
|
||||||
|
- Run `vercel --prod` only from protected branches (main/master)
|
||||||
|
- Use `vercel deploy` (without `--prod`) for staging/preview deployments
|
||||||
|
- Alias stable preview URLs with `vercel alias` for QA sign-off
|
||||||
|
- Use deployment protection (password or Vercel Access) on preview deployments for private projects
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
---
|
||||||
|
description: "Cursor rules for Vitest development with unit testing."
|
||||||
|
globs: **/*
|
||||||
|
alwaysApply: false
|
||||||
|
---
|
||||||
|
# Persona
|
||||||
|
|
||||||
|
You are an expert developer with deep knowledge of Vitest and TypeScript, tasked with creating unit tests for JavaScript/TypeScript applications.
|
||||||
|
|
||||||
|
# Auto-detect TypeScript Usage
|
||||||
|
|
||||||
|
Check for TypeScript in the project through tsconfig.json or package.json dependencies.
|
||||||
|
Adjust syntax based on this detection.
|
||||||
|
|
||||||
|
# Unit Testing Focus
|
||||||
|
|
||||||
|
Create unit tests that focus on critical functionality (business logic, utility functions)
|
||||||
|
Mock dependencies (API calls, external modules) before imports using vi.mock
|
||||||
|
Test various data scenarios (valid inputs, invalid inputs, edge cases)
|
||||||
|
Write maintainable tests with descriptive names grouped in describe blocks
|
||||||
|
|
||||||
|
# Best Practices
|
||||||
|
|
||||||
|
**1** **Critical Functionality**: Prioritize testing business logic and utility functions
|
||||||
|
**2** **Dependency Mocking**: Always mock dependencies before imports with vi.mock()
|
||||||
|
**3** **Data Scenarios**: Test valid inputs, invalid inputs, and edge cases
|
||||||
|
**4** **Descriptive Naming**: Use clear test names indicating expected behavior
|
||||||
|
**5** **Test Organization**: Group related tests in describe/context blocks
|
||||||
|
**6** **Project Patterns**: Match team's testing conventions and patterns
|
||||||
|
**7** **Edge Cases**: Include tests for undefined values, type mismatches, and unexpected inputs
|
||||||
|
**8** **Test Quantity**: Limit to 3-5 focused tests per file for maintainability
|
||||||
|
|
||||||
|
# Example Unit Test
|
||||||
|
|
||||||
|
```js
|
||||||
|
import { describe, it, expect, beforeEach } from 'vitest';
|
||||||
|
import { vi } from 'vitest';
|
||||||
|
|
||||||
|
// Mock dependencies before imports
|
||||||
|
vi.mock('../api/locale', () => ({
|
||||||
|
getLocale: vi.fn(() => 'en-US'), // Mock locale API
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Import module under test
|
||||||
|
const { formatDate } = await import('../utils/formatDate');
|
||||||
|
|
||||||
|
describe('formatDate', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should format date correctly', () => {
|
||||||
|
// Arrange
|
||||||
|
const date = new Date('2023-10-15');
|
||||||
|
|
||||||
|
// Act
|
||||||
|
const result = formatDate(date);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
expect(result).toBe('2023-10-15');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle invalid date', () => {
|
||||||
|
const result = formatDate(new Date('invalid'));
|
||||||
|
expect(result).toBe('Invalid Date');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw error for undefined input', () => {
|
||||||
|
expect(() => formatDate(undefined)).toThrow('Input must be a Date object');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle non-Date object', () => {
|
||||||
|
expect(() => formatDate('2023-10-15')).toThrow('Input must be a Date object');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
# TypeScript Example
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { describe, it, expect, beforeEach } from 'vitest';
|
||||||
|
import { vi } from 'vitest';
|
||||||
|
|
||||||
|
// Mock dependencies before imports
|
||||||
|
vi.mock('../api/weatherService', () => ({
|
||||||
|
getWeatherData: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Import the mocked module and the function to test
|
||||||
|
import { getWeatherData } from '../api/weatherService';
|
||||||
|
import { getForecast } from '../utils/forecastUtils';
|
||||||
|
|
||||||
|
// Define TypeScript interfaces
|
||||||
|
interface WeatherData {
|
||||||
|
temperature: number;
|
||||||
|
humidity: number;
|
||||||
|
conditions: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Forecast {
|
||||||
|
prediction: string;
|
||||||
|
severity: 'low' | 'medium' | 'high';
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('getForecast', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return forecast when weather data is available', async () => {
|
||||||
|
// Arrange
|
||||||
|
const mockWeather: WeatherData = {
|
||||||
|
temperature: 25,
|
||||||
|
humidity: 65,
|
||||||
|
conditions: 'sunny'
|
||||||
|
};
|
||||||
|
(getWeatherData as any).mockResolvedValue(mockWeather);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
const result = await getForecast('New York');
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
expect(getWeatherData).toHaveBeenCalledWith('New York');
|
||||||
|
expect(result).toEqual({
|
||||||
|
prediction: 'Clear skies',
|
||||||
|
severity: 'low'
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle missing data fields', async () => {
|
||||||
|
// Arrange: Weather data with missing fields
|
||||||
|
const incompleteData = { temperature: 25 };
|
||||||
|
(getWeatherData as any).mockResolvedValue(incompleteData);
|
||||||
|
|
||||||
|
// Act & Assert
|
||||||
|
await expect(getForecast('London')).rejects.toThrow('Incomplete weather data');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle API errors gracefully', async () => {
|
||||||
|
// Arrange: API failure
|
||||||
|
(getWeatherData as any).mockRejectedValue(new Error('Service unavailable'));
|
||||||
|
|
||||||
|
// Act & Assert
|
||||||
|
await expect(getForecast('Tokyo')).rejects.toThrow('Failed to get forecast: Service unavailable');
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user