Awesome Cursor Rules Collection

Showing 265-276 of 1033 matches

TypeScript
Frontend (TypeScript/React):
- Use functional components with TypeScript interfaces
- Prefer named exports for components
- Use declarative programming patterns; avoid classes where possible
- Structure files: exported component, subcomponents, helpers, static content, types
- Use descriptive variable names (e.g., isLoading, hasError)
- Implement responsive design with MUI (Material-UI)
- Use dynamic imports for non-critical components
- Optimize images: use appropriate formats, include size data, implement lazy loading
- Minimize use of useEffect; favor React Server Components where applicable
- Wrap client components in Suspense with fallback for better loading experience

TypeScript Usage:
- Use TypeScript for all frontend code
- Prefer interfaces over types for better extensibility
- Avoid enums; use string literal unions or const objects instead
- Enable strict mode in tsconfig.json

Naming Conventions:
- Use PascalCase for component files (e.g., SubscriptionList.tsx)
- Use camelCase for non-component files (e.g., urlUtils.ts)
- Use lowercase with dashes for directories (e.g., components/add-subscription)

Syntax and Formatting:
- Use arrow functions for component definitions and callbacks
- Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements
- Use optional chaining (?.) and nullish coalescing (??) operators
- Prefer template literals over string concatenation

Error Handling and Validation:
- Handle errors and edge cases early in the function
- Use try/catch blocks for async operations
- Implement proper error logging and user-friendly messages
- Use appropriate form validation (consider using a library like Formik or react-hook-form)

State Management:
- Use React hooks (useState, useContext) for local and shared state
- Consider using a state management library for complex state (e.g., Redux, Recoil)

Backend (Python):
- Use Python 3.8+ features
- Follow PEP 8 style guide with a line length of 120 characters
- Use type hints consistently
- Prefer functional programming patterns where appropriate
- Use async/await for asynchronous operations
- Structure code into modular, reusable functions

Python Specifics:
- Use f-strings for string formatting
- Do not use f-strings for log messages (use 'Message with %s', expensive_func1())')
- Use list/dict/set comprehensions where they improve readability
- Utilize dataclasses or Pydantic models for data structures
- Use pytest for testing

Naming Conventions:
- Use snake_case for function and variable names
- Use PascalCase for class names
- Use UPPER_CASE for constants

Error Handling:
- Use specific exception types
- Implement proper logging
- Return meaningful error messages and appropriate HTTP status codes in API responses

API Design:
- Follow RESTful principles
- Use FastAPI for API development
- Implement proper request validation and error handling
- Use Pydantic models for request/response schemas

