Awesome Cursor Rules Collection

Showing 1609-1620 of 2626 matches

TypeScript
TypeScript
# Saas Frontend

Every time you choose to apply a rule(s), explicitly state the rule(s) in the output. You can abbreviate the rule description to a single word or phrase.

## Project Context

This is the frontend for our SaaS product, a platform for rewarding contributions to open source projects and helping maintainers manage their projects.
Users can:

- View their contributions
- View their projects
- Participate in hackathons
- View their sponsors
- View project ecosystems

## Code Style and Structure

- Write concise, technical TypeScript code with accurate examples
- Use domain driven design to implement business logic and api endpoints
- Prefer iteration and modularization over code duplication
- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError)
- Structure repository files as follows:

```
app/					# Next.js pages
core/					# Core business logic
├── application/    	# Adapters related to the application (React Query hooks, etc)
├── bootstrap/      	# Bootstrap logic (React Query client, etc)
├── domain/         	# Domain logic (use cases, etc)
├── helpers/        	# Helper functions
└── infrastructure/		# Infrastructure logic (api clients, etc)
design-system/			# Design system components
├── atoms/     			# Atomic design system components
├── helpers/       		# Design system helpers
├── molecules/       	# Molecular design system components
└── organisms/         	# Organism design system components
public/					# Public assets
├── flags/    			# Country flags
├── fonts/      		# Custom fonts
└── images/         	# Image files
shared/					# Reusable elements across the project that don't belong to the design system
├── charts/    			# Shared charts
├── components/    		# Shared components
├── constants/    		# Shared constants
├── features/    		# Shared features
├── helpers/    		# Shared helpers
├── hocs/    			# Shared higher order components
├── hooks/    			# Shared custom hooks
├── icons/    			# Shared custom icons
├── modals/    			# Shared modals
├── panels/    			# Shared panels and drawers
├── theme/    			# Tailwind theme configuration
├── tracking/      		# Posthog tracking components
└── translation/      	# Translations
```

## Tech Stack

- React
- Next.js
- TypeScript
- Tailwind CSS
- NextUI
- React Query
- React Hook Form
- Zod

## Naming Conventions

- Use kebab case for directories and file names (e.g., components/form-wizard, form-wizard.tsx)
- Favor named exports for components and utilities

## TypeScript Usage

- Use TypeScript for all code; prefer interfaces over types
- Use functional components with TypeScript interfaces
- Use absolute imports for all files @/...
- Use explicit return types for all functions

## State Management

- Use React Context for global state when needed
- Implement proper cleanup in useEffect hooks

## Syntax and Formatting

- Use "function" keyword for pure functions
- Use declarative JSX

## UI and Styling

- Implement NextUI when creating design system components
- Use design system components when implementing new features
- Implement Tailwind CSS for styling

## Error Handling

- Implement proper error boundaries
- Log errors appropriately for debugging
- Provide user-friendly error messages
- Handle network failures gracefully

## Testing

- Write unit tests for utilities and components

## Security

- Implement Content Security Policy
- Sanitize user inputs
- Handle sensitive data properly
- Implement proper CORS handling

## Git Usage

Commit Message Prefixes:

- "fix:" for bug fixes
- "feat:" for new features
- "perf:" for performance improvements
- "docs:" for documentation changes
- "style:" for formatting changes
- "refactor:" for code refactoring
- "test:" for adding missing tests
- "chore:" for maintenance tasks

Rules:

- Use lowercase for commit messages
- Keep the summary line concise
- Include description for non-obvious changes
- Reference issue numbers when applicable

## Documentation

- Maintain clear README with setup instructions
- Document API interactions and data flows
- Don't include comments unless it's for complex logic

## Development Workflow

- Use proper version control
- Implement proper code review process
- Test in multiple environments
- Follow semantic versioning for releases
- Maintain changelog
bootstrap
css
html
javascript
less
next.js
react
shell
+2 more
onlydustxyz/saas-frontend

Used in 1 repository

Python
# Directives Générales

## Réponses en Français
Toujours répondre en français.

## Documentation
- Utiliser toujours Markdown pour la documentation et les fichiers README.
- Maintenir la structure existante du fichier README.md.

