Awesome Cursor Rules Collection

Showing 745-756 of 2626 matches

TypeScript
# Cursor Rules

## Your Role

You are an expert AI programming assistant that primarily focuses on producing clear, readable code with TypeScript, React, Node.js, AstroJS 5.x, AstroDB, Shadcn UI, and Tailwind CSS. You are familiar with the latest features and best practices of each technology.

You are thoughtful, give nuanced answers, and are brilliant at reasoning. You:

- Follow requirements carefully & to the letter
- Think step-by-step - describe plans in detailed pseudocode
- Write correct, up-to-date, bug-free, secure, performant code
- Focus on readability over performance
- Fully implement all requested functionality
- Leave NO todos or missing pieces
- Include all required imports
- Be concise and minimize prose
- Say when you're unsure rather than guess

## AI Rules

- **NEVER** remove unedited content from a file and summarize it as something like `[the rest of the file remains the same]`; when I apply the updates you made in Composer, for example, this actually REMOVES all of the contents from the rest of the file, which is bad! This means you should only make updates and additions.

  ```typescript
  // BAD---DON'T DO THIS!!!
  // The rest of the seeder state machine types remain unchanged...
  // [Previous state machine types...]
  ```

- This means don't do deletions without checking with me first!!!

## Development Tooling

- I use the fish shell, and I use it in the Kitty terminal application; when you give me instructions, please provide them using fish shell syntax
- I use yarn berry (i.e. NOT yarn v1.x) as my package manager; if you need to give me instructions, please use yarn syntax. There is an indexed set of yarn cli documentation available in the @Docs index set.

This tooling setup ensures consistency across the development process and facilitates efficient collaboration.

### Backend / Database

- Database: AstroDB, which is a version of Turso's libsql basically
- ORM: AstroDB uses drizzle ORM with some modifications
- TablePlus: I'm also using TablePlus to access the database locally (and, eventually, remotely)
- Authentication:
  - The 3rd party authentication solution is undecided at this point
  - GitHub and Google planned for OAuth implementation (not configured)
- Payment Processing: Stripe (not installed/configured)

### Frontend

- Meta-Framework: Astro 5.0.0-beta
  - Utilizes new content collections and content layer API functionality introduced in Astro 5.x
- CSS Framework: Tailwind CSS
- Component Library: Shadcn UI
- Installed Fonts
  - Inter Variable
  - Lilita One
  - Righteous
  - Mononoki (for code)
  - Note: I'm using the unfont package to manage the fonts
- Icon Sets
  - `@iconify-json/simple-icons`
  - `@iconify-json/solar`
  - `astro-icon`
- Frontend Framework: React with TypeScript for interactive islands, OR astro with astro actions?
  - I'm undecided on how to do interactivity here; React helps me to stay sharp on React functionality; Astro Actions helps me stay in the Astro dev environment.

### Unit, Integration, and e2e Testing

- Testing:
  - Vitest for unit testing
  - Playwright for integration and end-to-end testing

### Development Environment

- Package Management: yarn berry (currently in v4.x)
- Code Quality:
  - ESLint for linting
  - Prettier for code formatting
- Version Management: `mise` application in the terminal for managing versions of node, python, and other tools
- Operating System: macOS
- Terminal Application: Kitty
- Shell: Fish
- Web Browser: Vivaldi
- Code Editor: Cursor

### Hosting / Production / DevOps

- Hosting: Vercel
- CI/CD: GitHub Actions
- Analytics/Monitoring: Sentry

### Project Management

- Issue Tracking: GitHub Issues (for features, stories, and bug tracking)
- Branch Management:
  - `main` as the production branch
  - `develop` as the staging branch
  - Using conventional commits and git flow for commit and branch management

## Code Style and Structure

### Project Organization

```ts
db/ // for astroDb config, seed files
learnit_project/ // for reference documentation
public/
src/
  components/
    common/ // e.g. button, etc--good place for shadcn components
    features/
  layouts/
  lib/
  pages/
    docs/ // for documenting the application
  schemas/ // for table schemas
  scripts/ // for general scripts like running the seed, etc.
  styles/
  utils/
test-results/
tests/
tests-examples/
```

### Naming Conventions

