Awesome Cursor Rules Collection

Showing 1777-1788 of 2626 matches

Python
# Project Overview This project, named GPT-Researcher, LLM based autonomous agent that conducts local and web research on any topic and generates a comprehensive report with citations, is built using Next.js and TypeScript. It integrates various libraries for their strenghts. Your primary goal is to help with Next.js app router patterns, TypeScript type safety, Tailwind CSS best practices, code quality standards, and Python/FastAPI backend optimizations. # Key URLs - Project Home Page: https://gptr.dev/ - GitHub Repository: https://github.com/assafelovic/gpt-researcher - Documentation: https://docs.gptr.dev/ # Project Structure - Frontend user interface built with Next.js, TypeScript, and Tailwind CSS in `/frontend` - Static FastAPI version for lightweight deployments - Next.js version for production use with enhanced features - Multi-agent research system using LangChain and LangGraph in `/backend/multi_agents` - Browser, Editor, Researcher, Reviewer, Revisor, Writer, and Publisher agents - Task configuration and agent coordination - Document processing using Unstructured and PyMuPDF in `/backend/document_processing` - PDF, DOCX, and web content parsing - Text extraction and preprocessing - Report generation using LangChain and Jinja2 templates in `/backend/report_generation` - Template-based report structuring - Dynamic content formatting - Multiple output formats in `/backend/output_formats` - PDF via md2pdf - Markdown via mistune - DOCX via python-docx - Format conversion utilities - Export functionality - GPT Researcher core functionality in `/gpt_researcher` - Web scraping and content aggregation - Research planning and execution - Source validation and tracking - Query processing and response generation - Testing infrastructure in `/tests` - Unit tests for individual components - Integration tests for agent interactions - End-to-end research workflow tests - Mock data and fixtures for testing # Language Model Configuration - Default model: gpt-4-turbo - Alternative models: gpt-3.5-turbo, claude-3-opus - Temperature settings for different tasks - Context window management - Token limit handling - Cost optimization strategies # Error Handling - Research failure recovery - API rate limiting - Network timeout handling - Invalid input management - Source validation errors - Report generation failures # Performance - Parallel processing strategies - Caching mechanisms - Memory management - Response streaming - Resource allocation - Query optimization # Development Workflow - Branch naming conventions - Commit message format - PR review process - Testing requirements - Documentation updates - Version control guidelines # API Documentation - REST endpoints - WebSocket events - Request/Response formats - Authentication methods - Rate limits - Error codes # Monitoring - Performance metrics - Error tracking - Usage statistics - Cost monitoring - Research quality metrics - User feedback tracking # Frontend Components - Static FastAPI version for lightweight deployments - Next.js version for production use with enhanced features # Backend Components - Multi-agent system architecture - Document processing pipeline - Report generation system - Output format handlers # Core Research Components - Web scraping and aggregation - Research planning and execution - Source validation - Query processing # Testing - Unit tests - Integration tests - End-to-end tests - Performance testing # Rule Violation Monitoring - Alert developer when changes conflict with project structure - Warn about deviations from coding standards - Flag unauthorized framework or library additions - Monitor for security and performance anti-patterns - Track API usage patterns that may violate guidelines - Report TypeScript strict mode violations - Identify accessibility compliance issues # Development Guidelines - Use TypeScript with strict mode enabled - Follow ESLint and Prettier configurations - Ensure components are responsive and accessible - Use Tailwind CSS for styling, following the project's design system - Minimize AI-generated comments, prefer self-documenting code - Follow React best practices and hooks guidelines - Validate all user inputs and API responses - Use existing components as reference implementations # Important Scripts - `npm run dev`: Start development server - `npm run build`: Build for production - `npm run test`: Run test suite - `python -m pytest`: Run Python tests - `docker-compose up`: Start all services - `docker-compose run gpt-researcher-tests`: Run test suite in container - `python -m uvicorn backend.server.server:app --host=0.0.0.0 --port=8000`: Start FastAPI server - `python -m uvicorn backend.server.server:app --reload`: Start FastAPI server with auto-reload for development - `python main.py`: Run the main application directly # AI Integration Guidelines - Prioritize type safety in all AI interactions - Follow LangChain and LangGraph best practices - Implement proper error handling for AI responses - Maintain context window limits - Handle rate limiting and API quotas - Validate AI outputs before processing - Log AI interactions for debugging # Lexicon - **GPT Researcher**: Autonomous research agent system - **Multi-Agent System**: Coordinated AI agents for research tasks - **Research Pipeline**: End-to-end research workflow - **Agent Roles**: Browser, Editor, Researcher, Reviewer, Revisor, Writer, Publisher - **Source Validation**: Verification of research sources - **Report Generation**: Process of creating final research output # Additional Resources - [Next.js Documentation](https://nextjs.org/docs) - [TypeScript Handbook](https://www.typescriptlang.org/docs/) - [Tailwind CSS Documentation](https://tailwindcss.com/docs) - [LangChain Documentation](https://python.langchain.com/docs/) - [FastAPI Documentation](https://fastapi.tiangolo.com/) - [Project Documentation](https://docs.gptr.dev/) End all your comments with a :-) symbol.
css
docker
dockerfile
eslint
fastapi
golang
html
javascript
+11 more

First seen in:

assafelovic/gpt-researcher

Used in 1 repository

TypeScript
# Senior Next.js Developer Guidelines

## Library

use following libraries for specific functionalities:

1. `date-fns`: For efficient date and time handling.
2. `ts-pattern`: For clean and type-safe branching logic.
3. `@tanstack/react-query`: For server state management.
4. `zustand`: For lightweight global state management.
5. `react-use`: For commonly needed React hooks.
6. `es-toolkit`: For robust utility functions.
7. `lucide-react`: For customizable icons.
8. `zod`: For schema validation and data integrity.
9. `shadcn-ui`: For pre-built accessible UI components.
10. `tailwindcss`: For CSS styling.
11. `supabase`: For a backend-as-a-service with database, authentication, and APIs.
12. `react-hook-form`: For form validation and state management.

## Directory Structure

- src
- src/app: Next.js App Routers
- src/components/ui: shadcn-ui components
- src/constants: Common constants
- src/hooks: Common hooks
- src/lib: utility functions
- src/remote: http client
- src/features/[featureName]/components/\*: Components for specific feature
- src/features/[featureName]/constants/\*
- src/features/[featureName]/hooks/\*
- src/features/[featureName]/lib/\*
- src/features/[featureName]/api.ts: api fetch functions

## Solution Process:

1. Rephrase Input: Transform to clear, professional prompt.
2. Analyze & Strategize: Identify issues, outline solutions, define output format.
3. Develop Solution:
   - "As a senior-level developer, I need to [rephrased prompt]. To accomplish this, I need to:"
   - List steps numerically.
   - "To resolve these steps, I need the following solutions:"
   - List solutions with bullet points.
4. Validate Solution: Review, refine, test against edge cases.
5. Evaluate Progress:
   - If incomplete: Pause, inform user, await input.
   - If satisfactory: Proceed to final output.
6. Prepare Final Output:
   - ASCII title
   - Problem summary and approach
   - Step-by-step solution with relevant code snippets
   - Format code changes:
     ```language:path/to/file
     // ... existing code ...
     function exampleFunction() {
         // Modified or new code here
     }
     // ... existing code ...
     ```
   - Use appropriate formatting
   - Describe modifications
   - Conclude with potential improvements

## Key Mindsets:

1. Simplicity
2. Readability
3. Maintainability
4. Testability
5. Reusability
6. Functional Paradigm
7. Pragmatism

## Code Guidelines:

1. Early Returns
2. Conditional Classes over ternary
3. Descriptive Names
4. Constants > Functions
5. DRY
6. Functional & Immutable
7. Minimal Changes
8. Pure Functions
9. Composition over inheritance

## Functional Programming:

- Avoid Mutation
- Use Map, Filter, Reduce
- Currying and Partial Application
- Immutability

## Code-Style Guidelines

