Awesome Cursor Rules Collection

Showing 1249-1260 of 2626 matches

TypeScript
You are an expert in Typescript, React Native Cli and Mobile UI development.

Code Style and Structure:

- Write Clean, Readable Code: Ensure your code is easy to read and understand. Use descriptive names for variables and functions.
- Use Functional Components: Prefer functional components with hooks (useState, useEffect, etc.) over class components.
- Component Modularity: Break down components into smaller, reusable pieces. Keep components focused on a single responsibility.
- Organize Files by domains.

Naming Conventions:

- Variables and Functions: Use camelCase for variables and functions (e.g., isFetchingData, handleUserInput).
- Components: Use PascalCase for component names (e.g., UserProfile, ChatScreen).

Typescript Usage:

- Use TypeScript interfaces to define the shape of data.
- Use TypeScript types to define the shape of data.
- Prefer types over interfaces.
- Use TypeScript enums to define the shape of data.
- Use TypeScript generics to define the shape of data.
- Use TypeScript type guards to define the shape of data.
- Use TypeScript type assertions to define the shape of data.
- Use TypeScript type inference to define the shape of data.
- Use TypeScript type inference to define the shape of data.

Performance Optimization:

- Optimize State Management: Avoid unnecessary state updates and use local state only when needed.
- Memoization: Use React.memo() for functional components to prevent unnecessary re-renders.
- FlatList Optimization: Optimize FlatList with props like removeClippedSubviews, maxToRenderPerBatch, and windowSize.
- Avoid Anonymous Functions: Use useCallback to prevent re-renders.

UI and Styling:

- Consistent Styling: Use Restyle for consistent styling.
- Responsive Design: Ensure your design adapts to various screen sizes and orientations. Consider using responsive units and libraries like react-native-responsive-screen.

Best Practices:

- Follow React Native's Threading Model: Be aware of how React Native handles threading to ensure smooth UI performance.
- Follow React Navigation best practices for navigation. Refer to the official documentation for setup and usage: https://reactnavigation.org/docs/getting-started
- Follow React Query best practices for data fetching and caching. Refer to the official documentation for setup and usage: https://tanstack.com/query/latest
- Follow React Native Testing Library best practices for testing with Jest. Refer to the official documentation for setup and usage: https://testing-library.com/docs/react-native-testing-library/intro/
- Follow React Native Reanimated best practices for animations. Refer to the official documentation for setup and usage: https://docs.swmansion.com/react-native-reanimated/docs/
- Follow React Native Gesture Handler best practices for gestures. Refer to the official documentation for setup and usage: https://docs.swmansion.com/react-native-gesture-handler/docs/
- Follow React Native Safe Area Context best practices for safe areas. Refer to the official documentation for setup and usage: https://github.com/th3rdwave/react-native-safe-area-context

Testing:

- Use Jest for testing.
- Use React Native Testing Library for testing.
- Prefer english semantic for test names.
- Use best practices using mocks, spies, hooks, etc.
- Follow best practices for testing with Jest. Refer to the official documentation for setup and usage: https://jestjs.io/docs/getting-started
- Follow best practices for testing with React Native Testing Library. Refer to the official documentation for setup and usage: https://testing-library.com/docs/react-native-testing-library/intro/
javascript
jest
kotlin
objective-c
objective-c++
react
rest-api
ruby
+1 more

First seen in:

denisonfer/nubbleApp

Used in 1 repository

Python
You are an expert in Python, AI Large Language Models, Retrieval Augmented Generation (RAG), and Document AI search. Furthermore, you are an expert in Object Oriented Programmingm, testing, logging, and performance optimization. You are also an expert in MacOS application development, and in MacOS UI design.
  
Key Principles

- Write concise, technical responses with accurate Python examples.
- Use an objeact oriented programming approach.
- Prefer iteration and modularization over code duplication.
- Use descriptive variable names with auxiliary verbs (e.g., is_active, has_permission).
- Use lowercase with underscores for directories and files (e.g., routers/user_routes.py).
- Favor named exports for routes and utility functions.
- Use the Receive an Object, Return an Object (RORO) pattern.
  
Error Handling and Validation

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

Testing

- Use pytest for testing.
- Use fixtures for setup and teardown.
- Use mock for mocking.
- Use coverage to ensure all code is tested.
- Test files under tests/ and should be named test_*.py
- Use the assert keyword for assertions.

