Awesome Cursor Rules Collection

Showing 277-288 of 1033 matches

TypeScript
## Instructions for Developers

1. Never remove code unless specifically asked to do so.
2. Never work on code that is not part of the specific request. 
3. When writing react unit tests, always put them in the same directory as the component they are testing.
4. Use the following design document as a guide for the extension:

# Design Document
The AI Pair Programmer Extension streamlines your development process by emphasizing code quality and providing flexible, user-friendly features for enhanced productivity

## Overview

This extension is a VS Code extension that allows you to use the AI Pair Programmer extension to pair program with AI.

## Features

AI pair is designed to be pair programmer that will use your test suite to generate code changes. Typical AI tools will generate code that may not pass your tests. AI pair will generate code that passes your tests.

## How to use

1. Open a folder in VS Code
2. Open the AI Pair extension
3. Click the Play button to start a new pair programming session (or alternatively you can use the `ai-pair.start` command from the vscode command palette)

The extension will run a number of cycles to generate code changes. Each cycle will several phases: `Building`, `Testing`, `Generating Code`, `Rebuilding`, `Retesting`, and `Completed` (in those orders).

At any point in the cycle you can click the `Stop` button to stop the cycle. It will finish the current phase and then stop.

On each cycle, the extension will first build and test to see if any changes are needed. If the build or tests fail, it will generate code changes to fix the build or tests. It will then rebuild and retest until the build and tests pass.

If the build and tests pass then it will stop the cycle.

The extension will continue to run cycles until it reaches the maximum number of retries or the build and tests pass. Retries can be configured in the settings.

## Viewing the results

You can see the progress and results of the AI Pair programmer by opening the sidebar. The sidebar shows a table where each cycle is represented as a row. You can expand any cycle to see the results from that cycle. When a cycle is expanded, you can see the results from each phase of the cycle including the compilation state, test results, code changes, and timing details.

You can also view the logs for parts of a cycle by clicking the `View Logs` link in the cycle details for the phase you are interested in. This will open a new tab with the logs for the cycle.

## Choosing the model

The extension will use the model you have selected in the settings. You can change the model by clicking the `Settings` button in the extension or by navigating to the `AI Pair Settings` section in the VS Code settings.

The extension supports most popular models including OpenAI, Anthropic, and Google. The extension requires a `apiKey` for the model you are using. You can get an API key from the model provider's website.

## Forcing

Even if the build and tests pass, you can force the extension to generate code changes by entering a hint in the `Generate Code` section. This will generate code changes (using your hint as a guide) and then rebuild and retest until the build and tests pass.

## Escalation

The extension can be configured to escalate to a more expensive model on the last cycle. This can be helpful if other models have failed to generate code that passes the tests.

## Design Principles

1. Keep the code simple and easy to understand.
2. Keep the code modular and easy to extend.
3. Keep the code performant.
4. Keep the code easy to test.
5. The webview code should never use dependencies that are not intended for webviews (fs, child_process, etc.)

golang
java
javascript
less
openai
react
rest-api
shell
+1 more

First seen in:

dandedj/ai-pair

Used in 1 repository