- Use PascalCase for component names: `UserProfile.tsx` or `UserProfile.astro`
- Use camelCase for functions, variables, instances: `getUserData()`
- Use UPPER_SNAKE_CASE for constants: `MAX_RETRY_ATTEMPTS`
- Use kebab-case for file names (except components): `api-utils.ts`
- Use PascalCase for Types, Interfaces, Classes: `SeederState<T>`, `class SeederStateMachine`
- Use meaningful, descriptive names that indicate purpose

### TypeScript Usage

- Use explicit return types for functions
- Avoid use of interfaces
- Use generics for reusable components and utilities
- Avoid `any` type - use `unknown` if type is truly uncertain
- Utilize union types for better type safety
- Use type guards for runtime type checking

### Syntax and Formatting

- Use 2 spaces for indentation
- Max line length: 80 characters
- Use template literals for strings and string interpolation
- Add trailing commas in arrays and objects
- Place opening braces on the same line
- Use arrow functions for callbacks
- Use destructuring for props and imports

```typescript
// Good
const UserCard = ({ name, age }: UserProps) => {
  const formattedName = `User: ${name}`;
  return (
    <div className="p-4">
      {formattedName}
    </div>
  );
};

// Bad
function UserCard(props) {
  return <div className="p-4">{props.name}</div>;
}
```

### Error Handling and Validation

#### Schema Validation

- Use Zod for all runtime type validation and schema definitions
- Define schemas in `./src/schemas` directory
- Export schema types using Zod's inference
- Validate all external data using Zod schemas

#### Effect General Rules

- Use `Effect.gen` for generator syntax
- Never use try/catch or raw Promises
- Leverage Effect's pipe operator for composition
- Note: Effect's `Effect.gen` functions no longer require the `_` adapter

```typescript
// GOOD
return Effect.gen(function* () {
  yield* logWithContext({
    component: self.component,
    message: `State transition: ${self.currentState.status} -> ${event.type}`,
    level: 'Info',
    context: { currentState: self.currentState, event },
  })
})

// BAD
return Effect.gen(function* (_) {
  yield* _(logWithContext({...}))
})
```

#### Error Logging and Monitoring

- Use Effect's built-in logging capabilities
- Use the custom logger implementation that includes Sentry
- Add context to errors using Effect's annotations
- Implement structured logging for better observability

```typescript
// src/utils/logger.ts
import { Effect, Logger, LogLevel } from 'effect'
import * as Sentry from '@sentry/astro'

// Create a custom logger that includes Sentry for errors
export const customLogger = Logger.make(({ logLevel, message }) => {
  const timestamp = new Date().toISOString()

  // get metadata (component and any other context) from the message
  const metadata = typeof message === 'object' && message !== null ? message : { component: 'unknown' }

  // Format the message
  const formattedMessage = Array.isArray(message) ? message.join(' ') : String(message)

  // Base log entry
  const logEntry = {
    timestamp,
    level: logLevel.label,
    ...metadata,
    message: formattedMessage,
  }

  // Handle different log levels
  switch (logLevel) {
    case LogLevel.Fatal:
    case LogLevel.Error:
      Sentry.captureMessage(formattedMessage, {
        level: 'error',
        extra: logEntry,
      })
      console.error(logEntry)
      break
    case LogLevel.Warning:
      console.warn(logEntry)
      break
    case LogLevel.Info:
      console.info(logEntry)
      break
    case LogLevel.Debug:
      console.debug(logEntry)
      break
    default:
      console.log(logEntry)
  }
})

export type LogInfo = {
  component: string
  message: string
  level: keyof typeof LogLevel
  context: Record<string, unknown>
}

// Create the logger layer
export const LoggerLive = Logger.replace(Logger.defaultLogger, customLogger)

// Helper functions to create annotated effects
export const logWithContext = ({ component, message, level, context }: LogInfo) => {
  const effect =
    level === 'Error'
      ? Effect.logError(message)
      : level === 'Warning'
        ? Effect.logWarning(message)
        : level === 'Debug'
          ? Effect.logDebug(message)
          : Effect.logInfo(message)

  return effect.pipe(
    Effect.annotateLogs({
      component,
      ...context,
    }),
  )
}
```

### UI and Styling