Database:
- Use SQLModel for ORM (https://sqlmodel.tiangolo.com/)
- Use SQLAlchemy for database operations when needed but prefer to use SQLModel
- Implement database migrations for schema changes
- Use async database operations where possible

General:
- Write clear, concise comments and docstrings
- Keep functions and methods small and focused
- Follow the DRY (Don't Repeat Yourself) principle
- Implement proper error logging and monitoring
- Use environment variables for configuration
- Implement proper security measures (e.g., input validation, CORS, authentication)

Version Control:
- Write meaningful commit messages
- Use feature branches and pull requests for new features or significant changes
- Keep commits small and focused

Testing:
- Write unit tests for both frontend and backend code
- Aim for high test coverage, especially for critical paths
- Use mocking for external dependencies in tests

Performance:
- Optimize database queries
- Implement caching where appropriate
- Use pagination for large datasets

Accessibility:
- Ensure proper keyboard navigation
- Use semantic HTML elements
- Provide alternative text for images

Documentation:
- Maintain up-to-date README files
- Document API endpoints and their usage
- Keep inline documentation current with code changes

css
fastapi
golang
javascript
material-ui
mdx
python
react
+4 more

First seen in:

bthode/engawa

Used in 1 repository

Jupyter Notebook
name: "Land Use Change Detection Project"

description: |
  Land use change detection and monitoring system in Córdoba, Argentina, 
  using satellite imagery. The project uses pre-trained models and ensemble 
  learning techniques to analyze images at two time points (t1 and t2).

services:
  - name: "preprocessing_service"
    path: "preprocessing_service/**"
    description: "Satellite image preprocessing service"
    tags: ["python", "gdal", "rasterio", "numpy"]

  - name: "model_service"
    path: "model_service/**"
    description: "Pre-trained model inference service"
    tags: ["python", "pytorch", "tensorflow", "scikit-learn"]

  - name: "api_gateway"
    path: "api_gateway/**"
    description: "API Gateway implemented with FastAPI"
    tags: ["python", "fastapi", "pydantic"]

  - name: "queue_service"
    path: "queue_service/**"
    description: "Queue service using Redis and Celery"
    tags: ["python", "redis", "celery"]

  - name: "frontend"
    path: "frontend/**"
    description: "User interface implemented in React"
    tags: ["typescript", "react", "leaflet", "mapbox"]

  - name: "common"
    path: "common/**"
    description: "Shared code between services"
    tags: ["python", "typescript"]

conventions:
  python:
    - "Follow PEP 8"
    - "Google style docstrings"
    - "Mandatory type hints"
  
  typescript:
    - "ESLint Airbnb config"
    - "Prettier for formatting"
    - "TypeScript strict mode"

  git:
    - "Conventional Commits"
    - "Feature branches from develop"
    - "Mandatory pull requests"

key_concepts:
  - name: "Change Detection"
    description: "Detection of changes between two satellite images at different times"

  - name: "Pre-trained Models"
    description: "Use of pre-trained models to avoid manual data labeling"

  - name: "Queue System"
    description: "Redis queue system to handle multiple processing requests"

  - name: "Ensemble Learning"
    description: "Combination of multiple models to optimize results"

dependencies:
  python: "^3.11.8"
  node: "^18.0.0"
  redis: "^7.0.0"
  docker: "^24.0.0"
  docker_compose: "^2.0.0"

team_roles:
  - "Pre-Trained Models and Experimentation Team"
  - "Processing and Optimization Team"
  - "Data Preprocessing and Analysis Team"
  - "Front-End and Visualization Team"

documentation:
  architecture: "docs/architecture.md"
  api: "api-gateway/README.md"
  deployment: "docs/deployment.md"
  development: "docs/development.md"
css
docker
eslint
fastapi
golang
html
javascript
jupyter notebook
+8 more
OmdenaAI/CordobaArgentinaChapter_MonitoringLandUseTransformation

Used in 1 repository

TypeScript
{
  "typescript": {
    "style": {
      "preferFunctional": true,
      "preferNamedExports": true,
      "avoidEnums": true,
      "useInterfaces": true,
      "preferConst": true,
      "preferArrowFunctions": true
    },
    "formatting": {
      "indentSize": 2,
      "maxLineLength": 80,
      "useSemicolons": true,
      "quoteStyle": "double",
      "trailingComma": "all"
    },
    "imports": {
      "preferTypeImports": true,
      "noDefaultExports": true,
      "grouping": [
        "^react",
        "^next",
        "^@dub/",
        "^@/",
        "^[./]"
      ]
    }
  },
  "naming": {
    "directories": {
      "pattern": "kebab-case",
      "examples": ["auth-wizard", "user-settings"],
      "specialDirs": {
        "app": "Next.js app router directory",
        "lib": "Shared utilities and helpers",
        "ui": "Reusable UI components",
        "emails": "Email templates",
        "public": "Static assets",
        "styles": "Global styles",
        "tests": "Test files"
      }
    },
    "components": {
      "pattern": "PascalCase",
      "examples": ["AuthWizard", "UserSettings"],
      "clientSuffix": "-client",
      "serverSuffix": "-server",
      "layoutFile": "layout.tsx",
      "pageFile": "page.tsx",
      "loadingFile": "loading.tsx",
      "errorFile": "error.tsx"
    },
    "variables": {
      "pattern": "camelCase",
      "prefixes": {
        "boolean": ["is", "has", "should", "can", "will"],
        "event": ["on", "handle"],
        "ref": ["ref", "elementRef"],
        "count": ["num", "count", "total"],
        "callback": ["cb", "fn"]
      }
    },
    "constants": {
      "pattern": "UPPER_SNAKE_CASE",
      "location": "lib/constants"
    }
  },
  "fileStructure": {
    "app": {
      "layout": ["imports", "metadata", "layout component"],
      "page": ["imports", "metadata", "page component"],
      "route": ["imports", "validation", "middleware", "handlers"],
      "components": ["imports", "types", "component", "helpers"]
    },
    "lib": {
      "pattern": ["types", "constants", "helpers", "hooks"],
      "utils": "shared utility functions",
      "api": "API-related utilities",
      "auth": "Authentication utilities",
      "zod": "Schema validation"
    },
    "ui": {
      "pattern": ["component", "types", "styles"],
      "location": "ui/",
      "shared": "shared UI components",
      "layout": "layout components"
    }
  },
  "api": {
    "patterns": {
      "validation": {
        "library": "zod",
        "location": "lib/zod/schemas",
        "naming": "{resource}.schema.ts"
      },
      "middleware": {
        "auth": ["withSession", "withWorkspace", "withAdmin"],
        "error": ["handleAndReturnErrorResponse"],
        "cache": ["linkCache"]
      },
      "errorHandling": {
        "class": "DubApiError",
        "codes": ["not_found", "unauthorized", "forbidden", "internal_server_error"]
      },
      "responseType": {
        "success": "NextResponse.json(data)",
        "error": "handleAndReturnErrorResponse(error)"
      },
      "categories": {
        "auth": ["login", "callback", "providers"],
        "workspaces": ["domains", "links", "analytics"],
        "users": ["me", "settings", "billing"],
        "integrations": ["slack", "shopify", "stripe"],
        "features": ["ai", "analytics", "qr"],
        "admin": ["impersonate", "ban", "refresh-domain"]
      },
      "edgeRuntime": {
        "enabled": true,
        "routes": [
          "analytics",
          "links",
          "domains"
        ]
      }
    },
    "structure": {
      "route": "app/api/[resource]/route.ts",
      "handlers": ["GET", "POST", "PUT", "DELETE", "PATCH"],
      "middleware": "lib/auth/*.ts",
      "folders": {
        "auth": "Authentication endpoints",
        "workspaces": "Workspace management",
        "links": "Link management",
        "analytics": "Analytics endpoints",
        "webhooks": "External service webhooks",
        "ai": "AI features endpoints",
        "metatags": "Meta tags management",
        "categories": "Category management",
        "events": "Event tracking",
        "financial-settings": "Billing and subscriptions",
        "oauth": "OAuth integrations",
        "scim": "SCIM provisioning",
        "customers": "Customer management"
      }
    }
  },
  "database": {
    "orm": "prisma",
    "clients": {
      "edge": {
        "import": "@dub/prisma/edge",
        "usage": "prismaEdge",
        "location": "packages/prisma/edge.ts",
        "features": ["edge runtime", "connection pooling"]
      },
      "standard": {
        "import": "@dub/prisma",
        "usage": "prisma",
        "location": "packages/prisma/client.ts",
        "features": ["full API support"]
      }
    },
    "schema": {
      "location": "packages/prisma/schema",
      "files": {
      "main": "schema.prisma",
        "workspace": "workspace.prisma",
        "user": "user.prisma",
       "link": "link.prisma",
       "tag": "tag.prisma",
       "domain": "domain.prisma",
       "notification": "notification.prisma",
       "ai": "ai.prisma",
       "analytics": "analytics.prisma",
       "auth": "auth.prisma",
       "billing": "billing.prisma",
       "category": "category.prisma",
       "customer": "customer.prisma",
       "event": "event.prisma",
       "integration": "integration.prisma",
       "metatag": "metatag.prisma",
       "oauth": "oauth.prisma",
       "partner": "partner.prisma",
       "program": "program.prisma",
       "qr": "qr.prisma",
       "scim": "scim.prisma",
       "support": "support.prisma",
       "webhook": "webhook.prisma"
      },
      "conventions": {
        "models": {
          "naming": "PascalCase",
          "idField": {
            "type": "String",
            "default": "@default(cuid())"
          },
          "timestamps": {
            "createdAt": "DateTime @default(now())",
            "updatedAt": "DateTime @updatedAt"
          },
          "relations": {
            "oneToOne": "@relation(fields: [fieldId], references: [id])",
            "oneToMany": "@relation(\"RelationName\")",
            "manyToMany": "implicit through join table"
          },
          "cascading": {
            "delete": "onDelete: Cascade",
            "update": "onUpdate: Cascade"
          }
        },
        "fields": {
          "naming": "camelCase",
          "types": {
            "id": "String @id @default(cuid())",
            "foreignKey": "String",
            "enum": "defined in schema",
            "json": "Json",
            "boolean": "Boolean @default(false)",
            "number": "Int @default(0)",
            "date": "DateTime",
            "text": "String"
          },
          "attributes": {
            "required": "@required",
            "unique": "@unique",
            "default": "@default(value)",
            "map": "@map(\"column_name\")"
          }
        },
        "enums": {
          "naming": "PascalCase",
          "values": "UPPER_SNAKE_CASE"
        }
      }
    },
    "migrations": {
      "location": "packages/prisma/migrations",
      "naming": "YYYYMMDDHHMMSS_descriptive_name",
      "commands": {
        "generate": "prisma generate",
        "migrate": "prisma migrate dev",
        "deploy": "prisma migrate deploy",
        "reset": "prisma migrate reset"
      }
    },
    "packages": {
      "structure": {
        "client": "client.ts - Standard Prisma client",
        "edge": "edge.ts - Edge runtime client",
        "index": "index.ts - Package exports",
        "tsconfig": "TypeScript configuration",
        "package": "Package dependencies and scripts"
      },
      "dependencies": {
        "required": ["@prisma/client", "prisma"],
        "devDependencies": ["typescript"]
      }
    },
    "queries": {
      "patterns": {
        "find": {
          "single": "findUnique",
          "many": "findMany",
          "first": "findFirst"
        },
        "create": {
          "single": "create",
          "many": "createMany"
        },
        "update": {
          "single": "update",
          "many": "updateMany"
        },
        "delete": {
          "single": "delete",
          "many": "deleteMany"
        },
        "upsert": "upsert"
      },
      "includes": {
        "syntax": "include: { relation: true }",
        "select": "select: { field: true }",
        "nested": "include: { relation: { select: { field: true } } }"
      },
      "transactions": {
        "syntax": "prisma.$transaction",
        "usage": "atomic operations"
      }
    },
    "errorHandling": {
      "types": [
        "PrismaClientKnownRequestError",
        "PrismaClientUnknownRequestError",
        "PrismaClientRustPanicError",
        "PrismaClientInitializationError"
      ],
      "patterns": {
        "try": "try/catch with specific error types",
        "codes": {
          "P2002": "Unique constraint violation",
          "P2025": "Record not found"
        }
      }
    }
  },
  "components": {
    "ui": {
      "preferred": ["shadcn/ui", "radix-ui"],
      "styling": "tailwind",
      "location": "ui/",
      "patterns": {
        "props": "interface {Component}Props",
        "client": "'use client'",
        "server": "default RSC"
      }
    },
    "patterns": {
      "responsive": true,
      "mobileFirst": true,
      "accessibility": {
        "required": true,
        "aria": true,
        "semantics": true
      }
    }
  },
  "testing": {
    "framework": "vitest",
    "patterns": {
      "filePattern": "**/*.test.ts",
      "naming": "{name}.test.ts",
      "location": "tests/"
    },
    "coverage": {
      "statements": 80,
      "branches": 80,
      "functions": 80,
      "lines": 80
    }
  },
  "documentation": {
    "required": true,
    "format": "TSDoc",
    "scope": ["components", "hooks", "utils", "api"],
    "api": {
      "format": "swagger",
      "location": "app/api/**/route.ts"
    }
  },
  "environment": {
    "files": [".env", ".env.example"],
    "required": [
      "NEXT_PUBLIC_APP_NAME",
      "NEXT_PUBLIC_APP_DOMAIN",
      "DATABASE_URL",
      "NEXTAUTH_SECRET"
    ],
    "validation": "lib/env.ts"
  },
  "appRouter": {
    "structure": {
      "rootFiles": {
        "layout": "Root layout with providers",
        "not-found": "Global 404 page",
        "providers": "Global providers wrapper",
        "manifest": "Web app manifest",
        "sitemap": "SEO sitemap",
        "robots": "Robots.txt configuration"
      },
      "subdomains": {
        "app.dub.co": "Main application routes",
        "admin.dub.co": "Admin panel routes",
        "partners.dub.co": "Partners portal routes"
      },
      "dynamicRoutes": {
        "[domain]": "Custom domain handling",
        "proxy": "Proxy routes",
        "inspect": "Link inspection",
        "password": "Password protection"
      },
      "specialRoutes": {
        "expired": "Expired links handling",
        "deeplink": "Mobile deep linking",
        "banned": "Banned links handling",
        "cloaked": "Cloaked links"
      }
    },
    "conventions": {
      "metadata": {
        "required": true,
        "location": "layout.tsx or page.tsx",
        "function": "constructMetadata"
      },
      "loading": {
        "required": true,
        "implementation": "loading.tsx",
        "fallback": "LayoutLoader"
      },
      "error": {
        "required": true,
        "implementation": "error.tsx",
        "handling": "DubApiError"
      },
      "layout": {
        "structure": [
          "imports",
          "metadata export",
          "interface Props",
          "layout component"
        ],
        "components": [
          "MaxWidthWrapper",
          "Nav",
          "Footer"
        ]
      }
    }
  },
  "routing": {
    "patterns": {
      "authentication": {
        "public": ["/", "/login", "/register"],
        "protected": ["/app", "/admin", "/partners"],
        "middleware": "middleware.ts"
      },
      "redirects": {
        "auth": "/login",
        "workspace": "/app/[slug]",
        "notFound": "/404"
      },
      "parameters": {
        "workspace": "[slug]",
        "domain": "[domain]",
        "link": "[key]"
      }
    }
  },
  "security": {
    "middleware": {
      "required": true,
      "location": "middleware.ts",
      "features": [
        "authentication",
        "authorization",
        "rateLimit",
        "cors"
      ]
    },
    "headers": {
      "security": true,
      "cors": true,
      "csp": true
    }
  },
  "features": {
    "analytics": {
      "tracking": ["clicks", "locations", "devices"],
      "storage": "tinybird",
      "realtime": true
    },
    "ai": {
      "provider": "anthropic",
      "features": ["completion", "analysis"]
    },
    "auth": {
      "providers": ["email", "google", "github"],
      "session": "nextauth"
    },
    "links": {
      "features": [
        "custom-domains",
        "qr-codes",
        "password-protection",
        "expiration"
      ]
    }
  },
  "deployment": {
    "platform": "vercel",
    "regions": ["all"],
    "runtime": "edge",
    "configuration": {
      "location": "vercel.json",
      "required": true
    }
  }
}
analytics
cap'n proto
css
dockerfile
go
golang
html
javascript
+26 more
SolomonAIEngineering/core-enterprise

Used in 1 repository

TypeScript
# @diegovfeder

You are a Senior Front-End Developer and an Expert in SolidJS, TypeScript, HTML, CSS and modern UI/UX frameworks (e.g., TailwindCSS, @corvu, Kobalte). You are thoughtful, give nuanced answers, and are brilliant at reasoning.

- Follow the user's requirements carefully & to the letter
- First think step-by-step - describe your plan for what to build in pseudocode
- Always write correct, best practice, DRY principle code
- Focus on readability over performance
- Fully implement all requested functionality
- Leave NO todos or missing pieces
- Include all required imports
- Be concise and minimize prose
- If you're unsure, say so instead of guessing

## Coding Environment

The user works with:

- SolidJS
- TypeScript
- TailwindCSS
- @corvu components
- Kobalte
- HTML
- CSS

### Code Implementation Guidelines

Follow these rules when writing code:

- Use early returns for cleaner code flow
- Use Tailwind classes exclusively for styling; avoid raw CSS
- Prefer signals over local state when possible
- Use createEffect for reactive computations
- Use descriptive variable names and "handle" prefix for event handlers (e.g., handleClick)
- Implement proper accessibility:
  - Appropriate ARIA attributes
  - Keyboard navigation support
  - Focus management
  - Screen reader considerations
- Use arrow function syntax for component definitions
- Always type props and function parameters
- Use @corvu components for complex UI interactions
- Use Kobalte for accessible primitive components
- Follow SolidJS conventions:
  - Use () for signal access
  - Use createSignal for local state
  - Use createEffect for side effects
  - Use createMemo for derived values
- Prefer class objects over ternaries for conditional styling
- Export components as default when they're the main export
- Keep components focused and single-responsibility
css
golang
javascript
react
solidjs
tailwindcss
typescript

First seen in:

diegovfeder/portfolio

Used in 1 repository

TypeScript
  You are an expert in TypeScript, Node.js, Next.js App Router, React, Mongoose 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).
  - 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 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.

  Follow Next.js docs for Data Fetching, Rendering, and Routing.
  
css
golang
javascript
next.js
react
tailwindcss
typescript
NelsonMaty/ai-generated-nextjs-app

Used in 1 repository

TypeScript
You are an expert in mordern web development. You are aware and adhere to all existing best practices and industry standards. You will also follow the guidelines below.

You are "MonkAI", a peer programmer working alongside me, James on an informational blog website covering high level learning to improve soft skills.

To aid this, you are an expert within the fields of:

- Technical Communication
- Thinking Models
- Visualisation and Modelling
- Process Documentation
- Tools and Automation

Next.js Blog Website Code Guidelines

1. Project Structure
   Use a clean and modular directory structure:
   bash
   Copy code
   /src  
    ├── /pages  
    ├── /components  
    ├── /lib  
    ├── /styles  
    ├── /public  
    ├── /utils  
    └── /hooks  
   Guidelines:
   Pages Directory:

Use file-based routing.
Avoid deep nesting; max 2 levels under /pages.
Components Directory:

Split components into reusable (/components) and page-specific (/pages).
Use PascalCase for React component filenames: BlogCard.tsx.
Lib Directory:

Place external API calls, database interactions, or reusable logic.
Prefix functions with clear purpose, e.g., fetchPosts or updatePost.
Utils Directory:

Store helper functions (e.g., dateFormatter.ts).
Group utility files logically: stringUtils.ts, arrayUtils.ts.
Styles Directory:

Use global CSS, modules, or Tailwind CSS (avoid inline styles).
Maintain a single /globals.css or /tailwind.css file for global rules. 2. Code Conventions
General Coding Standards
Follow ESLint and Prettier to enforce consistent formatting.
Use TypeScript:
Define types for components, props, and API responses in a dedicated /types folder.
Use interface for objects and type for simple unions.
Naming Conventions
File Naming:
Use lowercase for API routes: /pages/api/posts.ts.
Use hyphenated filenames for non-component files: blog-fetcher.ts.
Variables:
Use camelCase: blogPostCount.
Constants:
Use UPPER_SNAKE_CASE: MAX_BLOG_LENGTH.
Code Comments
Use JSDoc comments for functions and complex logic. Example:
tsx
Copy code
/\*\*

- Fetches blog posts from the API.
- @param {number} limit - Number of posts to fetch.
- @returns {Promise<Post[]>} A promise resolving to an array of posts.
  \*/
  export const fetchPosts = async (limit: number): Promise<Post[]> => { ... }

3. API and Data Management
   API Routes
   Place all API endpoints in /pages/api.
   Use RESTful principles: /api/posts, /api/posts/[id].
   Always validate requests using libraries like zod or Joi.
   Data Fetching
   Use getStaticProps and getStaticPaths for static blogs.
   Use getServerSideProps only for dynamic updates on page load.
   Decision Matrix:

Data Type Method Use Case Example
Static Content getStaticProps Blog list, single blog page
Dynamic Content getServerSideProps User comments or live updates 4. SEO and Accessibility
SEO
Use the next/head component to define meta tags. Example:
tsx
Copy code

<Head>
  <title>{post.title} | My Blog</title>
  <meta name="description" content={post.excerpt} />
</Head>
Implement structured data (Schema.org JSON-LD) for blogs.
Accessibility
Use semantic HTML: <article>, <section>, <h1> for headings.
Add alt attributes to all images.
Ensure focus states are visible for interactive elements.
5. Performance and Optimisation
Image Optimisation: Use next/image with lazy loading.
Font Loading: Use next/font for optimised Google Fonts.
Code Splitting: Use dynamic imports:
tsx
Copy code
const BlogCard = dynamic(() => import('../components/BlogCard'));
Performance Checklist:

✅ Use gzip or brotli compression.
✅ Avoid large dependencies; monitor bundle size with Bundle Analyzer.
✅ Optimise third-party scripts with async or defer. 6. Testing and CI/CD
Testing
Use Jest for unit testing and React Testing Library for component tests.
Write tests for:
Components rendering.
API responses.
Data-fetching functions.
CI/CD
Integrate GitHub Actions:
Run ESLint, Prettier, and Jest tests on pull requests.
Automate deployments with Vercel. 7. Deployment Guidelines
Use Vercel for Next.js deployments.
Define environment variables securely using .env.local and Vercel secrets. 8. Security Standards
Avoid direct database connections in /pages/api.
Sanitize user inputs (use libraries like xss-clean).
Use Content-Security-Policy headers. 9. Glossary
Static Site Generation (SSG): Pre-rendering pages at build time.
Server-Side Rendering (SSR): Rendering pages on the server for every request.
API Routes: Backend functionality in Next.js under /pages/api.
JSDoc: Documentation standard for JavaScript/TypeScript.
Next Steps

Review and refine constraints for clarity.
Integrate specific use-case examples where needed.
bun
css
eslint
golang
java
javascript
jest
nestjs
+7 more
JamesHusband/TheCuriousCodeMonkey

Used in 1 repository

TypeScript
# Repository Rules & Implementation Guidelines

このドキュメントでは、本リポジトリのディレクトリ構成や、実装時における命名規則・スタイリング・エラーハンドリングなどのポリシーをまとめています。

## 1. リポジトリ概要

- mermaid.jsを簡単にexporr(画像)できるサービスプロジェクトです。
- **Next.js** は **Pages Router** を使用しているため、ページは `src/pages` ディレクトリに配置します。

## 2. ディレクトリ構成
├─ memos
  └─ 各種メモを md 形式で保存
├─ public
  └─ 公開するファイル群
├─ src
  ├─ pages
  │  └─ ページコンポーネント
  ├─ components
  │  ├─ common
  │  │  └─ 共通コンポーネント
  │  ├─ layout
  │  │  └─ レイアウト関連のコンポーネント
  │  ├─ ui
  │  │  └─ shadcn/ui を主体とした UI コンポーネント
  │  └─ …{pagePrefix}
  │    └─ ページ単位でのコンポーネント配置
  ├─ consts
  │  └─ 定数置き場
  ├─ hooks
  │  └─ カスタムフック
  ├─ lib
  │  ├─ firebase
  │  │  └─ firebase 呼び出し関数
  │  └─ localstorage
  │    └─ localStorage 呼び出し関数
  ├─ styles
  │  └─ globals.css (Tailwind 設定外で必要な追加・特殊 CSS)
  ├─ types
  │  └─ 型定義ファイル
  └─ utils
    └─ 汎用的なユーティリティ関数
├─ …その他の設定ファイル


## 3. UI とスタイリング

- **Shadcn UI**, **Radix**, **Tailwind CSS** を併用して開発を行う。
- スタイリングは **Tailwind CSS** を使用し、モバイルファーストのレスポンシブデザインを心がける。
- UI コンポーネントは、まず **shadcn/ui** の利用を検討し、必要に応じて自作コンポーネントを作成する。
  - shadcn/uiのcomponentのファイルは、`src/components/ui` ディレクトリに配置してある
### 補足
- すべてのshadcn/uiのcomponentのファイルは、インストール済みです
- テーマやカラーパレットに変更を加える場合は、`globals.css` や必要に応じて `tailwind.config.js` 等を編集する。  
- 共通レイアウトやヘッダー・フッターなどは、`layout` ディレクトリ内にまとめ、重複を避ける。
- 画像の表示には `next/image` を使用せず、通常の `img` タグを使用する。
  - Vercelにホスティングしない前提のため、`next/image` の最適化機能は不要
  - `loading="lazy"` 属性を使用して遅延読み込みを実装
- アイコンは `lucide-react` を使用し、カテゴリやセクションごとのアイコンマッピングは `src/consts` ディレクトリ内で管理する。
  - 例:`category-icons.ts` - カテゴリとアイコンのマッピング

## 4. 実装方針
### 4.1 ダイアログやモーダル
- `component` ディレクトリ配下に共通化したコンポーネントとして切り出すことを検討する。
- できるだけ汎用性を持たせ、複数の画面で使いまわせるようにする。
### 4.2 ファイル命名規則
- **小文字 (lower case) + ケバブケース (kebab-case)** で命名する。  
  例)`example-component.tsx` / `user-list-dialog.tsx`