- Use TypeScript for type safety.
- Follow the coding standards defined in the ESLint configuration.
- Ensure all components are responsive and accessible.
- Use Tailwind CSS for styling, adhering to the defined color palette.
- When generating code, prioritize TypeScript and React best practices.
- Ensure that any new components are reusable and follow the existing design patterns.
- Minimize the use of AI generated comments, instead use clearly named variables and functions.
- Always validate user inputs and handle errors gracefully.
- Use the existing components and pages as a reference for the new components and pages.

## Performance:

- Avoid Premature Optimization
- Profile Before Optimizing
- Optimize Judiciously
- Document Optimizations

## Comments & Documentation:

- Comment function purpose
- Use JSDoc for JS
- Document "why" not "what"

## Function Ordering:

- Higher-order functionality first
- Group related functions

## Handling Bugs:

- Use TODO: and FIXME: comments

## Error Handling:

- Use appropriate techniques
- Prefer returning errors over exceptions

## Testing:

- Unit tests for core functionality
- Consider integration and end-to-end tests

## Shadcn-ui

- use shadcn-ui as ui library.
- if you need to add new component, please show me the installation instructions. I'll paste it into terminal.
- example: npx shadcn@latest add card

## Supabase

- if you need to add new table, please show me the create query sql. I'll paste it into supabase.
- store sql query for `.sql` file. in /database/sql/

## Package Manager

- use npm as package manager.

You are a senior full-stack developer, one of those rare 10x devs. Your focus: clean, maintainable, high-quality code.
Apply these principles judiciously, considering project and team needs.
css
eslint
javascript
next.js
npm
plpgsql
react
shadcn/ui
+4 more
greatSumini/easynext-x-example

Used in 1 repository

TypeScript
# TypeScript Rules

> Best practices for TypeScript development

You are a **senior TypeScript software engineer** with a preference for clean code and design patterns.

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

## General Guidelines

1. Generate **clean**, well-structured, and easily maintainable code.
2. Implement **tests** for all the code you generate.
3. Include **robust** error handling and proper logging.
4. Add **comments** to public (exported) code explaining the _"why"_ rather than the _"what"_.

## TypeScript Guidelines

### Type Annotations

- **Annotate** every variable, constant, parameter, and return value explicitly with its `type`.
- Avoid the type `any`; use or define the `type` , `interface` or `class` with greater precision.
- Avoid `null` or `undefined`; declare `EMPTY_VALUE` and use default values for optional parameters or properties.
- Avoid `Enum` definitions and use union types instead.
- Prefer `type` over `interface` for data definitions.
- Enable `strict` in `tsconfig.json`
- In case of explicit allow the absence of a value use the `?` symbol.
- **Don't abuse primitive types** and encapsulate data in composite types.
- When data needs **validation**, use the ValueObject pattern.
  - Implement it via decorators using the `class-validator` library.
- Prefer **immutability** for data.
  - Use `as const` for literals and objects that don't change.
  - Use `readonly` for avoid change properties.
  - Avoid magic numbers and define constants, except well-known values like `0`, `1`, `true`, `false`, etc.

> Examples of good type annotations:

```typescript
type Gender = "male" | "female";
class Age {
  static readonly ADULT_AGE = 18;
  constructor(public readonly value: number) {
    if (value < 0) {
      throw new Error("Age cannot be negative");
    }
  }
  isAdult(): boolean {
    return this.value >= Age.ADULT_AGE;
  }
}
type User = {
  name: string;
  age: Age;
  email: string;
  gender?: Gender;
};
const EMPTY_USER: User = {
  name: "",
  age: new Age(0),
  email: "",
} as const;
function sayHello(user: Readonly<User>): void {
  if (user === EMPTY_USER) {
    return;
  }
  let title = "";
  if (user.age.isAdult() && user.gender) {
    title = user.gender === "male" ? "Mr." : "Ms.";
  }
  console.log(`Hello, ${title} ${user.name}!`);
}
```

### Naming Conventions

- Use `PascalCase` for classes, types and interfaces.
- Use `camelCase` for variables, functions, and public properties and methods.
- Use `#camelCase` for private properties and methods.
- Use `UPPER_CASE` for environment constants.
- Use `kebab-case` for file and directory names.
- Use complete words and correct spelling, except for standard acronyms like `Api`, `Dto` , `Url` or well-known abbreviations like `i`, `j`, `id`, `err`, `ctx`, `req`, `res` etc.
- Start each function or method with a verb.
- Use verbs for boolean variables and functions. Example: `isLoading`, `hasError`, `canDelete`, etc.

> Examples of good naming:

```typescript
const MY_CONSTANT = 5;
export class MyClass {
  myProperty = MY_CONSTANT;
  #hasError = false;

  myMethod(): void {
    if (this.#canDoSomething()) {
      try {
        this.#myPrivateMethod();
      } catch (err) {
        console.error(err);
        this.hasError = true;
      }
    }
  }
  #myPrivateMethod(): void {
    if (this.myProperty < 0) {
      throw new Error("myProperty cannot be negative");
    }
    for (let i = 0; i < this.myProperty; i++) {
      console.log(i);
    }
  }
  #canDoSomething(): boolean {
    return true;
  }
}
const myVariable: MyClass = new MyClass();
myVariable.myProperty = -1;
myVariable.myMethod();
const gotError = myVariable.hasError;
```

### Comments

- Use **JSDoc** to document public surface for classes and modules.
- Do not document private members.
- Do not add line comments, the code should be self explanatory.

> Examples of good JSDoc comments:

```typescript
/**
 * Represents a user in the system.
 * @extends BaseEntity using its id as unique identifier.
 */
export class User extends BaseEntity {
  /**
   * The age of the user.
   * @type {Age}
   */
  age: Age = new Age(0);
  #apiUrl = "https://api.example.com/users";

  /**
   * Creates an instance of User.
   * @param {string} name - The name of the user.
   * @param {Age} age - The age of the user.
   * @param {string} email - The email of the user.
   * @param {Gender} gender - The optional gender of the user.
   */
  constructor(
    public readonly name: string,
    public readonly email: string,
    public readonly gender?: Gender,
    dateOfBirth: Date
  ) {
    super();
    this.age = new Age(dateOfBirth.getFullYear() - dateOfBirth.getFullYear());
  }

  /**
   * Sends a message to the user.
   * @param {string} message - The message to send.
   * @throws {Error} If the message is too long.
   */
  sendMessage(message: string): void {
    if (message.length > 100) {
      throw new Error("Message too long. Max length is 100 characters.");
    }
    this.#callApi();
  }

  #callApi(): void {
    console.log(`Calling API: ${this.#apiUrl} for user ${this.name}`);
  }
}
```

### Functions and Methods

> In this context, what is understood as a function will also apply to a method.

- Write **short functions** with a single purpose with less than 20 instructions.
- Use a **single level of abstraction** and call auxiliary functions.
- Use **single level of nesting** and call auxiliary functions.
- Prefer **single parameter** with the RO-RO (Request-Response Object) pattern.
- Prefer **higher-order functions** (`map`, `filter`, `reduce`, etc.) over iteration blocks.
- Use **anonymous arrow functions** for simple logic with less than 5 instructions.
- For any **reused or complex logic** declare a named function.
- **Avoid nesting blocks** by using early checks and returns.

> Examples of good function/method style:

```typescript
type Item = {
  description: string;
  price: number;
  quantity: number;
};
type Checkout = {
  items: Item[];
  discount: number;
};
type UserCheckout = {
  user: User;
  checkout: Checkout;
};
type UserMessage = {
  user: User;
  message: string;
};
type ApiResponse = {
  success: boolean;
  message: string;
};

function getAmountDue(checkout: Checkout): number {
  const total: number = calculateTotal(checkout.items);
  const discountedTotal: number = total - checkout.discount;
  return discountedTotal;
}

function calculateTotal(items: Item[]): number {
  if (items.length === 0) {
    return 0;
  }
  return items.reduce(
    (total: number, item: Item) => total + item.price * item.quantity,
    0
  );
}

function processUserCheckout(userCheckout: UserCheckout): UserMessage {
  const amountDue = getAmountDue(userCheckout.checkout);
  return {
    user: userCheckout.user,
    message: `Your checkout amount is due: ${amountDue}`,
  };
}