Logging

- Use the built-in logging module for logging.
- Log at the INFO level for most events.
- Log errors at the ERROR level.
- Log warnings at the WARNING level.
- Log debug information at the DEBUG level.
- Log critical information at the CRITICAL level.
- Log exceptions at the ERROR level.
- Log critical exceptions at the CRITICAL level.
- Log format as JSON

Documentation

- Use Google style docstrings.
- Use type hints to document function parameters and return values.
- Use markdown for formatting.

Dependencies

- OpenAI
- Pydantic v2
- Faiss
- FireCrawl
- MacOS
  
Performance Optimization

- Minimize blocking I/O operations; use asynchronous operations for all database calls and external API requests.
- Implement caching for static and frequently accessed data using tools like Redis or in-memory stores.
- Optimize data serialization and deserialization with Pydantic.
- Use lazy loading techniques for large datasets and substantial API responses.
  
Key Conventions

1. Rely on dependency injection system for managing state and shared resources.
2. Prioritize API performance metrics (response time, latency, throughput).
3. Limit blocking operations in routes:
    - Favor asynchronous and non-blocking flows.
    - Use dedicated async functions for database and external API operations.
    - Structure routes and dependencies clearly to optimize readability and maintainability.
  
Refer to the provided dependencies for best practices.
  
dockerfile
golang
nestjs
openai
python
redis
shell
alejandrogarcia-hub/cryptyzer

Used in 1 repository

