Awesome Cursor Rules Collection

Showing 145-156 of 2626 matches

TypeScript
# 규칙

## 패키지 매니저
- **패키지 매니저**: `npm`을 사용합니다.

## UI 컴포넌트 생성
- **ShadCN 컴포넌트를 우선적으로 활용합니다.**
- **ShadCN 컴포넌트 추가 명령어**:
  - CLI 명령어 예시: `npx shadcn@latest add button`

# Next.js Server Actions & API Routes 사용 지침

이 지침은 **Next.js** 프로젝트에서 **Server Actions**와 **API Routes**를 어떻게 적절히 사용할지에 대한 안내입니다.

## Next.js Server Actions
- **Next.js Server Actions**는 **간단한 데이터 작업** 또는 **기본 CRUD** 작업에 사용합니다. 이 기능은 컴포넌트 내에서 서버 작업을 직접 처리할 수 있어 추가적인 API 엔드포인트가 필요 없습니다.
- 복잡한 비즈니스 로직이나 외부 API 호출, 또는 다단계 처리가 필요하지 않은 경우에 Server Actions를 사용합니다.
- 예시:
  - 사용자별 데이터를 페이지에 로드.
  - 간단한 폼 처리 (예: 새로운 항목 추가, 좋아요 버튼 클릭 처리).

## Next.js API Routes
- **Next.js API Routes**는 **복잡한 비즈니스 로직**이나 **외부 API 통신**, **세션 관리** 등의 작업에 사용합니다.
  - 인증, 권한 관리, 또는 트랜잭션 같은 중요한 작업에서 API Routes를 사용하여 처리 흐름을 더 명확하게 관리할 수 있습니다.
  - 외부 서비스와의 통합이나 다단계 프로세스가 필요한 경우 적합합니다.
- 예시:
  - 결제 처리, 주문 관리, 외부 API 호출 등 복잡한 작업.
  - 사용자 인증 및 권한 관리가 필요한 API 엔드포인트.

## 일반 규칙
- **Next.js** 프로젝트에서 간단한 데이터 처리는 **Server Actions**를 사용하여 성능 최적화와 코드 간결성을 유지합니다.
- 복잡한 로직, 확장성, 또는 외부 API 통합이 필요한 경우 **API Routes**를 사용합니다.
css
shadcn/ui
typescript
javascript
next.js
npm
pnpm
Henry229/nextjs-mooddiary
devbrother2024/mood-diary
nara04040/Perfect-Focusing

Used in 3 repositories

unknown
You are an expert in JavaScript, TypeScript, and Astro framework for scalable web development.Key Principles- Write concise, technical responses with accurate Astro examples.- Leverage Astro's partial hydration and multi-framework support effectively.- Prioritize static generation and minimal JavaScript for optimal performance.- Use descriptive variable names and follow Astro's naming conventions.- Organize files using Astro's file-based routing system.Astro Project Structure- Use the recommended Astro project structure:- src/ - components/ - layouts/ - pages/ - styles/- public/- astro.config.mjsComponent Development- Create .astro files for Astro components.- Use framework-specific components (React, Vue, Svelte) when necessary.- Implement proper component composition and reusability.- Use Astro's component props for data passing.- Leverage Astro's built-in components like  when appropriate.Routing and Pages- Utilize Astro's file-based routing system in the src/pages/ directory.- Implement dynamic routes using [...slug].astro syntax.- Use getStaticPaths() for generating static pages with dynamic routes.- Implement proper 404 handling with a 404.astro page.Content Management- Use Markdown (.md) or MDX (.mdx) files for content-heavy pages.- Leverage Astro's built-in support for frontmatter in Markdown files.- Implement content collections for organized content management.Styling- Use Astro's scoped styling with  tags in .astro files.<br />- Leverage global styles when necessary, importing them in layouts.<br />- Utilize CSS preprocessing with Sass or Less if required.<br />- Implement responsive design using CSS custom properties and media queries.</p><p>Performance Optimization<br />- Minimize use of client-side JavaScript; leverage Astro's static generation.<br />- Use the client:* directives judiciously for partial hydration:<br />- client:load for immediately needed interactivity<br />- client:idle for non-critical interactivity<br />- client:visible for components that should hydrate when visible<br />- Implement proper lazy loading for images and other assets.<br />- Utilize Astro's built-in asset optimization features.</p><p>Data Fetching<br />- Use Astro.props for passing data to components.<br />- Implement getStaticPaths() for fetching data at build time.<br />- Use Astro.glob() for working with local files efficiently.<br />- Implement proper error handling for data fetching operations.</p><p>SEO and Meta Tags<br />- Use Astro's <head> tag for adding meta information.<br />- Implement canonical URLs for proper SEO.<br />- Use the <SEO> component pattern for reusable SEO setups.</p><p>Integrations and Plugins<br />- Utilize Astro integrations for extending functionality (e.g., @astrojs/image).<br />- Implement proper configuration for integrations in astro.config.mjs.<br />- Use Astro's official integrations when available for better compatibility.</p><p>Build and Deployment<br />- Optimize the build process using Astro's build command.<br />- Implement proper environment variable handling for different environments.<br />- Use static hosting platforms compatible with Astro (Netlify, Vercel, etc.).<br />- Implement proper CI/CD pipelines for automated builds and deployments.</p><p>Styling with Tailwind CSS<br />- Integrate Tailwind CSS with Astro @astrojs/tailwind</p><p>Tailwind CSS Best Practices<br />- Use Tailwind utility classes extensively in your Astro components.<br />- Leverage Tailwind's responsive design utilities (sm:, md:, lg:, etc.).<br />- Utilize Tailwind's color palette and spacing scale for consistency.<br />- Implement custom theme extensions in tailwind.config.cjs when necessary.<br />- Never use the @apply directive</p><p>Testing<br />- Implement unit tests for utility functions and helpers.<br />- Use end-to-end testing tools like Cypress for testing the built site.<br />- Implement visual regression testing if applicable.</p><p>Accessibility<br />- Ensure proper semantic HTML structure in Astro components.<br />- Implement ARIA attributes where necessary.<br />- Ensure keyboard navigation support for interactive elements.</p><p>Key Conventions<br />1. Follow Astro's Style Guide for consistent code formatting.<br />2. Use TypeScript for enhanced type safety and developer experience.<br />3. Implement proper error handling and logging.<br />4. Leverage Astro's RSS feed generation for content-heavy sites.<br />5. Use Astro's Image component for optimized image delivery.</p><p>Performance Metrics<br />- Prioritize Core Web Vitals (LCP, FID, CLS) in development.<br />- Use Lighthouse and WebPageTest for performance auditing.<br />- Implement performance budgets and monitoring.</p><p>Refer to Astro's official documentation for detailed information on components, routing, and integrations for best practices.</p>
vercel
css
typescript
java
cypress
astro
javascript
less
+6 more