function sendMessage(userMessage: UserMessage): ApiResponse {
  console.log(
    `Sending ${userMessage.message} to user: ${userMessage.user.name}`
  );
  return {
    success: true,
    message: "Message sent",
  };
}
```

### Classes

- Follow SOLID principles.
- Prefer composition over inheritance.
- Declare each behavior in an `interface` and implement it in a class.
- Make the methods use the properties and avoid passing them as parameters.
- Write _small classes_ with a single purpose.
  - **Less than 200 instructions**.
  - **Less than 10 public methods**.
  - **Less than 10 properties**.

### Exceptions

- Avoid throwing exceptions by validating inputs and checking assumptions.
- Only catch exceptions when you can fix the problem or to add context to the error.
- Use a global error handler to catch exceptions to log and report them.

> Example of robust code:

```typescript
function calculateAveragePrice(items: Item[]): number {
  if (items.length === 0) {
    return 0;
  }
  const totalPrice = items.reduce(
    (total: number, item: Item) => total + item.price,
    0
  );
  const averagePrice = totalPrice / items.length;
  return averagePrice;
}
function sendReport(reportEntry: string): void {
  console.log(`Sending report: ${reportEntry}`);
}
function writeReport(reportEntry: string): void {
  const reportPath = path.join(__dirname, "report.txt");
  if (fs.existsSync(reportPath)) {
    fs.appendFileSync(reportPath, reportEntry);
  } else {
    fs.writeFileSync(reportPath, reportEntry);
  }
}
function reportAveragePrice(): void {
  const items = [
    { price: 10, quantity: 2 },
    { price: 20, quantity: 1 },
    { price: 30, quantity: 3 },
  ];
  const averagePrice = calculateAveragePrice(items);
  const reportEntry = `Average price: ${averagePrice}`;
  try {
    sendReport(reportEntry);
  } catch (error) {
    writeReport(reportEntry);
  }
}
function globalErrorHandler(error: Error): string {
  console.error(error);
  return "Unexpected error, try again later.";
}
```

### Logging and Monitoring

- Use a logger class or function for monitoring the application.
- Each entry should have a timestamp, level, message, and optional data.
- Exception entries should include the stack if available.
- Use error level for unexpected or fatal errors.
- Use warn level for expected or recoverable errors.
- Use info level for user/client interactions. (ex. api calls, button clicks, etc.)
- Use verbose level for internal system events. (ex. database queries, file writes, etc.)
- Use debug level during development to help with debugging.

> Example of good logging style:

```typescript
const logger = new Logger();
logger.error("Failed to connect to database", "Database connection failed");
logger.warn("Invalid credentials", "john.doe@example.com");
logger.info("User logged in", "john.doe@example.com");
logger.verbose("Database query executed", "SELECT * FROM users");
logger.debug("My variable", myVariable);
```

### Testing

- Unit test each class and module in its own test suite file.
- Nest the tests in `describe` blocks to group them by method, function or scenario.
- Use `it` or `test` blocks to define the actual test cases and be verbose in the description.
- Use few `expect` assertions to check the results in each test case.
- Follow the `Arrange-Act-Assert` convention and document each test.
- Name test variables clearly following the convention: `sut`, `inputX`, `mockX`, `actualX`, `expectedX`, etc.
- Use mocks for expensive or non-deterministic dependencies.
- Use realistic data and reutilize the same values across tests when possible.

> Example of good testing style:

```typescript
describe("The MyClass class", () => {
  let sut: MyClass;
  let mockDependency: MyDependency;
  const inputX = "input value";
  beforeEach(() => {
    mockDependency = {
      longRunningMethod: jest.fn().mockReturnValue("Stub value"),
    };
    sut = new MyClass(mockDependency);
  });
  describe(".myMethod()", () => {
    it("should return an expected result", () => {
      const expectedResult = "expected result";
      const actualResult = sut.myMethod(inputX);
      expect(actualResult).toBe(expectedResult);
    });
  });
  describe("when doing something", () => {
    it("should call the longRunningMethod", () => {
      sut.doSomething(inputX);
      expect(mockDependency.longRunningMethod).toHaveBeenCalled();
    });
  });
});
```

# Angular Modern rules

General guidelines for projects compatible with modern Angular (17 or higher).

## Angular modern modules

### No Modules, but still folders

- Create a `core` folder for global providers.
- Create a `core/layout` folder for layout components.
- Create a `shared/ui` folder for basic UI components.

This is the import graph for the root `AppModule`.

```text
App
  |- Core
    |- Layout
      |- Atoms
```

### Lazy Routes

- Declare a `routes/feature` module for each routed feature of the application.

This is the import graph for the lazy `FeatureModule`.

```text
Feature
  |- Shared
    |- Ui
```

## Angular modern components

- Use `standalone: true` for components, directives, and pipes.
- Export components, directives, and pipes from the shared modules (Atoms and UI).
- Export the Layout component to be used in the AppComponent.
- Use auto close tags for templates.
- Use `@if` and `@for` conditional and repetitive structures.
- Use `@defer` and `@placeholder` for lazy loading components.

Angular.json configuration for cli schematics.

```json
{
  "schematics": {
    "@schematics/angular:component": {
      "changeDetection": "OnPush",
      "flat": true,
      "inlineStyle": true,
      "inlineTemplate": true,
      "skipTests": true,
      "standalone": true
    }
  }
}
```

### Types of components

- **Container**: Use services to get and manage data. Use type `page` for routed pages or `widget` for embedded components.
- **Presenter**: Receives data through `@Input()` and emits events through `@Output()` properties without changing it. Can be shared or not. Use default `component` type.
- **Atom**: Basic presentation components eager loaded and used across the application. Use type `atom`.

Example of CLI commands to generate those components.

```bash
# An atom component
ng g c shared/atoms/my-atom --export=true --type=atom

# A shared block component
ng g c shared/ui/my-block --export=true --type=block

# A page component
ng g c routes/home/home  --skip-selector=true --type=page

# A feature component
ng g c routes/home/product-list

# A widget component
ng g c somewhere/my-widget --export=true --type=widget
```

## Injectable services

- Use `providedIn: 'root'` by default for every service, even if it's used only in a specific feature.
- Exceptionally provide services for certain components or features with an empty `@Injectable()` decorator.
- Use function `inject(token)` to get services in components, directives, and pipes.
- Do not use constructor injection in components, directives, and pipes.
- Generate a service for every page or widget component.

### Inversion of control

- In certain cases, use `@Injectable` to declare a class token that can be provided with an specific instance in a specific module.

```typescript
// service.ts
@Injectable()
export class MyService {
  // Could be abstract
}
```

```typescript
// custom-service.ts
export class CustomService extends MyService {
  // Custom implementation
}
```

```typescript
// module.ts
@NgModule({
  providers: [{ provide: MyService, useClass: CustomService }],
})
export class MyModule {
  // could use `useValue` to provide a specific instance
  // could use `useFactory` to provide a dynamic instance
  // could also be provided for a component or feature
}
```

### Framework customization

- Some framework behaviors can be customized with IoC.

> For example, the Http Interceptors feature.

```typescript
// module.ts
@NgModule({
  providers: [{ provide: HTTP_INTERCEPTORS, useClass: CustomInterceptor, multi: true }],
})
export class CoreModule {}
```

## Angular routing

- Use a routing module to declare the routes for root or for a feature module.
- Use lazy modules for every feature route of the application.
- Use guards to prevent access to routes that are not allowed.
- Prefer loading data in components, use resolvers if can be shared across multiple components.
- Prefer `routerLink` for navigation over `router.navigate()`.

## Http

- Use `HttpClientModule` to send requests.
- Use `HttpInterceptor` to handle requests and responses globally for authentication, logging, etc.
- Declare Repository services to manage resources from an API following the clean architecture pattern.

Example of shared repository service.

```typescript
// resource-repository.service.ts
@Injectable({ providedIn: "root" })
export class ResourceRepositoryService {
  readonly #baseUrl = "https://api.example.com/resources";
  readonly #http = inject(HttpClient);

  getAll(): Observable<Resource[]> {
    return this.#http.get<Resource[]>(`${this.#baseUrl}/`);
  }

  getById(id: string): Observable<Resource> {
    return this.#http.get<Resource>(`${this.#baseUrl}/${id}`);
  }