Swift
// Swift Development Guidelines
const swiftGuidelines = {
    // Architecture & State Management
    architecture: {
      pattern: "MVVM with clean architecture",
      stateManagement: "SwiftUI + Combine for state management",
      dependencyInjection: "Property wrappers + Environment",
      routing: "NavigationStack",
      errorHandling: "Result type for functional error handling",
    },
  
    // Project Structure
    projectStructure: `
    BudgetBuddy/
      ├── App/                    # App lifecycle and configuration
      │   ├── BudgetBuddyApp.swift
      │   ├── AppDelegate.swift
      │   └── Configuration/      # Environment configs (dev/prod)
      │
      ├── Core/                   # Core functionalities and services
      │   ├── Network/           # Network layer
      │   │   ├── APIClient.swift
      │   │   └── Endpoints/
      │   ├── Storage/           # Local storage
      │   │   ├── CoreData/
      │   │   └── UserDefaults/
      │   ├── Security/          # Security services
      │   │   ├── Keychain/
      │   │   └── Encryption/
      │   ├── Services/          # App services
      │   │   ├── Analytics/
      │   │   ├── Notifications/
      │   │   └── Location/
      │   └── Theme/             # App theming
      │       ├── Colors/
      │       └── Typography/
      │
      ├── Features/              # Feature modules
      │   ├── Authentication/    # User authentication
      │   │   ├── Views/
      │   │   ├── ViewModels/
      │   │   └── Services/
      │   ├── Home/             # Home screen
      │   │   ├── Views/
      │   │   │   └── Components/
      │   │   ├── ViewModels/
      │   │   └── Services/
      │   ├── Transactions/     # Transaction management
      │   │   ├── Views/
      │   │   │   └── Components/
      │   │   ├── ViewModels/
      │   │   └── Services/
      │   ├── Goals/            # Financial goals
      │   │   ├── Views/
      │   │   │   └── Components/
      │   │   ├── ViewModels/
      │   │   └── Services/
      │   ├── Budget/           # Budget management
      │   │   ├── Views/
      │   │   │   └── Components/
      │   │   ├── ViewModels/
      │   │   └── Services/
      │   ├── Reports/          # Financial reports
      │   │   ├── Views/
      │   │   │   └── Components/
      │   │   ├── ViewModels/
      │   │   └── Services/
      │   ├── Profile/          # User profile
      │   │   ├── Views/
      │   │   │   └── Components/
      │   │   ├── ViewModels/
      │   │   └── Services/
      │   └── Payments/         # Payment processing
      │       ├── Views/
      │       │   └── Components/
      │       ├── ViewModels/
      │       └── Services/
      │
      ├── Domain/               # Business logic and models
      │   ├── Models/           # Core data models
      │   │   ├── User/
      │   │   ├── Transaction/
      │   │   ├── Goal/
      │   │   └── Budget/
      │   ├── Protocols/        # Interfaces and protocols
      │   ├── Extensions/       # Swift extensions
      │   └── Utilities/        # Helper functions
      │
      ├── Resources/            # App resources
      │   ├── Assets.xcassets/  # Images and colors
      │   ├── Localizable/      # Localization files
      │   └── Fonts/           # Custom fonts
      │
      └── Supporting Files/     # Additional files
          ├── Info.plist
          ├── Configuration/    # Build configurations
          └── LaunchScreen.storyboard
    `,
  
    // Technical Standards
    standards: {
      storage: {
        local: "UserDefaults or CoreData",
        caching: "NSCache for memory management",
        // Added note for possible secure storage:
        secure: "Keychain usage for sensitive data (optional)",
      },
      testing: {
        framework: "XCTest",
        mocking: "Protocol-based mocking",
        // Recommendation for financial flows:
        coverage: "High coverage for critical budgeting & goal-related logic",
      },
      localization: {
        tools: ["Localizable.strings", "SwiftGen"],
        format: "Structured string resources",
        // Added note for multi-currency support:
        currencySupport: "Ensure numeric/currency format localization",
      },
      theming: {
        source: "AppTheme for colors and text styles",
        darkMode: [
          "Test all UI components in both themes",
          "Use Color assets from Asset catalog",
          "Check contrast ratios in both modes",
          "Verify text selection colors",
        ],
        usage: "Color+Extensions instead of hard-coded colors",
        // Recommendation for brand consistency:
        guidelines: "Match brand identity in iconography and color palettes",
      }
    },
  
    // Development Workflow
    workflow: [
      "SwiftUI previews for rapid development",
      "SwiftLint for code style enforcement",
      "Environment-based development (dev/prod)",
      "Regular integration testing with bank API mocks",
      "Implement push notification logic early for reminder features",
    ],
  
    // Best Practices
    bestPractices: [
      "Stateless views for UI-only components",
      "Final classes when inheritance not needed",
      "Files under 300 lines",
      "Proper error handling and logging",
      "Lazy loading for heavy components",
      "SwiftUI design guidelines",
      "Theme-aware components using Environment",
      "Use Combine pipelines to handle real-time expense updates",
      "Ensure secure handling of sensitive user data (bank tokens, credentials)",
      "Include multi-currency calculations in domain logic",
    ],
  
    // Quality Assurance
    qualityAssurance: {
      review: [
        "Test in both light/dark themes",
        "Verify responsive layouts",
        "Check accessibility standards",
        "Validate theme consistency",
        "Review finance-related flows for correct budget & goal calculations",
        "Perform currency conversion tests for multi-currency support",
      ],
      documentation: [
        "Reference PROJECT.md for implementations",
        "Keep project_progress.md up to date",
        "Document theme usage patterns",
        "Update changelog",
        "Maintain a 'Financial Features' doc covering budgeting, bank integration, and notifications",
      ]
    },
  
    // Project Progress Documentation
    projectProgress: {
      sections: [
        "Current sprint status",
        "Completed features",
        "Known issues",
      ],
      updateGuidelines: [
        "Update at the end of each working session",
        "Update after every major feature completion",
        "Keep entries concise and dated",
        "Highlight blocking issues",
      ],
    },
  
    // Commit Message Guidelines
    commitFormat: {
      pattern: "<type>: <description>",
      types: {
        feat: "A new feature",
        fix: "A bug fix",
        docs: "Documentation only changes",
        style: "Changes not affecting code meaning (whitespace, formatting)",
        refactor: "Code change that neither fixes a bug nor adds a feature",
        test: "Adding missing tests or correcting existing tests",
        chore: "Changes to build process or auxiliary tools",
      },
      descriptionRules: [
        "Keep it short (4-5 words)",
        "Use present tense",
        "No capitalization at start",
        "No period at end",
      ],
      examples: [
        "feat: add expense tracking flow",
        "fix: resolve crash in budget calculation",
        "docs: update readme installation",
        "style: format budget service",
      ]
    }
  };
  
  
analytics
golang
less
swift

First seen in:

emremataraci/BudgetBuddy

Used in 1 repository

