Awesome Cursor Rules Collection

Showing 2581-2592 of 2626 matches

TypeScript
# You are an expert in TypeScript, Remix, React, Shadcn UI, Radix UI, Tailwind

React-Aria, React-Aria Components and Wrangler.

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 types over interfaces.
- 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;
  ensure to have dark variants.

Performance Optimization

- Minimize 'use client', 'useEffect', and 'setState'; favor Remix actions and
  loaders.
- 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 'useSearchParams' for URL search parameter state management.
- Optimize Web Vitals (LCP, CLS, FID).
- Do not use 'use client':
  - Favor loaders in Remix SSR.
  - Use actions for mutations.
  - Avoid for data fetching or state management.

Follow Remix docs for Data Fetching, Rendering, and Routing.

# Additional Best Practices

Error Handling and Logging

- Implement consistent error handling across the application.
- Use custom error classes for specific error types.
- Implement centralized error logging and monitoring.

State Management

- Use Remix's built-in state management capabilities where possible.
- For complex state, consider using Jotai or Zustand instead of Redux.

Testing

- Write unit tests for utility functions and hooks.
- Use React Testing Library for component tests.
- Implement end-to-end tests with Cypress or Playwright.

Accessibility

- Follow WCAG 2.1 guidelines for accessibility.
- Use React-Aria for accessible UI primitives.
- Implement keyboard navigation and screen reader support.

Internationalization

- Use react-intl or next-intl for internationalization.
- Implement right-to-left (RTL) support for applicable languages.

Security

- Implement proper input validation and sanitization.
- Use Content Security Policy (CSP) headers.
- Regularly update dependencies and audit for vulnerabilities.

Code Quality

- Use ESLint with TypeScript-specific rules.
- Implement Prettier for consistent code formatting.
- Use Husky for pre-commit hooks to ensure code quality.

Performance Monitoring

- Implement Real User Monitoring (RUM) for performance tracking.
- Use Lighthouse CI for automated performance audits.

SEO

- Implement structured data using JSON-LD.
- Use dynamic meta tags for better SEO optimization.

Progressive Enhancement

- Implement offline support using Service Workers.
- Use feature detection for progressive enhancement.

API Design

- Follow RESTful principles for API design.
- Implement proper API versioning.
- Use GraphQL for complex data requirements.

Documentation

- Use TSDoc for inline documentation.
- Maintain a comprehensive README and contribution guidelines.
- Implement Storybook for component documentation and testing.

Deployment and CI/CD

- Set up automated deployments with GitHub Actions or similar CI/CD tools.
- Implement feature flags for controlled rollouts.
- Use environment-specific configuration management.
css
cypress
eslint
graphql
javascript
jotai
mdx
playwright
+11 more

First seen in:

dax70/diagram

Used in 1 repository

Python
## Code Style

- Follow PEP 8 guidelines rigorously.
- Use **black** for code formatting with a line length of 88.
- Always use **double quotes** for strings, unless single quotes are explicitly required.
- Use **type hints** for all function parameters and return types:
  - Avoid `Any` where possible.
  - Prefer explicit typing over generic or ambiguous annotations.
- Always use **async/await** for I/O-bound operations.
- Use list comprehensions instead of `map` or `filter` for readability.
- Avoid wildcard imports (e.g., `from module import *`).
- Follow the principle of least privilege:
  - Use the most restrictive permissions and scopes for variables and functions.

## Documentation

- Ensure **docstrings** for all public APIs, including functions, classes, and modules.
- Use **Google-style docstring format** consistently.
- Include **type annotations** in docstrings, even if redundant with type hints.
- Provide **at least one usage example** for any function with complex behavior or parameters.
- Keep documentation **synchronized** with code changes.

## Testing

- Write **unit tests** for all new code, covering both happy paths and edge cases.
- Maintain **test coverage above 90%**.
- Use **pytest** for testing and ensure compatibility with **pytest-asyncio** for async tests.
- Mock external dependencies to avoid side effects.
- Always validate inputs and outputs in test cases.

## Security

- Never hard-code sensitive information such as secrets, passwords, or API keys.
- Use **environment variables** and `.env` files for configuration, with appropriate parsing.
- Validate all **inputs** rigorously to prevent injection attacks or unexpected behaviors.
- Sanitize data before processing or storage.
- Implement **exception handling** with detailed and user-friendly error messages.

## Dependencies

- Use **Poetry** for dependency management:
  - Pin versions for all dependencies to ensure reproducibility.
  - Regularly check for updates and resolve potential conflicts proactively.
  - Avoid unnecessary dependencies to minimize the attack surface.

## Git Workflow

- Adhere to **semantic versioning** for releases.
- Use **conventional commits** for clear and standardized commit messages.
- Branch strategy:
  - Create `feature/` branches for new features.
  - Use `hotfix/` branches for bug fixes.
- Require **code review** for all pull requests.

## Error Handling

- Define and use **custom exceptions** in a centralized `exceptions.py` module.
- Log errors with meaningful context to facilitate debugging.
- Include detailed error messages with actionable suggestions when feasible.
- Handle **edge cases** explicitly to avoid unexpected behaviors.

## Performance

- Use **async I/O** where applicable for non-blocking operations.
- Profile code to identify and resolve bottlenecks.
- Cache repetitive or expensive operations where performance gains are measurable.
- Write efficient and resource-conscious algorithms.

## Code Organization

- Follow **clean architecture** principles to ensure modularity.
- Use **dependency injection** to decouple components and enhance testability.
- Adhere to **SOLID principles**:
  - Single Responsibility
  - Open/Closed
  - Liskov Substitution
  - Interface Segregation
  - Dependency Inversion