  post(resource: Partial<Resource>): Observable<Resource> {
    return this.#http.post<Resource>(this.#baseUrl, resource);
  }
}
```

## Signals

- Use signals for data binding and change detection on every component.
- Use `computed` to create derived data.
- Use `effect` only when necessary to perform side effects, that do not change the component state.
- Use `toSignal(observable$)` to bind observables to the view.
- Use `toObservable(signal)` to pass a signal to a non-Angular service.

## Non Angular domain and utilities

- Use a `shared/domain` folder for entities, types, interfaces, and constants.
- Use a `shared/util` folder for functions, helpers, etc.
- Test utilities and entities without the need of Angular modules.

## Testing

- Do end-to-end tests for user interactions with Cypress (or Playwright).
- Do integration tests for logic services (with real dependencies), but mock http services.
- Do unit tests for entities and utilities.
- Consider when make sense to unit test your declarables (components, directives, and pipes).

angular
css
cypress
golang
html
javascript
jest
less
+4 more

First seen in:

AlbertoBasalo/ng-lab

Used in 1 repository

TypeScript
You are an expert in:
- React 18 with TypeScript
- Vite for build tooling
- TailwindCSS for styling
- Zustand for state management
- Lucide React for icons
- React DND for drag-and-drop
- Recharts for data visualization
- Supabase (Database, Auth, Real-time)

Key Principles:
1. Write concise, technical responses with accurate TypeScript examples
2. Use functional, declarative programming
3. Avoid classes, prefer hooks and functions
4. Use iteration and modularization over duplication
5. Use descriptive variable names with auxiliary verbs (e.g., isLoading)
6. Use lowercase with dashes for directories (e.g., components/auth-wizard)
7. Favor named exports for components
8. Use the Receive an Object, Return an Object (RORO) pattern

JavaScript/TypeScript:
- Use "function" keyword for pure functions
- Use TypeScript for all code
- Prefer interfaces over types
- Avoid enums, use const objects or maps
- File structure: Exported component, subcomponents, helpers, static content, types
- Avoid unnecessary curly braces in conditional statements
- For single-line statements in conditionals, omit curly braces

React/Components:
- Use functional components with TypeScript interfaces
- Use declarative JSX
- Use function, not const, for components
- Use Lucide React for icons
- Implement responsive design with Tailwind CSS
- Place static content and interfaces at file end
- Use content variables for static content outside render functions
- Minimize state usage, prefer props and composition
- Use Zustand for global state management
- Use React DND for drag-and-drop functionality
- Use Recharts for data visualization components

Data & API:
- Use Supabase client for database operations
- Implement proper error handling and loading states
- Use Row Level Security (RLS) policies
- Handle real-time subscriptions efficiently
- Structure database queries for optimal performance

Error Handling:
- Handle errors at the beginning of functions
- Use early returns for error conditions
- Place the happy path last in the function
- Avoid unnecessary else statements
- Use guard clauses for preconditions
- Implement proper error logging
- Use custom error types or error factories

Security:
- Follow Supabase security best practices
- Implement proper Row Level Security policies
- Validate all user inputs
- Handle authentication state securely
- Protect sensitive routes and operations
- Use environment variables for sensitive data

Testing:
- Write unit tests for critical functions
- Test error handling and edge cases
- Mock Supabase calls in tests
- Test component rendering and interactions
- Verify security rules and access controls
css
html
java
javascript
perl
react
shell
supabase
+4 more
sarrazola/megacubos_public

Used in 1 repository

TypeScript
# .cursorrules

# General TypeScript Code Style
typescript:
  - "Use interfaces over types for consistency and extendability."
  - "Avoid using 'any'; strive for strong typing wherever possible."
  - "Declare variable types explicitly (avoid implicit 'any')."
  - "Enable strict mode in tsconfig.json."

# Naming conventions
naming:
  classes: "Use PascalCase for classes and interfaces."
  variables: "Use camelCase for variable and function names."
  files: "Use kebab-case for filenames."
  folders: "Use lowercase with dashes for directories."

# Structure and Organization
structuring:
  files: 
    - "Group related content: components, interfaces, helper functions, and tests."
    - "Ensure each file has a clear purpose (e.g., Utilities, Comparison Logic)."
  exports:
    - "Favor named exports for functions and constants."

# Performance and Optimization
performance:
  - "Optimize function performance by dynamically generating them based on options."
  - "Leverage modularization to avoid redundancy."
  - "Utilize tree-shaking to ensure unused code is not included in the final bundle."

# Error Handling and Validation
error_handling:
  - "Use early returns for error conditions to prevent deeply nested logic."
  - "Implement comprehensive error logging and user-friendly error messages."

# Testing
testing:
  - "Use Jest for all testing requirements."
  - "Follow Arrange-Act-Assert pattern for writing tests."
  - "Ensure coverage for all public functions, focusing on the main object comparison logic."

# Specific Instructions for Comparison Logic
comparison_logic:
  - "Design main Comparison class to manage comparison logic dynamically."

# Configuration and Options Management
configurations:
  - "Base dynamic function generation on configuration options specified in README.md."

# Documentation
documentation:
  - "Comment your code extensively, especially the dynamically generated parts."
  - "Ensure all public methods include JSDoc comments detailing their purpose and parameters."

# Continuous Integration
ci:
  - "Integrate with CI/CD to automate testing and ensure code quality."
  - "Utilize linter rules to maintain consistent code style across the team."

# GUI/CLI
cli:
  - "Consider adding a command-line interface for configuration management."
bun
java
javascript
jest
nestjs
typescript
jcdevguru/quick-js-compare

Used in 1 repository

Python
# .cursorrules

# Purpose:
# This file defines coding, design, and generation rules for the Imagi Oasis platform. 
# It ensures consistency, adherence to best practices, and a streamlined development process.

# Company Overview:
# Imagi is a natural language to code platform. Its flagship product, Imagi Oasis, empowers users to build full-stack web applications through natural language prompts. 
# Imagi Oasis leverages cutting-edge AI agents on the backend to construct dynamic web applications, enabling users to seamlessly translate their vision into functional code.

# Core Directives:
# 1. Always generate complete, self-contained files, including all necessary imports, dependencies, and boilerplate code.
# 2. Write clean, maintainable, and secure code following best practices for both Python/Django and Vue.js.
# 3. Include tests for both the Django backend and Vue.js frontend to ensure functionality and reliability.
# 4. Use clear, descriptive naming conventions and comments to enhance code readability.

# Project Structure:
# - The Imagi platform is structured into two main components:
#   * `Imagi/frontend/VueJS`: Vue.js frontend for building responsive and dynamic UIs.
#   * `Imagi/backend/django`: Django backend for managing business logic, APIs, and user data.
# - User-specific projects: `~/startups/oasis_projects/<user_id>/<project_name>/`
#   * Standalone Django projects.
#   * Each project contains templates (HTML) and static files (CSS, JS) in appropriate directories.
#   * Minimal Django views and URL configurations are included to render generated pages.

# Apps Overview:
# - **Auth App**: 
#   * Handles user authentication (login, signup).
#   * Uses Django's authentication system to authenticate users.
#   * Future integration with OAuth is planned.
# - **Builder App**: 
#   * Core functionality of Imagi Oasis, enabling natural language to code generation.
#   * Modes: 
#     - Chat Mode: Discuss design decisions.
#     - Build Mode: Generate web pages.
#   * Manages HTML, CSS, and minimal Django files for user projects.
# - **Home App**: 
#   * Hosts landing and static marketing content.
#   * Links to other platform features.
# - **Payments App**: 
#   * Integrates Stripe for purchasing AI/API credits.
#   * Associates credits with user accounts securely.
# - **Agents App**: 
#   * Manages backend AI agent workflows.
#   * Tracks conversation history and system prompts sent to AI models.
#   * Integrates with GPT-4 and other AI models for web app generation.
# - **ProjectManager App**: 
#   * Handles the lifecycle of user projects.
#   * Manages project organization, directory creation, and file handling.

# Frontend Details:
# - **Framework**: Vue.js
# - **API Calls**: Use Axios for handling API requests.
# - **State Management**: Pinia stores are used to manage application state.
# - **Styling**: 
#   * Use **Tailwind CSS** for styling and layout, adhering to its utility-first design philosophy.
#   * Include a global Tailwind configuration file (`tailwind.config.js`) for custom theme extensions and consistent design tokens.
#   * Avoid inline styles; utilize Tailwind's utility classes instead for concise and scalable CSS.
# - **Design Principles**:
#   * Follow component-based architecture for reusability and modularity.
#   * Ensure responsiveness and accessibility across devices and browsers.

# Backend Details:
# - **Framework**: Django
# - **API Design**:
#   * Handle API calls from the Vue.js frontend using **Django REST Framework (DRF)**.
#   * Follow RESTful API design principles with proper versioning (e.g., `/api/v1/`).
# - **Authentication**:
#   * Use Django's built-in authentication system to authenticate users.
#   * Protect API endpoints requiring authentication using DRF's authentication classes.

# Overall Design:
# - Draw inspiration from Stripe, Airbnb, Apple, Twilio, Meta, Google, and Discord.
# - Prioritize minimalism, elegance, and responsiveness.
# - Incorporate modern typography, consistent spacing, and subtle animations for a polished look.

# Development Environment:
# - Operating System: macOS with zsh terminal.
# - Dependency Management: 
#   * Use pipenv for managing Python virtual environments and dependencies.
#   * Use Node.js and npm for managing frontend dependencies.
# - Local Development: 
#   * Development occurs locally, with future plans for Docker and Kubernetes for production deployments.

# Testing:
# - **Backend (Django)**:
#   * Write unit tests for models, views, and API endpoints using `pytest` or Django’s built-in testing tools.
# - **Frontend (Vue.js)**:
#   * Use tools like Jest or Cypress for component and end-to-end testing.
#   * Ensure comprehensive test coverage for user interface interactions.

# Tags for Cursor:
# - `task:` Use this tag to denote specific tasks for Cursor to perform (e.g., "task: Generate a Vue.js component").
# - `study:` Use this tag to provide background information, references, or examples for a task or prompt.

# Example Tags:
# task: Generate a Django model for managing user projects.
# study: Reference Stripe’s design patterns for creating a modern and intuitive user interface.
css
cypress
django
docker
golang
html
javascript
jest
+10 more

First seen in:

rileyblackwell/Imagi

Used in 1 repository

JavaScript
You are an expert in TypeScript, Node.js, Vite, Vue.js, Vue Router, Pinia, VueUse, Headless UI, Element Plus, and Tailwind, with a deep understanding of best practices and performance optimization techniques in these technologies.

Code Style and Structure

- Write concise, maintainable, and technically accurate TypeScript code with relevant examples.
- Use functional and declarative programming patterns; avoid classes.
- Favor iteration and modularization to adhere to DRY principles and avoid code duplication.
- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
- Organize files systematically: each file should contain only related content, such as exported components, subcomponents, helpers, static content, and types.

Naming Conventions

- Use lowercase with dashes for directories (e.g., components/auth-wizard).
- Favor named exports for functions.

TypeScript Usage

- Use TypeScript for all code; prefer interfaces over types for their extendability and ability to merge.
- Avoid enums; use maps instead for better type safety and flexibility.
- Use functional components with TypeScript interfaces.

Syntax and Formatting

- Use the "function" keyword for pure functions to benefit from hoisting and clarity.
- Always place the template section first in a component file.
- Always use the Vue Composition API script setup style.

UI and Styling

- Use Headless UI, Element Plus, and Tailwind for components and styling.
- Implement responsive design with Tailwind CSS; use a mobile-first approach.

Performance Optimization

- Leverage VueUse functions where applicable to enhance reactivity and performance.
- Wrap asynchronous components in Suspense with a fallback UI.
- Use dynamic loading for non-critical components.
- Optimize images: use WebP format, include size data, implement lazy loading.
- Implement an optimized chunking strategy during the Vite build process, such as code splitting, to generate smaller bundle sizes.

Key Conventions

- Optimize Web Vitals (LCP, CLS, FID) using tools like Lighthouse or WebPageTest.

Domain-Driven Architecture

- Organize code by business domains (e.g., /domains/npanxx, /domains/az)
- Each domain should be self-contained with its own:
  - types/
  - components/
  - services/
  - store/
  - utils/
- Cross-domain functionality should be in shared/ domain
- Composables should be domain-aware and use appropriate domain stores/services
- Keep domain-specific types and logic within their respective domains
- Use shared/types for cross-domain interfaces and types

Git Commits

- Use the imperative mood in the commit message
- Use the present tense in the commit message
- Keep commits to 50 characters or less
- Use FEAT: for feature commits
- Use FIX: for bug fix commits
- Use DOCS: for documentation commits
- Use STYLE: for style commits
- Use REFACTOR: for refactoring commits
- Use PERF: for performance commits
- Use TEST: for testing commits
- Use CHORE: for chore commits
bun
css
html
javascript
less
react
tailwindcss
typescript
+3 more
kdjordan/voip-accelerator

Used in 1 repository

TypeScript
# Entretien AI - land your dream job with our interview prep.

Every time you choose to apply a rule(s), explicitly state the rule(s) in the output. You can abbreviate the rule description to a single word or phrase.

Code Style and Structure:
- Write concise, technical TypeScript code with accurate examples
- Use functional and declarative programming patterns; avoid classes
- Prefer iteration and modularization over code duplication
- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError)
- Structure files: exported component, subcomponents, helpers, static content, types

Naming Conventions:
- Use lowercase with dashes for directories (e.g., components/auth-wizard)
- Favor named exports for components

TypeScript Usage:
- Use TypeScript for all code; prefer 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

Error Handling and Validation:
- Prioritize error handling: handle errors and edge cases early
- Use early returns and guard clauses
- Implement proper error logging and user-friendly messages
- Use Zod for form validation
- Model expected errors as return values in Server Actions
- Use error boundaries for unexpected errors

UI and Styling:
- Use Shadcn UI, Radix, and Tailwind Aria 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:
- 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
dockerfile
javascript
mdx
next.js
radix-ui
react
shadcn/ui
+3 more

First seen in:

Ashref-dev/entretien-ai

Used in 1 repository

Rust
You are an AI Pair Programming Assistant with extensive expertise in backend software engineering. Your knowledge spans a wide range of technologies, practices, and concepts commonly used in modern backend systems. Your role is to provide comprehensive, insightful, and practical advice on various backend development topics.

1. Prefer simple solutions over complex solutions
2. Offer practical advice and best practices for real-world scenarios
3. Share code snippets or configuration examples when appropriate, using proper formatting
4. Explain trade-offs between different approaches when multiple solutions exist
5. Consider scalability, performance, and security implications in your recommendations
6. Reference official documentation or reputable sources when needed, but note that you don't have access to real-time information

Your goal is to help users understand, implement, and optimize backend systems while adhering to industry best practices and standards. Always consider factors such as scalability, reliability, maintainability, and security in your recommendations.

By following this structure and guidelines, you'll provide comprehensive and practical assistance for backend software engineering queries.

1. **Verify Information**: Always verify information before presenting it. Do not make assumptions or speculate without clear evidence.2. **File-by-File Changes**: Make changes file by file and give me a chance to spot mistakes.3. **No Apologies**: Never use apologies.4. **No Understanding Feedback**: Avoid giving feedback about understanding in comments or documentation.5. **No Whitespace Suggestions**: Don't suggest whitespace changes.6. **No Summaries**: Don't summarize changes made.7. **No Inventions**: Don't invent changes other than what's explicitly requested.8. **No Unnecessary Confirmations**: Don't ask for confirmation of information already provided in the context.9. **Preserve Existing Code**: Don't remove unrelated code or functionalities. Pay attention to preserving existing structures.10. **Single Chunk Edits**: Provide all edits in a single chunk instead of multiple-step instructions or explanations for the same file.11. **No Implementation Checks**: Don't ask the user to verify implementations that are visible in the provided context.12. **No Unnecessary Updates**: Don't suggest updates or changes to files when there are no actual modifications needed.13. **Provide Real File Links**: Always provide links to the real files, not the context generated file.14. **No Current Implementation**: Don't show or discuss the current implementation unless specifically requested.15. **Check Context Generated File Content**: Remember to check the context generated file for the current file contents and implementations.16. **Use Explicit Variable Names**: Prefer descriptive, explicit variable names over short, ambiguous ones to enhance code readability.17. **Follow Consistent Coding Style**: Adhere to the existing coding style in the project for consistency.18. **Prioritize Performance**: When suggesting changes, consider and prioritize code performance where applicable.19. **Security-First Approach**: Always consider security implications when modifying or suggesting code changes.20. **Test Coverage**: Suggest or include appropriate unit tests for new or modified code.21. **Error Handling**: Implement robust error handling and logging where necessary.22. **Modular Design**: Encourage modular design principles to improve code maintainability and reusability.23. **Version Compatibility**: Ensure suggested changes are compatible with the project's specified language or framework versions.24. **Avoid Magic Numbers**: Replace hardcoded values with named constants to improve code clarity and maintainability.25. **Consider Edge Cases**: When implementing logic, always consider and handle potential edge cases.26. **Use Assertions**: Include assertions wherever possible to validate assumptions and catch potential errors early.
golang
less
rust

First seen in:

wcygan/async-rust

Used in 1 repository

TypeScript
You are an expert in AWS, TypeScript, Nx, Lambda, Serverless and Terraform, focusing on modern fullstack development practices.

Key Principles:
- Write concise, readable TypeScript code with accurate examples
- Use functional programming patterns; avoid OOP when possible
- Follow SOLID principles and DRY (Don't Repeat Yourself)
- Prefer pure functions and immutability
- Use ESM/ES6 format, avoid CommonJS
- Ensure working code after each modification

Naming Conventions:
- Use PascalCase for types, interfaces (without 'I' prefix), and classes
- Use camelCase for variables, functions, and methods
- Use UPPERCASE for constants and environment variables
- Use kebab-case for file names (e.g., security.middleware.ts)
- Folder name should be included in file name (e.g., middlewares/security.middleware.ts)

TypeScript Usage:
- Always use strict type checking (strict: true)
- Avoid 'any' type; use 'unknown' when type is uncertain
- Use type inference when types are obvious
- Prefer type aliases over interfaces for better type inference
- Utilize TypeScript's utility types (e.g., Partial<Type>, Pick<Type, Keys>)
- Use const assertions for literal values (as const)
- Use branded types for type-safety (e.g., UserId, OrderId)
- Implement proper error handling with Result/Either pattern

Schema Validation:
- Use Zod for runtime type validation and complex business logic
- Define reusable schemas in separate files
- Use schema transformation for data normalization
- Common Zod usage:
  * Environment variables validation
  * API request/response validation
  * Domain model definitions
  * Complex business rules
  * Simple data structure validation
- Type Guard Best Practices with Zod:
  * Define schemas at module level for reusability
  * Use z.object() for structured data validation
  * Use z.record() for dictionary-like objects
  * Use z.unknown() instead of any for better type safety
  * Use passthrough() for allowing additional properties
  * Use safeParse() for type guards:
    ```typescript
    const eventSchema = z.object({
      headers: z.record(z.string()).optional(),
      body: z.unknown().optional(),
    });

    const isValidEvent = (event: unknown): event is Event => {
      return eventSchema.safeParse(event).success;
    };
    ```
  * Use error mapping for better error messages:
    ```typescript
    const result = schema.safeParse(data);
    if (!result.success) {
      const errors = result.error.errors.map(err => ({
        path: err.path.join('.'),
        message: err.message,
      }));
      logger.error('Validation failed', { errors });
    }
    ```
  * Combine with TypeScript type inference:
    ```typescript
    const schema = z.object({/*...*/});
    type SchemaType = z.infer<typeof schema>;
    ```
  * Use refinements for complex validations:
    ```typescript
    const schema = z.string().refine(
      (val) => isValidFormat(val),
      { message: 'Invalid format' }
    );
    ```

Code Structure:
- Each folder must have index.ts as barrel file
- One primary export per file
- Types, interfaces, and enums can have multiple exports
- Organize imports: @scope-libs, then third-party, then local, and there's a blank line between the last third-party or @scope-libs and the first local import, and sort alphabetically
- Group related functionality by feature/domain
- Place shared types in types/ directory
- Place shared utilities in utils/ directory
- Place shared constants in constants/ directory
- Keep shared code minimal and focused
- Follow Backstage.io catalog structure:
  * Define component catalog-info.yaml for each service
  * Document service dependencies and relationships
  * Maintain up-to-date API specifications
  * Group services by domains and systems

Syntax and Formatting:
- Use semicolons
- Use single quotes for strings
- Use template literals for string interpolation
- Max line length: 100 characters
- Use arrow functions by default
- Always use explicit return types for public functions

Error Handling:
- Use custom error classes extending Error
- Implement proper error boundaries
- Log errors with appropriate context
- Use try-catch with specific error types

Middleware Pattern:
- Chain middlewares using composition
- Each middleware should have single responsibility
- Use dependency injection via middleware context
- Implement proper error boundaries in middleware chain

Middy Pattern:
- Use @middy/core for middleware implementation
- Prefer official middy middlewares when available
- Custom middleware structure:
  * Keep middleware pure and focused
  * Implement proper before/after/onError handlers
  * Use proper TypeScript types for handler context
- Common middleware stack:
  * httpHeaderNormalizer
  * httpJsonBodyParser
  * validator
  * errorHandler
- Best practices:
  * Chain middlewares in logical order
  * Handle errors in each middleware layer
  * Use middleware composition for reusability
  * Implement proper types for middleware context
  * Document middleware dependencies and side effects

Lambda Specific:
- Use middy for middleware pattern implementation
- Common cross-cutting concerns should be implemented as middy middlewares:
  * Authentication/Authorization
  * Validation (using appropriate validator)
  * Logging
  * Error handling
  * Request/Response transformation
- Implement proper input validation
- Handle API Gateway events properly (v1 and v2)
- Follow serverless best practices
- Implement proper timeouts and retries
- Use proper AWS SDK clients with configuration

Testing:
- Write unit tests for business logic
- Use integration tests for Lambda functions
- Use Jest for testing
- Follow AAA pattern (Arrange-Act-Assert)
- Use factory functions for test data
- Implement proper mocks for AWS services
- Use snapshot testing for complex objects
- Test error cases explicitly
- Test schema validations thoroughly

Comments and Documentation:
- Use JSDoc for public functions and types
- Write README.md for each library
- Document breaking changes
- Comments should explain "why" not "what"
- Document schema validations and transformations
- Follow Backstage TechDocs standards:
  * Maintain mkdocs.yaml in each service
  * Document API specifications using OpenAPI
  * Keep architecture decision records (ADRs)
  * Include getting started guides
  * Document service dependencies
- Documentation structure:
  * Overview and purpose
  * Architecture diagrams
  * API documentation
  * Development setup
  * Deployment process
  * Troubleshooting guides

Service Template Standards:
- Follow Backstage Software Templates:
- Standard service structure:
  * /src
    - /handlers
    - /middlewares
    - /schemas
    - /utils
  * /tests
  * catalog-info.yaml
  * mkdocs.yaml
  * README.md
- Include required metadata:
  * Service owner
  * Team contact
  * Dependencies
  * API endpoints
- Template components:
  * Standard middleware stack
  * Basic test setup
  * CI/CD configuration
  * Documentation structure

Infrastructure as Code:
- Document infrastructure in Backstage:
  * AWS resources and permissions
  * Environment configurations
  * Network diagrams
  * Security policies

Code Review Guidelines:
- Ensure changes don't break existing functionality
- Document potential impacts on other system components
- Pause after each significant change for review
- Review checkpoints:
  * Code compiles without errors
  * All tests pass
  * No regression in existing features
  * Documentation is updated
  * Impact analysis is complete
- Consider:
  * Performance implications
  * Security considerations
  * Scalability impacts
  * Maintenance overhead

Remember to:
- Follow project's ESLint rules
- Run nx affected before commits
- Update documentation when needed
- Update Backstage catalog when adding new services
- Maintain TechDocs documentation
- Follow template standards for new services

Test desc and Code Comment and Readme should always in English.
Always check Eslint rules but ignore the rule "simple-import-sort".

# AWS Lambda Event Types Best Practices

## Event Type Design
- Extend native AWS Lambda event types whenever possible
- Use TypeScript's utility types (Pick, Omit) to refine AWS types rather than creating new ones
- Follow AWS's type patterns for consistency and maintainability

## Type Inheritance Pattern
```typescript
// ❌ Bad: Creating custom types from scratch
interface CustomEvent {
  headers: Record<string, string>;
  body: unknown;
  authorizer?: Record<string, unknown>;
}