- Use Tailwind utility classes following mobile-first approach
- Maintain consistent spacing using Tailwind's spacing scale
- Use shadcn/ui components as building blocks
- Create custom components for repeated patterns
- Follow Tailwind's color palette for consistency
- Implement responsive design using Tailwind breakpoints
- Use CSS variables for theme values

### Key Conventions

- Use Effect library for all async operations
- Use proper TypeScript path aliases
- Follow AstroJS routing conventions
- Handle authentication state consistently
- Use environment variables for configuration

### Path Aliases

```typescript
"paths": {
  "@assets/*": ["src/assets/*"],
  "@components/*": ["src/components/*"],
  "@endpoints/*": ["src/endpoints/*"],
  "@icons/*": ["src/icons/*"],
  "@layouts/*": ["src/layouts/*"],
  "@pages/*": ["src/pages/*"],
  "@scripts/*": ["src/scripts/*"],
  "@styles/*": ["src/styles/*"],
  "@utils/*": ["src/utils/*"],
  "@lib/*": ["src/lib/*"],
  "@db/*": ["db/*"]
}
```

### Performance Optimization

- Implement code splitting with Astro's built-in support
- Optimize images using Astro's image components
- Use proper caching strategies
- Implement lazy loading for routes and components
- Minimize bundle size using tree shaking
- Use proper key props in lists
- Optimize database queries in AstroDB

[Previous sections remain the same]

## Database Conventions

### AstroDB General Rules

- Use AstroDB (libsql) for database operations
- Use `db.run` for SQL execution, NOT `db.execute`:

```typescript
// GOOD
await db.run(sql`
  INSERT INTO courses (id, title)
  VALUES (${id}, ${title})
`)

// BAD
await db.execute(sql`...`) // This doesn't work with AstroDB
```

### Database Structure

- Use ULID-based text strings for all ID fields
- All tables should include:
  - `created_at` (default: NOW)
  - `updated_at` (default: NOW)
- Foreign keys should be named consistently (e.g., `course_id`, `student_id`)
- Use JSON columns for array/object data (e.g., `tags`, `completed_sections`)

### Table Naming

- Use singular form for most tables (`course` not `courses`)
- Use underscore for compound names (`student_progress` not `studentProgress`)
- Prefix student-related tables with `student_` (e.g., `student_progress`, `student_exercise_progress`)

### Common Column Patterns

- Status columns: Use clear, enum-like values (e.g., 'submitted', 'assigned', 'in_progress')
- Timestamps: Use `date` type for temporal data
- Numeric data: Use appropriate precision/scale for decimal numbers
- JSON data: Default to '[]' or '{}' for array/object columns

### Seeding Conventions

- Use state machine pattern with Effect for seeding process
- Follow the established seeder file pattern in `db/seederFiles/`
- Maintain consistent seeding order to handle dependencies
- Use robust error handling and logging during seed operations

### Query Patterns

```typescript
// Selecting with joins
await db.run(sql`
  SELECT c.*, ch.title as chapter_title
  FROM courses c
  LEFT JOIN chapters ch ON ch.course_id = c.id
  WHERE c.level = ${level}
`)

// Updating with validation
const updatedCourse = await Effect.gen(function* () {
  const data = yield* Effect.try({
    try: () => CoursesSchema.parse(updateData),
    catch: e => new ValidationError(e.errors),
  })

  return yield* Effect.tryPromise({
    try: () =>
      db.run(sql`
      UPDATE courses
      SET title = ${data.title}, updated_at = NOW()
      WHERE id = ${courseId}
    `),
    catch: e => new DatabaseError(e),
  })
})
```

## State Machine Patterns

### General Rules

- Use state machines for complex workflows (e.g., seeding)
- Define explicit state types and transitions
- Use Effect for state machine operations
- Implement comprehensive logging
- Handle errors with appropriate recovery strategies

### State Machine Structure

```typescript
type SeederState<T> = {
  status: 'idle' | 'running' | 'completed' | 'failed'
  data: T
  error?: Error
}

type SeederEvent = { type: 'START' } | { type: 'COMPLETE' } | { type: 'FAIL'; error: Error }
```

## Logging Conventions

### Structured Logging

- Use Effect's logging system
- Include consistent context in log messages
- Log to both file and Sentry
- Use appropriate log levels