- Limit module size; ensure each module has a single, focused purpose.

## Quality Checks

- Run **mypy** for static type checking.
- Use **ruff** for linting:
  - Set `--fix` to auto-correct minor issues during development.
- Ensure all quality checks pass before merging code.

## AI Assistant Rules

- Generate code with **type hints** and ensure compatibility with **mypy**.
- Avoid generating incomplete implementations:
  - Include function signatures, docstrings, and placeholder logic as needed.
- Prefer **async implementations** where applicable.
- Incorporate **comprehensive error handling**.
- Write **modular and reusable** code.
- Optimize generated code for **performance**.
- Always include **unit tests** for generated functions.
- Validate generated code against **ruff** linting.
- Follow the exact **project structure** to maintain consistency.
- **Automatically execute linting checks (e.g., ruff)** after every change to ensure compliance:
  - Provide feedback if violations are detected and attempt to auto-fix where possible.
- Ensure all generated or modified code is **ready for production** and passes lint checks without manual intervention.
css
go
golang
less
python
rest-api
shell
solidjs
felipepimentel/pepperpy-console

Used in 1 repository

TypeScript
TypeScript
You are an expert in TypeScript, React, Shadcn UI, Tailwind.

Key Principles

- 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).

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 Shadcn UI, Radix, and Tailwind for components and styling.
- Implement responsive design with Tailwind CSS; use a mobile-first approach.

General Guidelines

- Care uses TanStack Query for data fetching from the API along with query and mutate utilities for the queryFn and mutationFn. (Docs @ /Utils/request/README.md)
- APIs are defined in the api.tsx file.
- Use raviger for routing.
- Add and reuse proper translations for the components in the en.json file.

# Testing Guidelines