TypeScript

    You are an expert in Ionic, Cordova, and Firebase Firestore, Working with Typescript and Angular building apps for mobile and web.

    Project Structure and File Naming
    - Organize by feature directories (e.g., 'services/', 'components/', 'pipes/')
    - Use environment variables for different stages (development, staging, production)
    - Create build scripts for bundling and deployment
    - Implement CI/CD pipeline
    - Set up staging and canary environments
    - Structure Firestore collections logically (e.g., 'users/', 'spots/', 'bookings/')
    - Maintain Firebase configurations for different environments
  
  
    ## Project Structure and Organization
    - Use descriptive names for variables and functions (e.g 'getUsers', 'calculateTotalPrice').
    - Keep classes small and focused.
    - Avoid global state when possible.
    - Manage routing through a dedicated module
    - Use the latest ES6+ features and best practices for Typescript and Angular.
    - Centralize API calls and error handling through services
    - Manage all storage through single point of entry and retrievals. Also put storage keys at single to check and find.
    - Create dedicated Firebase services for each collection type
    - Implement Firebase error handling in a centralized service
    - Use Firebase transactions for data consistency
    - Use Firebase rules for data security
    - Use Firebase functions for serverless backend logic
    - Use Firebase storage for file uploads and downloads
    - Use Firebase authentication for user management
    - Use Firebase analytics for tracking user behavior
    - Use Firebase crash reporting for error tracking
    - Structure Firestore queries for optimal performance
    
    ## Naming Conventions
    - camelCase: functions, variables (e.g., `getUsers`, `totalPrice`)
    - kebab-case: file names (e.g., `user-service.ts`, `home-component.ts`)
    - PascalCase: classes (e.g., `UserService`)
    - Booleans: use prefixes like 'should', 'has', 'is' (e.g., `shouldLoadData`, `isLoading`).
    - UPPERCASE: constants and global variables (e.g., `API_URL`, `APP_VERSION`).
    - Firestore collections: plural nouns (e.g., `users`, `bookings`).
    - Firestore documents: descriptive IDs (e.g., `user-${uid}`, `booking-${timestamp}`).
  
    ## Dependencies and Frameworks
    - Avoid using any external frameworks or libraries unless its absolutely required.
    - Use native plugins through Ionic Native wrappers with proper fallbacks for a smooth user experience in both web and native platforms.
    - While choosing any external dependency, check for the following things:
        - Device compatibility
        - Active maintenance
        - Security
        - Documentation
        - Ease of integration and upgrade
    - Use native components for both mobile and web if available and fullfill the requirements.
    - If any native plugin is being used for andriod or ios, it should be handled in a centralized service and should not be used directly in the component.
    - Use official Firebase SDKs and AngularFire for Firestore integration.
    - Implement proper Firebase initialization and configuration.
    - Handle Firebase Authentication properly.
    - Set up appropriate Firebase Security Rules.
  
    ## UI and Styles
    - Prefer Ionic components.
    - Create reusable components for complex UI.
    - Use SCSS for styling.
    - Centralize themes, colors, and fonts.
    - Implement loading states for Firebase operations.
    - Handle Firebase offline data gracefully.
    - Show appropriate error messages for Firebase operations.
    - Implement real-time UI updates with Firebase snapshots.

    ## Performance and Optimization
    -  Implement lazy loading.
    - Use pre-fetching for critical data.
    - Use caching for all the data that is needed multiple times.
    - Use global error and alert handlers.
    - Integrate any crash reporting service for the application.
    - Use a centralised alert handler to handle all the alert in the application.
    - Implement Firebase offline persistence.
    - Use Firebase query cursors for pagination.
    - Optimize Firestore reads with proper indexing.
    - Cache Firestore query results.
    - Use Firestore batch operations for bulk updates.
    - Monitor Firestore quota usage.
    
    ## Testing
    - Write comprehensive unit tests
    - Make sure to cover all the edge cases and scenarios.
    - In case of Native plugins, write mock services for the same.
    - Test Firebase integration thoroughly
    - Mock Firestore services in tests
    - Test Firebase security rules
    - Implement Firebase emulator for testing
    - Test offline functionality
    - Verify Firebase error handling

    Follow the official Ionic/React and Firebase/Firestore guides for best practices.

    #Paystack
    - Use the official Paystack SDK for React Native.
    #resendemail
    - Use the official Resend Email SDK for React Native.
    #twilio
    - Use the official Twilio SDK for React Native.
    #razorpay
    - Use the official Razorpay SDK for React Native.
    #flutterwave
    - Use the official Flutterwave SDK for React Native.
    #flutterwave
    - Use the official Flutterwave SDK for React Native.
analytics
angular
bun
css
firebase
html
javascript
less
+3 more

First seen in:

spaco67/okiapp

Used in 1 repository

TypeScript
You are an expert full-stack developer proficient in TypeScript, React, Next.js, and modern UI/UX frameworks (Chakra UI 3.0, NextJS). You are obsessed about writing clean, consistent and functional code. You carefully provide accurate, factual, thoughtful answers, and are a genius at reasoning. You are short and direct. No chattiness, no yapping.

## Your coding style

- You write code that is easy to read, maintain and understand
- Write concise, technical TypeScript code with accurate examples.
- Use functional and declarative programming patterns; avoid classes.
- Favor iteration and modularization over code duplication
- Use descriptive variable names with auxiliary verbs (e.g., `isLoading`, `hasError`).
- Structure files with exported components, subcomponents, helpers, static content, and types.
- Use lowercase with dashes for directory names and components (e.g., `components/auth-wizard`).

## Error Handling and Validation

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

## Your working principles

- You always thrive to present honest, direct and accurate answers (Even when presented with an assupmtion, suggestion or loaded question)
- You are not afraid to disagree
- If there is anything you need that’s missing, you ask for it
- If you’re unsure about any aspect of the task, you ask for clarification. You don’t guess. You don’t make assumptions.
- Before suggesting new code, you look through all files in the codebase to see if there are functions and excisting archicture you can use or rewrite to avoid duplication and isolated implementations
chakra-ui
css
javascript
nestjs
next.js
react
typescript

First seen in:

wirtzdan/project-rocket

Used in 1 repository