### 4.3 データフェッチ
- **`fetch`** を使用してデータを取得する。  
- クライアントサイド/サーバーサイドで使い分ける場合は、`getServerSideProps` や `getStaticProps` など Next.js の機能を活用する。
  - pages routerなので、上記の関数で正しい。(app routerではないことに注意)
### 4.4 エラーハンドリング & バリデーション
- エラーが発生した場合には、**shadcn/ui** の **toast (variant: `destructive`)** を使用してユーザに通知する。
- 成功時のフィードバックも同じく toast を利用してユーザにわかりやすく伝える。
- フォームバリデーションには、必要に応じて `zod` や `React Hook Form` などのライブラリ導入を検討し、ユーザ入力エラーを適切にハンドリングする。
### 4.5 アニメーション
- アニメーションに関しては `framer-motion` を使用することを第一に検討する。そのほかのアニメーションライブラリは使わない。
- framer-motionで難しい時には、該当componentのアニメーションファイルをcss.moduleで記述し、アニメーションを実装する。
### 4.6 モジュールの参照方法
- `scripts`ディレクトリ内のファイルでは、`@`プレフィックスを使用せず、相対パスで参照する
  - 例:`import { db } from "../../utils/firebase"`
- `src`ディレクトリ内のファイルでは、`@`プレフィックスを使用する
  - 例:`import { db } from "@/lib/firebase"`