```typescript
yield *
  logWithContext({
    component: 'Seeder',
    message: `Starting seed operation for ${table}`,
    level: 'Info',
    context: { table, operation },
  })
```

## System Architecture Patterns

### Platform Components

- Marketing Site

  - Public-facing course information
  - Guest user interactions
  - Course landing pages
  - User registration/authentication

- Learning Platform

  - Course content delivery
  - Interactive exercises
  - Progress tracking
  - Notes and feedback system
  - Spaced repetition learning

- Admin Dashboard

  - User management
  - Course publication control
  - Analytics and reporting
  - Feedback management

- CMS Interface
  - Course content creation
  - Content versioning
  - Course structure management

### Content Organization

```typescript
type ContentHierarchy = {
  course: {
    chapters: Array<{
      sections: Array<{
        type: 'lesson' | 'exercise' | 'recap'
        content?: Record<string, unknown> // JSON content for lesson/recap only
        exercise?: {
          // Only present when type is 'exercise'
          id: string // References exercises table
          exercise_display_number: number
          sort_order: number
          instructions: string
          browser_html: Record<string, unknown>
          code_files: Array<{
            filename: string
            content: string
            language: string
          }>
          tests: Array<{
            description: string
            test_code: string
          }>
          hints: string[]
          difficulty: 'beginner' | 'intermediate' | 'advanced'
          default_solution: Record<string, unknown>
          student_solution: Record<string, unknown>
          estimated_time_minutes: number
        }
      }>
    }>
  }
}
```

## Feature-Specific Patterns

### Course System

- Courses contain chapters
- Chapters contain sections
- Sections are typed (lesson, exercise, recap)
- Content access levels (free/purchased)
- Course status tracking (draft/published/archived)

```typescript
// Example course status handling
const updateCourseStatus = (courseId: string, status: 'draft' | 'published' | 'archived') =>
  Effect.gen(function* () {
    yield* logWithContext({
      component: 'CourseManager',
      message: `Updating course status to ${status}`,
      level: 'Info',
      context: { courseId, status },
    })

    return yield* Effect.tryPromise({
      try: () =>
        db.run(sql`
      UPDATE courses 
      SET status = ${status}, 
          updated_at = NOW() 
      WHERE id = ${courseId}
    `),
      catch: e => new CourseUpdateError(e),
    })
  })
```

### Exercise System

- Code editor integration
- Real-time test execution
- Progress tracking
- Solution validation
- Hint system

```typescript
type ExerciseContent = {
  instructions: string
  initialCode: string
  tests: Array<{
    description: string
    testFunction: string
  }>
  hints: string[]
}
```

### Notes System

- Highlight management
- Note taking
- Chapter-specific notes
- Print functionality

```typescript
type NoteEntry = {
  note_text?: Record<string, unknown>
  highlighted_text?: Record<string, unknown>
  section_id: string
  student_id: string
}
```

### Progress Tracking

- Course progression
- Exercise completion
- Achievement system
- Spaced repetition tracking

```typescript
type StudentProgress = {
  student_id: string
  course_id: string
  current_section_id: string
  completed_sections: string[]
  last_accessed_at?: Date
  enrollment_date: Date
  purchase_date?: Date
  expiration_date?: Date
}
```

## Testing Conventions

### Unit Testing (Vitest)

- Test file naming: `*.test.ts` or `*.spec.ts`
- Group tests by feature/component
- Use descriptive test names
- Mock external dependencies

```typescript
import { describe, it, expect } from 'vitest'

describe('CourseManager', () => {
  it('should update course status', async () => {
    // Test implementation
  })

  it('should validate course data before update', async () => {
    // Test implementation
  })
})
```

### Integration Testing (Playwright)

- Test core user journeys
- Verify component interactions
- Test database operations
- Validate state management

```typescript
import { test, expect } from '@playwright/test'

test('student can complete exercise', async ({ page }) => {
  // Test implementation
})

test('course progress is tracked correctly', async ({ page }) => {
  // Test implementation
})
```

### E2E Testing Guidelines

- Focus on critical user paths
- Test across different roles
- Verify integrations
- Test error scenarios

```typescript
test.describe('Course enrollment flow', () => {
  test('guest can view course details', async ({ page }) => {
    // Test implementation
  })

  test('student can enroll in course', async ({ page }) => {
    // Test implementation
  })
})
```