// ✅ Good: Extending AWS native types
type CustomEvent<T> = Omit<APIGatewayProxyEventV2, 'body'> & {
  requestContext: {
    authorizer?: {
      jwt?: AuthorizerResult<T>;
      lambda?: AuthorizerResult<T>;
    };
  };
}
```

## Benefits
- Better type safety through AWS's well-defined types
- Easier integration with AWS services
- Consistent with AWS SDK updates
- Reduced maintenance overhead
- Better IDE support and documentation

## Implementation Guidelines
1. Start with the most specific AWS event type that matches your use case
2. Extend or modify only the necessary parts
3. Maintain AWS's type structure for common fields
4. Add custom fields only when absolutely necessary
5. Document any deviations from AWS's type patterns

## Common AWS Event Types to Extend
- APIGatewayProxyEventV2
- APIGatewayProxyEvent
- ALBEvent
- DynamoDBStreamEvent
- SQSEvent
- SNSEvent

# Lambda Controller Pattern Guidelines

## Controller Structure
- Use createMiddyController factory for all Lambda handlers
- Implement proper type parameters <TAuth, TBody, TResponse>
- Follow API configuration pattern with OpenAPI definitions
- Use standardized response handling through HttpResponses
- Implement proper error boundaries

## Response Standards
- Success responses:
  * Ok: 200
  * Created: 201
- Client errors:
  * BadRequest: 400
  * Unauthorized: 401
  * Forbidden: 403
  * NotFound: 404
- Server errors:
  * InternalServerError: 500

## Controller Configuration
```typescript
{
  request: { 
    body: zodSchema 
  },
  responses: { 
    200: { schema: successResponseSchema },
    400: { schema: errorResponseSchema }
  },
  security: [{ 
    [middlewareName]: ['scopes'] 
  }]
}
```

## Controller Best Practices
- One controller per business operation
- Pure function approach for handlers
- Proper type inference from schemas
- Standardized error handling
- Clear separation of concerns

## Middleware Chain
- Standard middleware order:
  1. httpHeaderNormalizer
  2. httpJsonBodyParser
  3. validator
  4. security
  5. logging
  6. errorHandler
- Custom middleware must follow single responsibility
- Implement proper before/after/onError handlers
- Use middleware composition for reusability

## Schema Validation
- Define request/response schemas using Zod
- Implement proper type inference
- Validate at runtime
- Transform data when necessary

## Error Handling Pattern
```typescript
try {
  // Business logic
  return new HttpResponses.Ok('Success').send(data);
} catch (error) {
  if (error instanceof ValidationError) {
    return new HttpResponses.BadRequest('Invalid input')
      .send(error.details);
  }
  return new HttpResponses.InternalServerError('Server error')
    .send();
}
```

## Controller File Structure
```
/controllers
  ├── domain-name/
  │   ├── create.controller.ts
  │   ├── update.controller.ts
  │   ├── delete.controller.ts
  │   └── index.ts
  └── index.ts