TypeScript
一、初始项目评估 - 详细指南(适合初学者)
1. 项目文档审查
1.1 README.md 文件解读
这是你接触项目的第一个文件
通常包含项目描述、安装步骤、使用方法
查找关键词:Installation(安装)、Getting Started(入门)、Prerequisites(前置要求)
尝试按照步骤在本地运行项目
记录遇到的问题和解决方法
1.2 package.json 分析
这个文件包含项目的所有依赖项
dependencies:项目运行需要的包
devDependencies:开发时需要的包
scripts:可用的命令(如 npm start, npm test)
尝试理解每个主要依赖的作用
记录版本号,避免版本冲突
1.3 环境配置文件检查
查找 .env 或 .env.example 文件
了解需要配置的环境变量
确认是否需要特殊的API密钥或访问令牌
检查不同环境的配置(开发、测试、生产)
注意安全相关的配置项
1.4 项目配置文件
检查 next.config.js/webpack.config.js 等配置文件
了解项目的特殊配置需求
查看是否有自定义的构建过程
注意性能相关的配置项
技术栈评估
2.1 前端技术
确认使用的框架(React/Vue/Angular等)
查看UI库(Material-UI/Tailwind等)
了解状态管理方案(Redux/Mobx等)
检查路由实现方式
注意特殊的前端功能(如WebSocket、Canvas)
2.2 后端技术
确认后端框架(Node.js/Python/Java等)
了解数据库选择(MySQL/MongoDB等)
检查API实现方式(REST/GraphQL)
查看认证方案(JWT/Session等)
注意性能相关的实现
2.3 构建和部署
了解构建工具(Webpack/Vite等)
检查部署方案(Docker/Kubernetes等)
查看CI/CD配置(GitHub Actions/Jenkins等)
了解监控方案
注意自动化测试配置
实践步骤
3.1 本地运行
克隆项目代码
安装依赖(npm install/yarn)
配置环境变量
启动开发服务器
确认基本功能是否正常
3.2 代码阅读
从入口文件开始(如 index.js/App.js)
查看主要组件的实现
理解数据流转过程
注意错误处理方式
学习代码组织方式
3.3 调试技巧
使用浏览器开发者工具
添加 console.log 进行调试
使用断点调试
查看网络请求
分析性能问题
4. 记录和总结
4.1 建立学习笔记
记录项目结构
总结关键技术点
记录问题和解决方案
整理有用的代码片段
建立个人知识库
4.2 提问和交流
在团队中提出疑问
查阅相关文档
在Stack Overflow上搜索
参与技术社区讨论
与其他开发者交流
5. 进阶学习
5.1 深入理解
研究核心算法
分析设计模式
学习最佳实践
理解性能优化
掌握测试方法
5.2 贡献代码
修复简单bug
添加新功能
改进文档
优化性能
提交Pull Request
注意事项:
不要试图一次理解所有内容
从简单的部分开始
多动手实践
保持耐心
及时记录和总结
善用搜索引擎
多与他人交流
循序渐进地学习
angular
css
docker
golang
graphql
java
javascript
jwt
+17 more

First seen in:

Kelin0x/figma_clone

Used in 1 repository

TypeScript
**General Principles**

- Use modular architecture for better scalability and maintainability.
- Encapsulate the application logic in services and separate concerns.
- Write clean, readable, and maintainable code adhering to SOLID principles.
- Prefer TypeScript over JavaScript for type safety and better tooling support.
- Document all public classes, methods, and modules using JSDoc.
- Implement comprehensive error handling and logging.
- Ensure the application adheres to security best practices.

**Folder Structure**

- Use consistent naming conventions: kebab-case for file and directory names, camelCase for variables, and PascalCase for classes.

**Module Design**

- Each module should encapsulate a single feature or domain.
- Modules should expose only the necessary providers and imports.
- Use dependency injection to manage dependencies between services.

**Controllers**

- Use controllers to handle incoming requests and return responses.
- Keep controllers lightweight; delegate business logic to services.
- Use descriptive route names and HTTP methods.
- Use DTOs (Data Transfer Objects) for request validation and type safety.
- Document controller methods with JSDoc or Swagger annotations.

**Services**

- Encapsulate all business logic in services.
- Use Dependency Injection to manage dependencies.
- Write small, focused methods that perform a single task.
- Ensure proper separation of concerns; avoid mixing database logic with business logic.

**Data Validation**

- Use `class-validator` and `class-transformer` for validating and transforming incoming data.
- Define DTOs (Data Transfer Objects) for each endpoint.
- Validate input at the controller level using the `@Body()`, `@Param()`, and `@Query()` decorators.
- Use pipes for global or custom validation logic.

**Database Integration**

- Encapsulate database logic within repositories or dedicated services.
- Define entities with proper relationships and constraints.
- Use migrations for schema changes and version control.

**Error Handling**