# Documentations des Commits
Les messages de commit doivent suivre les règles CONVENTIONNALCOMMITS: https://www.conventionalcommits.org/en/v1.0.0/#summary
Le descriptif du commit doit décrire le contenu du diff du commit.

# Directives pour Python

## Structure du Projet
- Utiliser une structure de projet claire avec des répertoires séparés pour le code source, les tests, la documentation et la configuration.

## Conception Modulaire
- Adopter une conception modulaire avec des fichiers distincts pour les modèles, les services, les contrôleurs et les utilitaires.

## Gestion de la Configuration
- Gérer la configuration en utilisant des variables d'environnement.

## Gestion des Erreurs et Journalisation
- Implémenter une gestion robuste des erreurs et la journalisation, y compris la capture du contexte.

## Tests
- Effectuer des tests complets avec pytest.

## Documentation
- Fournir une documentation détaillée en utilisant des docstrings et des fichiers README.

## Gestion des Dépendances
- Gérer les dépendances via les fichiers pyproject.toml et requirements.txt; ainsi que grace à l'utilisation des environnements virtuels.

## Consistance du Style de Code
- Assurer la consistance du style de code en utilisant Ruff.

## CI/CD
- Implémenter CI/CD avec GitHub Actions ou GitLab CI.

## Pratiques de Codage AI-Friendly
- Utiliser des noms de variables et de fonctions descriptifs.
- Ajouter des annotations de type.
- Fournir des commentaires détaillés pour la logique complexe.
- Capturer un contexte riche pour le débogage.

# Maintenance et Mises à Jour

## Mise à Jour du README.md
- Mettre à jour le fichier README.md lorsqu'un module Python est modifié.
- S'assurer que tous les liens dans le fichier README.md sont relatifs et corrects.
- Maintenir l'exactitude de la table des matières dans le fichier README.md.
python
shell
grostim/Beancount-myTools

Used in 1 repository

TypeScript
You are an expert in TypeScript, Node.js, Next.js 14 App Router, React, NextAuth, Prisma ORM, Postgress, react-email library, TanStack React Query, Zod, Shadcn UI, and Tailwind CSS.

Code Style and Structure

- Write concise, technical TypeScript code with accurate examples.
- Use functional and declarative programming patterns; avoid classes.
- Prefer iteration and modularization over code duplication.
- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
- Structure files: exported component, subcomponents, helpers, static content, types.

Naming Conventions

- Use lowercase with dashes for directories (e.g., components/auth-wizard).
- Favor named exports for components.

TypeScript Usage

- Use TypeScript for all code; prefer interfaces over types.
- Avoid enums; use maps instead.
- Use functional components with TypeScript interfaces.

Syntax and Formatting

- Use the "arrow function" keyword for pure functions.
- Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements.
- Use declarative JSX.

UI and Styling

- Use Shadcn UI, Radix, and Tailwind for components and styling.
- Implement responsive design with Tailwind CSS; use a mobile-first approach.

Error Handling and Validation

- Prioritize error handling and edge cases:
- Use early returns for error conditions.
- Implement guard clauses to handle preconditions and invalid states early.
- Use custom error types for consistent error handling.

State Management and datafetching

- Use modern state management solutions (TanStack React Query) to handle global state and data fetching.
- Implement validation using Zod for schema validation.

Performance Optimization

- Minimize 'use client', 'useEffect', and 'setState'; favor React Server Components (RSC).
- Wrap client components in Suspense with fallback.
- Use dynamic loading for non-critical components.
- Optimize images: use WebP format, include size data, implement lazy loading.

Security and Performance

- Implement proper error handling, user input validation, and secure coding practices.
- Follow performance optimization techniques, such as reducing load times and improving rendering efficiency.

Key Conventions

- Use 'nuqs' for URL search parameter state management.
- Optimize Web Vitals (LCP, CLS, FID).
- Limit 'use client':
  - Favor server components and Next.js SSR.
  - Use only for Web API access in small components.
  - Avoid for data fetching or state management.

Methodology 1. System 2 Thinking: Approach the problem with analytical rigor. Break down the requirements into smaller, manageable parts and thoroughly consider each step before implementation. 2. Tree of Thoughts: Evaluate multiple possible solutions and their consequences. Use a structured approach to explore different paths and select the optimal one. 3. Iterative Refinement: Before finalizing the code, consider improvements, edge cases, and optimizations. Iterate through potential enhancements to ensure the final solution is robust.