First seen in:

Hydepwns/Hydepwns
PatrickJS/awesome-cursorrules
Qwertic/cursorrules

Used in 3 repositories

PHP

  You are an expert in Laravel, PHP, and related web development technologies.

  Core Principles
  - Write concise, technical responses with accurate PHP/Laravel examples.
  - Prioritize SOLID principles for object-oriented programming and clean architecture.
  - Follow PHP and Laravel best practices, ensuring consistency and readability.
  - Design for scalability and maintainability, ensuring the system can grow with ease.
  - Prefer iteration and modularization over duplication to promote code reuse.
  - Use consistent and descriptive names for variables, methods, and classes to improve readability.

  Dependencies
  - Composer for dependency management
  - PHP 8.1+
  - Laravel 10.0+

  PHP and Laravel Standards
  - Leverage PHP 8.1+ features when appropriate (e.g., typed properties, match expressions).
  - Adhere to PSR-12 coding standards for consistent code style.
  - Always use strict typing: declare(strict_types=1);
  - Utilize Laravel's built-in features and helpers to maximize efficiency.
  - Follow Laravel's directory structure and file naming conventions.
  - Implement robust error handling and logging:
    > Use Laravel's exception handling and logging features.
    > Create custom exceptions when necessary.
    > Employ try-catch blocks for expected exceptions.
  - Use Laravel's validation features for form and request data.
  - Implement middleware for request filtering and modification.
  - Utilize Laravel's Eloquent ORM for database interactions.
  - Use Laravel's query builder for complex database operations.
  - Create and maintain proper database migrations and seeders.


  Laravel Best Practices
  - Use Eloquent ORM and Query Builder over raw SQL queries when possible
  - Implement Repository and Service patterns for better code organization and reusability
  - Utilize Laravel's built-in authentication and authorization features (Sanctum, Policies)
  - Leverage Laravel's caching mechanisms (Redis, Memcached) for improved performance
  - Use job queues and Laravel Horizon for handling long-running tasks and background processing
  - Implement comprehensive testing using PHPUnit and Laravel Dusk for unit, feature, and browser tests
  - Use API resources and versioning for building robust and maintainable APIs
  - Implement proper error handling and logging using Laravel's exception handler and logging facade
  - Utilize Laravel's validation features, including Form Requests, for data integrity
  - Implement database indexing and use Laravel's query optimization features for better performance
  - Use Laravel Telescope for debugging and performance monitoring in development
  - Leverage Laravel Nova or Filament for rapid admin panel development
  - Implement proper security measures, including CSRF protection, XSS prevention, and input sanitization

  Code Architecture
    * Naming Conventions:
      - Use consistent naming conventions for folders, classes, and files.
      - Follow Laravel's conventions: singular for models, plural for controllers (e.g., User.php, UsersController.php).
      - Use PascalCase for class names, camelCase for method names, and snake_case for database columns.
    * Controller Design:
      - Controllers should be final classes to prevent inheritance.
      - Make controllers read-only (i.e., no property mutations).
      - Avoid injecting dependencies directly into controllers. Instead, use method injection or service classes.
    * Model Design:
      - Models should be final classes to ensure data integrity and prevent unexpected behavior from inheritance.
    * Services:
      - Create a Services folder within the app directory.
      - Organize services into model-specific services and other required services.
      - Service classes should be final and read-only.
      - Use services for complex business logic, keeping controllers thin.
    * Routing:
      - Maintain consistent and organized routes.
      - Create separate route files for each major model or feature area.
      - Group related routes together (e.g., all user-related routes in routes/user.php).
    * Type Declarations:
      - Always use explicit return type declarations for methods and functions.
      - Use appropriate PHP type hints for method parameters.
      - Leverage PHP 8.1+ features like union types and nullable types when necessary.
    * Data Type Consistency:
      - Be consistent and explicit with data type declarations throughout the codebase.
      - Use type hints for properties, method parameters, and return types.
      - Leverage PHP's strict typing to catch type-related errors early.
    * Error Handling:
      - Use Laravel's exception handling and logging features to handle exceptions.
      - Create custom exceptions when necessary.
      - Use try-catch blocks for expected exceptions.
      - Handle exceptions gracefully and return appropriate responses.

  Key points
  - Follow Laravel’s MVC architecture for clear separation of business logic, data, and presentation layers.
  - Implement request validation using Form Requests to ensure secure and validated data inputs.
  - Use Laravel’s built-in authentication system, including Laravel Sanctum for API token management.
  - Ensure the REST API follows Laravel standards, using API Resources for structured and consistent responses.
  - Leverage task scheduling and event listeners to automate recurring tasks and decouple logic.
  - Implement database transactions using Laravel's database facade to ensure data consistency.
  - Use Eloquent ORM for database interactions, enforcing relationships and optimizing queries.
  - Implement API versioning for maintainability and backward compatibility.
  - Optimize performance with caching mechanisms like Redis and Memcached.
  - Ensure robust error handling and logging using Laravel’s exception handler and logging features.
  
laravel
typescript
redis
python
css
vue
javascript
dockerfile
+8 more

First seen in:

himanshubhadoria2727/Property-Listing
jpkontreras/iiiii
marlof2/GESTAB-API

Used in 3 repositories

TypeScript
## Role and Expertise:

You are an elite software engineer and product manager with the following expertise:

- Extensive experience in implementing multi-provider architectures for Large Language Models (LLMs)
- Master of functional programming, especially in TypeScript
- Deep understanding of TypeScript and its ecosystem
- Expert at creating code libraries with APIs that delight developers
- Advocate for composability, immutability, and simple pragmatic solutions
- Prefer Function over Class if possible
- Prefer Types over Interfaces if possible

## Coding Standards:

### Naming Conventions:
- Use kebab-case for file names (e.g., `my-component.ts`)
- Use camelCase for variables and function names (e.g., `myVariable`, `myFunction()`)
- Use UpperCamelCase (PascalCase) for classes, types, and interfaces (e.g., `MyClass`, `MyInterface`)
- Use ALL_CAPS for constants and enum values (e.g., `MAX_COUNT`, `Color.RED`)

### File Organization:
- Group related functionality into modules
- Use index files to simplify imports
- Separate concerns: keep business logic, UI components, and utilities in different directories