- Use global filters (e.g., `@Catch()`) to handle exceptions.
- Define custom exceptions for specific use cases.
- Return meaningful error messages and HTTP status codes.
- Log errors using a logging service or library (e.g., `winston` or NestJS Logger).

**Security Best Practices**

- Use `helmet` for setting secure HTTP headers.
- Implement rate limiting using `nestjs-rate-limiter` or similar libraries.
- Sanitize user inputs to prevent SQL injection or XSS attacks.
- Use environment variables to store sensitive information (e.g., database credentials, API keys).
- Implement authentication and authorization using Passport.js or JWT strategies.

**Performance Optimization**

- Enable caching for frequently accessed data using the `CacheModule`.
- Use interceptors to handle cross-cutting concerns (e.g., logging, transformation).
- Optimize database queries using indexes and efficient relationships.
- Use lazy loading for modules and services where applicable.

**Testing**

- Write unit tests for services and controllers using Jest.
- Follow the Arrange-Act-Assert pattern for test structure.
- Use test doubles (e.g., mocks, stubs, spies) for dependencies.
- Write e2e (end-to-end) tests to validate the complete application flow.
- Organize test files alongside the feature they belong to, e.g., `feature-name.controller.spec.ts`.

**Configuration Management**

- Use the `@nestjs/config` module for managing configuration.
- Store environment-specific settings in `.env` files.
- Avoid hardcoding configuration values; use environment variables instead.
- Validate configuration values using `class-validator` and a dedicated configuration schema.

**Event-Driven Architecture**

- Use the `EventEmitterModule` for handling events within the application.
- Define event classes to encapsulate event data.
- Use a message broker like RabbitMQ or Kafka for distributed systems.

**Swagger Documentation**

- Use `@nestjs/swagger` to generate API documentation.
- Annotate controllers and DTOs with Swagger decorators.
- Include details for endpoints, request bodies, query parameters, and responses.
- Host the Swagger UI at a dedicated endpoint, e.g., `/api/docs`.

**Logging**

- Use NestJS' Logger for application-wide logging.
- Implement a centralized logging service for consistency.
- Configure logging levels (e.g., debug, info, error) based on the environment.
- Log important events and errors with sufficient context information.

**Asynchronous Operations**

- Use async/await for asynchronous operations.
- Leverage RxJS observables for reactive programming where appropriate.
- Use queues (e.g., Bull) for background tasks and job processing.
java
javascript
jest
jwt
nestjs
react
shell
solidjs
+1 more

First seen in:

montarist/nilvera-api

Used in 1 repository

TypeScript
# Full-Stack Development Standards

## Technology Stack
- Frontend: React, Next.js (planned), TypeScript
- Backend: Flask, SQLAlchemy
- State Management: Zustand
- UI: Radix UI, Shadcn UI
- Styling: Tailwind CSS, Stylus
- Testing: Jest, React Testing Library, pytest
- Build Tools: Vite (current), Next.js (planned)

## Code Style and Structure
- Write clean, typed TypeScript/Python code
- Use functional programming patterns; avoid classes in frontend code
- Prefer iteration and modularization over code duplication
- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError)
- Structure React files: exported component, subcomponents, helpers, static content
- Structure Python files: imports, config, models, routes/controllers, helpers

## TypeScript/JavaScript Standards
- Use 2 space indentation
- Use single quotes for strings except to avoid escaping
- No semicolons (unless required to disambiguate statements)
- No unused variables
- Add a space after keywords
- Add a space before function declarations
- Always use === instead of ==
- Infix operators must be spaced
- Commas should have a space after them
- Keep else statements on same line as curly braces
- Use curly braces for multi-line if statements
- Always handle errors appropriately
- Use camelCase for variables/functions
- Use PascalCase for React components

## Python Standards
- Use 4 space indentation
- Follow PEP 8 guidelines
- Use type hints
- Use docstrings for classes and functions
- Handle exceptions appropriately
- Use snake_case for variables/functions
- Use PascalCase for classes

## File Structure
```
app/
  routes/
  models/
  services/
  utils/
  tests/
web/
  src/
    components/
      feature-name/
        FeatureName.tsx
        FeatureName.test.tsx
        FeatureName.module.styl
    hooks/
    stores/
    utils/
    types/
```

## React/Next.js Best Practices
- Use Server Components by default in Next.js
- Only use 'use client' when necessary
- Implement proper error boundaries
- Use TypeScript for type safety
- Follow React Server Components patterns:
  ```typescript
  // Server Component (default)
  async function UserProfile({ id }: { id: string }) {
    const user = await fetchUser(id)
    return <div>{user.name}</div>
  }

  // Client Component (when needed)
  'use client'
  function InteractiveButton() {
    const [count, setCount] = useState(0)
    return <button onClick={() => setCount(count + 1)}>{count}</button>
  }
  ```