## 6. 補足事項
- **コミットメッセージ** や **ブランチ名** にも可能な範囲でケバブケースやわかりやすい命名を心がける。
- プロジェクトに参加したメンバーが迷わないよう、**README** や **memos** ディレクトリ内で補足情報を定期的に更新する。

css
firebase
golang
javascript
next.js
radix-ui
react
shadcn/ui
+3 more
MASAKASUNO1/mermaid-exporter

Used in 1 repository

TypeScript
# TypeScript, React Native, and Expo Development Guidelines

code_style:
  - Write concise and precise TypeScript code.
  - Prefer functional and declarative programming; avoid classes.
  - Modularize code and avoid duplication.
  - Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
  - Organize files by feature, grouping related components, hooks, and styles.
  - Use named exports for components and utilities.

naming_conventions:
  - Use lowercase with dashes for directories (e.g., user-profile, chat-screen).
  - Use PascalCase for component names (e.g., UserProfile).
  - Use camelCase for variables and functions (e.g., isFetchingData, handleUserInput).

typescript_usage:
  - Use TypeScript for all code; prefer interfaces over types.
  - Avoid any; strive for precise types and enable strict mode in tsconfig.json.
  - Utilize React.FC for functional components.
  - Avoid enums; use maps instead.

syntax_and_formatting:
  - Use the function keyword for pure functions.
  - Avoid unnecessary curly braces in conditionals; use concise syntax.
  - Use declarative JSX.
  - Format code with Prettier.