### Code Style:
- Prefer `const` over `let` when variables won't be reassigned
- Use arrow functions for better lexical scoping and concise syntax
- Utilize TypeScript's type system fully: use interfaces, type aliases, and generics where appropriate
- Implement error handling with custom error types
- Write pure functions where possible to improve testability and reduce side effects

### Best Practices:
- Follow the Single Responsibility Principle
- Use dependency injection to improve testability and flexibility
- Implement proper error handling and logging
- Write comprehensive unit tests for all business logic
- Use async/await for asynchronous operations instead of callbacks or raw promises
- Leverage TypeScript's strict mode for enhanced type checking

### Documentation:
- Use JSDoc comments for functions, classes, and complex types
- Include examples in documentation where appropriate
- Keep README files up-to-date with setup instructions, usage examples, and contribution guidelines

## Library Usage:
Utilize the following libraries effectively:
- axios (^1.7.5): For HTTP requests, implement interceptors for global error handling and authentication
- js-yaml (^4.1.0): For parsing and stringifying YAML, use type-safe schemas
- mime-types (^2.1.35): For MIME type detection and file extension mapping
- node-gyp (^10.2.0): For native addon build tool, ensure proper setup in your build pipeline
- uuid (^10.0.0): For generating unique identifiers, prefer v4 for random UUIDs
- zod (^3.23.8): For runtime type checking and data validation, create reusable schemas


dockerfile
javascript
less
python
typescript

First seen in:

quantalogic/qllm
PatrickJS/awesome-cursorrules
Qwertic/cursorrules

Used in 3 repositories

JavaScript
Writing code is like giving a speech. If you use too many big words, you confuse your audience. Define every word, and you end up putting your audience to sleep. Similarly, when you write code, you shouldn't just focus on making it work. You should also aim to make it readable, understandable, and maintainable for future readers. To paraphrase software engineer Martin Fowler, "Anybody can write code that a computer can understand. Good programmers write code that humans can understand."As software developers, understanding how to write clean code that is functional, easy to read, and adheres to best practices helps you create better software consistently.This article discusses what clean code is and why it's essential and provides principles and best practices for writing clean and maintainable code.What Is Clean Code?Clean code is a term used to refer to code that is easy to read, understand, and maintain. It was made popular by Robert Cecil Martin, also known as Uncle Bob, who wrote "Clean Code: A Handbook of Agile Software Craftsmanship" in 2008. In this book, he presented a set of principles and best practices for writing clean code, such as using meaningful names, short functions, clear comments, and consistent formatting.Ultimately, the goal of clean code is to create software that is not only functional but also readable, maintainable, and efficient throughout its lifecycle. Why Is Clean Code Important?When teams adhere to clean code principles, the code base is easier to read and navigate, which makes it faster for developers to get up to speed and start contributing. Here are some reasons why clean code is essential.Readability and maintenance: Clean code prioritizes clarity, which makes reading, understanding, and modifying code easier. Writing readable code reduces the time required to grasp the code's functionality, leading to faster development times.Team collaboration: Clear and consistent code facilitates communication and cooperation among team members. By adhering to established coding standards and writing readable code, developers easily understand each other's work and collaborate more effectively.Debugging and issue resolution: Clean code is designed with clarity and simplicity, making it easier to locate and understand specific sections of the codebase. Clear structure, meaningful variable names, and well-defined functions make it easier to identify and resolve issues.Improved quality and reliability: Clean code prioritizes following established coding standards and writing well-structured code. This reduces the risk of introducing errors, leading to higher-quality and more reliable software down the line.Now that we understand why clean code is essential, let's delve into some best practices and principles to help you write clean code.Principles of Clean CodeLike a beautiful painting needs the right foundation and brushstrokes, well-crafted code requires adherence to specific principles. These principles help developers write code that is clear, concise, and, ultimately, a joy to work with.Let's dive in.1. Avoid Hard-Coded NumbersUse named constants instead of hard-coded values. Write constants with meaningful names that convey their purpose. This improves clarity and makes it easier to modify the code.Example:The example below uses the hard-coded number 0.1 to represent a 10% discount. This makes it difficult to understand the meaning of the number (without a comment) and adjust the discount rate if needed in other parts of the function.Before:def calculate_discount(price):  discount = price * 0.1 # 10% discount  return price - discountThe improved code replaces the hard-coded number with a named constant TEN_PERCENT_DISCOUNT. The name instantly conveys the meaning of the value, making the code more self-documenting. After :def calculate_discount(price): TEN_PERCENT_DISCOUNT = 0.1 discount = price * TEN_PERCENT_DISCOUNT return price - discountAlso, If the discount rate needs to be changed, it only requires modifying the constant declaration, not searching for multiple instances of the hard-coded number.2. Use Meaningful and Descriptive NamesChoose names for variables, functions, and classes that reflect their purpose and behavior. This makes the code self-documenting and easier to understand without extensive comments. As Robert Martin puts it, “A name should tell you why it exists, what it does, and how it is used. If a name requires a comment, then the name does not reveal its intent.”Example:If we take the code from the previous example, it uses generic names like "price" and "discount," which leaves their purpose ambiguous. Names like "price" and "discount" could be interpreted differently without context. Before:def calculate_discount(price): TEN_PERCENT_DISCOUNT = 0.1 discount = price * TEN_PERCENT_DISCOUNT return price - discountInstead, you can declare the variables to be more descriptive.After:def calculate_discount(product_price):  TEN_PERCENT_DISCOUNT = 0.1  discount_amount = product_price * TEN_PERCENT_DISCOUNT  return product_price - discount_amountThis improved code uses specific names like "product_price" and "discount_amount," providing a clearer understanding of what the variables represent and how we use them.3. Use Comments Sparingly, and When You Do, Make Them MeaningfulYou don't need to comment on obvious things. Excessive or unclear comments can clutter the codebase and become outdated, leading to confusion and a messy codebase.Example:Before:def group_users_by_id(user_id):  # This function groups users by id  # ... complex logic ...  # ... more code …The comment about the function is redundant and adds no value. The function name already states that it groups users by id; there's no need for a comment stating the same.Instead, use comments to convey the "why" behind specific actions or explain behaviors.After:def group_users_by_id(user_id):  """Groups users by id to a specific category (1-9).  Warning: Certain characters might not be handled correctly.  Please refer to the documentation for supported formats.  Args:    user_id (str): The user id to be grouped.  Returns:    int: The category number (1-9) corresponding to the user id.  Raises:    ValueError: If the user id is invalid or unsupported.  """  # ... complex logic ...  # ... more code …This comment provides meaningful information about the function's behavior and explains unusual behavior and potential pitfalls.4. Write Short Functions That Only Do One ThingFollow the single responsibility principle (SRP), which means that a function should have one purpose and perform it effectively. Functions are more understandable, readable, and maintainable if they only have one job. It also makes testing them very easy. If a function becomes too long or complex, consider breaking it into smaller, more manageable functions.Example:Before:def process_data(data):  # ... validate users...  # ... calculate values ...  # ... format output …This function performs three tasks: validating users, calculating values, and formatting output. If any of these steps fail, the entire function fails, making debugging a complex issue. If we also need to change the logic of one of the tasks, we risk introducing unintended side effects in another task.Instead, try to assign each task a function that does just one thing. After:def validate_user(data):  # ... data validation logic ...def calculate_values(data):  # ... calculation logic based on validated data ...def format_output(data):  # ... format results for display …The improved code separates the tasks into distinct functions. This results in more readable, maintainable, and testable code. Also, If a change needs to be made, it will be easier to identify and modify the specific function responsible for the desired functionality. 5. Follow the DRY (Don't Repeat Yourself) Principle and Avoid Duplicating Code or LogicAvoid writing the same code more than once. Instead, reuse your code using functions, classes, modules, libraries, or other abstractions. This makes your code more efficient, consistent, and maintainable. It also reduces the risk of errors and bugs as you only need to modify your code in one place if you need to change or update it.Example:Before:def calculate_book_price(quantity, price): return quantity * pricedef calculate_laptop_price(quantity, price): return quantity * priceIn the above example, both functions calculate the total price using the same formula. This violates the DRY principle.We can fix this by defining a single calculate_product_price function that we use for books and laptops. This reduces code duplication and helps improve the maintenance of the codebase. After:def calculate_product_price(product_quantity, product_price): return product_quantity * product_price6. Follow Established Code-Writing StandardsKnow your programming language's conventions in terms of spacing, comments, and naming. Most programming languages have community-accepted coding standards and style guides, for example, PEP 8 for Python and Google JavaScript Style Guide for JavaScript. Here are some specific examples:Java:Use camelCase for variable, function, and class names.Indent code with four spaces.Put opening braces on the same line.Python:Use snake_case for variable, function, and class names.Use spaces over tabs for indentation.Put opening braces on the same line as the function or class declaration.JavaScript:Use camelCase for variable and function names.Use snake_case for object properties.Indent code with two spaces.Put opening braces on the same line as the function or class declaration.Also, consider extending some of these standards by creating internal coding rules for your organization. This can contain information on creating and naming folders or describing function names within your organization.7. Encapsulate Nested Conditionals into FunctionsOne way to improve the readability and clarity of functions is to encapsulate nested if/else statements into other functions. Encapsulating such logic into a function with a descriptive name clarifies its purpose and simplifies code comprehension. In some cases, it also makes it easier to reuse, modify, and test the logic without affecting the rest of the function.In the code sample below, the discount logic is nested within the calculate_product_discount function, making it difficult to understand at a glance.Example:Before:def calculate_product_discount(product_price): discount_amount = 0 if product_price > 100:  discount_amount = product_price * 0.1 elif price > 50:  discount_amount = product_price * 0.05 else:  discount_amount = 0 final_product_price = product_price - discount_amount return final_product_priceWe can clean this code up by separating the nested if/else condition that calculates discount logic into another function called get_discount_rate and then calling the get_discount_rate in the calculate_product_discount function. This makes it easier to read at a glance. The get_discount_rate is now isolated and can be reused by other functions in the codebase. It’s also easier to change, test, and debug it without affecting the calculate_discount function.After:def calculate_discount(product_price): discount_rate = get_discount_rate(product_price) discount_amount = product_price * discount_rate final_product_price = product_price - discount_amount  return final_product_pricedef get_discount_rate(product_price): if product_price > 100:  return 0.1 elif product_price > 50:  return 0.05 else:  return 08. Refactor ContinuouslyRegularly review and refactor your code to improve its structure, readability, and maintainability. Consider the readability of your code for the next person who will work on it, and always leave the codebase cleaner than you found it.9. Use Version ControlVersion control systems meticulously track every change made to your codebase, enabling you to understand the evolution of your code and revert to previous versions if needed. This creates a safety net for code refactoring and prevents accidental deletions or overwrites.Use version control systems like GitHub, GitLab, and Bitbucket to track changes to your codebase and collaborate effectively with others.
css
python
nestjs
golang
java
javascript
shell
typescript
+1 more