## State Management
- Use Zustand for global state
- Implement proper state splitting
- Example store pattern:
```typescript
interface UserStore {
  user: User | null
  setUser: (user: User) => void
  logout: () => void
}

const useUserStore = create<UserStore>((set) => ({
  user: null,
  setUser: (user) => set({ user }),
  logout: () => set({ user: null })
}))
```

## API Integration
- Use typed API calls
- Handle errors gracefully
- Implement proper loading states
```typescript
interface ApiResponse<T> {
  data?: T
  error?: string
  loading: boolean
}

async function fetchData<T>(url: string): Promise<ApiResponse<T>> {
  try {
    const response = await fetch(url)
    const data = await response.json()
    return { data, loading: false }
  } catch (error) {
    return { error: error.message, loading: false }
  }
}
```

## Styling Approach
- Use Tailwind for layout and simple styling
- Use Stylus modules for complex component-specific styles
- Never use @apply directive
- Example hybrid approach:
```typescript
import styles from './Card.module.styl'

function Card({ children }) {
  return (
    <div className={`p-4 rounded-lg shadow-md ${styles.cardContainer}`}>
      {children}
    </div>
  )
}
```

## Testing
- Write unit tests for components and utilities
- Use integration tests for critical flows
- Test server components appropriately
```typescript
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'

test('button click increments counter', async () => {
  render(<Counter />)
  await userEvent.click(screen.getByRole('button'))
  expect(screen.getByText('1')).toBeInTheDocument()
})
```

## Performance
- Use React Suspense for loading states
- Implement proper code splitting
- Optimize images and assets
- Monitor Core Web Vitals
- Use proper caching strategies

## Security
- Implement proper CSRF protection
- Sanitize user inputs
- Use proper authentication/authorization
- Follow OWASP guidelines

## Accessibility
- Use semantic HTML
- Implement ARIA attributes
- Ensure keyboard navigation
- Test with screen readers

This standard guide aligns with your current codebase as seen in:

```1:146:web/src/App.tsx
import { Flex, Heading, Separator, Table } from '@radix-ui/themes';
import { useEffect, useState } from 'react';
import Plot from 'react-plotly.js';
import { Link } from 'react-router-dom';
import { Routes } from 'routes';

// Input data from the simulation
type AgentData = Record<string, number>;
type DataFrame = Record<string, AgentData>;
type DataPoint = [number, number, DataFrame];

// Output data to the plot
type PlottedAgentData = Record<string, number[]>;
type PlottedFrame = Record<string, PlottedAgentData>;

const App = () => {
  // Store plot data in state.
  const [positionData, setPositionData] = useState<PlottedAgentData[]>([]);
  const [velocityData, setVelocityData] = useState<PlottedAgentData[]>([]);
  const [initialState, setInitialState] = useState<DataFrame>({});

  useEffect(() => {
    // fetch plot data when the component mounts
    let canceled = false;

    async function fetchData() {
      console.log('calling fetchdata...');

      try {
        // data should be populated from a POST call to the simulation server
        const response = await fetch('http://localhost:8000/simulation');
        if (canceled) return;
        const data: DataPoint[] = await response.json();
        const updatedPositionData: PlottedFrame = {};
        const updatedVelocityData: PlottedFrame = {};

        setInitialState(data[0][2]);

        data.forEach(([t0, t1, frame]) => {
          for (let [agentId, { x, y, vx, vy }] of Object.entries(frame)) {
            updatedPositionData[agentId] = updatedPositionData[agentId] || { x: [], y: [] };
            updatedPositionData[agentId].x.push(x);
            updatedPositionData[agentId].y.push(y);

            updatedVelocityData[agentId] = updatedVelocityData[agentId] || { x: [], y: [] };
            updatedVelocityData[agentId].x.push(vx);
            updatedVelocityData[agentId].y.push(vy);
          }
        });

        setPositionData(Object.values(updatedPositionData));
        setVelocityData(Object.values(updatedVelocityData));
        console.log('Set plot data!');
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    }

    fetchData();

    return () => {
      canceled = true;
    };
  }, []);
  return (
    <div
      style={{
        height: '100vh',
        width: '100vw',
        margin: '0 auto',
      }}
    >
      {/* Flex: https://www.radix-ui.com/themes/docs/components/flex */}
      <Flex direction='column' m='4' width='100%' justify='center' align='center'>
        <Heading as='h1' size='8' weight='bold' mb='4'>
          Simulation Data
        </Heading>
        <Link to={Routes.FORM}>Define new simulation parameters</Link>
        <Separator size='4' my='5' />
        <Flex direction='row' width='100%' justify='center'>
          <Plot
            style={{ width: '45%', height: '100%', margin: '5px' }}
            data={positionData}
            layout={{
              title: 'Position',
              yaxis: { scaleanchor: 'x' },
              autosize: true,
              dragmode: 'pan',
            }}
            useResizeHandler
            config={{
              scrollZoom: true,
            }}
          />
          <Plot
            style={{ width: '45%', height: '100%', margin: '5px' }}
            data={velocityData}
            layout={{
              title: 'Velocity',
              yaxis: { scaleanchor: 'x' },
              autosize: true,
              dragmode: 'pan',
            }}
            useResizeHandler
            config={{
              scrollZoom: true,
            }}
          />
        </Flex>
        <Flex justify='center' width='100%' m='4'>
          <Table.Root
            style={{
              width: '800px',
            }}
          >
            {/* Table: https://www.radix-ui.com/themes/docs/components/table */}
            <Table.Header>
              <Table.Row>
                <Table.ColumnHeaderCell>Agent</Table.ColumnHeaderCell>
                <Table.ColumnHeaderCell>Initial Position (x,y)</Table.ColumnHeaderCell>
                <Table.ColumnHeaderCell>Initial Velocity (x,y)</Table.ColumnHeaderCell>
              </Table.Row>
            </Table.Header>

            <Table.Body>
              {Object.entries(initialState).map(([agentId, { x, y, vx, vy }]) => (
                <Table.Row key={agentId}>
                  <Table.RowHeaderCell>{agentId}</Table.RowHeaderCell>
                  <Table.Cell>
                    ({x}, {y})
                  </Table.Cell>
                  <Table.Cell>
                    ({vx}, {vy})
                  </Table.Cell>
                </Table.Row>
              ))}
            </Table.Body>
          </Table.Root>
        </Flex>
      </Flex>
    </div>
  );
};

export default App;
```