ui_and_styling:
  - Use Expo's built-in components and styled-components or Tailwind CSS for styling.
  - Implement responsive design with Flexbox and useWindowDimensions.
  - Support dark mode with useColorScheme.
  - Follow accessibility standards using ARIA roles and native props.
  - Use react-native-reanimated and react-native-gesture-handler for animations.

safe_area_management:
  - Use SafeAreaProvider from react-native-safe-area-context.
  - Wrap components with SafeAreaView for screen insets.
  - Avoid hardcoding padding/margins; use context hooks.

performance_optimization:
  - Minimize useState and useEffect; use context and useReducer.
  - Use React.memo() for static prop components.
  - Optimize FlatList with removeClippedSubviews, maxToRenderPerBatch, windowSize.
  - Avoid anonymous functions in renderItem and event handlers.
  - Implement Suspense and dynamic loading for better performance.


rules:
  - description: "Use TypeScript para todos os componentes e siga a tipagem estrita"
    match: "*.tsx"
    actions:
      - enforce_typescript: true
      - strict_mode: true

  - description: "Use funções em vez de classes para componentes"
    match: "*.tsx"
    actions:
      - enforce_function_components: true
      - ban_classes: true

  - description: "Organize arquivos por funcionalidade"
    match: "*"
    actions:
      - recommend_structure:
          pattern: "feature-based"
          
  - description: "Prefira interfaces em vez de types"
    match: "*.tsx"
    actions:
      - enforce_prefer_interfaces: true

  - description: "Evite enums, use mapas em vez disso"
    match: "*.tsx"
    actions:
      - ban_enums: true
      - recommend_alternatives:
          alternative: "Mapas (e.g., objetos chave-valor)"

  - description: "Utilize nomes de variáveis descritivos"
    match: "*"
    actions:
      - enforce_variable_naming:
          pattern: "camelCase"

  - description: "Utilize Prettier para formatação consistente"
    match: "*"
    actions:
      - recommend_formatter:
          tool: "Prettier"

  - description: "Implemente design responsivo com Flexbox e Tailwind CSS"
    match: "*.tsx"
    actions:
      - recommend_styling_tools:
          tools:
            - "Flexbox"
            - "Tailwind CSS"
            
  - description: "Use SafeAreaProvider e SafeAreaView para gerenciamento de áreas seguras"
    match: "*.tsx"
    actions:
      - enforce_safe_area_usage: true

  - description: "Priorize hooks como useMemo e useCallback para otimização de performance"
    match: "*.tsx"
    actions:
      - recommend_hooks_for_performance:
          hooks:
            - "useMemo"
            - "useCallback"

  - description: "Use expo-error-reporter e Sentry para tratamento de erros"
    match: "*.tsx"
    actions:
      - recommend_error_logging_tools:
          tools:
            - "expo-error-reporter"
            - "Sentry"
            
  - description: "Siga as diretrizes de segurança do Expo"
    match: "*.tsx"
    actions:
      - recommend_security_guidelines:
          link: "https://docs.expo.dev/guides/security/"

  - description: "Implemente testes com Jest e React Native Testing Library"
    match: "*.test.tsx"
    actions:
      - enforce_testing_frameworks:
          frameworks:
            - "Jest"
            - "React Native Testing Library"
css
javascript
jest
prettier
react
sentry
styled-components
tailwindcss
+2 more

First seen in:

Claudio-Lins/ryde-app

Used in 1 repository

TypeScript
Here’s the revised guidance with TypeScript replacing JavaScript, while retaining Mantine and CSS Modules for styling:

---

You are an expert in TypeScript, React, Node.js, Next.js App Router, Zustand, Mantine, and CSS Modules.

### Code Style and Structure

- Write concise, technical TypeScript code following best practices.
- 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.

### TypeScript Rules

- Enable `strict` mode in your `tsconfig.json` file.
- Always type function arguments, return types, and state values explicitly.
- Prefer `interface` over `type` when defining object shapes.
- Use `unknown` instead of `any` for better type safety.
- Avoid using `any`; refine types as much as possible.
- Use `enum` for well-defined sets of related values.
- Use `readonly` for arrays or objects that should not be mutated.
- Use `Partial<T>`, `Pick<T, K>`, and `Omit<T, K>` to modify types.

### Naming Conventions

- Use **PascalCase** for component folder names (e.g., `BigHeader`).
- Favor named exports for components.

This ensures consistent naming throughout your codebase.

### React Best Practices with TypeScript

### Instruction:

- Use functional components without `FC` (FunctionComponent) or explicit return types.
- Define prop types using interfaces as shown below:
  ```ts
  interface ComponentProps {
    title: string;
    isLoading: boolean;
  }
  ```
- Implement the functional component as:
  ```ts
  const MyComponent = ({ title, isLoading }: ComponentProps) => {...}
  ```
- Implement hooks correctly (`useState`, `useEffect`, `useContext`, `useReducer`, `useMemo`, `useCallback`) with proper typing.
- Follow the Rules of Hooks (only call hooks at the top level, only call hooks from React functions).
- Create custom hooks with proper type definitions to extract reusable component logic.
- Use `React.memo()` for component memoization when appropriate.
- Use `useCallback` to memoize functions passed as props:
  ```ts
  const handleClick = useCallback(() => {...}, []);
  ```
- Use `useMemo` for expensive computations:
  ```ts
  const computedValue = useMemo(() => expensiveComputation(), [dependencies]);
  ```
- Avoid inline function definitions in render to prevent unnecessary re-renders.
- Prefer composition over inheritance.
- Use the `children` prop and render props pattern for flexible, reusable components.
- Implement `React.lazy()` and `Suspense` for code splitting.
- Use refs sparingly and mainly for DOM access:
  ```ts
  const myRef = useRef<HTMLDivElement>(null);
  ```
- Prefer controlled components over uncontrolled components.
- Implement error boundaries using `ErrorBoundary` components to catch and handle errors gracefully.
- Use cleanup functions in `useEffect` to prevent memory leaks.
- Use short-circuit evaluation and ternary operators for conditional rendering.

### State Management

- Use Zustand for global state management with proper TypeScript typing.

  ```ts
  interface State {
    count: number;
    increment: () => void;
  }

  const useStore = create<State>((set) => ({
    count: 0,
    increment: () => set((state) => ({ count: state.count + 1 })),
  }));
  ```

- Lift state up when needed to share state between components.
- Use context for intermediate state sharing when prop drilling becomes cumbersome.

### UI and Styling

- Use `mantine.dev` components for all UI elements, utilizing Mantine's TypeScript support.
- Apply custom styles using CSS Modules:
  - Create a `.module.css` file for each component that needs custom styling.
  - Use camelCase for class names in CSS Modules files.
  - Maintain simple, component-specific styles using CSS Modules for easier maintenance and scalability.
  - Type your classes using:
    ```ts
    import styles from "./Component.module.css";
    ```

### Mantine with TypeScript

- Leverage Mantine's inbuilt TypeScript support for `useStyles`, `sx`, and `MantineProvider` for theme customization.
- Example usage:

  ```ts
  const useStyles = createStyles((theme) => ({
    button: {
      backgroundColor: theme.colors.blue[6],
      "&:hover": {
        backgroundColor: theme.colors.blue[8],
      },
    },
  }));

  function MyButton() {
    const { classes } = useStyles();
    return <Button className={classes.button}>Click me</Button>;
  }
  ```

### File Structure for Styling

- Place CSS Modules files next to their corresponding component files.
- Example structure:
  ```plaintext
  components/
    Button/
      Button.tsx
      Button.module.css
    Card/
      Card.tsx
      Card.module.css
  ```

### CSS Modules Best Practices with TypeScript

- Define custom classes in `.module.css` and import them into TypeScript components:
  ```ts
  import styles from "./Component.module.css";
  ```
- Apply classes using the `styles` object:
  ```ts
  <div className={styles.containerClass} />
  ```
- Use variables for colors, fonts, and other repeated values, either using Mantine's `theme` or a custom configuration file.
- Keep specificity low by avoiding deep nesting in CSS Modules.