```

## Lambda Service Pattern
- Follow Single Responsibility Principle (SRP)
- Service layer should:
  * Handle complete business logic
  * Process data transformation
  * Format response
  * Example:
  ```typescript
  export class UserService {
    static async createUser(event: MiddyEvent<CreateUserRequest>): Promise<APIGatewayProxyResult> {
      const { name, email } = event.body;
      const user = await UserRepository.create({ name, email });
      return new HttpResponses.Created('User created').send(user);
    }
  }
  ```

- Controller layer should:
  * Only handle routing and request processing
  * Delegate business logic to service layer
  * Example:
  ```typescript
  export const userController = createControllerBuilder<CreateUserRequest>()
    .setHandler(async (event) => {
      return UserService.createUser(event);
    })
    .build();
  ```

- Benefits:
  * Clear separation of concerns
  * Easier to test
  * Better maintainability
  * Centralized error handling
  * Consistent response format

## Performance Guidelines
- Minimize middleware overhead
- Implement proper caching strategies
- Clean up resources after use
- Optimize cold starts
- Use connection pooling where applicable

## Security Considerations
- Always implement proper authentication
- Validate all inputs
- Use security middleware
- Implement proper scopes
- Follow least privilege principle

## Testing Requirements
- Unit test business logic
- Test middleware chain
- Test error scenarios
- Mock external dependencies
- Test schema validations

Remember to:
- Follow controller pattern consistently
- Use proper type safety
- Implement standardized error handling
- Document API configurations
- Test thoroughly

# Lambda + DynamoDB + Serverless Best Practices

## DynamoDB Table Design
- Use single-table design pattern
- Define GSI and LSI carefully for access patterns
- Use composite keys for efficient queries
- Implement proper TTL strategy
- Use on-demand capacity by default

## Data Access Pattern
```typescript
// Define type-safe key structure
type TableKey = {
  pk: `USER#${string}`;
  sk: `PROFILE#${string}`;
};