And your Flask backend structure as shown in:

```1:80:app/app.py
# HTTP SERVER

import json

from flask import Flask, request
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from simulator import Simulator
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from store import QRangeStore


class Base(DeclarativeBase):
    pass


############################## Application Configuration ##############################

app = Flask(__name__)
CORS(app, origins=["http://localhost:3000"])

db = SQLAlchemy(model_class=Base)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///database.db"
db.init_app(app)


############################## Database Models ##############################


class Simulation(db.Model):
    id: Mapped[int] = mapped_column(primary_key=True)
    data: Mapped[str]


with app.app_context():
    db.create_all()


############################## API Endpoints ##############################


@app.get("/")
def health():
    return "<p>Sedaro Nano API - running!</p>"


@app.get("/simulation")
def get_data():
    # Get most recent simulation from database
    simulation: Simulation = Simulation.query.order_by(Simulation.id.desc()).first()
    return simulation.data if simulation else []


@app.post("/simulation")
def simulate():
    # Get data from request in this form
    # init = {
    #     "Planet": {"x": 0, "y": 0.1, "vx": 0.1, "vy": 0},
    #     "Satellite": {"x": 0, "y": 1, "vx": 1, "vy": 0},
    # }

    # Define time and timeStep for each agent
    init: dict = request.json
    for key in init.keys():
        init[key]["time"] = 0
        init[key]["timeStep"] = 0.01

    # Create store and simulator
    store = QRangeStore()
    simulator = Simulator(store=store, init=init)

    # Run simulation
    simulator.simulate()

    # Save data to database
    simulation = Simulation(data=json.dumps(store.store))
    db.session.add(simulation)
    db.session.commit()

    return store.store
```
css
dockerfile
flask
golang
html
java
javascript
jest
+11 more
dangphung4/sedaro-take-home

Used in 1 repository

TypeScript
# Witch House CRM - Cursor AI Development Instructions

## Important Distinction - AI Roles

### Your Role (Cursor AI)

- You are the AI development agent using Cursor
- Your purpose is to help develop and maintain the codebase
- You follow these rules and development guidelines
- You document your development decisions in ai_record.md

### Product AI Features (Separate System)

- The CRM system being built includes AI customer service agents
- These are separate from you and are part of the product features
- When developing these features, you are implementing them, not being them
- Always maintain this distinction in your understanding and documentation

## Project Documentation Structure

### Core Documentation Files

1. **docs/Directory_Structure.md**
   - Contains complete project structure documentation
   - Reference for all file and folder organizations
   - Update when new directories or structural changes occur
   - Maintain clear hierarchical formatting

2. **docs/Project_Requirements.md**
   - Source of truth for project requirements
   - Contains mandatory features
   - Must be completed before optional features
   - Exception: Core architectural features needed early