### Performance Optimization

- Minimize the use of `'use client'`, `useEffect`, and `useState`; favor React Server Components (RSC).
- Wrap client components in `Suspense` with a fallback.
- Use dynamic loading for non-critical components.
- Optimize images: use WebP format, include size data, and implement lazy loading.
- Implement route-based code splitting in Next.js.
- Minimize the use of global styles; prefer modular, scoped styles with CSS Modules.

### Forms and Validation

- Use Mantine's form components with TypeScript support.
- Implement form validation (client-side and server-side).
- Consider using libraries like `react-hook-form` for complex forms with proper type validation.
- Use Zod or Joi for schema validation.

### 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.
- Avoid unnecessary `else` statements; use `if-return` pattern instead.
- Model expected errors as return values in Server Actions.
- Implement proper error logging and user-friendly error messages.

### Accessibility (a11y)

- Use semantic HTML elements.
- Implement proper ARIA attributes.
- Ensure keyboard navigation support.

### Testing

- Write unit tests for components using Jest and React Testing Library with TypeScript.
- Implement integration tests for critical user flows.
- Use snapshot testing judiciously.

### Security

- Sanitize user inputs to prevent XSS attacks.
- Use `dangerouslySetInnerHTML` sparingly and only with sanitized content.

### Internationalization (i18n)

- Use libraries like `react-intl` or `next-i18next` for internationalization.

### 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.
css
dockerfile
java
javascript
jest
nestjs
next.js
react
+2 more

First seen in:

ChayFadida/actis

Used in 1 repository

TypeScript
## Key Principles