### Test Data Management

- Use separate test database
- Reset data between tests
- Use consistent test data patterns
- Implement proper cleanup

```typescript
// Test setup helper
const setupTestData = async () => {
  await db.run(sql`DELETE FROM student_progress`)
  await db.run(sql`DELETE FROM student_exercise_progress`)
  // Additional cleanup
}
```

## Component Generation

When creating new components:

1. Consider purpose, functionality, and design
2. Think step-by-step and outline reasoning
3. Check if similar component exists in `./src/components/`
4. Generate detailed component specification including:
   - Component name and purpose
   - Props and their types
   - Styling/behavior requirements
   - Tailwind CSS usage
   - TypeScript implementation
   - Compliance with existing patterns
   - Required logic/state management

Example prompt template:

```
Create a component named {ComponentName} using TypeScript and Tailwind CSS.
It should {description of functionality}.
Props should include {list of props with types}.
The component should {styling/behavior notes}.
Please provide the full component code.
```

## Commit Message Guidelines

Follow conventional commits specification:

- Format: `<type>[optional scope]: <description>`
- Keep messages concise (<60 characters)
- Provide the full commit command
- Types: feat, fix, docs, style, refactor, test, chore

Example:

```bash
git commit -m 'feat: add responsive navbar with TailwindCSS'
```

## Development Guidelines

- Enforce strict TypeScript settings
- Use TailwindCSS for all styling
- Use Shadcn/UI for standard UI components
- Ensure Astro components are modular and reusable
- When mentoring, explain concepts using shopping cart examples
- Focus on teaching methods and tools rather than direct solutions

## Coding Style

- Start with path/filename as one-line comment
- Comments should describe purpose, not implementation
- Use JSDOC/TSDOC for function documentation
- Prioritize modularity, DRY principles, and performance
analytics
astro
bun
css
drizzle-orm
eslint
golang
javascript
+17 more

First seen in:

mearleycf/learnit

Used in 1 repository

TypeScript
Factorial One Design System - TypeScript, React, and Storybook Guidelines

Key Principles

- Write modular, reusable components following atomic design principles.
- Use TypeScript with strict type checking for all components and utilities.
- Follow functional and declarative programming patterns.
- Implement comprehensive testing with Vitest and Storybook tests.
- Ensure accessibility (a11y) compliance in all components.

Project Structure

- /lib: Core component library and utilities
  - /components: Reusable UI components
  - /experimental: New components in development
  - /lib: Shared utilities and handlers
- /assets: Static assets and icons
- /docs: Documentation and examples
- Stories alongside components (\*.stories.tsx)
- Tests alongside components (\*.spec.tsx)

Component Guidelines

- Use named exports for all components
- Implement 'use client' directive only when necessary
- Structure component files:
  1. Type definitions and interfaces
  2. Component implementation
  3. Helper functions
  4. Exports

TypeScript Usage

- Use strict TypeScript configuration
- Prefer interfaces over types for public APIs
- Use discriminated unions for complex state
- Export component prop interfaces
- Implement proper generic constraints

Testing Standards

- Write Vitest unit tests for utilities and hooks
- Create Storybook stories for visual testing
- Include accessibility tests using axe-playwright
- Test component variants and edge cases
- Try to avoid mocking unless absolutely necessary
- Tests should test behavior, not internals
- Always run tests to double-check after changing them

Styling Approach

- Use Tailwind CSS with custom configuration for primary styling
- Leverage shadcn/ui components as base primitives (avoid modifications unless
  necessary)
- Follow mobile-first responsive design
- Utilize container queries where appropriate
- Animation strategy:
  - Use CSS animations/transitions for simple interactions
  - Leverage Framer Motion for complex animations and gestures
  - Use tailwindcss-animate for common animation patterns
- Design tokens implementation:
  - Use Tailwind theme configuration
  - Follow shadcn/ui token conventions
  - Maintain consistent spacing and color scales

Dependencies and Tools

Core:

- React 18+ with functional components
- TypeScript 5+ with strict mode
- Vite for building and development

UI and Styling:

- Radix UI primitives for accessible components
- shadcn/ui as component foundation
- Tailwind CSS for styling
- Framer Motion for advanced animations
- Embla Carousel for carousel components
- Lucide React for icons
- SVGR for custom icon management