3. **docs/TODO.md**
   - Living document of all tasks
   - Organized by feature categories
   - Format: [ ] for pending, [✅] for completed
   - Never delete tasks without explicit instruction
   - Contains "Current Focus" section for priority items
   - Update status only after owner confirmation

4. **docs/project_owner_notes.md**
   - Reserved for project owner's ideas and plans
   - Reference only - do not modify
   - Contains future enhancement ideas
   - Used for understanding project direction

5. **docs/ai_record.md**
   - Your development decision log
   - Document architectural decisions
   - Record implementation strategies
   - Update as project understanding evolves
   - Keep separate from product AI feature documentation

## Core Project Context

### Technology Stack

- React 19
- Next.js 15
- Supabase (latest)
- Shadcn UI
- Latest Lexical Editor
- TailwindCSS

### Brand Identity

- Company Name: Witch House
- Logo Location: public/images/Shapes 14.png
- Design Philosophy: Modern tech aesthetic (Shadcn-based) with boho/indie
  influences
- Visual Assets: Abstract design elements available in public/images/
- UI/UX Direction:
  - Primary: Clean, modern Shadcn components
  - Secondary: Subtle boho/indie elements for character
  - Dark theme prioritized with light theme support
  - Use Shadcn components by default for consistency
  - Landing page in screenshots serves as design reference

## Operating Guidelines

### Documentation Management

1. When Modifying TODO.md
   - Maintain existing categories
   - Keep completed tasks with checkmarks
   - Add new tasks to appropriate sections
   - Update "Current Focus" section as needed
   - Preserve task history

2. When Updating Directory_Structure.md
   - Keep ASCII tree structure format
   - Update when adding new directories/files
   - Maintain consistent indentation
   - Include brief descriptions

3. When Using ai_record.md
   - Document key decisions with rationale
   - Track major implementation choices
   - Update architectural decisions
   - Keep separate from product features

4. When Reading project_owner_notes.md
   - Use for context and future planning
   - Never modify this file
   - Reference for understanding project direction

### Technology Usage

1. Lexical Editor
   - Always use latest version
   - Request documentation if uncertain
   - Do not assume deprecated paths/components

2. Shadcn UI
   - Use whenever possible for consistency
   - Follow Shadcn patterns and best practices
   - Maintain uniform styling across components

3. Component Development
   - Prioritize Shadcn components
   - Custom components only when necessary
   - Maintain boho/indie aesthetic within modern framework

### Task Management

1. New Task Process
   - Add to appropriate section in TODO.md
   - Use consistent formatting
   - Update "Current Focus" if priority
   - Include context and requirements

2. Task Completion
   - Implement solution
   - Test thoroughly
   - Await owner confirmation
   - Mark with [✅] only after confirmation

### Error Prevention

- Request documentation when uncertain
- Verify latest package versions
- Test assumptions before implementation
- Maintain clear separation between your role and product AI features

## Quality Standards

1. Code Quality
   - Follow React 19 best practices
   - Implement proper Next.js 15 patterns
   - Maintain consistent styling
   - Optimize for performance

2. UI/UX Standards
   - Consistent with brand aesthetic
   - Responsive design
   - Accessibility compliance
   - Performance optimization

3. Documentation Quality
   - Clear and organized
   - Regular updates
   - Proper markdown formatting
   - Comprehensive reasoning

Remember:

1. You are the development AI, helping build the system
2. The AI customer service agents are features of the system you're building
3. Keep documentation organized according to the structure above
4. When in doubt, ask for documentation or clarification
css
golang
javascript
langchain
next.js
plpgsql
react
shadcn/ui
+4 more
JoshJarabek7/witch-house-crm

Used in 1 repository

TypeScript
I am building a decentralized service marketplace website where users solve their tasks with human and AI service provider agents. The web app connects to the Solana blockchain (local or devnet) and uses the Gigentic smart contract program.

You are an expert in TypeScript, Node.js, Next.js App Router, React, Shadcn UI, Radix UI and Tailwind.
You are also an expert in Solana full-stack web3 dApp development, focusing on building and deploying smart contracts using Rust and Anchor, and integrating on-chain data with Web3.js in React and Next.js.

I use Rust with the Solana Anchor framework for chain program development, and TypeScript with Mocha / Chai for testing the programs.

And I use Next.js, Tailwind, Shadcn UI, and Solana Anchor/Web3.js libraries on the frontend.

I use Nx for tooling and build process.

I want to implement the Jest / Playwright for testing the frontend.

## Code Style & Structure

- Use declarative programming patterns when fitting.
- Functional programming: prefer small, reusable components, avoid classes.
- Write concise, technical TypeScript code with accurate examples.
- 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.

### Documentation

- Document your code structure clearly—README for usage instructions.
- Update documentation as features evolve or change.

## Frameworks and Libraries

### Solana Program Development (Rust + Anchor)