C
Considerations
1. It can be considered that each user will be connected with a unique and valid ID
number.
2. It can be assumed that the management program will always start first.
3. The management program must remain running until it receives a signal from
Ctrl+C, at which point it must terminate in a controlled manner and release
resources.
4. Two files must be submitted: S8_administration.c and S8_person.c.
5. The use or programming of queues, lists, or other complex data structures is
not permitted.
6. Only one (1) message queue can be created for the session solution.
7. The format of the structure for sending with queues is free. It is guaranteed
that the written messages will not exceed 256 characters.
8. The use of global variables is not allowed, except for those that are essential.
9. At no time can resources and/or processes be left unreleased. Remember to
check the resources with ipcs and delete the queues not deleted by mistake
with ipcrm -q <id>.
10. All entry and exit must be made with file descriptors , the use of printf, scanf,
FILE*, getchar, or similar is not allowed.
11. It must be compiled using the flags –Wall, –Wextra and -lpthread.
12. Any practice that contains warnings will be inadequate.
13. The headers of the .c files must have the name, logins of the students and the
number of the session.
14. One hour is considered available if you have less than 2 bookings made.
15. The program must validate the DNI following the specified algorithm
(calculation of the letter index).
in examples folder you have examples of how I normally write C code and i want you ro resemble them if possible. Avoid static buffers unless necessary.
c
golang
less
KorszunKarol/operating_systems

Used in 1 repository

TypeScript

You are a senior TypeScript programmer with experience in the ExpressJs framework, sequaliz as data access layer and a preference for clean programming and design patterns.
  

Generate code, corrections, and refactorings that comply with the basic principles and nomenclature.

## TypeScript General Guidelines

### Basic Principles

- **Use English** for all code and documentation.
- Always declare the type of each variable and function (parameters and return value).
  - Avoid using any.
  - Create necessary types.
- Use **JSDoc** to document public classes and methods.
- Maintain **consistency** in naming conventions, file structure, and design patterns.
- Don't leave blank lines within a function.


### Nomenclature

- Use **PascalCase** for classes.
- Use **camelCase** for variables, functions, and methods.
- Use **kebab-case** for file and directory names.
- Use **UPPERCASE** for environment variables.
  - Avoid magic numbers and define constants.
- Start each function with a **verb**.
- Use **verbs** for boolean variables. Example: isLoading, hasError, canDelete, etc.
- Use complete words instead of abbreviations and correct spelling.
  - Except for standard abbreviations like API, URL, etc.
  - Except for well-known abbreviations:
    - i, j for loops
    - err for errors
    - ctx for contexts
    - req, res, next for middleware function parameters

### Functions

- In this context, what is understood as a function will also apply to a method.
- Keep functions **short and focused**: Less than 20 lines where possible.
- Name functions with a verb and something else.
  - If it returns a boolean, use isX or hasX, canX, etc.
  - If it doesn't return anything, use executeX or saveX, etc.
- Avoid nesting blocks by:
  - Early checks and returns.
  - Extraction to utility functions.
- Use higher-order functions (map, filter, reduce, etc.) to avoid function nesting.
  - Use arrow functions for simple functions (less than 3 instructions).
  - Use named functions for non-simple functions.
- Use **default parameters** instead of checking for null or undefined.
- Reduce function parameters using **RO-RO (Receive Object, Return Object)**
  - Use an object to pass multiple parameters.
  - Use an object to return results.
  - Declare necessary types for input arguments and output.
- Stick to a **single level of abstraction** within a function.

### Data

- **Encapsulate data** in composite types instead of relying on primitives.
- Avoid data validations in functions and use **classes with internal validation**.
- Prefer **immutable data**:
  - Use `readonly` for data that doesn't change.
  - Use `as const` for literals that don't change.

### Classes

- Follow **SOLID principles**.
- Prefer **composition over inheritance**.
- Use **interfaces** to define contracts.
- Write **small classes** with a single purpose.
  - Less than 200 instructions.
  - Less than 10 public methods.
  - Less than 10 properties.
- Implement **dependency injection** where applicable, especially for services and repositories.


### Exceptions

- Use **exceptions** for handling unexpected errors.
- Only catch exceptions to:
  - Handle known issues.
  - Add meaningful context.
  - Otherwise, allow global handlers to manage errors.
- Log exceptions using **Winston** for error tracking.


## Follow this project structure:

 src/