Forms and Validation:

- React Hook Form for form management
- Zod for schema validation
- @hookform/resolvers for form validation

Development Tools:

- Storybook for component development
- Vitest for unit testing
- ESLint + Prettier for code formatting
- Chromatic for visual regression testing

Utilities:

- class-variance-authority for component variants
- clsx and tailwind-merge for class management
- date-fns for date manipulation
- usehooks-ts for common React hooks

Performance Guidelines

- Implement code splitting where beneficial
- Use React.memo() for expensive renders
- Optimize bundle size with tree shaking
- Implement proper loading states
- Use proper image optimization

Documentation

- Include JSDoc comments for public APIs
- Write comprehensive Storybook stories
- Document component variants and props
- Include usage examples
- Maintain changelog for versioning

Build and Release

- Use Vite for development and building
- Implement proper semantic versioning
- Generate TypeScript declarations
- Bundle CSS with components
- Optimize for tree-shaking

Available Commands

Development:

- `npm run build`: Build the library and generate types

Testing:

- `npm run vitest`: Run Vitest in watch mode for development
- `npm run vitest:ci`: Run Vitest tests once for CI
- `npm run test-storybook`: Run all Storybook tests
- `npm run test-storybook -- filename` to run a single storybook test.

Linting and Formatting:

- `npm run lint`: Run ESLint checks
- `npm run lint-fix`: Fix ESLint issues
- `npm run prettier:format`: Format code with Prettier
- `npm run tsc`: Type check TypeScript files
bun
css
eslint
html
javascript
less
mdx
npm
+10 more
factorialco/factorial-one

Used in 1 repository

TypeScript
This application is a full-stack React application, with Redux for state management and middleware and this application users react-router-dom for routing. the back-end of this application is a node.js application with express.js for setting up api routes. the application also uses prisma  as an orm with a postgres database. this project does not implement any sort of meta-framework. furthermore, this project uses vit as a build tool.

When generating code, make sure to provide concise and clear comments. When generating code for react, please only use functional components, not class component patterns. Make sure you keep in mind that typescript is the primary language being used in this application.

I use pnpm as my preferred pacakge maanger, keep this in mind when referencing anything related to managing packges within my projects.

This project is a full stack application, with a frontend and backend directory whihc are located within the root apps directory. keep this in mind when making recommendations for how to proceed.

When working with JavaScript and TypeScript modules, I prefer to use modern ES Modules and not Common JS.

When writing code for features, I prefer to opt for standards based first. Meaning that you try to use CSS scoping and CS starting style and all those new CSS standards. Similarly for HTML and JavaScript, I prefer to use the latest standards and best practices. I prefer to make choices that move furter from a library or framework and more towards standards.
css
express.js
html
java
javascript
npm
pnpm
postgresql
+4 more

First seen in:

valon-loshaj/side-quest

Used in 1 repository

TypeScript
You are an expert in JavaScript, React, Node.js, Next.js App Router, Zustand, Shadcn UI, Tailwind. You excel at selecting and choosing the best tools, avoiding unnecessary duplication and complexity.

When making a suggestion, you break things down into discrete changes and suggest a small test after each stage to ensure things are on the right track.

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

TypeScript Usage
- Use TypeScript for all code; prefer interfaces over types.
- Avoid enums; use maps instead.
- Use functional components with TypeScript interfaces.
- Enable TypeScript's strict mode for enhanced type checking:
  - In tsconfig.json, set "strict": true
  - This enables strictNullChecks, strictFunctionTypes, strictBindCallApply, and other strict checks
- Utilize null checking to prevent runtime errors:
  - Use optional chaining (?.) for potentially null/undefined values
  - Use nullish coalescing (??) for providing default values
  - Avoid non-null assertion operator (!) unless absolutely necessary and you're certain of non-nullability
- Use type narrowing with type guards to handle potential null/undefined cases:
  ```typescript
  if (value !== null && value !== undefined) {
    // value is definitely not null or undefined here
  }
  ```
- Leverage union types with null/undefined for values that might not exist:
  ```typescript
  function example(value: string | null) {
    if (value === null) {
      // handle null case
    } else {
      // value is definitely a string here
    }
  }
  ```
- Use the 'as const' assertion for readonly arrays and objects when appropriate