- Prioritize performance, modularity, and clear separation of concerns.
- Utilize Anchor for simplifying account management, error handling, and program interaction.
- Ensure secure smart contracts with input validation and strict access control.

### Frontend Development (React + Web3.js + Tailwind)

- Use Solana Web3.js for optimized chain interactions.
- Implement responsive design and error handling.
- Use Shadcn UI, Radix, and Tailwind for styling with a mobile-first approach.
- Keep React functional and concise in line with best practices.

## Programming Conventions

### TypeScript Usage

- Use TypeScript for all code; prefer interfaces over types.
- Use TypeScript for static checking with 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.

### Performance Optimization

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

### Key Conventions

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

### Testing & Deployment

- Perform local validation testing before devnet deployment.
- Use continuous deployment pipelines to automate testing/rollouts.

## Additional Guidelines

### Next.js

- Follow Next.js docs for Data Fetching, Rendering, and Routing. I am using App Router.

### ChatGPT Models

- Please be aware that 'gpt-4o' is a new model of OpenAI. Don't correct me on this.

### Vercel AI SDK

- Please note that the StreamingTextResponse helper was part of the Vercel AI SDK when it was initially introduced in 2023. However, the SDK underwent a significant update with version 3.2 on June 18, 2024, focusing on new features like Agents, expanded provider support, embeddings, and developer experience improvements. As part of this update, there were breaking changes, and the StreamingTextResponse helper is no longer directly referenced in the newer documentation. The latest verion is 3.4 and I am using this version.
css
javascript
jest
less
next.js
openai
playwright
radix-ui
+6 more
Gigentic/gigentic-frontend

Used in 1 repository

TypeScript
You are an expert in TypeScript, Node.js, Next.js App Router, React, Shadcn UI, Radix UI and Tailwind.
  
  Code Style and Structure
- Write concise, technical TypeScript code with accurate examples, following Standard.js rules.
- 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.
- Prefer to use the "@/components" alias for importing components.

  Standard.js Rules
  - Use 2 space indentation.
  - Use single quotes for strings except to avoid escaping.
  - No semicolons (unless required to disambiguate statements).
  - No unused variables.
  - Add a space after keywords.
  - Add a space before a function declaration's parentheses.
  - Always use === instead of ==.
  - Infix operators must be spaced.
  - Commas should have a space after them.
  - Keep else statements on the same line as their curly braces.
  - For multi-line if statements, use curly braces.
  - Always handle the err function parameter.
  - Use camelcase for variables and functions.
  - Use PascalCase for constructors and React components.

  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.

  React Best Practices
  - Use functional components with prop-types for type checking.
  - Use the "function" keyword for component definitions.
  - Implement hooks correctly (useState, useEffect, useContext, useReducer, useMemo, useCallback).
  - Follow the Rules of Hooks (only call hooks at the top level, only call hooks from React functions).
  - Create custom hooks to extract reusable component logic.
  - Use React.memo() for component memoization when appropriate.
  - Implement useCallback for memoizing functions passed as props.
  - Use useMemo for expensive computations.
  - Avoid inline function definitions in render to prevent unnecessary re-renders.
  - Prefer composition over inheritance.
  - Use children prop and render props pattern for flexible, reusable components.
  - Implement React.lazy() and Suspense for code splitting.
  - Use refs sparingly and mainly for DOM access.
  - Prefer controlled components over uncontrolled components.
  - Implement error boundaries to catch and handle errors gracefully.
  - Use cleanup functions in useEffect to prevent memory leaks.
  - Use short-circuit evaluation and ternary operators for conditional rendering.

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

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

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

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

  Forms and Validation
- Use controlled components for form inputs.
- Implement form validation (client-side and server-side).
- Consider using libraries like react-hook-form for complex forms.
- Use Zod or Joi for schema validation.

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

  Accessibility (a11y)
- Use semantic HTML elements.
- Implement proper ARIA attributes.
- Ensure keyboard navigation support.

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

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

  Internationalization (i18n)
- Use libraries like react-intl or next-i18next for internationalization.

  Key Conventions
- Use 'nuqs' for URL search parameter state management.
- Optimize Web Vitals (LCP, CLS, FID).
- Limit 'use client':
  - Favor server components and Next.js SSR.
  - Use only for Web API access in small components.
  - Avoid for data fetching or state management.
- Balance the use of Tailwind utility classes with Stylus modules:
  - Use Tailwind for rapid development and consistent spacing/sizing.
  - Use Stylus modules for complex, unique component styles.

  Follow Next.js docs for Data Fetching, Rendering, and Routing.
css
javascript
jest
less
nestjs
next.js
radix-ui
react
+5 more
builders-garden/xmtp-1in1million

Used in 1 repository