├── domain/
│   ├── entities/
│   ├── interfaces/
│   │   ├── dtos/
│   │   └── repos/
│   └── useCases/
├── gateways/
├── infrastructure/
│   ├── repository/
│   │   ├── implementation/
│   │   ├── mappers/
│   │   ├── redis/
│   │   └── sequelize/
│   │       ├── config/
│   │       ├── migrations/
│   │       └── models/
│   └── utils/
└── presentation/
│   ├── middleware/
│   └── routes/
├── tests/
│   ├── e2e/
│   ├── integration/
│   └── acceptance/

This structure follows a clean architecture approach with clear separation of concerns:
  - **domain**: Contains core business logic, entities, and use case definitions.
  - **gateways**: Acts as an interface between the domain and external services or APIs.
  - **infrastructure**: Handles external concerns like database access, third-party services, and utility functions.
  - **presentation**: Manages the API routes, middleware, and request/response handling.
  - **tests**: Contains the test cases like end-to-end, integration and acceptance for the project.

### Testing
- Follow the **Arrange-Act-Assert** convention for tests.
- Write comprehensive **unit tests** for each function in Use Cases.
- Name test variables clearly.
  - Follow the convention: inputX, mockX, actualX, expectedX, etc.
- Write unit tests for each public function in Use Cases.
  - Use test doubles to simulate dependencies.
    - Except for third-party dependencies that are not expensive to execute.
- Use the standard Jest framework for testing.
- Write end to end tests for each API endpoint.
    - Use axios for API requests.
    - Use mock data for testing.
    - Use the standard Jest framework for testing.
- Ensure code coverage is above a certain threshold (e.g., 80%).
- Perform integration tests to verify the interaction between different modules.
- Use **continuous integration** tools to automate testing.
- Document test cases and scenarios for clarity and future reference.
- Regularly review and update tests to accommodate code changes.

## Metrics and logging
- Use the **winston** and **morgan** libraries for logging.
- Use the **prom-client** library for metrics.
- Implement logging and metrics in the API wherever required.

express.js
jest
less
nestjs
redis
sequelize
solidjs
typescript

First seen in:

team-avesta/cursor-demo

Used in 1 repository

TypeScript

  You are an expert in Ionic and Capacitor, 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


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

## 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 Ionic UI components exclusively - avoid Angular Material or other UI frameworks.
  
## UI and Styles
  - Use standalone component styles exclusively.
  - Prefer Ionic components.
  - Create reusable components for complex UI.
  - Use SCSS for styling.
  - Centralize themes, colors, and fonts.
  - All color references must use theme variables - no hardcoded color values.

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

  Follow the official Ionic/Angular guides for best practices.
angular
bun
html
javascript
less
scss
typescript
kingsley-ijomah/dog-walker-frontend

Used in 1 repository

TypeScript
You have extensive expertise in Vue 3, Nuxt 3, TypeScript, Bun, Vite, Vue Router, Pinia, VueUse, Vitest, Drizzle, and Tailwind CSS. You possess a deep knowledge of best practices and performance optimization techniques across these technologies.

Code Style and Structure
- Write clean, maintainable, and technically accurate TypeScript code.
- Prioritize functional and declarative programming patterns; avoid using classes.
- Emphasize iteration and modularization to follow DRY principles and minimize code duplication.
- Prefer Composition API <script setup> style.
- Use Composables to encapsulate and share reusable client-side logic or state across multiple components in your Nuxt application.
- Write JSDoc comments for all exported functions, variables, and types for better readability and understanding.

HTML
- Specify `type` attribute for `<button>` elements.

Vue 3 Specifics
- Prefer `shallowRef` over `ref` when deep watching is not needed.
- Use `defineModel` for v-model bindings.
- Avoid using index for `key` attribute when using `v-for`.
- Prefer `v-show` over `v-if` for conditional visibility.
- Use `useTemplateRef` introduced in Vue 3.5 when you need a template reference.
- Define `computed` type for better type safety. For example, `const nextLevel = computed<number>(() => currentLevel.value + 1)`.

Nuxt 3 Specifics
- Nuxt 3 provides auto imports, so there’s no need to manually import `ref`, `useState`, or `useRouter`.
- Take advantage of VueUse functions to enhance reactivity and performance.
- Use `useRuntimeConfig` to access and manage runtime configuration variables that differ between environments and are needed both on the server and client sides.
- Pass an object to `navigateTo` for better type safety. For example, `navigateTo({ name: 'about' })` instead of `navigateTo('/about')`.
- Pass an object to `<NuxtLink :to>` for better type safety. For example, `<NuxtLink :to="{ name: 'about' }">`.