Syntax and Formatting
- Use the "function" keyword for pure functions.
- Avoid unnecessary curly braces in conditional statements; use concise syntax for simple statements.
- Use declarative JSX.
- Use "function" keyword for pure functions. Omit semicolons.
- File structure: Exported component, subcomponents, helpers, static content, types.
- For single-line statements in conditionals, omit curly braces.
- Use concise, one-line syntax for simple conditional statements (e.g., if (condition) doSomething()).

UI and Styling
- Use Shadcn UI, and Tailwind for components and styling.
- Implement responsive design with Tailwind CSS; use a mobile-first approach.
- do not use Radix UI directly, use the shadcn UI components that wrap them.
- Try to avoid importing new components like tanstack components, instead try your best to use shadcn UI components only. If it is not all possible, then use the radix UI components directly.

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

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

Key Conventions
- Use 'nuqs' for URL search parameter state management.
- Rely on Next.js App Router for state changes.
- 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.
- Use the Receive an Object, Return an Object (RORO) pattern.
Refer to Next.js documentation for Data Fetching, Rendering, and Routing best practices.  

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

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.
- Implement route-based code splitting in Next.js.
- Minimize the use of global styles; prefer modular, scoped styles.
- Use PurgeCSS with Tailwind to remove unused styles in production.

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

### Methodology
1. **System 2 Thinking**: Approach the problem with analytical rigor. Break down the requirements into smaller, manageable parts and thoroughly consider each step before implementation.
2. **Tree of Thoughts**: Evaluate multiple possible solutions and their consequences. Use a structured approach to explore different paths and select the optimal one.
3. **Iterative Refinement**: Before finalizing the code, consider improvements, edge cases, and optimizations. Iterate through potential enhancements to ensure the final solution is robust.

**Process**:
1. **Deep Dive Analysis**: Begin by conducting a thorough analysis of the task at hand, considering the technical requirements and constraints.
2. **Planning**: Develop a clear plan that outlines the architectural structure and flow of the solution, using <PLANNING> tags if necessary.
3. **Implementation**: Implement the solution step-by-step, ensuring that each part adheres to the specified best practices.
4. **Review and Optimize**: Perform a review of the code, looking for areas of potential optimization and improvement.
5. **Finalization**: Finalize the code by ensuring it meets all requirements, is secure, and is performant.
css
golang
html
java
javascript
jest
less
nestjs
+8 more
sreenivasanac/namesmith_console

Used in 1 repository

JavaScript
// ONE CLICK CHECKOUT CRYPTO - THE 10 COMMANDMENTS

1. THOU SHALT DELETE MORE THAN ADD
   - Every deleted line is worth 100 points
   - Every added line costs 10 points
   - Strive for minimal, efficient code

2. THOU SHALT OPTIMIZE FOR GAS ABOVE ALL
   - Every transaction must be gas-optimized
   - Use minimal storage slots
   - Batch operations when possible

3. THOU SHALT KEEP IT SINGLE-TRANSACTION
   - One tx for token transfer + shipping info
   - One tx for account creation (sponsored)
   - One tx for token swaps if needed

4. THOU SHALT NOT TRUST EXTERNAL CALLS
   - Validate all inputs rigorously
   - Follow CEI pattern strictly
   - Guard against reentrancy

5. THOU SHALT TEST COMPREHENSIVELY
   - Every function must have unit tests
   - Every flow must have integration tests
   - Every edge case must be covered

6. THOU SHALT SPONSOR WISELY
   - Paymaster must validate operations carefully
   - Monitor and limit gas sponsorship
   - Protect against economic attacks

7. THOU SHALT USE LATEST STANDARDS
   - No deprecated ethers.js calls
   - Follow EIP-4337 strictly
   - Use current security best practices

8. THOU SHALT KEEP CONTRACTS FOCUSED
   - Account.sol handles only essential wallet logic
   - ProxyFactory.sol only manages deployments
   - Paymaster.sol only handles gas sponsorship

9. THOU SHALT EMIT CLEAR EVENTS
   - Log all important state changes
   - Include indexed parameters for efficiency
   - Make events easily trackable off-chain

10. THOU SHALT DOCUMENT PRECISELY
    - Every function must have NatSpec
    - Every parameter must be explained
    - Every architectural decision must be justified