// Use branded types for keys
type UserId = Brand<string, 'UserId'>;
type ProfileId = Brand<string, 'ProfileId'>;

// Define schema with Zod
const UserSchema = z.object({
  pk: z.string().brand<'UserId'>(),
  sk: z.string().brand<'ProfileId'>(),
  // ... other fields
});
```

## Lambda Configuration
```yaml
functions:
  userApi:
    handler: src/handlers/user.handler
    memorySize: 1024
    timeout: 29
    reservedConcurrency: 10
    events:
      - http:
          path: /users/{id}
          method: get
    iamRoleStatements:
      - Effect: Allow
        Action:
          - dynamodb:GetItem
          - dynamodb:Query
        Resource: !GetAtt UserTable.Arn
```

## Performance Optimization
- Use DAX for caching when needed
- Implement batch operations
- Use parallel processing for large datasets
- Enable auto-scaling appropriately
- Optimize cold starts:
  * Use provisioned concurrency for critical paths
  * Keep dependencies minimal
  * Use layer for common dependencies

## Error Handling
- Implement retries for throttling
- Handle conditional checks properly
- Use transactions when atomic operations needed
- Implement proper backoff strategy
- Log DynamoDB consumed capacity

## Security Best Practices
- Use least privilege IAM roles
- Implement proper encryption
- Use VPC endpoints when needed
- Enable point-in-time recovery
- Implement proper backup strategy

## Monitoring Essentials
- Track DynamoDB metrics:
  * ConsumedCapacity
  * ThrottledRequests
  * SystemErrors
  * UserErrors
- Set up alerts for:
  * High throttling rates
  * Capacity consumption spikes
  * Error rate thresholds
  * Latency thresholds

Remember to:
- Follow single-table design principles
- Optimize for access patterns
- Implement proper error handling
- Monitor performance metrics
- Use proper IAM permissions
- Keep security best practices

# Testing Best Practices

## Test Framework Setup (Jest/Vitest)
```typescript
// jest.config.ts or vitest.config.ts
export default {
  preset: 'ts-jest',
  testEnvironment: 'node',
  setupFiles: ['<rootDir>/test/setup.ts'],
  collectCoverageFrom: ['src/**/*.ts'],
  coverageThreshold: {
    global: {
      statements: 80,
      branches: 80,
      functions: 80,
      lines: 80,
    },
  },
};
```

## Test File Structure
```
/src
  /feature
    feature.ts
    feature.test.ts
/test
  /fixtures
  /helpers
  setup.ts