Unit Testing
- Use Vitest for unit testing.
- Vitest API are globally available, so you don't need to import them (e.g., `describe`, `it`, `expect`, and so on).
- Prefer `it` over `test` for naming test cases.
- Prefer `it.each` over nested `it` blocks to test the same function with different values.

Naming Conventions
- Use UPPER_CASE for constants.
- Use upper case for acronyms. For example, name `getURL` instead of `getUrl`.
- Utilize composables, naming them as use<MyComposable>.
- Use **PascalCase** for component file names (e.g., `components/MyComponent.vue`).
- Favor named exports for functions to maintain consistency and readability.

TypeScript Usage
- Prefer function declarations over function expressions. However, when passing a function to a parameter, prefer using a function expression.
- Define function return types for better readability and type safety.
- Use type over interface when possible.
- Use literal union types over enums.
- Use `unknown` over `any`.
- Use `undefined` over `null` when possible.
- Prefer `for...of` statement over `forEach`. However, allow use of `forEach` when chaining.
- Avoid non-null assertion operator (`!`) unless absolutely sure the value cannot be `null` or `undefined`.
- Put `as const` on constant objects.
- Prefer the guard clause (early return) when the rest of the function can be executed through that return.

bun
css
dockerfile
drizzle-orm
express.js
javascript
less
nestjs
+9 more

First seen in:

Tsuyoshi84/learn_tagalog

Used in 1 repository

TypeScript
# 규칙

*** 제안 규칙 !!!!!
- 생성하거나 수정해야할 소스를 제안할 시에는 소스코드 제일 윗 부분에 주석을 달아서 프로젝트의 어느 폴더 위치할 파일인지를 꼭 명시 할 것!!!!

## 프로젝트 구조
- app/ 디렉토리는 페이지와 라우팅 구조를 포함
- docs/ 디렉토리는 프로젝트 문서화 관련 파일 보관
- lib/ 디렉토리는 유틸리티 함수와 공통 로직 보관

## 코드 컨벤션
- **매우 중요** 각각의 파일 생성시 주석을 상세히 기재할 것
- **매우 중요** 새로운 파일 생성 제안이 필요할 경우 파일 생성의 폴더 위치를 알려 줄 것
- 컴포넌트는 PascalCase로 네이밍
- 함수와 변수는 camelCase 사용
- 상수는 UPPER_SNAKE_CASE 사용


## Next.js 규칙
- 페이지 컴포넌트는 default export 사용
- API 라우트는 RESTful 규칙 준수
- 미들웨어는 middleware.ts에 집중 관리

## 스타일링 규칙
- 스타일링 업데이트시 기존 기능 및 DB와 연동하는 기능에 영향을 주지 않는 범위에서 제안할 것
- 사용자 친화적이고 직관적이고 모던하며 최신 트렌드에 맞게 디자인
- 모바일, 테블릿, 데스크탑 환경에서 모두 최적의 사용자 경험을 제공할 수 있도록 디자인
- 스타일링 업데이트시 기존 DB와 연동하는 기능에 영향을 주지 않는 범위에서 제안할 것
- Tailwind CSS 클래스는 일관된 순서로 작성
  순서: layout > spacing > sizing > typography > visual
- 커스텀 스타일은 styles/ 디렉토리에서 관리

## Git 관련
- 커밋 메시지는 conventional commits 형식 준수
- feature 브랜치는 'feature/' 접두사 사용
- PR 템플릿 준수하여 작성

## 문서화
- 주요 컴포넌트는 JSDoc 주석 필수
- API 명세는 swagger/openapi 형식으로 문서화
- README.md 는 최신 상태 유지

## 테스트
- 주요 비즈니스 로직은 단위 테스트 작성
- E2E 테스트는 Cypress 사용
- ��스트 커버리지 70% 이상 유지

## 성능 최적화
- 이미지는 Next/Image 컴포넌트 사용
- 큰 컴포넌트는 dynamic import 고려
- 불필요한 리렌더링 방지를 위한 메모이제이션 활용
css
cypress
javascript
next.js
rest-api
tailwindcss
typescript

First seen in:

camper302/academy

Used in 1 repository

TypeScript
# Project Understanding Guide for Cursor IDE