First seen in:

PatrickJS/awesome-cursorrules
geromii/map2
Qwertic/cursorrules

Used in 3 repositories

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, accurate TypeScript code following strict typescript rules and conforming to typescript eslint 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.
  
  Naming Conventions
  - Use lowercase with dashes for directories (e.g., components/auth-wizard).
  - Favor named exports for components.
  
  TypeScript Usage
  - Use TypeScript for all code; prefer interfaces over types.
  - Avoid enums; use maps instead.
  - Use functional components with TypeScript interfaces.
  
  Syntax and Formatting
  - Use the "function" keyword for pure functions.
  - Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements.
  - Use declarative JSX.
  
  UI and Styling
  - Use Shadcn UI, Radix, and Tailwind for components and styling.
  - Implement responsive design with Tailwind CSS; use a mobile-first approach.
  
  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.
  
  Follow Next.js docs for Data Fetching, Rendering, and Routing.
  
css
eslint
javascript
next.js
plpgsql
radix-ui
react
shadcn/ui
+3 more
Simplereally/personal-finance-tracker
Iwoooooods/next-social
liam-germain/personal

Used in 3 repositories

TypeScript
You are an expert AI programming assistant that primarily focuses on producing clear, readable Rell code.You carefully provide accurate, factual, thoughtful answers, and excel at reasoning.- Follow the user’s requirements carefully & to the letter.- First think step-by-step - describe your plan for what to build in pseudocode, written out in great detail.- Confirm, then write code!- Always write correct, up to date, bug free, fully functional and working, secure, performant and efficient code.- Focus on readability over being performant.- Fully implement all requested functionality.- Leave NO todo’s, placeholders or missing pieces.- Be concise. Minimize any other prose.- If you think there might not be a correct answer, you say so. If you do not know the answer, say so instead of guessing.You have studied the instructions below extensively for how to write Rell code. If you do not know how to do something in Rell, then ask instead of guessing.--Rell is designed to be expressive and concise, combining features from languages like SQL and Kotlin. It's specifically tailored for writing blockchain applications (dapps) on the Chromia platform.Key features:- Statically-typed- Blockchain-oriented- Built-in database operations- Modular design# Core Concepts## ModulesRell code is organized into modules. A module is a collection of related declarations such as entities, operations, and functions.Example of a simple module:```module;entity user { key username: text; name: text; age: integer;}function get_user(username: text) { return user @? { .username == username };}query get_all_users() { return user @* {};}```## EntitiesEntities are the primary way to define data structures in Rell. They correspond to database tables.```entity product { key id: integer; name: text; price: decimal; category: text;}```## OperationsOperations are used to modify the blockchain state. They're similar to functions but are specifically for state-changing actions.```operation create_user(username: text, name: text, age: integer) { create user(username, name, age);}```## QueriesQueries are used to retrieve data from the blockchain without modifying the state.```query get_user_by_age(min_age: integer, max_age: integer) { return user @* { .age >= min_age and .age <= max_age };}```# Language Features## TypesRell supports various types:- Simple Types:- integer: Whole numbers- decimal: Decimal numbers- boolean: True or false- text: Text strings- byte_array: Array of bytesExamples:```val age: integer = 25;val price: decimal = 19.99;val is_active: boolean = true;val name: text = "Alice";val data: byte_array = x"0A0B0C";```Complex Types:- list: Ordered collection of elements- set: Unordered collection of unique elements- map<K, V>: Key-value pairs```val numbers: list = [1, 2, 3, 4, 5];val unique_names: set = {"Alice", "Bob", "Charlie"};val ages: map<text, integer> = {"Alice": 30, "Bob": 25, "Charlie": 35};```## FunctionsFunctions in Rell are defined using the function keyword.Example:```function calculate_total(prices: list): decimal { return prices @ {} ( @sum($) );}```## Control StructuresIf Statement:```if (condition) { // Code block} else if (not another_condition) { // Code block} else { // Code block}```When Statement (Similar to switch in other languages):```when (value) { case1 -> // Code for case1 case2 -> // Code for case2 else -> // Default case}val result: text = when (age) { case 18 -> "Adult" case 13 -> "Teenager" else -> "Child"}```Loop Statements:For loop:```for (item in collection) { // Code block}```While loop:```while (condition) { // Code block}```## Database Operations### Create:To create a new entity instance:```create user(username = "alice", name = "Alice Smith", age = 30);```### Update:To update an existing entity instance:```update entity @? { .key == value } ( field1 = new_value1, field2 = new_value2);```### Delete:To delete an existing entity instance:```delete entity @? { .key == value };```## System LibrariesRell provides several system libraries for common operations:###chain_context:Provides information about the current blockchain state.```val current_block = chain_context.block_height;```### op_context:Provides information about the current operation context.```val signer = op_context.signer;```### crypto:Provides cryptographic functions.Example:```val hash = crypto.sha256("Hello, World!");```### require Function:Used for asserting conditions. If the condition is false, it throws an error.```function transfer(from: text, to: text, amount: decimal) { require(amount > 0, "Amount must be positive"); // Transfer logic}```## NamespacesNamespaces are used to organize code and avoid naming conflicts.```namespace utils { function helper1() { /* ... */ } function helper2() { /* ... */ }}// Usageutils.helper1();```## Importing ModulesImporting allows you to include entities from other modules in your current module.```import my_module;query get_data() { return my_module.some_entity @* {};}```
typescript
golang
javascript
kotlin
express.js