Process: 1. Deep Dive Analysis: Begin by conducting a thorough analysis of the task at hand, considering the technical requirements and constraints. 2. Planning: Develop a clear plan that outlines the architectural structure and flow of the solution, using <PLANNING> tags if necessary. 3. Implementation: Implement the solution step-by-step, ensuring that each part adheres to the specified best practices. 4. Review and Optimize: Perform a review of the code, looking for areas of potential optimization and improvement. 5. Finalization: Finalize the code by ensuring it meets all requirements, is secure, and is performant.

Follow Next.js docs for Data Fetching, Rendering, and Routing.
css
golang
javascript
next.js
nextauth
postgresql
prisma
radix-ui
+4 more
Dark-Developer93/LeaveTracker

Used in 1 repository

TypeScript

You are an expert in TypeScript, Node.js, Next.js App Router, React, Shadcn UI, Radix UI, Turborepo, Drizzle ORM and Tailwind.

Code Style and Structure
- Write concise, technical TypeScript code with accurate examples.
- Use functional and declarative programming patterns; avoid classes.
- Prefer iteration and modularization over code duplication.
- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
- Structure files: exported component, subcomponents, helpers, static content, types.

Naming Conventions
- Use lowercase with dashes for directories (e.g., components/auth-wizard).
- Use camelCase for variables, functions, and components.
- Use kebab-case for directories, files, and components.
- Favor named exports for components.

TypeScript Usage
- Use TypeScript for all code; prefer interfaces over types.
- Avoid enums; use maps instead.
- Use functional components with TypeScript interfaces.

Syntax and Formatting
- Use the "function" keyword for pure functions.
- Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements.
- Use declarative JSX.

UI and Styling
- Use Shadcn UI, Radix, and Tailwind for components and styling.
- Implement responsive design with Tailwind CSS; use a mobile-first approach.

Performance Optimization
- Minimize 'use client', 'useEffect', and 'setState'; favor React Server Components (RSC).
- Wrap client components in Suspense with fallback.
- Use dynamic loading for non-critical components.
- Optimize images: use WebP format, include size data, implement lazy loading.

Key Conventions
- Use 'nuqs' for URL search parameter state management.
- Optimize Web Vitals (LCP, CLS, FID).
- Limit 'use client':
- Favor server components and Next.js SSR.
- Use only for Web API access in small components.
- Avoid for data fetching or state management.

Follow Next.js docs for Data Fetching, Rendering, and Routing.
css
drizzle-orm
javascript
next.js
radix-ui
react
shadcn/ui
tailwindcss
+1 more

First seen in:

johnnietirado/margincalc

Used in 1 repository

TypeScript
**Background:** 👨‍💻🌐🚀
- As a programming maestro, you possess a broad spectrum of coding abilities, ready to tackle diverse programming challenges.
- Your areas of expertise include project design, efficient code structuring, and providing insightful guidance through coding processes with precision and clarity.

**Task Instructions:** 📋💻🔍
1. **Framework and Technology Synopsis:** 🎨🖥️
   - Initiate with a succinct, one-sentence summary that outlines the chosen framework or technology stack for the project.
   - This concise introduction serves as a focused foundation for any programming task.

2. **Efficient Solutions for Simple Queries:** 🧩💡
   - When faced with straightforward programming questions, provide clear, direct answers.
   - This method is designed to efficiently address simpler issues, avoiding over-complication.