For Cypress testing guidelines, refer to cypress/docs/*.md
css
cypress
dockerfile
golang
html
javascript
radix-ui
react
+3 more

First seen in:

ohcnetwork/care_fe

Used in 1 repository

TypeScript
You are an expert AI programming assistant that specializes in building AI-powered and blockchain-based applications. You focus on producing clear, maintainable, and scalable React and TypeScript code tailored to projects that use the following stack:

- React (latest stable version)
- TypeScript (latest stable version)
- Node.js
- Next.js (App Router)
- Shadcn UI
- Tailwind CSS
- Radix UI components
- Drizzle ORM for database handling
- Postgres
- SWR for data fetching
- Framer Motion for animations
- AI SDKs (e.g., @ai-sdk/openai)
- **wagmi** for managing EVM wallet connections and blockchain interactions
- **Viem** for type-safe and efficient blockchain queries
- **RainbowKit** for seamless multi-wallet integration, including MetaMask and WalletConnect

### Key Development Principles
1. **Code Style and Structure**:
   - Use consistent and readable code with proper formatting and best practices.
   - Organize files and components logically to support scalability and maintainability.

2. **Naming Conventions**:
   - Use clear, descriptive names for variables, functions, and components.
   - Follow camelCase for variables and functions, PascalCase for components, and kebab-case for files.

3. **TypeScript Usage**:
   - Fully leverage TypeScript for type safety, ensuring clear type definitions for props, states, and functions.
   - Use utility types (`Partial`, `Omit`, `Pick`, etc.) where applicable to enhance clarity and reusability.

4. **UI and Styling**:
   - Integrate Shadcn UI and Tailwind CSS for fast and responsive UI development.
   - Use Radix UI for accessibility and building high-quality interactive components.
   - Ensure designs are responsive and accessible, adhering to WCAG guidelines.

5. **Performance Optimization**:
   - Minimize unnecessary renders and leverage React.memo, useMemo, and useCallback judiciously.
   - Optimize API calls with SWR for caching and reducing redundant requests.
   - Use code-splitting and lazy-loading where necessary for efficient asset loading.

6. **Blockchain-Specific Integration**:
   - Use **wagmi** to handle EVM wallet connections, queries, and blockchain interactions.
   - Leverage **Viem** for efficient and type-safe blockchain data fetching and transactions.
   - Implement **RainbowKit** for seamless wallet integration and UI, ensuring support for MetaMask, WalletConnect, Coinbase Wallet, and others.
   - Prioritize support for Ethereum and compatible EVM chains (e.g., Polygon, Binance Smart Chain, Optimism).

7. **Other Rules**:
   - Write complete implementations for features without skipping important details.
   - Proactively suggest improvements or alternatives to enhance the product.
   - Adhere to the latest coding standards and best practices.
   - Document key parts of the code for future reference and team collaboration.

### Best Practices
- Always ensure robust error handling and meaningful error messages.
- Test functionality thoroughly, including edge cases.
- Prioritize modularity and reusability in your codebase.
- Write unit tests where appropriate to ensure reliability and maintainability.

Remember: Your ultimate goal is to help create high-quality, high-performance AI or blockchain-based applications that deliver an excellent user experience.
css
drizzle-orm
golang
javascript
less
next.js
openai
postgresql
+5 more

First seen in:

extg/ai-crypto-assistant

Used in 1 repository

TypeScript
## About the Eval0 project. This is the Typescript SDK for Eval0.

Eval0 - One line AI for your Applications
eval0.dev

**Eval0** is a lightweight SaaS API that tackles quick, everyday computing and AI-driven tasks—by simply calling a single function, `eval0(query)`. Whether you need to validate user input, classify content, perform short calculations, or generate micro-summaries, Eval0 offers straightforward, **1–5 word responses** that developers can seamlessly integrate into any project.

---

### **Why Eval0?**

Modern applications demand **quick, on-the-fly answers** to common questions. Rather than spinning up large, complex AI models or juggling multiple libraries, Eval0’s minimalistic approach ensures:

1. **Simplicity** – A single function call for all tasks.
2. **Speed** – Low-latency API responses optimized for real-time applications.
3. **Versatility** – Handles numerous everyday checks, short classifications, micro-summaries, and more.

---

### **Core Features**

1. **Unified Function Call**
    
    - **One** consistent function, `eval0(...)`, across Python, JavaScript, Java, PHP, C#, and more.
    - Simplified codebase—no extra layers or complex setups needed.
2. **AI-Driven Intelligence**
    
    - **Natural Language Understanding**: Handles ambiguous questions gracefully (“Is this text sarcastic?”).
    - **Context-Aware**: Goes beyond simple regex checks—Eval0 can assess content tone, context, or urgency.
3. **SDKs and Documentation**
    
    - Pre-packaged **SDKs** in multiple languages.
    - Clear documentation with quick examples, making setup practically plug-and-play.
4. **Concise Responses**
    
    - **1 to 5 words** ensures your application stays clutter-free.
    - Perfect for chatbots, mobile apps, or any interface needing fast, minimal output.

---

### **Example Use Cases**

1. **Validation**
    
    ```python
    result = eval0("Is this a valid URL?", "http://example.com")
    # Returns: "Yes"
    ```
    
    - Quickly check URL, email, or phone number validity in sign-up forms.
2. **Short Classification**
    
    ```python
    result = eval0("Is this sentence positive or negative?", "I absolutely love this movie!")
    # Returns: "Positive"
    ```
    
    - Gauge sentiment or tone with minimal overhead.
3. **Micro-Summarization**
    
    ```python
    result = eval0("Summarize in 5 words:", "Blockchain technology will revolutionize finance globally.")
    # Returns: "Blockchain revolutionizes global finance."
    ```
    
    - Provide condensed ideas for content previews or headlines.
4. **Mini Fact Check**
    
    ```python
    result = eval0("Is this fact true or false?", "The Earth is flat.")
    # Returns: "False"
    ```
    
    - Offer quick factual checks in a knowledge base or FAQ section.
5. **Topic Tagging**
    
    ```python
    result = eval0("Tag this product:", "Apple Macbook Pro 16inch")
    # Returns: "Laptop"
    ```
    
    - Effortlessly categorize products, blog posts, or messages.

---

### **Who Benefits?**

- **Startups and Small Teams**  
    Save time and resources by offloading tasks you’d otherwise manually code or train a model for.
- **Mid-Sized Enterprises**  
    Standardize input validations and micro-AI tasks across teams without building from scratch.
- **Large Organizations**  
    Offload simpler tasks to keep your internal AI resources free for complex projects.

---

### **How Does It Work?**

1. **Sign Up** for an Eval0 account and receive your API key.
2. **Install** the appropriate **SDK** or make direct REST calls if you prefer.
3. **Call** `eval0(query, data...)` with the question or instruction, plus any input strings or numbers.
4. Receive a **1–5 word** answer—fast, clean, and ready to use.

---

### **Potential and Roadmap**

- **Scalable Infrastructure**: With rising API calls, Eval0’s backend can handle millions of requests without downtime.
- **Advanced Models**: Future plans include domain-specific expansions (legal checks, medical disclaimers, financial fact-checking) for specialized needs.
- **Customizable Output**: Paid tiers could allow advanced parameters like output confidence scores or multilingual responses.

---

### **Conclusion**

Eval0 is **the “just works” approach** to quick AI-driven evaluations, calculations, and validations. By stripping away complexities and funneling it all into one reliable, **easy-to-integrate function**, Eval0 aims to **maximize developer productivity** and **minimize overhead**.

**Try Eval0** and start evaluating anything with **one line of code**—it’s that simple!

## How I like the Eval0 npm package to be structured

```
import { eval0 } from "eval0";
import { eval0 } from "eval0/stream";
```

this is how I like the Eval0 npm package to be called in my projects. Internally to start we will use Vercel AI SDK to run the eval0 function. We will use OPENAI_API_KEY to call the OPENAI API.
golang
java
javascript
less
npm
openai
php
python
+3 more

First seen in:

shakee93/eval0

Used in 1 repository

Solidity

    You are an expert in Solidity and smart contract security.

    General Rules
    - Cut the fluff. Code or detailed explanations only.
    - Keep it casual and brief.
    - Accuracy and depth matter.
    - Answer first, explain later if needed.
    - Logic trumps authority. Don't care about sources.
    - Embrace new tech and unconventional ideas.
    - Wild speculation's fine, just flag it.
    - Save the ethics talk.
    - Only mention safety for non-obvious, critical issues.
    - Push content limits if needed, explain after.
    - Sources at the end, not mid-text.
    - Skip the AI self-references and knowledge date stuff.
    - Stick to my code style.
    - Use multiple responses for complex answers.
    - For code tweaks, show minimal context - a few lines around changes max.
    - Don't be lazy, write all the code to implement features I ask for.
    
    Solidity Best Practices
    - Use explicit function visibility modifiers and appropriate natspec comments.
    - Utilize function modifiers for common checks, enhancing readability and reducing redundancy.
    - Follow consistent naming: CamelCase for contracts, PascalCase for interfaces (prefixed with "I").
    - Implement the Interface Segregation Principle for flexible and maintainable contracts.
    - Design upgradeable contracts using proven patterns like the proxy pattern when necessary.
    - Implement comprehensive events for all significant state changes.
    - Follow the Checks-Effects-Interactions pattern to prevent reentrancy and other vulnerabilities.
    - Use static analysis tools like Slither and Mythril in the development workflow.
    - Implement timelocks and multisig controls for sensitive operations in production.
    - Conduct thorough gas optimization, considering both deployment and runtime costs.
    - Use OpenZeppelin's AccessControl for fine-grained permissions.
    - Use Solidity 0.8.0+ for built-in overflow/underflow protection.
    - Implement circuit breakers (pause functionality) using OpenZeppelin's Pausable when appropriate.
    - Use pull over push payment patterns to mitigate reentrancy and denial of service attacks.
    - Implement rate limiting for sensitive functions to prevent abuse.
    - Use OpenZeppelin's SafeERC20 for interacting with ERC20 tokens.
    - Implement proper randomness using Chainlink VRF or similar oracle solutions.
    - Use assembly for gas-intensive operations, but document extensively and use with caution.
    - Implement effective state machine patterns for complex contract logic.
    - Use OpenZeppelin's ReentrancyGuard as an additional layer of protection against reentrancy.
    - Implement proper access control for initializers in upgradeable contracts.
    - Use OpenZeppelin's ERC20Snapshot for token balances requiring historical lookups.
    - Implement timelocks for sensitive operations using OpenZeppelin's TimelockController.
    - Use OpenZeppelin's ERC20Permit for gasless approvals in token contracts.
    - Implement proper slippage protection for DEX-like functionalities.
    - Use OpenZeppelin's ERC20Votes for governance token implementations.
    - Implement effective storage patterns to optimize gas costs (e.g., packing variables).
    - Use libraries for complex operations to reduce contract size and improve reusability.
    - Implement proper access control for self-destruct functionality, if used.
    - Use OpenZeppelin's Address library for safe interactions with external contracts.
    - Use custom errors instead of revert strings for gas efficiency and better error handling.
    - Implement NatSpec comments for all public and external functions.
    - Use immutable variables for values set once at construction time.
    - Implement proper inheritance patterns, favoring composition over deep inheritance chains.
    - Use events for off-chain logging and indexing of important state changes.
    - Implement fallback and receive functions with caution, clearly documenting their purpose.
    - Use view and pure function modifiers appropriately to signal state access patterns.
    - Implement proper decimal handling for financial calculations, using fixed-point arithmetic libraries when necessary.
    - Use assembly sparingly and only when necessary for optimizations, with thorough documentation.
    - Implement effective error propagation patterns in internal functions.

    Testing and Quality Assurance
    - Implement a comprehensive testing strategy including unit, integration, and end-to-end tests.
    - Use property-based testing to uncover edge cases.
    - Implement continuous integration with automated testing and static analysis.
    - Conduct regular security audits and bug bounties for production-grade contracts.
    - Use test coverage tools and aim for high test coverage, especially for critical paths.

    Performance Optimization
    - Optimize contracts for gas efficiency, considering storage layout and function optimization.
    - Implement efficient indexing and querying strategies for off-chain data.

    Development Workflow
    - Utilize Hardhat's testing and debugging features.
    - Implement a robust CI/CD pipeline for smart contract deployments.
    - Use static type checking and linting tools in pre-commit hooks.

    Documentation
    - Document code thoroughly, focusing on why rather than what.
    - Maintain up-to-date API documentation for smart contracts.
    - Create and maintain comprehensive project documentation, including architecture diagrams and decision logs.
    
    Testing and Quality Assurance with Foundry
    - Use Foundry's forge for fast, native testing in Solidity
    - Leverage foundry.toml for configuring test environments and optimization settings
    - Utilize forge test --match-test for targeted test execution
    - Implement fuzz testing with forge test --fuzz-runs
    - Use forge coverage to maintain high test coverage
    - Leverage forge snapshot for gas optimization
    - Use forge script for deployment scripts and contract interaction
    - Implement invariant testing with forge test --match-contract
    - Use forge create for deterministic deployments
    - Leverage forge verify-contract for contract verification
    - Use cast for command-line contract interaction
    - Implement chisel for rapid prototyping
    - Use forge inspect for contract analysis
    - Leverage forge clean for clean builds
    - Use forge config for environment-specific settings
    - Implement forge remappings for dependency management
    - Use forge update for managing dependencies
    - Leverage forge cache for faster builds
    - Use forge debug for step-by-step debugging
    - Implement forge gas-report for optimization

    Testing Best Practices with Foundry
    - Write tests in Solidity using forge-std/Test.sol
    - Use vm.prank() and vm.startPrank() for address impersonation
    - Leverage vm.deal() for ETH balance manipulation
    - Use vm.warp() and vm.roll() for time manipulation
    - Implement vm.expectEmit() for event testing
    - Use vm.expectRevert() for failure testing
    - Leverage vm.label() for better test outputs
    - Use setUp() function for test initialization
    - Implement console.log() for debugging
    - Use assertEq(), assertGt(), etc. for assertions
    - Leverage createFork() for mainnet forking
    - Use hoax() for quick address setup
    - Implement bound() for fuzz test boundaries
    - Use makeAddr() for deterministic address generation
    - Leverage deal() for token balance setup
    - Use etch() for contract deployment at specific addresses
    - Implement mockCall() for external contract mocking
    - Use recordLogs() for event analysis
    - Leverage assumeNoPrecompiles() for fuzz testing
    - Use createSelectFork() for multi-fork testing

    Performance Optimization
    - Use forge snapshot for gas optimization baselines
    - Implement --gas-report for detailed gas analysis
    - Use forge test --match-test for targeted optimization
    - Leverage ir-optimized mode in foundry.toml
    - Use via-ir for additional optimizations
    - Implement optimizer_runs setting tuning
    - Use forge profile for performance analysis

    Development Workflow
    - Use forge init for new project setup
    - Implement forge build --watch for development
    - Use forge test --watch for TDD
    - Leverage forge fmt for code formatting
    - Use forge clean for fresh builds
    - Implement forge cache-clean when needed
    - Use forge config for environment management
    - Leverage forge remappings for clean imports
    - Use forge install for dependency management
    - Implement forge update for dependency updates
    - Use forge verify for contract verification
    - Leverage forge create for deployments
    - Use forge script for deployment automation
    - Implement chisel for quick testing

    Documentation
    - Use forge doc for documentation generation
    - Implement comprehensive NatSpec comments
    - Use forge inspect for contract analysis
    - Leverage README.md for project documentation
    - Use CHANGELOG.md for version tracking
    - Implement architecture decision records (ADRs)
    - Use diagrams for complex interactions
    - Leverage forge-doc for API documentation
    - Use inline comments for complex logic
    - Implement test documentation
    
golang
less
solidity
solidjs

First seen in:

lcanady/tunefi

Used in 1 repository

TypeScript
# Technical Expertise
Expert in:
- TypeScript & Node.js
- SolidStart & SolidJS ecosystem
- UI libraries: Solid-UI, Kobalte, Corvu
- Styling: Tailwind CSS
- AI/ML integration patterns
- LLM integration & prompt engineering
- Vector databases & semantic search
- WebSocket & real-time communication

# Code Architecture
- Favor functional and declarative programming
- Prioritize pure functions and immutability
- Structure components hierarchically:
  1. Exported component
  2. Subcomponents
  3. Helper functions
  4. Static content
  5. Type definitions
- Implement modular, DRY code patterns
- Follow SolidJS conventions for data fetching, rendering, and routing
- Separate concerns between UI, business logic, and data layers
- Implement feature flags for gradual rollouts
- Use dependency injection for better testability

# TypeScript Best Practices
- Use strict TypeScript for all code
- Prefer type aliases over interfaces
- Avoid 'any'; use specific types or unknown
- Replace enums with const maps/objects
- Leverage discriminated unions where appropriate
- Use type inference when obvious
- Implement branded types for type-safe IDs
- Use const assertions for literal types
- Leverage utility types for DRY type definitions
- Define strict return types for async functions

# AI Integration Patterns
- Implement proper token counting and management
- Structure system prompts for consistent outputs
- Handle streaming responses efficiently
- Implement proper error handling for AI calls
- Cache AI responses when appropriate
- Use vector embeddings for semantic search
- Implement retry logic for API failures

# Security Best Practices
- Implement proper input sanitization
- Use environment variables for sensitive data
- Implement rate limiting for API endpoints
- Validate user permissions at every level
- Sanitize AI outputs before rendering
- Implement proper CORS policies
- Use Content Security Policy headers

# Testing Strategy
- Write unit tests for utility functions
- Implement integration tests for API endpoints
- Use component testing for UI elements
- Implement E2E tests for critical paths
- Mock external services in tests
- Use proper test isolation
- Implement proper error boundary testing

# Performance Optimization
- Optimize component re-renders
- Implement proper memo usage
- Use lazy loading for routes/components
- Follow SolidJS performance best practices
- Consider bundle size impact
- Implement proper caching strategies
- Use proper indexing for database queries
- Optimize API response sizes
- Implement proper connection pooling

# Documentation
- Document complex business logic
- Add JSDoc comments for public APIs
- Document environment setup requirements
- Keep README files up to date
- Document deployment procedures
- Add inline comments for complex algorithms
- Document AI prompt templates

# Naming Conventions
- Components: PascalCase
- Functions: camelCase with auxiliary verbs (isLoading, hasError)
- Directories: kebab-case (auth-wizard, user-settings)
- Types: PascalCase with descriptive names
- Constants: SCREAMING_SNAKE_CASE
- Favor named exports over default exports

# Component Patterns
- Write functional components with explicit type definitions
- Use the "function" keyword for component declarations
- Implement proper prop typing
- Handle loading and error states
- Follow accessibility best practices

# UI/UX Implementation
- Use Tailwind with mobile-first responsive design
- Leverage Solid-UI, Kobalte, and Corvu components
- Follow semantic HTML structure
- Ensure keyboard navigation support
- Implement proper loading states and transitions

# State Management
- Use signals for reactive state
- Implement stores for global state
- Handle side effects with createEffect
- Use resource for data fetching
- Implement proper error boundaries
bun
css
dockerfile
golang
javascript
react
solidjs
tailwindcss
+2 more
spirit-led-software/theaistudybible

Used in 1 repository

TypeScript
# コーディング規約 v2.0

## 0. AIコード生成・リファクタリングの基本方針
### 品質保証のためのチェックリスト
- [ ] 型安全性の確保
  - 厳密な型定義とTypeScriptの機能を最大限活用
  - any型の使用を禁止
  - unknown型の適切な使用
    - unknown型を別の型に変換する場合は、型ガードを使用する

- [ ] パフォーマンス最適化
  - 不要なレンダリングの防止
  - メモ化の適切な使用
  - バンドルサイズの最適化
  - 画像の最適化
  - Suspenseの活用

- [ ] セキュリティ対策
  - XSS対策の実装
  - 適切なバリデーション
  - 機密情報の適切な取り扱い

### リファクタリング優先順位
1. セキュリティ関連の修正
2. パフォーマンスに影響する問題
3. 型安全性の向上
4. コードの可読性向上
5. 保守性の改善

### AIによるコード生成時の注意点
- 既存のコードベースとの一貫性を保持
- ベストプラクティスの適用
- エッジケースの考慮
- テスト容易性の確保
- アクセシビリティへの配慮

## 1. スタイリング
### CSSライブラリ
  - tailwindcss
    - 不正なクラス名を使用しないこと
      - 任意の値を設定する場合は `"w-[250px]"` のように記述する
      - 動的なスタイルはtwMergeを使用する
    - レスポンシブデザインの実装
      - sm:, md:, lg:, xl:のブレークポイントを適切に使用

### スタイルルール
  - 汎用コンポーネントには設計上不可欠なスタイルのみを適用し、変更可能なものは下層で行う
  - 要素間の余白は marginではなくgapで指定する
  - 要素を並べるとき、それぞれが固定幅ならGrid、変動するならFlexを使う
    - Gridを使うべきケース
      - 複雑なレイアウト(例: ダッシュボードやグリッドデザイン)
      - 明確な領域分けが必要な場合(例: ヘッダー、サイドバー、メインコンテンツ、フッターを持つレイアウト)
      - 等間隔に要素を配置したい場合(例: 画像ギャラリー、商品リスト)
    - Flexを使うべきケース
      - 単一方向のアイテム配置(例: ナビゲーションバーやボタンの横並び)
      - コンテンツサイズに応じたレイアウト調整(例: ボタンの中央揃えや要素の自動調整)
      - アイテムの順序を動的に変更したい場合(Flexはorderプロパティを使って順序を変更できる)
      - 中央揃えが必要なケース

## 2. コード品質
### 命名と型
  ### 命名規則の統一
    - 状態や関数、変数の命名は一貫性を持たせる
    - 状態変数の接頭辞
      - is: ブール値(例: isActive)
      - has: 所有フラグ(例: hasPermission)
      - can: 能力フラグ(例: canEdit)
      - should: 条件フラグ(例: shouldUpdate)
      - on: イベントハンドラ(例: onClick, onSubmit)
    - 関数の命名規則
      - 動詞から始める(例: fetchData, updateUser)
      - 副作用を伴う関数にはdoやexecuteなどを使用
    - 変数の命名規則
      - 配列の場合は複数形にする
      - APIレスポンスから取り出した変数は、元のデータとの関連が分かる名前にする
      - 同じ概念の異なるバリエーションは、その違いが分かる修飾語を付ける
      - 抽象的な命名を避ける
        - Bad: data, info, content, item
      - APIレスポンスのデータは具体的な内容を示す名前をつける
        - Bad: const data = await fetchUsers()
        - Good: const users = await fetchUsers()

  - 型はinterfaceではなくtypeを使って統一する
  - `import React from 'react'`は不要
  - importのtypeは明示的にする
    - 例: `import { SomeType } from 'xxx'`
  - コンポーネントはFCで型をつける
    - propsを受け取る場合は`FC<Props>`の形で型をつける
    - FCは明示的にimportする `import { FC } from 'react'`
  - Propsの型を定義する場合は、そのコンポーネントと同じファイル内に記述する
    - コンポーネントが1つの場合は`type Props = {}`として定義する
    - コンポーネントが複数の場合は`type コンポーネント名 + Props = {}`として定義する
    - 子コンポーネントのpropsを受け取る場合はComponentPropsを使用して子コンポーネントの型を再利用すること
      - 例: `type ComponentBProps = ComponentProps<typeof ComponentB>`
  - `map`メソッドの引数や型は実態に合ったものにすることで、読みやすく、タイプセーフなコードを目指す
    - 例: `const articles.map((article) => {})`

  ### コールバック関数の切り分け基準
    - map/filter/reduceなどの配列メソッドのコールバック関数は以下の基準を参考に判断する:

    1. インラインで記述する場合
      - 単純なプロパティの参照や変換
      - 単純な条件判定
      例:
      ```typescript
      // Good
      users.map((user) => user.name)
      items.filter((item) => item.isActive)
      users.map((user) => ({
        id: user.id,
        name: user.name,
      }))
      ```

    2. 関数を切り出す場合
      - 複数の変換や加工処理が必要な場合
      - 条件分岐やビジネスロジックを含む場合
      - 同じロジックを複数箇所で使用する場合
      - 型の明示的な指定が必要な場合
      例:
      ```typescript
      // Good
      const formatUserData = (user: User) => {
        const role = getRoleLabel(user.role)
        const permissions = user.permissions.map(getPermissionLabel)

        return {
          name: `${user.firstName} ${user.lastName}`,
          role,
          permissions,
          lastLoginAt: formatDate(user.lastLoginAt)
        }
      }

      // 使用例
      users
        .filter((user) => user.isActive)
        .map(formatUserData)
      ```

      注意点:
      - パフォーマンスへの影響が小さい場合は、可読性を優先する
      - 過度な関数の切り出しは避ける
      - 切り出した関数名は処理内容が明確に分かるものにする
      - mapの中でnullを返すような条件分岐は避け、事前にfilterで対象を絞り込む

### 可読性の向上
  - Props型の各プロパティに説明コメントを記述する
  - JSDocを使ってコンポーネント、関数の説明を記述する
    - @description: コンポーネントの説明 条件分岐がある場合は、その条件分岐の説明を記述する
    - @param: 引数の説明 プロパティ名 - 説明 の形式で記述する
    - @example: 使用例 (使用方法が複雑な場合は、コメントを記述する)
  - 条件分岐が複雑な場合は、if文の前後に説明コメントを記述する
    - 特に以下のケースではコメントを必須とする:
      - 否定演算子(!)を使用している場合
      - 複数の条件を組み合わせている場合
      - 列挙型やステータスに基づく分岐の場合
    - コメントの記述例:
      ```typescript
      // ユーザーが参加済みまたは顧客が待機中でない場合は処理を終了
      if (!(status === 'USER_JOINED' || status === 'CUSTOMER_WAITING')) {
        return
      }
      ```
  - マジックナンバーは定数として定義する
  - 左辺がnullまたはundefinedのみをデフォルト判定条件にしたい場合は、null合体演算子を使用する
  - 冗長なカスタムHookを作成しない
    - シンプルなロジックの場合は、コンポーネントに直接記述する

## 3. アーキテクチャ
### Next.jsのルーティング
  - Linkコンポーネントの使用
    - 静的な遷移にはnext/linkのLinkコンポーネントを使用
    - import Link from 'next/link'
    - <Link href="/">...</Link>

  - ダイナミックルーティング
    - [id]や[slug]などのダイナミックセグメントを使用する場合は、
      型安全性のために、paramsの型を定義すること
    例:
    ```typescript
    type Props = {
      params: {
        id: string
      }
    }
    ```
  - window.location.hrefの直接操作は避け、useRouterを使用すること
    - import { useRouter } from 'next/navigation'
    - const router = useRouter()
    - router.push("/")を使用

### ディレクトリ構造
  #### 基本構造
    - page.tsx: サーバーコンポーネント(prefetch用)
    - ○○○○Page.tsx: クライアントコンポーネント実装
    - ○○○○_components/: ページ固有のコンポーネント
    - ○○○○_hooks/: ページ固有のフック
    - components/: 汎用コンポーネント
    - features/: 機能別コンポーネント

  #### リファクタリングガイドライン
    - ドメイン知識を含むコンポーネントは共通パッケージではなく、各アプリの_componentsディレクトリで管理する
      - これにより:
        - ドメインの責務が明確になる
        - 機能に関連するコンポーネントが適切な場所に配置される
        - 意図しない再利用を防ぐことができる

### コンポーネントの構成とexportの制限
  - _componentsフォルダの設計
    - 必ずコンポーネントの親子関係とディレクトリ構造が同じになるように作成する(子コンポーネントは子ディレクトリに配置する)
    - コンポーネントを適切な粒度で分割すること
      - 1ディレクトリにつき1コンポーネントを配置する
        - コンポーネントのexportのルール
          - 必ずindex.tsを1階層につき1つ作成し、同階層のコンポーネントをindex.tsでexportすること
            export { ComponentA } from './ComponentA'
      - 子コンポーネントは子ディレクトリに分割する
    - 意図しない階層からのimportが防止
    - 2階層以上下のコンポーネントを使用しないこと
  例:
    ├ _components // その画面でしか使用しないコンポーネント
    │   ├ ComponentA
    │   │   ├ ComponentA.tsx // ComponentBとComponentCを使用する
    │   │   ├ ComponentB
    │   │   │   ├ ComponentB.tsx
    │   │   │   ├ index.ts
    │   │   │   └ index.ts
    │   │   ├ ComponentC
    │   │   │   ├ ComponentC.tsx
    │   │   │   └ index.ts
    │   └ index.ts
    ├ _hooks // その画面でしか使用しないフック
    │   ├ use****.ts
    │   └ index.ts
    └ page.tsx // ComponentAを使用する

  - featuresフォルダの設計
  features
  ├ common
  │ ├ XxxxSection.tsx
  │ └ XxxxSection.stories.tsx
  └ Form
    ├ XxxxForm.tsx
    └ XxxxForm.stories.tsx
    - 別の画面でも使い回すようなコンポーネントは、components または features ディレクトリに格納する
      - components: 汎用的・分類が難しいコンポーネントをここに配置
      - Authorization, Confirmation, Error, Loading, Notification, Pagination, Search, Validation など:分類が可能なコンポーネントはそれぞれディレクトリを命名し配置

## 4. 実装ガイドライン
### リファクタルール
  ### 破壊的な操作の禁止
    - 配列やオブジェクトに対して破壊的(mutative)な操作を行うメソッドや関数を使用しないこと
    - 例: push, pop, splice, sort, reverse など
    - 不変性を保つために、非破壊的(immutable)なメソッドや関数を優先する
    - 例: map, filter, reduce, concat, slice など
    - 状態管理においても破壊的な変更を避け、常に新しい状態オブジェクトを作成して返すこと

  ### 再代入の制限
    - 再代入を避けるため、可能な限りconstを使用する(letの使用は最小限に抑える)
      - 状態や変数が変更される可能性がある場合でも、再代入を避ける工夫を優先する

  ### コードの分割
    - 関数やコンポーネントが複雑化した場合、責務ごとに小さく分割する
    - コード分割をしすぎない
      - 過剰な分割はかえって管理が煩雑になるため、バランスを考慮する
      - 目安: 1つの関数やファイルが単一責務を超えた場合に分割する
    - 明確な命名規則を守る
      - 分割したコードを理解しやすくするため、適切な名前を付ける
      - 例: UserList の子コンポーネントは UserListItem のように、親子関係がわかる名前にする
    - 依存関係を明確にする
      - 分割したモジュール間の依存関係が複雑にならないようにする
      - コンポーネント間のデータフローを単純に保つ

  ### 条件分岐の簡略化
    - 条件分岐がネストしすぎないようにする
    - 早期リターンを活用してネストを減らす

  ### 画像
    - src/public配下に配置する

### コンポーネント設計
  #### 基本原則
    - レンダリング時の負荷を最小限にする
    - コンポーネント間の状態管理はStateのリフトアップを使用
    - 適切な粒度でのコンポーネント分割

  #### コンポーネントの責務分担
    - 親コンポーネント
      - データの受け取りと下層コンポーネントへの受け渡し
      - 全体のレイアウト管理
      - 子コンポーネント間の連携
    - 子コンポーネント
      - 受け取ったデータの加工・変換ロジック
      - UIの詳細な実装
      - コンポーネント固有のロジック

    ```typescript
    // Bad
    const ParentComponent = () => {
      return (
        <ChildComponent
          value={calculateValue(data)} // 親でデータを加工している
          label={formatLabel(text)}    // 親でフォーマット処理をしている
        />
      )
    }

    // Good
    const ParentComponent = () => {
      return (
        <ChildComponent
          data={data}     // 生データをそのまま渡す
          text={text}     // 加工が必要なデータも生のまま渡す
        />
      )
    }
    ```

  #### 条件分岐とレンダリング
    - 条件分岐は必要最小限のスコープに限定する
      ```typescript
      // Bad - コンポーネント全体を条件分岐でラップ
      if (!task.assignee) return null

      return (
        <div>
          <p>{task.title}</p>
          <div>
            <Assignee assignee={task.assignee} /> // assigneeが必要な箇所のみ条件分岐すべき
            <p>{task.createdAt}</p>
          </div>
        </div>
      )

      // Good - 条件分岐が必要な箇所のみをラップ
      return (
        <div>
          <p>{task.title}</p>
          <div>
            {task.assignee && <Assignee assignee={task.assignee} />}
            <p>{task.createdAt}</p>
          </div>
        </div>
      )
      ```

    - 理由:
      - 必要のない箇所まで条件分岐に含めると、表示可能なコンテンツまで非表示になってしまう
      - コードの可読性が低下する
      - 条件分岐の意図が不明確になる
      - パフォーマンスに影響を与える可能性がある

    - 例外:
      - データの読み込み中の表示制御
      - エラー時の表示制御
      - ページ全体で必要なデータが存在しない場合

  #### イベントハンドリング
  - エラーハンドリングがなく、シンプルなイベントハンドラの場合は、handle○○○○という関数を作成せず、DOMのonChangeやonClickなどの属性で直接ロジックを記述する
    - シンプルなイベントハンドラとは
      - 実行関数をラップするだけのもの
        - 例: const handleClick = () => { someFunction({...}) }
    - ロジックが複雑な場合は、DOMの外側に定義しても良い

### API関連
  - featureディレクトリには、fetchの責務は持たせない
  - データの取得
    - page.tsx(サーバー)ではcreatePrefetchを使用してprefetchを行う
    - ○○○○Page.tsx(クライアント)ではcreateUseQueryを使用してデータ取得を行う


## 5. テスト・開発ツール
### Storybookの使用法
  - APIのMockデータを使い、Storybookのargsに適用。Mock作成の手間を最小限に抑えることで他者とのデータ共有とテストの信頼性が向上
    - Mockデータは、`src/repositories/mocks` に `Customer.tsx` のようなファイルを作成し、取得関数を定義する
      - `export const createCustomerMock = (引数) => ({ モックの中身 })`
  - storyは1ディレクトリにつき1ファイルのみ作成する

## 7. エラー処理
### エラーハンドリング
- try-catchの適切な使用
- エラーの型定義
- ユーザーフレンドリーなエラーメッセージ

## 8. パフォーマンス最適化
### レンダリング最適化
- useMemo、useCallbackの適切な使用
- 不要なレンダリングの防止
- 仮想化の活用

### 画面遷移の最適化
- router.prefetchを使用して画面遷移を最適化する
  - ユーザーが遷移する可能性が高い関数では事前にprefetchする
    ```typescript
    // Bad - フォーム送信後の遷移先ページをprefetchしていない
    const handleSubmit = async () => {
      await submitForm(formData)
      router.push('/complete')
    }

    // Good - フォーム送信中に遷移先ページをprefetchする
    const handleSubmit = async () => {
      router.prefetch('/complete')
      await submitForm(formData)
      router.push('/complete')
    }
    ```

### データ取得の最適化
- キャッシュ戦略
- プリフェッチの活用
- ページネーションの実装
- 並列リクエストの活用

## 9. セキュリティ対策
### XSS対策
- dangerouslySetInnerHTMLの使用制限
- 入力値のサニタイズ
- Content Security Policyの設定

### CSRF対策
- トークンの適切な管理
- セッション管理
- Cookieの適切な設定

## 10. アクセシビリティ

### アクセシブルな説明の追加
- コンテンツの意味や目的を説明する属性を追加する
  - リスト形式のコンテンツには`aria-label`で説明を追加
    ```typescript
    // Good
    <div
      role="list"
      aria-label="処方内容リスト"
    >
    ```
  - 合計金額などの重要な情報には`aria-label`で補足説明を追加
    ```typescript
    // Good
    <p aria-label="処方箋合計金額">
      {prescription.amount}円
    </p>
    ```
  - データを表示する領域には`role`属性を適切に設定
    ```typescript
    // Good
    <div
      role="region"
      aria-label="処方内容詳細"
    >
    ```

### キーボード操作のサポート
- フォーカス管理
- ショートカットキーの実装
css
golang
javascript
next.js
react
storybook
tailwindcss
typescript

First seen in:

daminchan/Store-App

Used in 1 repository

TypeScript
Write documentation in english.
html
peg.js
typescript

First seen in:

RSamaium/CanvasEngine

Used in 1 repository