First seen in:

PatrickJS/awesome-cursorrules
megayours/yours-protocol
Qwertic/cursorrules

Used in 3 repositories

Dart
## Dart 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.
- Don't leave blank lines within a function.
- One export per file.

### Nomenclature

- Use PascalCase for classes.
- Use camelCase for variables, functions, and methods.
- Use underscores_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.
- Write short functions with a single purpose. Less than 20 instructions.
- 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 parameter values instead of checking for null or undefined.
- Reduce function parameters using RO-RO
- Use an object to pass multiple parameters.
- Use an object to return results.
- Declare necessary types for input arguments and output.
- Use a single level of abstraction.

### Data

- Don't abuse primitive types and encapsulate data in composite types.
- Avoid data validations in functions and use classes with internal validation.
- Prefer immutability for 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.
- Declare interfaces to define contracts.
- Write small classes with a single purpose.
- Less than 200 instructions.
- Less than 10 public methods.
- Less than 10 properties.

### Exceptions

- Use exceptions to handle errors you don't expect.
- If you catch an exception, it should be to:
- Fix an expected problem.
- Add context.
- Otherwise, use a global handler.

### Testing

- Follow the Arrange-Act-Assert convention for tests.
- Name test variables clearly.
- Follow the convention: inputX, mockX, actualX, expectedX, etc.
- Write unit tests for each public function.
- Use test doubles to simulate dependencies.
- Except for third-party dependencies that are not expensive to execute.
- Write acceptance tests for each module.
- Follow the Given-When-Then convention.

## Specific to Flutter

### Basic Principles

- Use clean architecture
- see modules if you need to organize code into modules
- see controllers if you need to organize code into controllers
- see services if you need to organize code into services
- see repositories if you need to organize code into repositories
- see entities if you need to organize code into entities
- Use repository pattern for data persistence
- see cache if you need to cache data
- Use controller pattern for business logic with ChangeNotifier
- Use changeNotifierProvider to manage state
- see keepAlive if you need to keep the state alive
- Use freezed to manage UI states
- Controller always takes methods as input and updates the UI state that effects the UI
- Use Flutter Modular to manage dependencies
- Use singleton for services and repositories
- Use factory for use cases
- Use lazy singleton for controllers
- Use Flutter Modular to manage routes
- Use extras to pass data between pages
- Use extensions to manage reusable code
- Use ThemeData to manage themes
- Use AppLocalizations to manage translations
- Use constants to manage constants values
- When a widget tree becomes too deep, it can lead to longer build times and increased memory usage. Flutter needs to traverse the entire tree to render the UI, so a flatter structure improves efficiency
- A flatter widget structure makes it easier to understand and modify the code. Reusable components also facilitate better code organization
- Avoid Nesting Widgets Deeply in Flutter. Deeply nested widgets can negatively impact the readability, maintainability, and performance of your Flutter app. Aim to break down complex widget trees into smaller, reusable components. This not only makes your code cleaner but also enhances the performance by reducing the build complexity
- Deeply nested widgets can make state management more challenging. By keeping the tree shallow, it becomes easier to manage state and pass data between widgets
- Break down large widgets into smaller, focused widgets
- Utilize const constructors wherever possible to reduce rebuilds

### Testing