3. **Methodical Strategy for Complex Challenges:** 📊👣
   - **Project Structure Outline:** 
     - For complex programming tasks, start by detailing the project structure or directory layout.
     - Laying out this groundwork is essential for a structured approach to the coding process.

  You are an expert in Python, FastAPI, and scalable API development.
  
  Key Principles
  - 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).
  - Favor named exports for routes and utility functions.
  - Use the Receive an Object, Return an Object (RORO) pattern.
  
  Python/FastAPI
  - 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()).
  
  Error Handling and Validation
  - Prioritize error handling and edge cases:
    - Handle errors and edge cases at the beginning of functions.
    - Use early returns for error conditions to avoid deeply nested if statements.
    - Place the happy path last in the function for improved readability.
    - Avoid unnecessary else statements; use the if-return pattern instead.
    - Use guard clauses to handle preconditions and invalid states early.
    - Implement proper error logging and user-friendly error messages.
    - Use custom error types or error factories for consistent error handling.
  
  Dependencies
  - FastAPI
  - Langchain with OpenAI
  - Pydantic v2
  - Async database libraries like asyncpg or aiomysql
  
  FastAPI-Specific Guidelines
  - 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.
  
  Performance Optimization
  - 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.
  
css
fastapi
html
javascript
langchain
mysql
nestjs
openai
+3 more

First seen in:

psycho-baller/TinyGen

Used in 1 repository

TypeScript

Key Principles
- Write concise, technical responses with accurate TypeScript examples.
- Use functional, declarative programming. Avoid classes.
- Prefer iteration and modularization over duplication.
- Use descriptive variable names with auxiliary verbs (e.g., isLoading).
- Use lowercase with dashes for directories (e.g., components/auth-wizard).
- Favor named exports for components.
- Use the Receive an Object, Return an Object (RORO) pattern.

JavaScript/TypeScript
- Use "function" keyword for pure functions. Omit semicolons.
- Use TypeScript for all code. Prefer interfaces over types. Avoid enums, use maps.
- File structure: Exported component, subcomponents, helpers, static content, types.
- 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) doSomething()).

Error Handling and Validation
- Prioritize error handling and edge cases:
  - Handle errors and edge cases at the beginning of functions.
  - Use early returns for error conditions to avoid deeply nested if statements.
  - Place the happy path last in the function for improved readability.
  - Avoid unnecessary else statements; use if-return pattern instead.
  - Use guard clauses to handle preconditions and invalid states early.
  - Implement proper error logging and user-friendly error messages.
  - Consider using custom error types or error factories for consistent error handling.

React/Next.js
- Use functional components and TypeScript interfaces.
- Use declarative JSX.
- Use function, not const, for components.
- Use Shadcn UI, Radix, and Tailwind Aria for components and styling.
- Implement responsive design with Tailwind CSS.
- Use mobile-first approach for responsive design.
- Place static content and interfaces at file end.
- Use content variables for static content outside render functions.
- Minimize 'use client', 'useEffect', and 'setState'. Favor RSC.
- Use Zod for form validation.
- Wrap client components in Suspense with fallback.
- Use dynamic loading for non-critical components.
- Optimize images: WebP format, size data, lazy loading.

RainbowKit v2 & Wagmi Integration
- Setup RainbowKit v2 with Wagmi v2 using `configureChains` and `createClient` from Wagmi.
- Initialize chains and providers within a `RainbowKitProvider` wrapper.
- Store mnemonics in `expo-secure-store` or other secure storage solutions.
- Use React hooks like `useAccount`, `useConnect`, `useDisconnect` from Wagmi for wallet actions.
- Favor the use of hooks over directly accessing global state.

tRPC v11 Integration
- Use `@trpc/react-query` and define tRPC routers on the server.
- Set up queries and mutations using `trpc.useQuery` and `trpc.useMutation` on the client.
- Use Zod for input validation at both client and server levels.
- Handle optimistic updates in React Query using the `onMutate` and `onSuccess` methods.
- For error handling, ensure tRPC procedures return a consistent error structure.

Key Conventions
1. Rely on Next.js App Router for state changes.
2. Prioritize Web Vitals (LCP, CLS, FID).
3. Minimize 'use client' usage:
  - Prefer server components and Next.js SSR features.
  - Use 'use client' only for Web API access in small components.
  - Avoid using 'use client' for data fetching or state management.
css
dockerfile
java
javascript
nestjs
next.js
radix-ui
react
+5 more
grassrootseconomics/sarafu.network

Used in 1 repository

TypeScript
# AI Assistant Rules

## Project Context

Crustify: Building a micro-CMS for pizzerias for French market. The goal is to be easy to have their pizzerias website with removing all the hastle.

## Tech Stack

- Bun (always use this)
- Next.js app router
- TailwindCSS
- Shadcn UI
- Supabase
- Stripe
- zsa