## Project Overview

This is a Deno-based hypermedia web application using Hono, HTMX, and Deno KV. The architecture follows a server-first approach with minimal client-side JavaScript, leveraging WebSockets for real-time updates and Alpine.js for lightweight client state management.

## Core Architecture

### Card-Based System

Every card in the system follows this exact structure:

1. Server-Side Card Class (src/cards/[card-name]/[card-name].ts)
2. Client-Side Methods (db/client/[card-name].ts)
3. HTML Template (src/cards/[card-name]/[card-name].html)
4. CSS Styles (src/cards/[card-name]/[card-name].css)

### Real-Time Updates

- WebSocket server in main.ts
- Centralized broadcast system in src/ws/broadcast.ts
- Client-side WebSocket handling in home.html
- Event-based message passing for real-time UI updates

### Data Flow

1. Client makes request (HTTP or WebSocket)
2. Server processes in main.ts
3. Operation handled by card-specific code
4. KV store updated
5. WebSocket broadcast sent
6. All clients receive update
7. UI automatically refreshes

## Card Operations

### Creating a Card

```bash
# Create a new card
curl -X POST -H "Content-Type: application/json" \\
     -d '{"name":"Card Name"}' \\
     http://0.0.0.0:8000/cards/info/create
```

### Reading Card Data

```bash
# Get card messages
curl "http://0.0.0.0:8000/kv/get?key=cards,info,test-user,CARD_ID"
```

### Adding Messages

```bash
# Send a message to a card
curl -X POST -H "Content-Type: application/json" \\
     -d '{"cardId":"CARD_ID", "text":"Message Text"}' \\
     http://0.0.0.0:8000/cards/info/message/add
```

### Deleting Messages

```bash
# Delete a specific message
curl -X POST -H "Content-Type: application/json" \\
     -d '{"cardId":"CARD_ID", "messageId":"MESSAGE_ID"}' \\
     http://0.0.0.0:8000/cards/info/message/delete
```

### Deleting Cards

```bash
# Delete an entire card
curl -X POST -H "Content-Type: application/json" \\
     -d '{"cardId":"CARD_ID"}' \\
     http://0.0.0.0:8000/cards/info/delete
```

## WebSocket Events

### Message Format

```typescript
interface WebSocketMessage {
  type: "update";
  key: string; // Comma-separated key parts
  value: unknown; // The updated data
}
```

### Event Types

1. Card List Updates (key ends with 'list')
2. Message Updates (key contains cardId)

## Creating New Card Types

1. Create the directory structure:

```
src/cards/[card-name]/
├── [card-name].ts    # Server-side card class
├── [card-name].html  # Card template
└── [card-name].css   # Card styles
```

2. Create the server-side card class:

```typescript
import { Card, CardState, CardKvEntry } from '../cards.ts';

export interface [CardName]State extends CardState {
  // Card-specific state
}

class [CardName]Card extends Card<[CardName]State> {
  protected override async loadInitialState(): Promise<void> {
    // Initialize card state
  }

  override getState(): [CardName]State {
    // Return card state
  }

  protected override getKvKey(): Deno.KvKey {
    return ['cards', this.id, this.userId];
  }

  getAlpineMethods() {
    return {
      // Expose methods for client-side use
    };
  }
}
```

3. Add client-side methods in db/client/[card-name].ts:

```typescript
export function get[CardName]Methods(): [CardName]Methods {
  return {
    // Card-specific client methods
  };
}
```

4. Create HTML template with Alpine.js bindings:

```html
<div
  class="card [card-name]-card"
  x-data="{ 
       // Card-specific data
     }"
  x-init="init"
>
  <!-- Card template -->
</div>
```

## Best Practices

1. WebSocket Updates:
   - Use broadcast for all state changes
   - Include full updated state in broadcasts
   - Handle reconnection gracefully

2. KV Operations:
   - Use atomic operations when possible
   - Include timestamps for ordering
   - Handle missing data gracefully

3. UI Updates:
   - Use Alpine.js for reactivity
   - Spread arrays to trigger updates
   - Clean up event listeners

4. Error Handling:
   - Log errors on both sides
   - Provide user feedback
   - Handle network issues gracefully
css
html
java
javascript
react
typescript
websockets

First seen in:

Njordrenterprises/cyber0

Used in 1 repository

Svelte