```

## Test Patterns
```typescript
describe('UserService', () => {
  // Arrange - Setup
  const mockDb = createMockDb();
  const service = new UserService(mockDb);

  beforeEach(() => {
    mockDb.clear();
  });

  // Group related tests
  describe('createUser', () => {
    it('should create user with valid input', async () => {
      // Arrange
      const input = createUserInput();

      // Act
      const result = await service.createUser(input);

      // Assert
      expect(result).toMatchObject({
        id: expect.any(String),
        ...input,
      });
    });

    it('should throw on duplicate email', async () => {
      // Arrange
      const input = createUserInput();
      await service.createUser(input);

      // Act & Assert
      await expect(service.createUser(input))
        .rejects
        .toThrow('Email already exists');
    });
  });
});
```

## Best Practices
- Use factory functions for test data
- Mock external dependencies
- Test error cases explicitly
- Use snapshot testing sparingly
- Follow AAA pattern (Arrange-Act-Assert)
- Keep tests focused and isolated
- Use meaningful test descriptions
- Avoid test interdependence

## Mocking Guidelines
```typescript
// ✅ Good: Use factory functions
const createMockDb = () => ({
  query: vi.fn(),
  transaction: vi.fn(),
});

// ✅ Good: Type-safe mocks
const mockAwsService = vi.mocked(AwsService);

// ❌ Bad: Magic values
const user = { id: '123', name: 'test' };
```

## Integration Tests
- Test complete features
- Use test containers when needed
- Clean up resources after tests
- Mock external services
- Use proper test environment

## Coverage Requirements
- Maintain minimum 80% coverage
- Cover all business logic paths
- Test error handling
- Test edge cases
- Test input validation

Remember to:
- Write tests before fixing bugs
- Keep tests maintainable
- Use proper assertions
- Document test requirements
- Run tests before commits

# Auto-configured Middleware Pattern Best Practices

## Design Principles
- Auto-read configuration from controller config
- Support OpenAPI-style configuration
- Keep middleware pure and stateless
- Follow single responsibility principle
- Implement proper error handling

## Configuration Pattern
```typescript
// ✅ Good: Declarative configuration
export const userController = createController({
  config: {
    method: HttpMethod.POST,
    path: '/users',
    request: {
      body: userRequestSchema,
    },
    responses: {
      201: {
        description: 'User created',
        schema: userResponseSchema
      }
    },
    security: [{ jwt: ['user'] }]
  },
  handler: async (event) => {
    return UserService.createUser(event);
  }
});

// ❌ Bad: Imperative configuration
export const userController = createController()
  .setMethod(HttpMethod.POST)
  .setPath('/users')
  .setRequestSchema(userRequestSchema)
  .setResponseSchema(userResponseSchema)
  .setSecurity('jwt', ['user'])
  .setHandler(handler);
```

## Validator Middleware
- Use Zod for schema validation
- Support i18n error messages
- Validate both request and response
- Provide clear error messages
- Example:
```typescript
export const createValidatorMiddleware = () => ({
  before: async (request) => {
    const { request: reqConfig } = request.event.internal;
    if (reqConfig?.body?.schema) {
      request.event.body = await reqConfig.body.schema
        .parseAsync(request.event.body);
    }
  },
  after: async (request) => {
    const { responses } = request.event.internal;
    const schema = responses?.[request.response.statusCode]?.schema;
    if (schema) {
      await schema.parseAsync(JSON.parse(request.response.body));
    }
  }
});
```

## Auth Middleware
- Support multiple auth strategies
- Use strategy registration mechanism
- Support flexible combinations (OR/AND)
- Follow fail-fast principle
- Example:
```typescript
export const createAuthMiddleware = () => ({
  before: async (request) => {
    const { security } = request.event.internal;
    for (const requirement of security) {
      const [strategyName, scopes] = Object.entries(requirement)[0];
      const strategy = getAuthStrategy(strategyName);
      const result = await strategy.verify(request.event);
      if (result.authorized) {
        setEventAuthorizer(request.event, strategyName, result);
        return;
      }
    }
    return new HttpResponses.Unauthorized().send();
  }
});
```

## Benefits
- Declarative configuration
- Type safety through schemas
- Automatic OpenAPI documentation
- Consistent error handling
- Easy to test and maintain

## Implementation Guidelines
1. Keep middleware pure and focused
2. Use dependency injection for services
3. Implement proper error boundaries
4. Support type inference
5. Document configuration options

Remember to:
- Follow OpenAPI specifications
- Keep configuration declarative
- Implement proper error handling
- Support i18n where needed
- Document middleware behavior

# HTTP Response Pattern Best Practices

## Response Design Principles
- Use immutable response objects with chain methods
- Implement standardized response formatting
- Support metadata for tracing and monitoring
- Validate response structure at runtime
- Follow AWS Lambda response format
- Provide type-safe response builders
- Use proper error handling with ErrorFactory
- Support cold start detection
- Include request context information

## Implementation Pattern
```typescript
// ✅ Good: Chain method pattern
return new Ok('Operation successful')
  .withEvent(event)
  .withContext(context)
  .withHeaders({ 'Cache-Control': 'max-age=3600' })
  .send({ data: result });

// ✅ Good: Error handling with factory
return ErrorFactory.createErrorResponse(error, event, context);

// ❌ Bad: Manual response construction
return {
  statusCode: 200,
  body: JSON.stringify({ data })
};
```

## Response Structure
- Base Response:
  * statusCode: HTTP status code
  * statusKey: Status identifier (class name)
  * message: Human-readable message
  * requestId: Unique request identifier
  * meta: Request context information
  * headers: Response headers (CORS, etc.)

- Success Response (2xx):
```typescript
{
  statusCode: 200,
  statusKey: "Ok",
  message: "Operation successful",
  requestId: string,
  meta: {
    functionName: string,
    functionVersion: string,
    memoryLimitInMB: string,
    awsRequestId: string,
    coldStart: boolean,
    remainingTime: number,
    startTime: number,
    endTime: number,
    duration: number
  },
  data: unknown
}
```

- Error Response (4xx/5xx):
```typescript
{
  statusCode: 400,
  statusKey: "BadRequest",
  message: "Validation failed",
  requestId: string,
  meta: {
    functionName: string,
    functionVersion: string,
    memoryLimitInMB: string,
    awsRequestId: string,
    coldStart: boolean,
    remainingTime: number,
    startTime: number,
    endTime: number,
    duration: number
  },
  error: {
    code: number,
    name: string,
    context: {
      stage: string,
      requestId: string,
      path: string,
      method: string,
      details?: unknown
    },
    stack?: string, // Only in development
    cause?: unknown
  }
}
```

## Best Practices
- Response Creation:
  * Use chain methods for configuration
  * Validate response before sending
  * Include relevant metadata
  * Handle errors consistently
  * Support cold start detection
  * Track request context
  * Provide proper error details

- Error Handling:
  * Use ErrorFactory for error responses
  * Include error context and details
  * Log errors with proper severity
  * Hide sensitive info in production
  * Provide clear error messages
  * Support multiple error types:
    - ZodError for validation
    - HttpError for HTTP errors
    - Generic Error for others

- Metadata Handling:
  * Include Lambda context info
  * Track cold starts
  * Measure execution time
  * Include request ID
  * Support custom headers
  * Track environment/stage

- Response Validation:
  * Use Zod for runtime validation
  * Define reusable schemas
  * Validate both success and error responses
  * Log validation failures
  * Maintain type safety

## Usage Examples
```typescript
// Success with data
return new Ok('User created')
  .withEvent(event)
  .withContext(context)
  .withHeaders({ 'X-Custom-Header': 'value' })
  .send({ data: user });

// Error with details
return new BadRequest('Invalid input')
  .withEvent(event)
  .withContext(context)
  .withHeaders({ 'X-Error-Type': 'ValidationError' })
  .send({ 
    error: { 
      details: validationErrors 
    } 
  });

// Error factory usage
try {
  // Your code
} catch (error) {
  return ErrorFactory.createErrorResponse(error, event, context);
}
```

## Testing Considerations
- Test response structure
- Validate metadata presence
- Check error handling
- Verify header management
- Test response validation
- Ensure type safety
- Test cold start detection
- Verify context information
- Test error factory scenarios
- Check development vs production behavior

Remember to:
- Always include proper error context
- Use appropriate status codes
- Include relevant headers
- Track request lifecycle
- Handle cold starts properly
- Validate response structure
- Follow security best practices

aws
eslint
golang
javascript
jest
jwt
less
next.js
+4 more

First seen in:

iamcxa/nx-unified-app

Used in 1 repository