- Use the standard widget testing for flutter
- Use integration tests for each api module.
nestjs
less
swift
objective-c
c++
kotlin
dart
c
+4 more
thak1996/pokedex-json
yigtkaya/unipool
thak1996/school_app_teste

Used in 3 repositories

unknown
# Codebase OverviewThis codebase appears to be part of a web application built using TypeScript, React, and various NextUI components. It is structured to support a landing page, authentication flows, and a dashboard for logged-in users. The application integrates with Supabase for backend services, including authentication and database interactions.# Stack and Key TechnologiesFrontend Framework: ReactTypeScript: Used for type-safe code across the frontend.NextUI: A React UI library used for building the UI components like buttons, modals, inputs, etc.Supabase: An open-source Firebase alternative used for backend services like authentication, database, and storage.Next.js: Likely used as the React framework, indicated by the usage of next/navigation and server utilities.Iconify: For icons across the application.Purpose and Functionality## AuthenticationThe application includes a comprehensive authentication flow:Login: Users can log in using email/password or GitHub OAuth. The login logic is handled in frontend/app/(landing-page)/login/action.ts.Signup: New users can sign up with an email and password. The signup logic is also in frontend/app/(landing-page)/login/action.ts.Logout: Users can log out, with the logic located in frontend/app/(landing-page)/logout/action.ts.Email Confirmation: The application handles email confirmation through a callback route in frontend/app/auth/callback/confirm/route.ts.## User InterfaceLanding Page: Contains components like SubmitButton, LoginPage, and LogoutModal to facilitate user interactions.Dashboard: For logged-in users, showing personalized content and a sidebar for navigation within the dashboard.Error Handling: A generic error component is used to display errors and provide a retry mechanism.## Navigation and LayoutNavbar: A responsive navbar for the landing page and possibly other public pages.Sidebar: A collapsible sidebar for the dashboard, indicating a more complex, multi-page application structure for authenticated users.
firebase
golang
typescript
oauth
supabase
next.js
react

First seen in:

PatrickJS/awesome-cursorrules
ianmitch90/arrw
Qwertic/cursorrules

Used in 3 repositories

TypeScript
# FEATHER DOCS - A lightweight agent framework

I don't need layers of abstraction. Base LLMs are very capable. Feather lightly defines agents with tools that auto-execute.

Chaining agents together with Feather looks like this:

```typescript
const timelineData = twitterAgent.run("Get 50 tweets from my AI list and summarize it for me")
const videoScript = videoScriptAgent.run('Create me a video script based on todays AI news:' + timelineData.output)
```

## CREATING AN AGENT

Creating an agent is easy:

```typescript
const internetAgent = new FeatherAgent({
    model: "deepseek/deepseek-chat",
    systemPrompt: "You are a helpful assistant that can browse the internet", 
    tools: [internetTool],
})
```

Running an agent is easier:

```typescript
const result = internetAgent.run("What's the latest quantum chip that dropped? How does it advance AI?")
logger.info("Internet Agent said:", result.output)
```

The output comes from the .output property of the agent run.
Agent run has the following properties:

```typescript
interface AgentRunResult<TOutput> {
  // Whether the agent run completed successfully
  success: boolean;

  // The main output from the agent run
  // Type depends on agent configuration:
  // - string for normal text output
  // - TOutput for structured output (if structuredOutputSchema is used)
  // - Record<string, any> for JSON responses
  output: TOutput;

  // Only present if there was an error during the run
  error?: string;

  // Only present if autoExecuteTools is false and the agent wants to use tools
  functionCalls?: Array<{
    functionName: string;    // Name of the tool/function to call
    functionArgs: any;       // Arguments for the tool/function
  }>;
}
```

### FeatherAgent Parameters

Required:
- `systemPrompt` (string) - Core instructions that define the agent's behavior

Optional:
- `model` (string) - LLM model to use (defaults to "openai/gpt-4o")
- `agentId` (string) - Unique ID for the agent (auto-generates if not provided) 
- `dynamicVariables` (object) - Functions that return strings, executed on each .run() call
- `tools` (ToolDefinition[]) - Tools the agent can use (cannot use with structuredOutputSchema)
- `autoExecuteTools` (boolean) - Whether to auto-execute tool calls (default: true)
- `cognition` (boolean) - Enables `<think>, <plan>, <speak>` XML tags
- `chainRun` (boolean) - Enables chain running mode with finish_run tool
- `maxChainIterations` (number) - Maximum iterations for chain running (default: 5)
- `structuredOutputSchema` (object) - Schema for structured output (cannot use with tools or cognition)
- `additionalParams` (object) - Extra LLM API parameters (temperature etc.)
- `debug` (boolean) - Enables debug GUI monitoring
- `forceTool` (boolean) - Forces the agent to use exactly one tool (requires exactly one tool in tools array, cannot be used with chainRun)

### MODIFYING AN AGENT'S MESSAGE HISTORY
You can modify an agent's message history with the following methods:

```typescript
// Adding messages
agent.addUserMessage("Hello, how are you? Do you like my hat?", {images: ["https://example.com/blueHat.jpg"]}) // image optional
agent.addAssistantMessage("I am fine, thank you! Nice blue hat! Looks good on you!")

// Loading in custom message history
const history = [{role: "user", content: "Hello, how are you? Do you like my hat?", images: [{url: "https://example.com/blueHat.jpg"}]}, {role: "assistant", content: "I am fine, thank you! Nice blue hat! Looks good on you!"}] // array of messages
agent.loadHistory(history) // loads the chat history from an array of messages

// Extracting current message history
agent.extractHistory() // returns the chat history as an array of messages
```

### COGNITION
Cognition is the process of the agent thinking, planning, and speaking. It is enabled by the cognition property in the agent config. What is does is add forced instructions at the end of the agent's system prompt to use XML tags to think, plan, and speak. These XML tags are parsed and executed by the agent. `<think>...</think>`, `<plan>...</plan>`, `<speak>...</speak>` are the tags used. `<speak>` tags are parsed and returned as the agent's response.

I find that cognition is a great way to get increased accuracy and consistency with tool usage.

### TOOL USE
Tool calls (also known as function calling) allow you to give an LLM access to external tools.

Feather expects your tool to be defined WITH the function execution and output ready to go. By default, tools auto-execute - when giving an agent a tool, the agent will execute the tool, get the results saved in its chat history, then re-run itself to provide the user a detailed response with the information from the tool result.

However, you can disable auto-execution by setting `autoExecuteTools: false` in the agent config. In this case, tool calls will be available in the `functionCalls` property of the response, allowing for manual handling:

```typescript
const manualAgent = new FeatherAgent({
  systemPrompt: "You are a math tutor who can do calculations",
  tools: [calculatorTool],
  forceTool: true, // forces the agent to use this tool instantly and return the result
  autoExecuteTools: false // Disable auto-execution
});

const res = await manualAgent.run("What is 42 * 73?");
console.log("Agent response:", res.output);
console.log("Tool calls to handle:", res.functionCalls);
// functionCalls contains array of: { functionName: string, functionArgs: any }
```

example log of res:
```typescript
DEBUG: Agent response (manual execution)
    res: {
      "success": true,
      "output": "", // sometimes output is empty because the AI agent just decides to use a tool, which is completely fine.
      "functionCalls": [
        {
          "functionName": "calculator",
          "functionArgs": "{\"num1\":1294,\"num2\":9966,\"operation\":\"multiply\"}"
        }
      ]
    }
```

Parallel tool calls are supported in both auto and manual execution modes.

Setting up a tool function call following OpenAI structure + Execution
```typescript
const internetTool: ToolDefinition = {
  type: "function",
  function: {
    name: "search_internet",
    description: "Search the internet for up-to-date information using Perplexity AI",
    parameters: {
      type: "object", 
      properties: {
        query: {
          type: "string",
          description: "The search query to look up information about"
        }
      },
      required: ["query"]
    }
  },
  // Execute function to search using Perplexity AI
  async execute(args: Record<string, any>): Promise<{ result: string }> {
    logger.info({ args }, "Executing internet search tool");
    
    try {
      const params = typeof args === 'string' ? JSON.parse(args) : args;
      if (typeof params.query !== 'string') {
        throw new Error("Query must be a valid string");
      }

      // Call Perplexity API to get search results
      const searchResult = await queryPerplexity(params.query);
      
      return { result: searchResult };

    } catch (error) {
      logger.error({ error, args }, "Internet search tool error");
      throw error;
    }
  }
};
```

### FORCED TOOL USAGE
You can force an agent to use exactly one tool by enabling the `forceTool` parameter. This is useful when you want to ensure the agent uses a specific tool for a task.

```typescript
const searchAgent = new FeatherAgent({
  systemPrompt: "You are a search assistant that always searches for information.",
  tools: [searchTool], // Must provide exactly ONE tool
  forceTool: true     // Forces the agent to use searchTool
});

// The agent will ALWAYS use searchTool, no matter what the user asks
const result = await searchAgent.run("Tell me about quantum computers");
```

Requirements for forced tool usage:
- Must provide exactly ONE tool in the tools array
- Cannot be used with chainRun (as it returns after one tool use)
- The agent will be forced to use the tool regardless of the query

### CHAIN RUNNING
Chain running allows an agent to execute multiple tools in sequence until it decides to finish. This is useful for complex tasks that require multiple steps or tool calls.

The agent is given a `finish_run` tool that it must call to finish, with a 'final_response' string property that the agent fills out to output it's final response to the .run() command.

```typescript
const researchAgent = new FeatherAgent({
  systemPrompt: "You are a research assistant that can search and summarize information.",
  tools: [searchTool, summarizeTool],
  cognition: true, // <--- cognition + chain running is bread and butter
  chainRun: true, // Enable chain running
  maxChainIterations: 10 // Optional: Set max iterations (default: 5)
});

// The agent will automatically:
// 1. Execute tools in sequence
// 2. Process each tool's results
// 3. Decide if more tool calls are needed
// 4. Call finish_run when complete
const research = await researchAgent.run("Research the latest developments in quantum computing");
console.log(research.output); // Final summarized research
```

When chainRun is enabled:
- The agent gains access to a `finish_run` tool
- The agent MUST call `finish_run` to complete its execution
- The agent can execute up to maxChainIterations tools (default: 5)
- The final response from `finish_run` becomes the .output of run()

This ensures consistent and reliable multi-step tool execution flows.

### STRUCTURED OUTPUT
If you are using structured output instead of tools, the .run() function will return the structured output as a JSON object.

```typescript
  // Create a structured output agent with a specific schema
  // Note the generic type <{ answer: string; confidence: number }>
  const agent = new FeatherAgent<{ answer: string; confidence: number }>({
    agentId: "structured-test",
    model: "openai/gpt-4o",
    systemPrompt: "You are a helpful assistant that provides accurate, structured responses.",
    structuredOutputSchema: {
      name: "weather",
      strict: true,
      schema: {
        type: "object",
        properties: {
          answer: {
            type: "string", 
            description: "A concise answer to the user's question"
          },
          confidence: {
            type: "number",
            description: "A confidence score between 0 and 1"
          }
        },
        required: ["answer", "confidence"],
        additionalProperties: false
      }
    },
    debug: true
  });

  const userMessage = "What is the capital of France?";
  // The agent should produce a structured JSON answer
  const result = await agent.run(userMessage);

  if (result.success) {
    // Log full structured response
    console.log("Full structured response:", result.output);
    
    // result.output is now typed as { answer: string; confidence: number }
    const answer = result.output.answer;
    const confidence = result.output.confidence;
    
    console.log("Just the answer:", answer);
    console.log("Just the confidence:", confidence);
  } else {
    console.error("Agent error:", result.error);
  }
```

### DYNAMIC VARIABLES
Dynamic variables allow you to inject real-time data into your agent's system prompt. These variables are functions that return strings and are executed every time the agent's `.run()` method is called. This ensures your agent always has access to the most up-to-date information.

You can use the `{{variableName}}` syntax to specify exactly where in your system prompt the dynamic variable should be injected:

```typescript
// Create an agent with dynamic variables and custom placement
const agent = new FeatherAgent({
  systemPrompt: indentNicely`
    You are a helpful assistant that knows the current time.
    Right now, the time is: {{currentTime}}
    
    There are currently {{activeUsers}} users online.
  `,
  model: "openai/gpt-4o",
  dynamicVariables: {
    currentTime: () => new Date().toLocaleString(), // Updates every .run() call
    activeUsers: () => getActiveUserCount(), // Custom function example
  }
});

// The dynamic variables will be injected exactly where specified in the system prompt
// You are a helpful assistant that knows the current time.
// Right now, the time is: 12/25/2023, 3:45:00 PM
// 
// There are currently 1,234 users online.
```

Dynamic variables are perfect for:
- Injecting real-time data (time, date, metrics)
- System status information
- User context that changes frequently
- Any data that needs to be fresh each time the agent runs

### STRING UTILITIES
Feather comes with utility functions to help with common string operations:

#### indentNicely
A template literal tag that normalizes indentation in multi-line strings. It removes leading/trailing empty lines and normalizes indentation based on the first non-empty line:

```typescript
import { indentNicely } from './utils';

const myText = indentNicely`
    This text will have
    consistent indentation
        even with nested levels
    regardless of how it's
    formatted in the source code
`;

// Output:
// This text will have
// consistent indentation
//     even with nested levels
// regardless of how it's
// formatted in the source code
```

This is particularly useful for:
- Writing system prompts with clean formatting
- Generating code with proper indentation
- Creating multi-line text templates
- Maintaining readable source code while producing clean output

# LOGGING

We use the PINO logger for logging with the pino-pretty plugin. Please log everything with depth

- Use info to log the flow of the program
- Use debug to log more detailed and full outputs
- Use error to log errors

# COMMENTING
We must leave DETAILED comments in the code explaining the flow of the program and how we move step by step.

# DEBUG TERMINAL GUI
Feather comes with an optional GUI that displays the agent's current system prompt, the messages in it's chat history, the user input and the agent's output, and any detailed information about the run.
typescript
golang
nestjs
javascript
less
openai
html
kingbootoshi/feather
kingbootoshi/image-labeler
kingbootoshi/ai-os

Used in 3 repositories

PHP
You are an expert in the TALL stack: Laravel, Livewire, Alpine.js, and Tailwind CSS, with a strong emphasis on Laravel and PHP best practices.

Key Principles

- Write concise, technical responses with accurate PHP examples.

- Follow Laravel best practices and conventions.

- Use object-oriented programming with a focus on SOLID principles.

- Prefer iteration and modularization over duplication.

- Use descriptive variable and method names.

- Favor dependency injection and service containers.

PHP and Laravel Core

- Use PHP 8.1+ features when appropriate (e.g., typed properties, match expressions).

- Follow PSR-12 coding standards.

- Utilize Laravel's built-in features and helpers when possible.

- Follow Laravel's directory structure and naming conventions.

- Use lowercase with dashes for directories (e.g., app/Http/Controllers).

- Implement proper error handling and logging:
  - Use Laravel's exception handling and logging features.
  - Create custom exceptions when necessary.
  - Use try-catch blocks for expected exceptions.

- Use Laravel's validation features for form and request validation.

- Implement middleware for request filtering and modification.

- Utilize Laravel's Eloquent ORM for database interactions.

- Use Laravel's query builder for complex database queries.

- Implement proper database migrations and seeders.

- Everything should be typehinted.

- Always use artisan commands when generating files, like models, migrations, notifications, events, jobs, etc.

- In migrations, always have the id first followed by the timestamps then followed by all other fields.

- For migrations, never add any database constraints for relationships or cascading rules. When defining a relationship just make it ->index() and nullable() that's it.

- After creating a model and its migration, ensure you run the migration before generating a Filament resource. This allows the resource generator to automatically include fields based on the database schema.

- Use DTOs using spatie/laravel-data.

- Use enums when appropriate.

- Use Filament and Livewire for building dynamic user interfaces.

- Models should use guarded fields instead of fillable fields, initially guarding the id and timestamps.

Dependencies

- Laravel (latest stable version)

- Composer for dependency management

- Filament for admin panels and CRUD operations

- Livewire for dynamic front-end components

- Alpine.js for JavaScript functionality

- Tailwind CSS for styling

Laravel Best Practices

- Use Eloquent ORM instead of raw SQL queries when possible.

- Implement Repository pattern for data access layer.

- Use Laravel's built-in authentication and authorization features.

- Utilize Laravel's caching mechanisms for improved performance.

- Implement job queues for long-running tasks.

- Use Laravel's built-in testing tools (PHPUnit, Dusk) for unit and feature tests.

- Implement API versioning for public APIs.

- Use Laravel's localization features for multi-language support.

- Implement proper CSRF protection and security measures.

- Use Laravel Mix for asset compilation.

- Implement proper database indexing for improved query performance.

- Use Laravel's built-in pagination features.

- Implement proper error logging and monitoring.

Livewire Implementation

- Create modular, reusable Livewire components.

- Use Livewire's lifecycle hooks effectively (e.g., mount, updated, etc.).

- Implement real-time validation using Livewire's built-in validation features.

- Optimize Livewire components for performance, avoiding unnecessary re-renders.

- Integrate Livewire components with Laravel's backend features seamlessly.

Alpine.js Usage

- Use Alpine.js directives (x-data, x-bind, x-on, etc.) for declarative JavaScript functionality.

- Implement small, focused Alpine.js components for specific UI interactions.

- Combine Alpine.js with Livewire for enhanced interactivity when necessary.

- Keep Alpine.js logic close to the HTML it manipulates, preferably inline.

Tailwind CSS Styling

- Utilize Tailwind's utility classes for responsive design.

- Implement a consistent color scheme and typography using Tailwind's configuration.

- Use Tailwind's @apply directive in CSS files for reusable component styles.

- Optimize for production by purging unused CSS classes.

Performance Optimization

- Implement lazy loading for Livewire components when appropriate.

- Use Laravel's caching mechanisms for frequently accessed data.

- Minimize database queries by eager loading relationships.

- Implement pagination for large data sets.

- Use Laravel's built-in scheduling features for recurring tasks.

Security Best Practices

- Always validate and sanitize user input.

- Use Laravel's CSRF protection for all forms.

- Implement proper authentication and authorization using Laravel's built-in features.

- Use Laravel's prepared statements to prevent SQL injection.

- Implement proper database transactions for data integrity.

Testing

- Write unit tests for Laravel controllers and models.

- Implement feature tests for Livewire components using Laravel's testing tools.

- Use Laravel Dusk for end-to-end testing when necessary.

Key Conventions

1. Follow Laravel's MVC architecture.

2. Use Laravel's routing system for defining application endpoints.

3. Implement proper request validation using Form Requests.

4. Use Laravel's Blade templating engine for views, integrating with Livewire and Alpine.js.

5. Implement proper database relationships using Eloquent.

6. Use Laravel's built-in authentication scaffolding.

7. Implement proper API resource transformations.

8. Use Laravel's event and listener system for decoupled code.

9. Implement proper database transactions for data integrity.

10. Use Laravel's built-in scheduling features for recurring tasks.

When providing code examples or explanations, always consider the integration of all four technologies in the TALL stack. Emphasize the synergy between these technologies and how they work together to create efficient, reactive, and visually appealing web applications, while adhering to Laravel and PHP best practices.
blade
css
express.js
java
javascript
laravel
less
php
+3 more
SimpleDevTools/start-here
AbdelElrafa/islamic-trivia
AbdelElrafa/pif-demo

Used in 3 repositories