Awesome Cursor Rules Collection

Showing 2605-2616 of 2626 matches

TypeScript
Create a modern Next.js real estate website called "My Dream Home" with the following detailed specifications:

Core Requirements:

Use Next.js 14+ with TypeScript
Implement responsive design using Tailwind CSS
Include smooth animations using Framer Motion
Ensure SEO optimization
Implement modern UI/UX principles
Page Structure:

Homepage (index.js):
Sticky navigation with logo, menu items, and contact button
Full-width hero section with dynamic background and property search
Featured properties carousel
"Areas We Cover" section with interactive map
"Why Choose Us" section
Client testimonials
Call-to-action section for property consultation
Modern footer with sitemap, contact info, and social links
About Page:
Professional profile section for Sushil Bhardwaj
Career highlights and achievements
Professional certifications
Team member profiles with hover effects
Company values and mission statement
Image gallery of successful projects
Contact Page:
Interactive contact form with validation
Google Maps integration showing office location
Direct contact details (phone, email)
Office hours
Social media links
FAQ section
Property Search Page:
Advanced search filters (price, location, property type)
Interactive map showing property locations
Property cards with:
High-quality images
Basic details (price, beds, baths)
Location
Square footage
Amenities
Sort and filter options
Pagination or infinite scroll
Save/favorite functionality
Technical Specifications:

Use Next.js API routes for form handling
Implement data fetching using SWR or React Query
Add loading states and error boundaries
Include proper meta tags for SEO
Implement image optimization
Add proper form validation
Include accessibility features
Add Google Analytics integration
Design Elements:

Use a modern color scheme (suggest: #2C3E50, #E74C3C, #ECF0F1)
Implement subtle animations for user interactions
Use high-quality property images
Include micro-interactions
Implement skeleton loading states
Add hover effects on interactive elements
Please implement proper error handling, loading states, and responsive design for all pages.

Use uploaded images as inspration
analytics
css
golang
javascript
next.js
react
tailwindcss
typescript
jaskaran-online/sushilbhardwaj

Used in 1 repository

TypeScript
# アシスタント設定
- 役割: エキスパートプログラミングアシスタント
- 言語: 日本語(デフォルト)/ 英語
- フォーマット: Markdown

## 基本的にテスト駆動開発を行なってください。
- テストコードは`tests/`ディレクトリに作成してください。

## 応答フォーマット
1. 説明(マークダウン形式)
2. コードブロック(以下を含む):
   - 言語識別子
   - 編集対象ファイルパス
   - 変更箇所の前後のコンテキスト
3. 補足情報(必要な場合)

## コード編集ルール
1. 関連する変更箇所のみ表示
2. 関数のコンテキストを含める
3. 変更のない部分はコメントで省略
4. ファイル全体の表示は要求された場合のみ

## ファイル作成
- 常に完全なファイル内容を表示
- 言語とパスを含める: ```言語:パス/へ/ファイル

; ## タスク作成ルール
; 1. 対象ディレクトリで`tasks/todo/`ディレクトリが存在する場合は、`tasks/todo/`ディレクトリに作成。ない場合は、ディレクトリを作成してから作成。
; 2. フォーマット: NNN_タスク名.ts
; 3. 含めるべき内容:
;    - 概要
;    - 対象ファイル
;    - 目的
;    - 実装内容
;    - 注意点
;    - 想定される課題
;    - 参考情報
;    - ステータス
; - タスクは`tasks/doing/`ディレクトリに作成してください。
; - タスクは`tasks/done/`ディレクトリに移動してください。
; - タスクは`tasks/todo/`ディレクトリに作成してください。
; - できるだけタスクを消化してください。
; - 一つ一つのタスクは、小さく分割してください。一つが重く・大きくなりすぎないようにしてください。
; - ドキュメント作成系は`docs/`ディレクトリに作成するタスクにしてください。
; - 作成する際は、現在の最終番号を確認してください。タスク番号が重複しないようにしてください。

## CLIコマンド
- 必ずpwdで現在位置を確認
- 不明確な指示は確認を取る

## エラー処理
- 必要に応じて詳細を確認
- 詳細なエラーメッセージを提供
- 代替案を提案

## 要件⇄プログラム の同期
- 要件 と プログラムが一致しているか定期チェックを行なってください。要件は`docs/`ディレクトリに存在します。
- テストとプログラムが乖離している場合は、テストを修正してください。

## Next.jsについて
- デフォルトでは`tsconfig.json`に`"jsx": "preserve"`が設定されています。
- これは、`tsx`ファイルを`ts`ファイルとして扱うためのものです。
- ファイル・コンポーネントはできるだけ分割してください。
- 基本、React Server Componentを使用してください。
- Client Componentを使用する場合は、`use client`をつけてください。
- Client Componentは、最低限のコードのみを記述してください。

## パッケージマネージャー
- パッケージマネージャーは`pnpm`を使用してください。
- わからない場合は、lockファイルを見てください。pnpm: pnpm-lock.yaml, bun: bun.lockb, yarn: yarn.lock, npm: package-lock.json

## 命名規則
### データベース
- テーブル名: スネークケース(例: business_plans)
- カラム名: スネークケース(例: created_at)
- 外部キー: 参照先テーブル名の単数形_id(例: user_id)
- 列挙型: スネークケース(例: schedule_status)

### TypeScript/JavaScript
- 変数名: キャメルケース(例: createdAt)
- クラス名: パスカルケース(例: BusinessPlan)
- インターフェース名: パスカルケース(例: BusinessPlanInput)
- 型名: パスカルケース(例: ActionItem)
- 列挙型: パスカルケース(例: ScheduleStatus)
- 定数: 大文字スネークケース(例: MAX_RETRY_COUNT)

### 型変換
- データベース ⇄ TypeScript間の自動変換
  - スネークケース ⇄ キャメルケース
  - Date ⇄ ISO8601文字列
  - Array ⇄ JSON文字列

## データベース連携
### 型安全性
- 型定義の一貫性
  - フロントエンド型定義
  - API入力型定義
  - データベーススキーマ
  の3つで整合性を保つ

### 日付フォーマット
- データベース: timestamptz
- フロントエンド: Date型
- API: ISO8601文字列
- タイムゾーン: UTC

### オプショナル項目
- データベース: NULL許容
- TypeScript: Optional型(例: field?: string)
- バリデーション: zodスキーマで定義

### インデックスシグネチャ
- Record<string, unknown>の使用は避ける
- 具体的な型を指定する

### 配列のkey
- インデックスの使用は避ける
- タイムスタンプや一意なIDを使用

## エラーハンドリング
### 階層化されたエラー処理
- OpenAIエラー
- JSON解析エラー
- 型変換エラー
の順で処理

### エラー状態の型定義
- status: success/error/loading/pending
- data: 成功時のデータ
- error: エラー情報
- message: ユーザー向けメッセージ

## 認証・認可
### セッション管理
- supabase.auth.getUser()による統一的な認証
  - createClient()による認証クライアント取得
  - getUser()による認証チェック
  - cookieを使用しない認証
  - エラーハンドリング
    - userError || !user による統一的なチェック
    - 401エラーレスポンス
  - ユーザーIDの取得
    - user.id による一貫した参照

### エラーレスポンス
- 401: 認証が必要
- 403: アクセス権限なし
- 404: リソースが存在しない
- エラーメッセージの統一
  - message: エラーメッセージ
  - code: エラーコード
  - details: 詳細情報(オプション)
bun
css
java
javascript
next.js
npm
openai
plpgsql
+5 more

First seen in:

yu-Yoshiaki/coo-maeda

Used in 1 repository

TypeScript
You are an expert in Backstage web development, with deep knowledge of TypeScript, Node.js, React, Material-UI, and the Backstage plugin architecture. Your role is to assist developers in creating efficient, maintainable, and scalable Backstage plugins and components.

Code Style and Structure:
- Write concise, technical TypeScript code with accurate examples tailored for Backstage.
- Use functional and declarative programming patterns; avoid classes unless necessary for Backstage-specific implementations.
- Prefer iteration and modularization over code duplication.
- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
- Structure files according to Backstage conventions: plugin entry point, components, hooks, api handlers, types.

Naming Conventions:
- Follow Backstage naming conventions for plugins, components, and files.
- Use PascalCase for component names and camelCase for functions and variables.
- Prefix plugin-specific components with the plugin name (e.g., CatalogTable).

TypeScript Usage:
- Use TypeScript for all code; prefer interfaces over types when defining shapes.
- Leverage Backstage's built-in types and interfaces where applicable.
- Implement proper type checking for API responses and component props.

Syntax and Formatting:
- Use arrow functions for component definitions and handlers.
- Employ destructuring for props and state to enhance readability.
- Utilize optional chaining and nullish coalescing for cleaner code.

UI and Styling:
- Use Material-UI components and theming system as per Backstage guidelines.
- Implement responsive design using Material-UI's Grid and Box components.
- Utilize Backstage's common components (e.g., InfoCard, ErrorBoundary) where appropriate.

Backstage-specific Practices:
- Implement plugins following the Backstage plugin architecture.
- Use the Backstage backend system for API integrations and data fetching.
- Leverage Backstage's authentication and authorization mechanisms.
- Implement proper error handling and loading states in UI components.

Performance Optimization:
- Use React.memo() for expensive components that don't need frequent re-renders.
- Implement code splitting for large plugins using React.lazy() and Suspense.
- Optimize data fetching by using SWR or React Query for client-side caching.

Key Conventions:
- Follow Backstage's plugin development lifecycle (setup, development, testing, publishing).
- Use Backstage CLI for generating boilerplate code and running development tasks.
- Implement proper configuration options for plugins using app-config.yaml.
- Write unit and integration tests using Jest and React Testing Library.

Always refer to the latest Backstage documentation for best practices and conventions. When providing code examples or explanations, ensure they align with Backstage's architecture and design principles.

References:

The `backstage.io/techdocs-entity` annotation is used in Backstage to reference TechDocs from another entity. Here are the key points about this annotation. It allows you to reference TechDocs from a single source without duplicating the documentation or needing multiple builds of the same docs[1].

```yaml
metadata:
  annotations:
  backstage.io/techdocs-entity: component:default/example
```

YAML examples for the main API types supported by Backstage: OpenAPI, AsyncAPI, GraphQL, and gRPC.

## OpenAPI Example

```yaml
apiVersion: backstage.io/v1alpha1
kind: API
metadata:
  name: petstore-api
  description: The Petstore API
spec:
  type: openapi
  lifecycle: production
  owner: team-pets
  definition: |
      openapi: 3.0.0
      info:
        title: Petstore API
        version: 1.0.0
      paths:
        /pets:
          get:
            summary: List all pets
            responses:
              '200':
                description: A list of pets
                content:
                  application/json:
                    schema:
                      type: array
                      items:
                        $ref: '#/components/schemas/Pet'
      components:
        schemas:
          Pet:
            type: object
            properties:
              id:
                type: integer
              name:
                type: string
```

## AsyncAPI Example

```yaml
apiVersion: backstage.io/v1alpha1
kind: API
metadata:
  name: streetlights-api
  description: The Streetlights API
spec:
  type: asyncapi
  lifecycle: production
  owner: team-iot
  definition: |
    asyncapi: 2.0.0
    info:
      title: Streetlights API
      version: 1.0.0
    channels:
      light/measured:
        publish:
          summary: Inform about environmental lighting conditions of a particular streetlight.
          message:
            payload:
              type: object
              properties:
                lumens:
                  type: integer
                  minimum: 0
                  description: Light intensity measured in lumens.
                sentAt:
                  type: string
                  format: date-time
                  description: Date and time when the message was sent.
```

## GraphQL Example

```yaml
apiVersion: backstage.io/v1alpha1
kind: API
metadata:
  name: starwars-api
  description: The Star Wars GraphQL API
spec:
  type: graphql
  lifecycle: production
  owner: team-movies
  definition: |
    type Query {
      hero(episode: Episode): Character
      droid(id: ID!): Droid
    }

    enum Episode {
      NEWHOPE
      EMPIRE
      JEDI
    }

    interface Character {
      id: ID!
      name: String!
      friends: [Character]
      appearsIn: [Episode]!
    }

    type Human implements Character {
      id: ID!
      name: String!
      friends: [Character]
      appearsIn: [Episode]!
      homePlanet: String
    }

    type Droid implements Character {
      id: ID!
      name: String!
      friends: [Character]
      appearsIn: [Episode]!
      primaryFunction: String
    }
```

## gRPC Example

```yaml
apiVersion: backstage.io/v1alpha1
kind: API
metadata:
  name: helloworld-api
  description: The Hello World gRPC API
spec:
  type: grpc
  lifecycle: production
  owner: team-greetings
  definition: |
      syntax = "proto3";

      package helloworld;

      service Greeter {
        rpc SayHello (HelloRequest) returns (HelloReply) {}
      }

      message HelloRequest {
        string name = 1;
      }

      message HelloReply {
        string message = 1;
      }
```
dockerfile
graphql
html
javascript
jest
less
makefile
material-ui
+2 more

First seen in:

echohello-dev/backstage

Used in 1 repository

Ruby
You are an expert in Ruby on Rails, PostgreSQL, Hotwire (Turbo and Stimulus), and Tailwind CSS.

Code Style and Structure
- Write concise, idiomatic Ruby code with accurate examples.
- Follow Rails conventions and best practices.
- Use object-oriented and functional programming patterns as appropriate.
- Prefer iteration and modularization over code duplication.
- Use descriptive variable and method names (e.g., user_signed_in?, calculate_total).
- Structure files according to Rails conventions (MVC, concerns, helpers, etc.).

Naming Conventions
- Use snake_case for file names, method names, and variables.
- Use CamelCase for class and module names.
- Follow Rails naming conventions for models, controllers, and views.

Ruby and Rails Usage
- Use Ruby 3.3 features when appropriate (e.g., pattern matching, endless methods).
- Leverage Rails' built-in helpers and methods.
- Use ActiveRecord effectively for database operations.

JavaScript
- JavaScript functionality should be added into existing StimulusJS controllers or new controllers
- These are in app/javascript/controllers

Configuration
- For runtime configuration from env vars, or Rails secrets, use Anyway::Config
- For new config/configs classes, use a subclass of ApplicationConfig

Syntax and Formatting
- Follow the Ruby Style Guide (https://rubystyle.guide/)
- Use Ruby's expressive syntax (e.g., unless, ||=, &.)
- Prefer double quotes for strings

Error Handling and Validation
- Use exceptions for exceptional cases, not for control flow.
- Implement proper error logging and user-friendly messages.
- Use ActiveModel validations in models.
- Handle errors gracefully in controllers and display appropriate flash messages.

UI and Styling
- Use Hotwire (Turbo and Stimulus) for dynamic, SPA-like interactions.
- Implement responsive design with Tailwind CSS.
- Use Rails view helpers and partials to keep views DRY.

Performance Optimization
- Use database indexing effectively.
- Implement caching strategies (fragment caching, Russian Doll caching).
- Use eager loading to avoid N+1 queries.
- Optimize database queries using includes, joins, or select.

Key Conventions
- Follow RESTful routing conventions.
- Use concerns for shared behavior across models or controllers.
- Implement service objects for complex business logic.
- Use background jobs (e.g., Sidekiq) for time-consuming tasks.

Testing
- Write comprehensive tests using Minitest.
- Follow TDD/BDD practices.
- Add new fixtures as necessary

Security
- Implement proper authentication and authorization (e.g., Devise, Pundit).
- Use strong parameters in controllers.
- Protect against common web vulnerabilities (XSS, CSRF, SQL injection).

Follow the official Ruby on Rails guides for best practices in routing, controllers, models, views, and other Rails components.
express.js
java
javascript
less
postgresql
rest-api
ruby
shell
+1 more
scopeandgo/jumpstartpro_generators

Used in 1 repository

TypeScript
unknown
# AI Agent Creator Instructions for Crew AI Framework

Crew AI is a framework for orchestrating role-based autonomous AI agents. Your primary role is to help create and orchestrate crews of AI agents that work together to accomplish complex tasks. This involves:

1. **Planning**: First, plan the Crew structure, defining the roles, tasks, and tools needed for each agent based on the user's requirements. Ask for clarification if anything is unclear.
2. **Project Structure**: Create appropriate project structure following Python best practices.
3. **Agent Development**: Create agents with specific roles, goals, and backstories.
4. **Task Creation**: Define clear, atomic tasks for agents to work on.
5. **Tool Integration**: Integrate necessary tools and APIs for agents to use.
6. **Crew Assembly**: Create the crew by combining agents and defining their interactions.
7. **Testing**: Test the crew's performance and agent interactions.
8. **Iteration**: Refine the crew based on user feedback until desired performance is achieved.

You will find detailed guidance for each step below.

# Step 1: Planning

Before proceeding with implementation, ensure you have the following information:

- The overall goal and purpose of the crew
- The specific roles needed within the crew
- The tasks each agent needs to accomplish
- Required tools and APIs for the agents
- How agents should collaborate and share information

If any information is missing, ask the user for clarification.

# Step 1: Installation and Setup

## Python Version Requirements

CrewAI requires Python >=3.10 and <=3.13. Check your version:

```bash
python3 --version
```

If you need to update Python, visit python.org/downloads

## Installing CrewAI

1. **Install CrewAI**
   Install CrewAI with all recommended tools using either method:

   ```bash
   pip install 'crewai[tools]'
   ```
   or
   ```bash
   pip install crewai crewai-tools
   ```

2. **Upgrade CrewAI (Existing Installations Only)**
   If you have an older version installed:

   ```bash
   pip install --upgrade crewai crewai-tools
   ```

   If you see a Poetry-related warning, migrate to the new dependency manager:
   ```bash
   crewai update
   ```

3. **Verify Installation**
   Check your installed versions:
   ```bash
   pip freeze | grep crewai
   ```
   You should see something like:
   ```
   crewai==X.X.X
   crewai-tools==X.X.X
   ```

## Creating a New Project

We recommend using the YAML Template scaffolding for a structured approach:

1. **Generate Project Structure**
   ```bash
   crewai create crew <project_name>
   ```

   This creates a new project with the following structure:
   ```
   my_project/
   ├── .gitignore
   ├── pyproject.toml
   ├── README.md
   ├── .env
   └── src/
       └── my_project/
           ├── __init__.py
           ├── main.py
           ├── crew.py
           ├── tools/
           │   ├── custom_tool.py
           │   └── __init__.py
           └── config/
               ├── agents.yaml
               └── tasks.yaml
   ```

2. **Essential Files**:
   - `agents.yaml`: Define your AI agents and their roles
   - `tasks.yaml`: Set up agent tasks and workflows
   - `.env`: Store API keys and environment variables
   - `main.py`: Project entry point and execution flow
   - `crew.py`: Crew orchestration and coordination
   - `tools/`: Directory for custom agent tools

# Step 2: Project Structure

Create a well-organized project structure:

```
project_name/
├── agents/
│   ├── __init__.py
│   └── agent_definitions.py
├── tasks/
│   ├── __init__.py
│   └── task_definitions.py
├── tools/
│   ├── __init__.py
│   └── custom_tools.py
└── crew.py
```

# Step 3: Agent Development

To create effective agents, follow these guidelines:

1. **Define Clear Roles**: Each agent should have a specific role and expertise:

```python
from crewai import Agent

researcher = Agent(
    role='Research Analyst',
    goal='Conduct thorough research and analysis',
    backstory='Experienced research analyst with expertise in data analysis',
    verbose=True
)
```

2. **Agent Parameters**:
   - role: The agent's professional role
   - goal: The agent's primary objective
   - backstory: Context and expertise
   - tools: List of tools available to the agent
   - allow_delegation: Whether the agent can delegate tasks
   - verbose: Enable detailed logging

# Step 4: Task Creation

Create well-defined tasks for your agents:

```python
from crewai import Task

research_task = Task(
    description='Conduct market research on [specific topic]',
    agent=researcher,
    context='Focus on market trends and competitor analysis',
    expected_output='Detailed market analysis report'
)
```

Task parameters:
- description: Clear task description
- agent: Assigned agent
- context: Additional context or constraints
- expected_output: Desired output format
- tools: Specific tools for the task

# Step 5: Tool Integration

Create custom tools by extending CrewAI's tool system:

```python
from crewai import Tool

custom_tool = Tool(
    name='tool_name',
    description='Tool description',
    func=your_function
)
```

# Step 6: Crew Assembly

Create and configure your crew:

```python
from crewai import Crew

crew = Crew(
    agents=[agent1, agent2],
    tasks=[task1, task2],
    verbose=True
)

result = crew.kickoff()
```

Crew parameters:
- agents: List of agents in the crew
- tasks: List of tasks to be performed
- verbose: Enable detailed logging

# Step 7: Testing

Test your crew implementation:
1. Start with simple, isolated tasks
2. Gradually increase complexity
3. Monitor agent interactions
4. Verify output quality
5. Test error handling

# Step 8: Best Practices

1. **Agent Design**:
   - Give agents specific, focused roles
   - Provide clear, achievable goals
   - Write detailed backstories
   - Assign appropriate tools

2. **Task Design**:
   - Break down complex tasks
   - Provide clear context
   - Define expected outputs
   - Set reasonable constraints

3. **Tool Integration**:
   - Create reusable tools
   - Document tool usage
   - Handle errors gracefully
   - Test tool reliability

4. **Crew Management**:
   - Monitor agent interactions
   - Optimize task sequences
   - Handle failures gracefully
   - Document crew behavior

Remember to test thoroughly and iterate based on performance and user feedback.
golang
python
epireve/agent-boilerplate

Used in 1 repository

unknown
# AI Assistant Technical Instructions

You are an AI assistant with advanced problem-solving capabilities. Please follow these instructions to execute tasks efficiently and accurately.

First, confirm the instructions received from the user:
<instructions>
{{instructions}}
</instructions>

Please proceed with the following process based on these instructions:

---

## 1. Instruction Analysis and Planning
<Task Analysis>
- Summarize the main tasks concisely
- Review the specified tech stack and consider implementation methods within those constraints  
  **Note: Do not change versions listed in the tech stack without approval**
- Identify key requirements and constraints
- List potential challenges
- Enumerate specific steps for task execution in detail
- Determine the optimal execution order for these steps

### Preventing Duplicate Implementation
Before implementation, verify:
- Existence of similar functionality
- Functions or components with identical or similar names
- Duplicate API endpoints
- Identification of processes that can be shared

Take sufficient time for this section as it guides the entire subsequent process. Conduct thorough and comprehensive analysis.
</Task Analysis>

---

## 2. Task Execution
- Execute identified steps one by one
- Report progress concisely after completing each step
- Pay attention to the following during implementation:
  - Adherence to proper directory structure
  - Consistency in naming conventions
  - Appropriate placement of shared processes

---

## 3. Quality Control and Problem Resolution
- Quickly verify the execution results of each task
- If errors or inconsistencies occur, address them through the following process:
  a. Problem isolation and cause identification (log analysis, debug information verification)
  b. Creation and implementation of countermeasures
  c. Post-fix operation verification
  d. Debug log confirmation and analysis

- Record verification results in the following format:
  a. Verification items and expected results
  b. Actual results and discrepancies
  c. Required countermeasures (if applicable)

---

## 4. Final Confirmation
- Evaluate the entire deliverable once all tasks are completed
- Verify consistency with original instructions and make adjustments as needed
- Perform final confirmation that there are no duplicates in implemented functions

---

## 5. Results Report
Please report final results in the following format:
markdown
# Execution Results Report

## Overview
[Brief description of overall summary]

## Execution Steps
1. [Step 1 description and results]
2. [Step 2 description and results]
...

## Final Deliverables
[Details of deliverables, links if applicable]

## Issue Resolution (if applicable)
- Problems encountered and responses
- Future considerations

## Notes & Improvement Suggestions
- [List any observations or suggestions for improvement]


---

## Important Notes

- Always confirm any unclear points before beginning work
- Report and obtain approval for any important decisions as they arise
- Report unexpected problems immediately and propose solutions
- **Do not make changes that are not explicitly instructed.** If changes seem necessary, first report them as proposals and implement only after approval
- **UI/UX design changes (layout, colors, fonts, spacing, etc.) are prohibited** unless approved after presenting justification
- **Do not arbitrarily change versions listed in the tech stack** (APIs, frameworks, libraries, etc.). If changes are necessary, clearly explain the reason and wait for approval before making any changes

---

# Tech Stack

## Core Technologies
- **AI Model: GPT-4**

## Frontend
- Flutter: ^3.22.0

### State Management
- Riverpod: ^2.6.1

## BaaS
- Firebase
---


---

## Project Structure

Please implement following this directory structure:

lib/features/products/
├── data/
│   ├── models/
│   │   ├── product_dto.dart
│   │   └── product_category_dto.dart
│   └── product_repository.dart
├── presentation/
│   ├── screens/
│   │   ├── product_list_screen.dart
│   │   └── product_details_screen.dart
│   ├── controllers/
│   │   └── product_list_controller.dart
│   ├── widgets/
│       └── product_card.dart
├── domain/
│   ├── models/
│   │   ├── product.dart
│   │   └── product_category.dart
│   └── get_products_use_case.dart
└── shared/
    └── models/
        └── address.dart


## Placement Rules
### Flutter Project Structure Placement Rules

This document outlines the placement rules for files and folders within the recommended Flutter project structure, focusing on scalability, maintainability, and adherence to Clean Architecture principles.

#### Top-Level Structure

lib/
├── features/
├── models/
├── providers/
├── routes/
├── core/
├── app.dart
└── main.dart


*   **lib/**: Contains all Dart code.
*   **features/**: Feature-specific code.
*   **models/**: Global models (use sparingly).
*   **providers/**: Global providers (minimize use).
*   **routes/**: App navigation.
*   **core/**: Core app logic (networking, errors, DI).
*   **app.dart**: Root widget.
*   **main.dart**: Entry point.

#### features/ Structure
lib/features/
└── <feature_name>/
├── data/
│   ├── models/
│   └── <feature_name>_repository.dart
├── presentation/
│   ├── screens/
│   ├── controllers/
│   ├── widgets/
├── domain/
│   ├── models/
│   └── <feature_name>.dart
├── use_cases/
└── shared/
└── models/

*   **<feature_name>/**: A feature (e.g., authentication, products).
*   **data/**: Data access.
    *   **models/**: Data Transfer Objects (DTOs).
    *   **<feature_name>_repository.dart**: Data access logic.
*   **presentation/**: UI.
    *   **screens/**: UI screens (<feature_name>_<screen_name>_screen.dart).
    *   **controllers/**: State management (<feature_name>_controller.dart).
    *   **widgets/**: Feature-specific widgets (<widget_name>.dart).
*   **domain/**: Business logic.
    *   **models/**: Domain models.
    *   **<feature_name>.dart**: Main entity.
*   **use_cases/**: User interactions (<use_case_name>.dart).
*   **shared/models/**: Models shared between *related* features.

#### shared/ (Top-Level) Structure

lib/shared/
├── providers/
├── widgets/
├── models/
└── services/

*   **providers/**: Providers shared across *unrelated* features.
*   **widgets/**: Widgets shared across *unrelated* features.
*   **models/**: Models shared across *unrelated* features (use cautiously).
*   **services/**: Utility classes.

#### models/ (Top-Level) Structure

lib/models/
└── <model_name>.dart

*   Global models (use sparingly).

#### providers/ (Top-Level) Structure

lib/providers/
└── <provider_name>.dart

*   Global providers (minimize use).

#### core/ Structure

lib/core/
├── network/
│   └── api_client.dart
├── errors/
│   └── exceptions.dart
└── di/
└── injection.dart

*   **network/**: Networking code.
*   **errors/**: Error handling.
*   **di/**: Dependency injection.

## Naming Conventions

*   **Files:** snake_case (e.g., product_list_screen.dart).
*   **Classes:** PascalCase (e.g., ProductListScreen).
*   **Variables/Functions:** camelCase (e.g., productList).

## Key Principles

*   **Feature Isolation:** Self-contained feature code.
*   **Separation of Concerns:** Separate data, logic, and UI.
*   **Single Responsibility:** One purpose per class/file.
*   **DRY:** Avoid code duplication.
*   **Prefer Feature-Specific:** Prioritize feature-level placement.


Please adhere to the above content when executing tasks.
firebase
golang
less

First seen in:

PatrickJS/awesome-cursorrules

Used in 1 repository

Solidity
This is a repository for getting started with the MetaMask Delegation Toolkit.

## The following is pasted directly from the docs/docs/get-started/llm-intro.md file, and should be
replaced as that file is updated.

# MetaMask Delegation Toolkit LLM introduction

The following text is a condensed introduction to the MetaMask Delegation Toolkit, for use in an
LLM's limited context.

Copy the following text by selecting the copy icon in the upper right corner of the text block:

````markdown
This is a software toolkit for developing applications for the Ethereum Virtual Machine (EVM) in a
novel way, where users of the application have embedded "delegator" accounts, which are smart
contract accounts adhering to ERC-4337. Users can sign "delegations" to other addresses, either
granting them unconditional permissions, or creating "offers," by writing enforcement terms around
the permission's usage.

By putting the responsibility of permissions management onto the individual users' accounts, you can
reduce the complexity of the business logic in your smart contracts, and you can express any custom
authorization-related code as `CaveatEnforcer` contracts. Core business logic may still deal with
ownership and transfer rights, but you can use the toolkit to express the logic around delegations,
offers, and caveats.

Additionally, any holder of a delegation message from one of these accounts can re-delegate that
permission or offer, even with additional terms, creating an invitation link experience that can be
used to invite new users to the system to enjoy some permissions without the need for them to have a
pre-existing crypto account.

A delegator account can be initialized "counterfactually" (without any gas, because its address is
deterministic from the signatory's address and the salt), and can even grant delegations to other
accounts before it's been put on-chain. The account redeeming a delegation is the one that ends up
needing to put the delegating account on-chain (and any intermediate delegating accounts, as these
delegations can be chained).

Let's look at how you can initialize a delegator account using the MetaMask Delegation Toolkit.

First, install Viem and the toolkit's modules into your project:

```bash
yarn add viem delegator-core-viem delegator-shared && yarn add viem @codefi/delegator-core-viem
```

Then, import the modules and initialize a burner account (you can back it up later):

```typescript
import { http } from "viem";
import { privateKeyToAccount, generatePrivateKey } from "viem/accounts";
import {
  Implementation,
  createDeleGatorClient,
  PimlicoVerifyingPaymasterSponsor,
  createBundlerClient,
  createRootDelegation,
  createAction,
  type DeleGatorClient,
  type DelegationStruct,
  type UserOperationV07,
  getExplorerAddressLink,
  getExplorerTransactionLink,
} from "delegator-core-viem";

const transport = http();
const deploySalt = 0x1n; // Can be any BigInt value.

const privateKey: Hex = generatePrivateKey();
const signatory = privateKeyToAccount(privateKey);

const viemClient = createDeleGatorClient({
  transport,
  chain,
  account: {
    implementation: Implementation.Hybrid,
    deployParams: [signatory.address, [], [], []],
    deploySalt,
    isDeployed: false,
    signatory,
  },
});
```

## Send a user operation

The following example demonstrates how to send a user operation using the toolkit:

```typescript
const userOp = await client.createUserOp(
  data,
  {
    verificationGasLimit: 100000000n,
    preVerificationGas: 100000000n,
    callGasLimit: 100000000n,
  }
);

const bundlerUrl = "<bundler-url>";
const bundler = createBundlerClient(bundlerUrl);

const hash = await bundler.sendUserOp(
  userOp,
  client.account.environment.EntryPoint,
)

const { result: receipt } = await bundler.pollForReceipt(hash);
console.log(receipt.receipt.transactionHash);
```

:::warning
In this example, `verificationGasLimit`, `preVerificationGas`, and `callGasLimit` are set to
arbitrarily high values. This might result in overpayment for the user operation, and might even
cause the bundler to reject the user operation, so we recommend replacing these values with a
correct estimate before submitting to the bundler.
:::

## Create a delegation

A delegation is an instance of `DelegationStruct`, where `delegator` is the account granting
permission to the `delegate` account. Here's a simple example of creating a delegation without any
caveats:

```typescript
import {
  createRootDelegation,
} from "delegator-core-viem";

const delegatorAddress = "0x1234..."; // The address of the delegator account
const delegateAddress = "0x5678..."; // The address of the delegate account

const delegation = createRootDelegation(
  delegateAddress,
  delegatorAddress
);
```

This creates a basic delegation where the `delegateAddress` is granted full permissions to act on
behalf of the `delegatorAddress`. However, it's important to note that this delegation has no
restrictions or caveats applied to it.

## Apply caveats to a delegation

While the previous example demonstrates a simple delegation, granting unrestricted access is
generally not recommended. It's crucial to apply caveats to limit the scope of the delegated
permissions.

Caveat enforcers are solidity contracts that extend the `ICaveatEnforcer.sol` interface, and are
passed to the delegation struct to enable fine-grained control over delegated permissions.

Here's an example of how to apply a caveat to a delegation:

```typescript
import {
  createRootDelegation,
} from "delegator-core-viem";

const delegatorAddress = "0x1234...";
const delegateAddress = "0x5678...";
const limitedCallsEnforcerAddress = "0x4CE4..."; // Address of the LimitedCallsEnforcer contract

const caveat = {
  enforcer: limitedCallsEnforcerAddress,
  terms: encodeAbiParameters([{ type: "uint256" }], [2]), // Limit to 2 calls
  args: "0x"
};

const delegation = createRootDelegation(
  delegateAddress,
  delegatorAddress,
  undefined, // No specific authority
  [caveat] // Array of caveats
);
```

This example applies the `LimitedCallsEnforcer` caveat, which restricts the delegate to only two
calls using this delegation. This demonstrates how caveats can be used to add specific restrictions
to a delegation.

You can apply multiple caveats to a single delegation by adding more caveat objects to the array,
allowing for highly customizable access control.

## Create a custom caveat enforcer

While the MetaMask Delegation Toolkit provides several out-of-the-box caveat enforcers, you can
create custom ones for more specific needs:

1. Create a contract that extends the `ICaveatEnforcer.sol` interface.
2. Implement the required functions, such as `beforeHook` and `afterHook`.

Here's a basic example of a custom caveat enforcer:

```solidity
// This enforcer provides functionality to enforce a limit on the number of times a delegate may
// perform transactions on behalf of the delegator.
contract LimitedCallsEnforcer is CaveatEnforcer {

  mapping(address delegationManager => mapping(bytes32 delegationHash => uint256 count)) public callCounts;

  event IncreasedCount(address indexed sender, bytes32 indexed delegationHash, uint256 limit, uint256 callCount);
 
  function beforeHook(
    bytes calldata _terms, // Maximum number of times the delegate can redeem the delegation.
    bytes calldata,
    Action calldata,
    bytes32 _delegationHash, // Hash of the delegation being operated on.
    address,
    address
  )
    public
    override
  {
    uint256 limit_ = getTermsInfo(_terms);
    uint256 callCounts_ = ++callCounts[msg.sender][_delegationHash];
    require(callCounts_ <= limit_, "LimitedCallsEnforcer:limit-exceeded");
    emit IncreasedCount(msg.sender, _delegationHash, limit_, callCounts_);
  }
```

This example shows a `LimitedCallsEnforcer` that restricts the number of times a delegate can
perform transactions on behalf of the delegator.

## Concepts

### Delegation

Delegation allows an account owner (the delegator) to grant permission to another account to perform
specific actions on their behalf. Delegations can include caveats to apply rules and restrictions.

A delegation conforms to the following structure:


```typescript
export type DelegationStruct = {
  delegate: Hex; // The account that receives permissions to perform actions on behalf of another account.
  delegator: Hex; // The account that assigns the permission to another account.
  authority: Hex; // The authority under which the delegation is made. The default is ROOT_AUTHORITY.
  caveats: CaveatStruct[]; // An array of caveat enforcers.
  salt: bigint; // A unique value to ensure the uniqueness of the delegation.
  signature: Hex; // The cryptographic signature that verifies the delegation.
};
```

### Caveat Enforcers

Caveat enforcers apply specific conditions or restrictions to a delegation. The MetaMask Delegation
Toolkit provides several out-of-the-box caveat enforcers, including:

- `AllowedCalldataEnforcer.sol`
- `AllowedMethodsEnforcer.sol`
- `AllowedTargetsEnforcer.sol`
- `BlockNumberEnforcer.sol`
- `DeployedEnforcer.sol`
- `ERC20TransferAmountEnforcer.sol`
- `ERC20BalanceGteEnforcer.sol`
- `NonceEnforcer.sol`
- `LimitedCallsEnforcer.sol`
- `IdEnforcer.sol`
- `TimestampEnforcer.sol`
- `ValueLteEnforcer.sol`

Each of these enforcers provides specific functionality to limit and control delegated actions.

## Paid delegations

Sometimes you may want to require a user to pay for a delegation. You can do this by using the
`NativePaidEnforcer` to accept that EVM chain's native token as payment for the delegation.

```typescript
// Start by initializing two clients, one for the delegator and one for the delegate.
const createCounterfactualDelegatorClient = () => {
  const privateKey = generatePrivateKey();
  const owner = privateKeyToAccount(privateKey);

  const viemClient = createDeleGatorClient({
    transport: http(),
    chain,
    account: {
      implementation: Implementation.Hybrid,
      deployParams: [owner.address, [], [], []],
      isAccountDeployed: false,
      signatory: owner,
      deploySalt: SALT,
    },
  });

  return viemClient;
};

const delegatorClient = createCounterfactualDelegatorClient();
const delegateClient = createCounterfactualDelegatorClient();

// Set up payment terms
const paymentAmount = 0.1 ether;
const paymentTerms = PaymentTerms({ amount: paymentAmount, recipient: address(users.alice.deleGator) });

// Create caveat with payment terms
const paymentCaveat = Caveat({ 
    enforcer: address(paidEnforcer), 
    terms: abi.encode(paymentTerms), 
    args: hex"" 
});

// Create delegation with payment caveat
const delegation = createRootDelegation(
  delegateClient.account.address,
  delegatorClient.account.address,
  {
    caveats: [paymentCaveat]
  }
);

// Sign delegation
const signedDelegation = await delegatorClient.signDelegation(delegation);

// Create action
const action = createAction(
    to: address(someContract),
    value: 0,
    data: abi.encodeWithSelector(SomeContract.someMethod.selector)
);

// Redeem delegation
delegateClient.redeemDelegation([signedDelegation], action);
```

This example demonstrates creating a delegation with a `NativePaidEnforcer` caveat, signing it, and
using it to execute an action. The caveat ensures that Bob pays Alice 0.1 ether when using the
delegation.

You can create your own conditional caveat enforcer using the `afterHook` function when defining a
custom `CaveatEnforcer` contract. For example, to make sure that the delegator owns a specific NFT
before allowing the delegation to be used (enabling any action that results in owning that NFT), you
could do something like this:

```solidity
import { CaveatEnforcer } from "@delegator/src/enforcers/CaveatEnforcer.sol";
import { Action } from "@delegator/src/utils/Types.sol";
import { IERC721 } from "@openzeppelin/contracts/token/ERC721/IERC721.sol";

contract NFTOwnershipEnforcer is CaveatEnforcer {
  struct OwnershipTerms {
    address nftContract;
    uint256 tokenId;
  }

  error NotNFTOwner(address account, address nftContract, uint256 tokenId);

  function beforeHook(
    bytes calldata _terms,
    bytes calldata,
    Action calldata,
    bytes32,
    address,
    address _redeemer
  ) external view override returns (bool) {
    return true;
  }

  function afterHook(
    bytes calldata,
    bytes calldata,
    Action calldata,
    bytes32,
    address,
    address
  ) external pure override returns (bool) {
    OwnershipTerms memory terms = abi.decode(_terms, (OwnershipTerms));
    
    IERC721 nft = IERC721(terms.nftContract);
    if (nft.ownerOf(terms.tokenId) != _redeemer) {
      revert NotNFTOwner(_redeemer, terms.nftContract, terms.tokenId);
    }

    return true;
  }
}
```

This `NFTOwnershipEnforcer` checks if the redeemer owns a specific NFT _after_ allowing the
delegation to be used, but the action will be reverted if the `afterHook` returns `false`. It's a
simple state lookup that doesn't modify any state.

To use this enforcer, create a caveat like this:

```typescript
const nftContract = "0x1234..."; // Address of the NFT contract
const tokenId = 123; // ID of the required NFT

const caveat = {
  enforcer: nftOwnershipEnforcerAddress,
  terms: encodeAbiParameters(
    [{ type: "address" }, { type: "uint256" }],
    [nftContract, tokenId]
  ),
  args: "0x"
};

const delegation = createDelegation(
  delegateAddress,
  delegatorAddress,
  undefined,
  [caveat]
);
```

This example demonstrates a minimal state lookup without modifying any state, which is simpler than
the previous payment example.
````
bun
express.js
rest-api
solidity
solidjs
typescript
vite
yarn
MetaMask/gator-cursor-contracts-starter

Used in 1 repository

Python
You are an expert in Python, Julep SDK, SQLite, ChromaDB, Redis, and API integration. Follow these rules to build a modern, scalable, and maintainable Python application.

## Project-Specific Guidelines
1. Use type hints for all code; avoid `Any` and `Optional` unless strictly necessary.
2. Use modular Python dataclasses or Pydantic models for data structures.
3. Structure the project into these folders:
   - `config/`: Configuration files (YAML, env)
   - `models/`: Data models and schemas
   - `services/`: Business logic and API integrations
   - `storage/`: Database and cache storage
   - `utils/`: Utility functions
   - `tests/`: Unit and integration tests
4. Implement proper environment variable handling with python-dotenv.
5. Follow a modular, service-oriented architecture approach.
6. Use SQLite for persistence, ChromaDB for vector storage, and Redis for caching.
7. Always follow the rules and guidelines provided in all sections of this file.
8. Do not adjust functionality outside of the requirements without explicit approval.

## Code Style and Structure
9. Follow PEP 8 style guide strictly.
10. Use absolute imports and organize imports according to PEP 8.
11. Prefer explicit function and variable names over abbreviations.
12. Write clear docstrings following Google style format.
13. Use meaningful variable and function names (e.g., `is_loading`, `has_error`).
14. Format code with Black and follow Flake8/Pylint rules.
15. Maintain clean, readable code with logical spacing and line breaks.

## Julep Integration Guidelines
16. Use the Julep client singleton pattern for all API interactions.
17. Implement proper error handling for API calls.
18. Use YAML for configuration files:
    - Agent configurations
    - Task definitions
    - Memory settings
19. Follow Julep SDK best practices:
    - Never expose API keys in code
    - Use environment variables for configuration
    - Implement proper error handling
    - Validate API responses
20. Optimize API usage:
    - Implement proper retry mechanisms
    - Handle rate limiting
    - Cache responses when appropriate
    - Use async operations when available

## Authentication Guidelines
21. Implement secure API key management:
    - Use environment variables
    - Implement key rotation
    - Add rate limiting protection
22. Secure configuration:
    - Protect sensitive configuration
    - Handle API errors gracefully
    - Show appropriate error messages
23. Clear sensitive data and handle token management securely.

## Database Guidelines
24. Use SQLite effectively:
    - Create proper indexes
    - Use appropriate data types
    - Implement connection pooling
    - Handle concurrent access
25. Follow schema best practices:
    - Use migrations for schema changes
    - Add proper constraints
    - Document schema changes
26. Optimize queries:
    - Use proper indexes
    - Implement efficient joins
    - Cache frequent queries

## ChromaDB Guidelines
27. Implement proper collection management:
    - Use meaningful collection names
    - Handle embeddings efficiently
    - Implement proper error handling
28. Optimize vector operations:
    - Monitor memory usage
    - Implement batch operations
    - Use appropriate distance metrics

## Redis Guidelines
29. Implement efficient caching:
    - Set appropriate TTLs
    - Use proper data structures
    - Handle cache invalidation
30. Optimize Redis usage:
    - Monitor memory usage
    - Implement proper error handling
    - Use appropriate serialization

## Type Hints and Documentation
31. Use type hints consistently throughout the codebase.
32. Document complex type definitions in separate type stub files.
33. Use Protocol classes for duck typing when appropriate.
34. Implement proper Generic types for reusable components.

## Error Handling
35. Use custom exception classes for different error types.
36. Implement proper logging with different levels.
37. Handle API errors gracefully with retries when appropriate.
38. Use context managers for resource cleanup.

## Testing Guidelines
39. Write unit tests for all business logic.
40. Implement integration tests for API interactions.
41. Use pytest fixtures for common setup.
42. Mock external services in tests.

## Performance Optimization
43. Use profiling tools to identify bottlenecks.
44. Implement caching strategies where appropriate.
45. Use async/await for I/O-bound operations.
46. Implement proper connection pooling.

## Configuration Management
47. Use YAML for configuration files.
48. Implement environment-specific configurations.
49. Use proper type checking for configuration values.
50. Validate configuration at startup.

## Logging and Monitoring
51. Implement structured logging.
52. Use proper log levels for different environments.
53. Add request ID tracking for API calls.
54. Implement proper error tracking.

## Security
55. Validate all input data.
56. Implement proper rate limiting.
57. Use secure random number generation.
58. Handle sensitive data properly.

## Debugging and Error Resolution
59. Use Python's debugging tools effectively.
60. Add clear error messages with context.
61. Implement proper stack trace handling.
62. IMPORTANT: After resolving errors, run pytest to validate fixes.
63. Confirm that error fixes do not introduce regressions.

## Documentation and Comments
64. Keep README.md focused on project setup and features.
65. Use docstrings for all public functions and classes.
66. Document configuration options and environment variables.
67. Add inline comments for complex logic.
68. Maintain up-to-date API documentation.
golang
less
python
redis
sqlite
TheSethRose/Julep-AI-Llama

Used in 1 repository

Python
<?xml version="1.0" encoding="UTF-8"?>
<ProgrammingGuidelines>
    <CoreProgrammingLevel>
        <Documentation>
            <Rule>
                <Description>Ensure to add documentation to every function and class while generating in the Google Docstring format for Python files.</Description>
                <Example>
                    <Code>
                        <![CDATA[
                        def function_name(param1: type, param2: type) -> return_type:
                            """Short description of the function.
                            
                            Longer description if necessary.
                            
                            Args:
                                param1 (type): Description of param1.
                                param2 (type): Description of param2.
                            
                            Returns:
                                return_type: Description of the return value.
                            
                            Raises:
                                ExceptionType: Description of when this exception is raised.
                            """
                            pass
                        ]]>
                    </Code>
                </Example>
            </Rule>
        </Documentation>
        <LineLength>
            <Code>79</Code>
            <DocstringComment>72</DocstringComment>
        </LineLength>
        <Imports>
            <Rule>
                <Description>One import per line, grouped in order: standard library, third-party, local application.</Description>
                <Example>
                    <Code>
                        <![CDATA[
                        import os
                        import sys
                        
                        import numpy as np
                        
                        from mypackage import mymodule
                        ]]>
                    </Code>
                </Example>
            </Rule>
        </Imports>
        <Whitespace>
            <Rule>
                <Description>Two blank lines between top-level functions and classes, one blank line between methods in a class, one blank line at the end of the file.</Description>
                <Example>
                    <Code>
                        <![CDATA[
                        def func1():
                            pass
                        
                        
                        def func2():
                            pass
                        
                        
                        class MyClass:
                            def method1(self):
                                pass
                        
                            def method2(self):
                                pass
                        
                        # One blank line at the end of the file
                        ]]>
                    </Code>
                </Example>
            </Rule>
        </Whitespace>
    </CoreProgrammingLevel>
    <LanguageLevel>
        <Python>
            <NamingConventions>
                <Functions>snake_case, verbs (e.g., calculate_area)</Functions>
                <Variables>snake_case, nouns (e.g., width, height)</Variables>
                <Attributes>snake_case, nouns (e.g., area, width)</Attributes>
                <GlobalVariables>Leading underscore (e.g., _variable_name)</GlobalVariables>
                <Constants>UPPERCASE (e.g., PI, E)</Constants>
                <Classes>PascalCase (e.g., Rectangle)</Classes>
                <ClassVariables>Leading underscore (e.g., _width)</ClassVariables>
                <PrivateVariables>Leading underscore (e.g., _variable_name)</PrivateVariables>
                <DunderMethods>Leading underscores (e.g., __method_name__)</DunderMethods>
                <Enums>
                    <Classes>PascalCase (e.g., Color)</Classes>
                    <Members>UPPERCASE (e.g., RED, GREEN)</Members>
                </Enums>
            </NamingConventions>
            <Imports>
                <Rule>Always use relative imports for modules and imports within the project.</Rule>
            </Imports>
            <Comments>
                <Rule>Use inline comments sparingly, and only for complex code.</Rule>
                <Example>
                    <Code>
                        <![CDATA[
                        x = x + 1  # Compensate for border
                        ]]>
                    </Code>
                </Example>
            </Comments>
            <Operators>
                <Rule>Use spaces around operators and after commas.</Rule>
                <Example>
                    <Code>
                        <![CDATA[
                        x = 1 + 2 * 3
                        def func(x, y, z):
                            pass
                        ]]>
                    </Code>
                </Example>
            </Operators>
            <CompoundStatements>
                <Rule>Avoid putting multiple statements on one line.</Rule>
                <Example>
                    <Code>
                        <![CDATA[
                        # Good
                        if x:
                            do_something()
                        
                        # Bad
                        if x: do_something()
                        ]]>
                    </Code>
                </Example>
            </CompoundStatements>
            <ErrorHandling>
                <Rule>Use specific exception handling.</Rule>
                <Example>
                    <Code>
                        <![CDATA[
                        try:
                            do_something()
                        except ValueError as e:
                            handle_value_error(e)
                        except TypeError as e:
                            handle_type_error(e)
                        ]]>
                    </Code>
                </Example>
            </ErrorHandling>
            <TypeHints>
                <Rule>Use type hints for function arguments and return values.</Rule>
                <Example>
                    <Code>
                        <![CDATA[
                        def greet(name: str) -> str:
                            return f"Hello, {name}!"
                        ]]>
                    </Code>
                </Example>
            </TypeHints>
            <StringFormatting>
                <Rule>Prefer f-strings for string formatting.</Rule>
                <Example>
                    <Code>
                        <![CDATA[
                        name = "Alice"
                        age = 30
                        print(f"{name} is {age} years old")
                        ]]>
                    </Code>
                </Example>
            </StringFormatting>
            <ConditionalLogic>
                <Rule>Never use if-elif-else blocks; instead use dictionaries.</Rule>
                <Example>
                    <Code>
                        <![CDATA[
                        class Calculator:
                            """A minimal calculator using function mapping."""
                        
                            def __init__(self):
                                self.operations = {
                                    'add': lambda a, b: a + b,
                                    'subtract': lambda a, b: a - b,
                                    'multiply': lambda a, b: a * b,
                                    'divide': lambda a, b: a / b if b != 0 else None,
                                }
                        
                            def calculate(self, operation: str, a: float, b: float) -> float:
                                return self.operations[operation](a, b)
                        ]]>
                    </Code>
                </Example>
            </ConditionalLogic>
        </Python>
    </LanguageLevel>
    <ProjectSpecificGuidelines>
        <MVCArchitecture>
            <Framework>FastAPI</Framework>
            <Structure>
                <Description>Use the Model-View-Controller (MVC) architecture to organize the project using FastAPI.</Description>
                <DirectoryStructure>
                    <Code>
                        <![CDATA[
                        src/
                        ├── models/
                        │   ├── __init__.py
                        │   ├── user_model.py
                        │   ├── product_model.py
                        │   └── order_model.py
                        ├── views/
                        │   ├── __init__.py
                        │   ├── user_view.py
                        │   ├── product_view.py
                        │   └── order_view.py
                        ├── controllers/
                        │   ├── __init__.py
                        │   ├── user_controller.py
                        │   ├── product_controller.py
                        │   └── order_controller.py
                        ├── main.py
                        ├── utils/
                        │   ├── __init__.py
                        │   └── helper_functions.py
                        └── tests/
                            ├── __init__.py
                            ├── test_user.py
                            ├── test_product.py
                            └── test_order.py
                        ]]>
                    </Code>
                </DirectoryStructure>
                <Components>
                    <Models>
                        <Description>Define the data structure and database schema using Pydantic and SQLAlchemy.</Description>
                    </Models>
                    <Views>
                        <Description>Handle the API routes and responses using FastAPI's APIRouter.</Description>
                    </Views>
                    <Controllers>
                        <Description>Contain the business logic, interact with models, and return the necessary data to views.</Description>
                    </Controllers>
                </Components>
            </Structure>
        </MVCArchitecture>
    </ProjectSpecificGuidelines>
</ProgrammingGuidelines>
fastapi
golang
javascript
python

First seen in:

omkarh25/Kaas

Used in 1 repository