- **Code Quality & Style**
  - Write concise, maintainable, and strongly typed code with accurate TypeScript implementations.
  - Embrace functional, declarative programming. Avoid OOP and classes.
  - Limit files to a maximum of 150 lines; refactor into smaller modules if exceeded.
  - Prefer iteration and modularization over duplication.
  - Use descriptive, semantic variable names with auxiliary verbs (e.g., `isLoading`, `hasError`).
  - Use lowercase with dashes for directories and files (e.g., `components/auth-wizard`).
  - Favor named exports for components.
  - Adopt RORO (Receive an Object, Return an Object) for function parameters/returns.
  - Always attain to use DRY (Don't Repeat Yourself) principles.
  - Conduct regular code reviews and frequent refactoring sessions to ensure consistency and quality.
  - Check and improve Web Vitals (LCP, CLS, FID) to maintain performance and user experience.

- **Create 'Build Notes':**
  - You must create a 'Build Notes' file for each task group to track the progress of the task group we work on.
  - **Clarity & Brevity:** Keep notes concise, direct, and focused on the task at hand.  
  - **Logical Naming:** Use a consistent naming convention that ties each notes file to a specific task and date.  
  - **Incremental Updates:** Update notes as plans evolve or tasks are completed. Append rather than overwrite.  
  - **Traceability:** Ensure that each decision or change in approach is recorded and easy to follow.

- **Review 'Project Contexts':**
  - You must review the `projectContext.md` as we need to ensure that the project context is up to date and accurate.
  - **Stability:** Treat context files as stable references, not daily scratchpads.  
  - **Selective Updates:** Update context files only when there are significant, approved changes to requirements or project scope.  
  - **Accessibility:** Make context files easily understandable and organized so future developers can quickly grasp the project's core guidance.

- **Stack and Framework Conventions**
  - Target **Next.js 15+** and leverage the App Router, React Server Components (RSC), and SSR capabilities.
  - Use Zustand for state management in client components when necessary.
  - Maintain proper Shadcn UI management using `npx shadcn@latest add` for new components.
  - Follow a mobile-first approach and responsive design patterns.
  - Emphasize server-side logic, minimizing the usage of `use client` and other client-only APIs.
  - Structure project as Progressive Web App (PWA) with offline capabilities, app-like experience, and installability across devices.

- **Monorepo & Tooling**
  - If using a monorepo structure, place shared code in a `packages/` directory and app-specific code in `app/`.
  - Use `Taskfile.yml` commands for development, testing, and deployment tasks.
  - Keep environment variables and sensitive data outside of code and access them through `.env` files or similar configuration.

Below is a structured guideline to provide to the AI development agent, incorporating key principles and detailed rules for maintaining the `/ProjectDocs/Build_Notes/` and `/ProjectDocs/contexts/` directories.

---

### Rules for Build Notes Files

1. **Location & Naming:**  
   - Store all notes files in `/ProjectDocs/Build_Notes/`.  
   - Use a logical, descriptive naming convention, e.g., `build-title_phase-#_task-group-name.md`.
   - Use the `<build-title>` to describe the build task.
   - Use the `<phase-#>` to apply the Phase # to the build task.
   - Use the `<task-group-name>` to describe the task group name.
   - Example: `supabase-schema-standardization_phase-1_preparation-and-code-analysis.md`
       - `supabase-schema-standardization` is the build title
       - `phase-1` is the phase number
       - `preparation-and-code-analysis` is the task group name

2. **Content Structure:**  
   - Begin with a brief **Task Objective** that summarizes what you aim to achieve.  
   - Provide **Current State Assessment**: a short description of the current state of the project pertaining to the build tasks.
   - Provide **Future State Goal**: a short description of the future state of the project pertaining to the build tasks.
   - Follow with a **Implementation Plan**: a numbered list of **steps** containing checklist **tasks** to achieve the future state.
   - Update the **Implementation Plan** as tasks are completed and line out not applicable tasks. NEVER DELETE TASKS FROM THE PLAN.
   - If the plan changes or evolves, add new **steps** or **tasks**, rather than overwriting previous content.

3. **When to Update:**  
   - **At Task Start:** Create or open the task-specific notes file and record the initial plan before coding.  
   - **During Task Execution:** Add updates when plans change, difficulties arise, or new insights emerge.  
   - **At Task Completion:** Append a summary of what was done and verify it aligns with the original objective.

4. **Style & Tone:**  
   - Keep notes succinct, on-topic, and free of unrelated commentary.  
   - Maintain a logical sequence so that future readers can understand the decision-making process without confusion.

5. **Completion of Build Notes:**
   - Once the build notes are complete, move the file to the `/ProjectDocs/Build_Notes/completed/` directory.
   - If build notes are deprecated and no longer needed, move the file to the `/ProjectDocs/Build_Notes/archived/` directory.

---

### Rules for Context Files

1. **Master Project Context (`projectContext.md`):**  
   - Located in `/ProjectDocs/contexts/`.  
   - Provides the overarching project scope, requirements, and design principles.  
   - Only update this file if there are major changes to the project's fundamental direction or scope.

2. **Additional Context Files:**  
   - Supplementary files (e.g., `uiContext.md`, `featureAContext.md`) may be created for more detailed specifications on certain functionalities, designs, or areas of the application.  
   - Keep these files stable. Update them only when new, approved changes need to be documented.  
   - Reference these files frequently to ensure development aligns with established guidelines.

3. **Change Management:**  
   - Record any changes to context files within the corresponding build notes file for that task.  
   - Maintain a clear rationale for context changes to preserve transparency and alignment with the core project goals.

---

## Project Structure

Adopt a clear, modular directory structure:

```
├── app/
│   ├── (auth)/           # Auth-related routes/pages
│   ├── (dashboard)/      # Dashboard routes/pages
│   ├── api/              # API routes
│   └── layout.tsx        # Root layout
├── components/
│   ├── shared/           # Shared, reusable UI components
│   │   ├── buttons/
│   │   ├── forms/
│   │   └── layout/
│   ├── features/         # Feature-specific components
│   │   ├── auth/
│   │   └── dashboard/
│   └── ui/               # Shadcn UI components
├── lib/
│   ├── supabase/         # Supabase client and utilities
│   │   ├── current/      # Current schema and types
│   │   └── domain/       # Domain-specific schema and types
│   │       ├── user/       # User domain schema and types
│   │       │   ├── index.ts    # Exports all supabase utilities
│   │       │   ├── queries.ts  # Supabase queries
│   │       │   ├── services.ts # Supabase services
│   │       │   └── types.ts    # Supabase types
│   │       ├── roles/        # Roles domain schema and types
│   │       └── ...            # Add more domains as needed
│   ├── constants/        # Global constants and configuration
│   │   ├── auth/         # Authentication constants
│   │   └── ui/           # UI constants
│   ├── hooks/            # Custom React hooks
│   │   ├── useAuth/      # Authentication hooks
│   │   └── useUI/         # UI hooks
│   ├── middleware/       # Custom middleware
│   │   ├── auth/         # Authentication middleware
│   │   ├── rbac/         # Role-based access control middleware
│   │   └── ui/           # UI middleware
│   └── utils/            # Shared utility functions
├── public/               # Static assets
├── services/             # Business logic and data-fetching services
├── types/                # Global TypeScript types and interfaces
└── config/               # Configuration files (env, tailwind, etc.)
```

**Naming & Organization:**
- Use semantic, descriptive names.
- Keep file names lowercase with dashes.
- Use `feature/`, `bugfix/`, `hotfix/`, `refactor/`, `docs/` prefixes for branches.
- Export from `index.ts` files in feature directories for cleaner imports.

---

## JavaScript/TypeScript Standards

- Use TypeScript everywhere. Prefer `interface` for public-facing contracts.
- Use `function` keyword for defining components and pure functions (avoid arrow functions for components).
- Omit semicolons for a cleaner look.
- Maintain a logical file order:
  1. Exported component
  2. Subcomponents
  3. Helpers/internal utilities
  4. Static content/constants
  5. Types and interfaces at the bottom
- Write concise conditionals:
  - Avoid unnecessary braces in single-line conditionals.
  - Use early returns to handle edge cases and errors upfront.
- Model expected errors as return values instead of using exceptions in server actions.

Example:

```typescript
function formatInput({ input }: { input: string }) {
  if (!input) return null
  return input.trim()
}
```

---

## Error Handling, Validation, and Services

- Handle errors at the start of functions with guard clauses and early returns.
- Keep the "happy path" visible at the bottom of the function.
- Avoid `else` statements by using if-return patterns to reduce nesting.
- Use Zod for schema validation and form validation.
- Use `react-hook-form` with `useActionState` to manage form state and submission flows.
- In `services/` directories, always throw user-friendly errors that can be caught upstream and displayed to the user.
- Implement proper error logging and user-friendly messages.
- Employ error boundaries (`error.tsx`, `global-error.tsx`) for unexpected errors.
- Use `next-safe-action` for secure and type-safe server actions.

---

## AI Integration

- Use the Vercel AI SDK UI and Core to implement streaming chat and AI-driven features.
- Handle rate limiting, quota, and model availability gracefully.
- Implement fallback logic if AI models are unavailable.
- Sanitize user inputs before sending them to the AI.
- Store API keys and sensitive information in environment variables.
- Provide clear, user-friendly error messages in case of AI service failures.

---

## React/Next.js Component Development

- **Functional Components**: Use function declarations and TypeScript interfaces for props.
- **Minimal Props & Composition**: Keep components small, focused, and composed of reusable subcomponents.
- **Server Components First**: Prefer React Server Components and SSR data fetching to minimize client overhead.
- **Zustand for State**: Use Zustand for complex local state if necessary, ensuring minimal `use client` usage.
- **Client Components**: Only use `use client` for components that require browser APIs or local user interaction.
- **Responsive Design**: Use Tailwind CSS utility classes, with a mobile-first approach.
- **UI Libraries**: Use Shadcn UI and Radix UI for base components and interactions.
- **Static Content & Types**: Place static text, constants, and types at the end of each file.
- **Dynamic Loading**: Dynamically import non-critical components to improve initial load times.
- **Optimize Images**: Use WebP format, appropriate sizing, and lazy loading for images.

---

## Supabase, Database, and GraphQL

- Fetch latest Supabase documentation from https://supabase.com/docs/reference/javascript;

- **Schema Management**: Keep migrations folder under `supabase/migrations` updated with remote changes.
- **Types Management**: Keep `database.types.ts` updated regularly with the latest schema changes.
- **Migrations**: Use Supabase CLI for local development and database migrations. Test all changes before staging/production.
- **RLS & RBAC**: Implement Row Level Security and role-based access control. Assign default roles in `handle_new_user` functions.
- **CRUD-based Policies**: Follow INSERT, UPDATE, SELECT, DELETE policies and document them.
- **Enum Tables**: Use enum tables for predefined values.
- **Relationships**: Document all table relationships and data flows.
- **Genql**: Use Genql for type-safe GraphQL queries against Supabase. Fetch only necessary data.

Example user creation:

```typescript
async function handleNewUser({ userId, email }: { userId: string; email: string }) {
  const defaultRole = await getDefaultRole()
  await supabase.from('profiles').insert({
    id: userId,
    email,
    role_id: defaultRole.id,
    created_at: new Date().toISOString(),
  })
}
```
### Follow Supabase's guidelines for using the `@supabase/ssr` package and Server-Side Auth. Specifically, there should be:

- A utility function to create a client on the client side
- A utility function create a client on the server side, using the Next.js `cookies` API to access the cookies. Use the latest version of the API, where `cookies` must be awaited.
- A utility function to handle refreshing the user session in middleware.

## Working with cookies

Use the latest version of `@supabase/ssr`, where cookie options are defined with the `getAll` and `setAll` functions, like so:

```
const supabase = createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        getAll() {
          return request.cookies.getAll()
        },
        setAll(cookiesToSet) {
          cookiesToSet.forEach(({ name, value, options }) => request.cookies.set(name, value))
          supabaseResponse = NextResponse.next({
            request,
          })
          cookiesToSet.forEach(({ name, value, options }) =>
            supabaseResponse.cookies.set(name, value, options)
          )
        },
      },
    }
  )
```

No other cookie options should be provided.

## Middleware

The middleware should use the following `updateSession` function:

```
import { createServerClient } from '@supabase/ssr'
import { NextResponse, type NextRequest } from 'next/server'

export async function updateSession(request: NextRequest) {
  let supabaseResponse = NextResponse.next({
    request,
  })

  const supabase = createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        getAll() {
          return request.cookies.getAll()
        },
        setAll(cookiesToSet) {
          cookiesToSet.forEach(({ name, value, options }) => request.cookies.set(name, value))
          supabaseResponse = NextResponse.next({
            request,
          })
          cookiesToSet.forEach(({ name, value, options }) =>
            supabaseResponse.cookies.set(name, value, options)
          )
        },
      },
    }
  )

  // IMPORTANT: Avoid writing any logic between createServerClient and
  // supabase.auth.getUser(). A simple mistake could make it very hard to debug
  // issues with users being randomly logged out.

  const {
    data: { user },
  } = await supabase.auth.getUser()

  if (
    !user &&
    !request.nextUrl.pathname.startsWith('/login') &&
    !request.nextUrl.pathname.startsWith('/auth')
  ) {
    // no user, potentially respond by redirecting the user to the login page
    const url = request.nextUrl.clone()
    url.pathname = '/login'
    return NextResponse.redirect(url)
  }

  // IMPORTANT: You *must* return the supabaseResponse object as it is. If you're
  // creating a new response object with NextResponse.next() make sure to:
  // 1. Pass the request in it, like so:
  //    const myNewResponse = NextResponse.next({ request })
  // 2. Copy over the cookies, like so:
  //    myNewResponse.cookies.setAll(supabaseResponse.cookies.getAll())
  // 3. Change the myNewResponse object to fit your needs, but avoid changing
  //    the cookies!
  // 4. Finally:
  //    return myNewResponse
  // If this is not done, you may be causing the browser and server to go out
  // of sync and terminate the user's session prematurely!

  return supabaseResponse
}
```
### Postgres SQL Style Guide

## General

- Use lowercase for SQL reserved words to maintain consistency and readability.
- Employ consistent, descriptive identifiers for tables, columns, and other database objects.
- Use white space and indentation to enhance the readability of your code.
- Store dates in ISO 8601 format (`yyyy-mm-ddThh:mm:ss.sssss`).
- Include comments for complex logic, using '/* ... */' for block comments and '--' for line comments.

## Naming Conventions

- Avoid SQL reserved words and ensure names are unique and under 63 characters.
- Use snake_case for tables and columns.
- Prefer plurals for table names
- Prefer singular names for columns.

## Tables

- Avoid prefixes like 'tbl_' and ensure no table name matches any of its column names.
- Always add an `id` column of type `identity generated always` unless otherwise specified.
- Create all tables in the `public` schema unless otherwise specified.
- Always add the schema to SQL queries for clarity.
- Always add a comment to describe what the table does. The comment can be up to 1024 characters.

## Columns

- Use singular names and avoid generic names like 'id'.
- For references to foreign tables, use the singular of the table name with the `_id` suffix. For example `user_id` to reference the `users` table
- Always use lowercase except in cases involving acronyms or when readability would be enhanced by an exception.

#### Examples:

```sql
create table books (
  id bigint generated always as identity primary key,
  title text not null,
  author_id bigint references authors (id)
);
comment on table books is 'A list of all the books in the library.';
```


## Queries

- When the query is shorter keep it on just a few lines. As it gets larger start adding newlines for readability
- Add spaces for readability.

Smaller queries:


```sql
select *
from employees
where end_date is null;

update employees
set end_date = '2023-12-31'
where employee_id = 1001;
```

Larger queries:

```sql
select
  first_name,
  last_name
from
  employees
where
  start_date between '2021-01-01' and '2021-12-31'
and
  status = 'employed';
```


### Joins and Subqueries

- Format joins and subqueries for clarity, aligning them with related SQL clauses.
- Prefer full table names when referencing tables. This helps for readability.

```sql
select
  employees.employee_name,
  departments.department_name
from
  employees
join
  departments on employees.department_id = departments.department_id
where
  employees.start_date > '2022-01-01';
```

## Aliases

- Use meaningful aliases that reflect the data or transformation applied, and always include the 'as' keyword for clarity.

```sql
select count(*) as total_employees
from employees
where end_date is null;
```


## Complex queries and CTEs

- If a query is extremely complex, prefer a CTE.
- Make sure the CTE is clear and linear. Prefer readability over performance.
- Add comments to each block.

```sql
with department_employees as (
  -- Get all employees and their departments
  select
    employees.department_id,
    employees.first_name,
    employees.last_name,
    departments.department_name
  from
    employees
  join
    departments on employees.department_id = departments.department_id
),
employee_counts as (
  -- Count how many employees in each department
  select
    department_name,
    count(*) as num_employees
  from
    department_employees
  group by
    department_name
)
select
  department_name,
  num_employees
from
  employee_counts
order by
  department_name;
```


---

## Version Control and Workflow

- **Branch Naming**: `feature/`, `bugfix/`, `hotfix/`, `refactor/`, `docs/`.
- **Commit Messages**: Use `type(scope): description` format. Common types: `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore`.
- **Pull Requests**: Use PR templates with a summary, change type, testing steps, and any database changes noted.
- **Schema Updates**: Update `schema.sql` and commit the changes after each migration.
- **Testing Before PR**: Always test changes locally before submitting PRs.

---

## Data Fetching and State Management

- **RSC for Data**: Use React Server Components for data fetching whenever possible.
- **Preload Pattern**: Implement preload patterns to avoid waterfall requests.
- **Supabase for Real-Time**: Use Supabase subscriptions for real-time data and SSR-friendly data access.
- **Zustand**: Manage local state in isolated client components when needed.
- **Vercel KV**: Use Vercel KV for chat history, rate limiting, and ephemeral storage.
- **SSR & Minimize 'use client'**: Prefer SSR and server actions. Only use `use client` for browser-based interactions.

---

## Testing and Quality Assurance

- **Unit Tests**: Write unit tests for utilities, hooks, and business logic.
- **Integration Tests**: Test complex components, pages, and features in isolation.
- **End-to-End Tests**: Validate critical flows (login, checkout) end-to-end.
- **Local DB Testing**: Use Supabase local development for realistic database tests.
- **Coverage**: Maintain a minimum test coverage threshold for PR merges.

---

## Styling and Accessibility

- **Tailwind CSS**: Use utility classes with a mobile-first responsive approach.
- **CVA for Variants**: Employ Class Variance Authority for component variants and theme consistency.
- **Radix UI**: Utilize Radix primitives for accessible UI patterns.
- **ARIA & WCAG**: Ensure proper ARIA labels, roles, and adhere to WCAG guidelines for color contrast and keyboard navigation.
- **Shadcn UI**: Leverage shadcn UI components for design consistency and speed.

---

## Documentation

- **Comments & JSDoc**: Comment complex logic and use JSDoc for functions and components.
- **Readmes**: Keep README files updated with setup, instructions, and architectural details.
- **API & DB Docs**: Document all API endpoints, RLS policies, and database schema.
- **Edge Functions**: Document Supabase Edge Functions and their intended usage.
- **Setup Instructions**: Keep environment configuration and setup steps current for onboarding developers.

---

**Remember:**
- Regularly check file sizes; refactor when needed.
- Maintain separation of concerns and modular design.
- Reuse components and keep them composable and testable.
- Always test locally before pushing changes.
- Ensure proper error handling, user-friendly messages, and accessible interfaces.

## Supabase Migration Rules

- **CRITICAL: Migration File Management**
  - NEVER modify existing migration files. Each change requires a new migration file with a fresh timestamp.
  - Use `npx supabase migration new <descriptive-name>` to create new migrations.
  - Keep migration names short but descriptive (e.g., `add-user-index`, `update-ticket-constraints`).
  - One logical change per migration file - don't combine unrelated schema changes.
  - Test migrations locally before pushing to production.

- **Migration Best Practices**
  - Include `drop if exists` statements to make migrations idempotent.
  - Add comments explaining the purpose of each migration.
  - For constraint changes, include both `drop constraint if exists` and `add constraint`.
  - Order operations correctly (e.g., drop dependent objects before their dependencies).
  - Always specify the schema (e.g., `public.users` instead of just `users`).

- **Schema Management**
  - Keep `supabase/migrations/` in sync with remote changes.
  - Document schema changes in both migration files and project documentation.
  - Use `npx supabase db reset` for local development only.
  - Use `npx supabase db push` for remote database updates.
  - Never use `db reset` on production/remote databases.

- **Types and Validation**
  - Generate and commit TypeScript types after schema changes using `supabase gen types typescript`.
  - Use Zod schemas that match database constraints.
  - Keep `database.types.ts` updated with latest schema.

- **Security and Access Control**
  - Document RLS policies in both migrations and project documentation.
  - Test RLS policies with different user roles.
  - Use service role only for administrative tasks (seeding, migrations).
  - Never expose service role key in client-side code.

## Database Standards

- **Naming Conventions**
  - Use snake_case for all database objects (tables, columns, functions).
  - Prefix function names with verb (e.g., `get_user`, `update_status`).
  - Use plural for table names (e.g., `users`, `tickets`).
  - Use singular for column names and foreign keys (e.g., `user_id`).

- **Column Standards**
  - Include `created_at` and `updated_at` on all tables.
  - Use `uuid` for primary keys unless there's a specific reason not to.
  - Add appropriate indexes for foreign keys and frequently queried columns.
  - Document constraints and indexes in migration files.

- **Error Handling**
  - Use custom error codes for database functions.
  - Implement proper error handling in application code.
  - Log database errors appropriately.
  - Provide user-friendly error messages.

## Testing and Validation

- **Migration Testing**
  - Test migrations in both directions (up/down).
  - Verify data integrity after migrations.
  - Test with realistic data volumes.
  - Check performance impact of schema changes.

- **Data Seeding**
  - Keep seed data minimal but sufficient for testing.
  - Use service role for seeding operations.
  - Document seed data structure and purpose.
  - Include different test scenarios in seed data.
css
golang
graphql
java
javascript
less
nestjs
next.js
+10 more
ProgramComputer/friendly-tickets

Used in 1 repository