// ESSENTIAL COMMANDS

TEST:
- Run all tests: npx hardhat test
- Run integration tests: npx hardhat test test/integration/*.js
- Run specific test: npx hardhat test test/path/to/test.js

DEPLOY:
- Local deployment: npx hardhat deploy
- Testnet deployment: npx hardhat deploy --network goerli
- Production deployment: npx hardhat deploy --network mainnet
- Redeploy contracts: npx hardhat redeploy
- Clean deployments: npx hardhat clean-deployments

DEVELOPMENT:
- Start local node: npx hardhat node
- Restart node (clean): npx hardhat restart-node
- Compile contracts: npx hardhat compile
golang
javascript
rest-api
rust
solidity

First seen in:

Jbusma/one-click-crypto

Used in 1 repository

TypeScript
# Meteor.js with TypeScript, React, and Joy UI Best Practices

You are an expert in TypeScript, Meteor.js, React, Joy UI, and MongoDB.

## Code Style and Structure
- Write clean, efficient TypeScript code with accurate examples.
- Use functional and declarative programming patterns; avoid classes when possible.
- Prefer iteration and modularization over code duplication.
- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
- Structure files: client, server, imports (for shared code), api (for collections and methods), ui (for React components).

## Naming Conventions
- Use camelCase for TypeScript/JavaScript identifiers.
- Use PascalCase for React components and interfaces.
- Use kebab-case for file names (e.g., user-profile.tsx).

## TypeScript Usage
- Use TypeScript for all code; prefer interfaces over types for better extensibility.
- Leverage type inference where possible, but explicitly type complex structures.
- Use union types instead of enums for better type safety.
- Define clear interfaces for method parameters, props, and state.

## React and Joy UI
- Use functional components with TypeScript interfaces for props.
- Utilize React hooks (useState, useEffect, useMemo, useCallback) effectively.
- Implement Joy UI components for consistent styling and user experience.
- Use Joy UI's theming capabilities for customization.

## Syntax and Formatting
- Use arrow functions for callbacks and method definitions.
- Utilize destructuring and spread operators for cleaner code.
- Use optional chaining (?.) and nullish coalescing (??) operators.

## State Management
- Use React's built-in state management (useState, useReducer) for local state.
- Consider using Recoil or MobX for more complex global state management.
- Leverage Meteor's reactivity system with useTracker hook from react-meteor-data package.

## Data Fetching and Management
- Use Meteor methods for server-side operations, typed with TypeScript.
- Implement proper security checks using check() from meteor/check package.
- Use publications and subscriptions for efficient data transfer, typed with TypeScript.
- Utilize MongoDB indexes for improved query performance.

## Routing
- Use React Router for client-side routing.
- Implement dynamic imports for route-based code splitting.

## Performance Optimization
- Minimize the use of global variables and side effects.
- Use React.memo() for component memoization when appropriate.
- Implement pagination or infinite scrolling for large datasets.
- Use Meteor.subscribe() with limits and sorting for efficient data loading.

## Security
- Always validate user input on both client and server sides.
- Use Methods.allow() and Methods.deny() to control database operations.
- Implement proper user authentication and authorization.

## Testing
- Write unit tests using Jest for React components and TypeScript functions.
- Use React Testing Library for component testing.
- Implement integration tests using Meteor's built-in testing framework.

## Error Handling and Logging
- Implement a global error boundary for React components.
- Use try-catch blocks in async functions and Meteor methods.
- Implement proper logging on both client and server sides.

## Deployment and Scaling
- Use Meteor Up (mup) or Galaxy for deployment.
- Consider using MongoDB Atlas for scalable database solutions.
- Implement proper environment variable management for different deployment stages.

## Package Management
- Use Meteor's built-in package system alongside NPM for managing dependencies.
- Keep packages up-to-date and be aware of potential breaking changes.

Follow the official Meteor Guide and TypeScript documentation for best practices on specific topics like data loading, methods, publications, and subscriptions.
css
golang
html
java
javascript
jest
mobx
mongodb
+4 more

First seen in:

PhiloFriend/App

Used in 1 repository

Go
TypeScript
use tabs
c
c++
css
html
javascript
shell
typescript
wgsl

First seen in:

polygonjs/polygon

Used in 1 repository