## App folder structure

- `[domain]` is my customers websites
- `app` is the dashboard
- `home` is the landing page for crustify website


## Next.js Guidance

- Use Next.js app router for file-based routing
- Prefer server components over client components if possible
- If not possible, use client components with tanstack query combined with supabase for data fetching
- Implement loading.tsx for loading states
- Use error.tsx for error handling
- for forms we use zsa to better handle server actions, refer to the zsa documentation

## TailwindCSS Usage

- Utilize Tailwind CSS for responsive design with a mobile-first approach
- Leverage Tailwind's utility classes for rapid prototyping

## Shadcn UI Integration

- Use Shadcn UI components for consistent and accessible UI elements
- Integrate Shadcn and Tailwind for a cohesive styling approach


## ZSA Integration
### Creating your first action
```ts
// actions.ts
"use server"

import { createServerAction } from "zsa"
import z from "zod"

export const incrementNumberAction = createServerAction() 
    .input(z.object({
        number: z.number()
    }))
    .handler(async ({ input }) => {
        // Sleep for .5 seconds
        await new Promise((resolve) => setTimeout(resolve, 500))
        // Increment the input number by 1
        return input.number + 1;
    });
```

Let's break down the code:

createServerAction initializes a server action.
input sets the input schema for the action using a Zod schema.
handler sets the handler function for the action. The input is automatically validated based on the input schema.
A ZSAError with the code INPUT_PARSE_ERROR will be returned if the handler's input is does not match input schema.

### Calling from the server
Server actions can also be called directly from the server without the need for a try/catch block.


```ts
"use server"

const [data, err] = await incrementNumberAction({ number: 24 }); 

if (err) {
    return;
} else {
    console.log(data); // 25
}
```


However, usually you will want to use the useServerAction hook to make your life easier.

Server actions come with built-in loading states, making it easy to handle asynchronous operations. Here's an example of using the incrementNumberAction as a mutation:

```tsx
"use client"

import { incrementNumberAction } from "./actions";
import { useServerAction } from "zsa-react";
import { useState } from "react";
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle } from "ui";

export default function IncrementExample() {
    const [counter, setCounter] = useState(0);
    const { isPending, execute, data } = useServerAction(incrementNumberAction); 

    return (
        <Card>
            <CardHeader>
                <CardTitle>Increment Number</CardTitle>
            </CardHeader>
            <CardContent className="flex flex-col gap-4">
                <Button
                    disabled={isPending} 
                    onClick={async () => {
                        const [data, err] = await execute({ 
                            number: counter, 
                        }) 

                        if (err) {
                            // handle error
                            return
                        }

                        setCounter(data);
                    }}
                >
                    Invoke action
                </Button>
                <p>Count:</p>
                <div>{isPending ? "saving..." : data}</div>
            </CardContent>
        </Card>
    );
}
```

### Basic Form
You can use a server action directly with a regular form. Set the type to "formData" to indicate that the input is a FormData object.
```ts
"use server"

import z from "zod"
import { createServerAction } from "zsa"

export const produceNewMessage = createServerAction()
  .input(
    z.object({
      name: z.string().min(5),
    }),
    {
      type: "formData", 
    }
  )
  .handler(async ({ input }) => {
    await new Promise((resolve) => setTimeout(resolve, 500))
    return "Hello, " + input.name
  })
  ```

  ```tsx
  "use client"

import { useServerAction } from "zsa-react"
import { produceNewMessage } from "./actions";

export default function FormExample() {

  const {executeFormAction} = userServerAction(produceNewMessage)
    return (
        <form
            action={executeFormAction} 
        >
            <label>
                Name:
                <input type="text" name="name" required />
            </label>
            <button type="submit">Submit</button>
        </form>
    );
}
  ```

## General Guidance

- Ensure SEO optimization for websites visibility
- Implement internationalization to cater to the French market
- ALWAYS use the french language for the website contents
- Implement early returns for better readability
- Prefix event handlers with "handle" (handleClick, handleSubmit)
bun
css
golang
javascript
next.js
react
rust
shadcn/ui
+4 more

First seen in:

Karnak19/crustify

Used in 1 repository