Awesome Cursor Rules Collection

Showing 961-972 of 1033 matches

TypeScript
name: Next.js AI Chat Application Rules

# Main Rules
main:
  - Fix all linting errors before running build tests or committing
  - Fix all typescript errors before running build tests or committing
  - Prioritize to build for mobile first, desktop second
  - Check to see if there is a components folder first before creating or installing new ones.
  - Use "npx shadcn@latest add" to install new components

# OpenAI Rules
documentation:
  - Refer to the OpenAI API documentation when writing new code

# Code Changing Rules
code_changing:
  - Run build tests before pushing to github
  - Check for errors before submitting to user
  - Verify all code is written with best practices

# File Organization Rules
file_organization:
  components:
    - path: components/
      rules:
        - All reusable UI components go in components/ui/
        - Feature-specific components go in components/ root
        - Use PascalCase for component file names
        - Each component should have its own file
        - Group related components in subdirectories

  pages:
    - path: app/
      rules:
        - Follow Next.js 13+ app directory structure
        - Use lowercase for route folders
        - Place layouts in layout.tsx files
        - Place pages in page.tsx files
        - Keep page components focused on layout and composition

  styles:
    - path: app/globals.css
      rules:
        - Use Tailwind CSS utilities when possible
        - Custom CSS only for complex animations or overrides
        - Maintain consistent color scheme using CSS variables
        - Follow mobile-first responsive design

# Code Style Rules
code_style:
  typescript:
    - Use strict TypeScript with explicit types
    - Prefer interfaces over type aliases for objects
    - Use type inference when types are obvious
    - Export types and interfaces that are used across files

  components:
    - Use function components with arrow function syntax
    - Add display names to forwardRef components
    - Use composition over inheritance
    - Keep components focused and single-responsibility
    - Extract complex logic into custom hooks

  naming:
    - Use PascalCase for components and interfaces
    - Use camelCase for functions and variables
    - Use UPPER_CASE for constants
    - Use descriptive names that indicate purpose

# Development Workflow
development:
  commits:
    - Write clear commit messages with prefixes:
      - feat: New features
      - fix: Bug fixes
      - refactor: Code improvements
      - style: Formatting changes
      - docs: Documentation updates
      - test: Test updates

  branches:
    - main: Production-ready code
    - develop: Integration branch
    - feature/*: New features
    - fix/*: Bug fixes
    - release/*: Release preparation

# Testing Rules
testing:
  unit:
    - Test all utility functions
    - Test custom hooks
    - Test component logic
    - Use React Testing Library
    - Focus on user behavior over implementation

  integration:
    - Test key user flows
    - Test API integrations
    - Test state management
    - Test routing behavior

# Performance Rules
performance:
  optimization:
    - Use Next.js Image component for images
    - Implement code splitting
    - Lazy load non-critical components
    - Optimize bundle size
    - Monitor Core Web Vitals

  state:
    - Use local state for UI-only state
    - Use context for shared state
    - Avoid prop drilling
    - Memoize expensive calculations

# Accessibility Rules
accessibility:
  requirements:
    - Follow WCAG 2.1 guidelines
    - Use semantic HTML
    - Implement keyboard navigation
    - Provide ARIA labels
    - Maintain sufficient color contrast
    - Support screen readers

# Mobile Responsiveness
mobile:
  requirements:
    - Design mobile-first
    - Test on multiple devices
    - Use responsive Tailwind classes
    - Implement touch-friendly interactions
    - Ensure readable font sizes

# Dependencies
dependencies:
  management:
    - Keep dependencies updated
    - Audit security regularly
    - Remove unused dependencies
    - Use exact versions in package.json
    - Document major dependency changes

# Documentation
documentation:
  requirements:
    - Maintain README.md
    - Document component props
    - Document custom hooks
    - Document API integrations
    - Include setup instructions
    - Document environment variables

# Error Handling
error_handling:
  requirements:
    - Implement error boundaries
    - Handle API errors gracefully
    - Provide user-friendly error messages
    - Log errors appropriately
    - Implement fallback UI

# Security
security:
  requirements:
    - Validate user input
    - Implement CSRF protection
    - Use secure authentication
    - Follow security best practices
    - Regular security audits 
bun
css
golang
javascript
next.js
openai
react
shadcn/ui
+2 more

First seen in:

while-basic/v0-chatbot

Used in 1 repository

Svelte
You are an expert in Svelte 5, SvelteKit, TypeScript, and modern web development.

Key Principles

- Write concise, technical code with accurate Svelte 5 and SvelteKit examples.
- Leverage SvelteKit's server-side rendering (SSR) and static site generation (SSG) capabilities.
- Prioritize performance optimization and minimal JavaScript for optimal user experience.
- Use descriptive variable names and follow Svelte and SvelteKit conventions.
- Organize files using SvelteKit's file-based routing system.

Code Style and Structure

- Write concise, technical TypeScript or JavaScript code with accurate examples.
- Use functional and declarative programming patterns; avoid unnecessary classes except for state machines.
- Prefer iteration and modularization over code duplication.
- Structure files: component logic, markup, styles, helpers, types.
- Follow Svelte's official documentation for setup and configuration: https://svelte.dev/docs

Naming Conventions

- Use lowercase with hyphens for component files (e.g., `components/auth-form.svelte`).
- Use PascalCase for component names in imports and usage.
- Use camelCase for variables, functions, and props.

TypeScript Usage

- Use TypeScript for all code; prefer interfaces over types.
- Avoid enums; use const objects instead.
- Use functional components with TypeScript interfaces for props.
- Enable strict mode in TypeScript for better type safety.

Svelte Runes

- `$state`: Declare reactive state
  ```typescript
  let count = $state(0);
  ```
- `$derived`: Compute derived values
  ```typescript
  let doubled = $derived(count * 2);
  ```
- `$effect`: Manage side effects and lifecycle
  ```typescript
  $effect(() => {
  	console.log(`Count is now ${count}`);
  });
  ```
- `$props`: Declare component props
  ```typescript
  let { optionalProp = 42, requiredProp } = $props();
  ```
- `$bindable`: Create two-way bindable props
  ```typescript
  let { bindableProp = $bindable() } = $props();
  ```
- `$inspect`: Debug reactive state (development only)
  ```typescript
  $inspect(count);
  ```
- Don't import $state from 'svelte'
  No need to import $state from 'svelte'. Just use it as:
  ```typescript
  let count = $state(0);
  ```

Don't use `export let` in runes mode

- In runes mode, `export let` cannot be used
- Instead, use `$props()`

User Authenticaion

- Use Supabase Auth for User Authenticaion. Refer to https://supabase.com/docs/guides/auth
- Use Supabase JavaScript Client Library: https://supabase.com/docs/reference/javascript/introduction

Forms and components

- Use flowbite-svelte for form components. Refer to https://flowbite-svelte.com
- Use SvelteKit's form actions for server-side form handling.
- Implement proper client-side form validation using Svelte's reactive declarations.
- Use progressive enhancement via use:enhance for JavaScript-optional form submissions.

Database and Authentication

- Use Supabase for database and Authentication operations. Refer to https://supabase.com/docs
- Use Postgres for the database. Refer to https://supabase.com/docs/guides/database/overview
- Use Postgres PostGIS for the database. Refer to https://supabase.com/docs/guides/database/overview

Edge Functions

- Use Supabase Edge Functions. Refer to https://supabase.com/docs/guides/functions

UI and Styling

- Use Tailwind CSS for utility-first styling approach.
- Leverage flowbite-svelte components for pre-built, customizable UI elements.
- Use Svelte's built-in transition and animation features.

SvelteKit Project Structure

- Use the recommended SvelteKit project structure:
  ```
  - src/
    - lib/
    - routes/
    - app.html
  - static/
  - svelte.config.js
  - vite.config.js
  ```

Component Development

- Create .svelte files for Svelte components.
- Use .svelte.ts files for component logic and state machines.
- Implement proper component composition and reusability.
- Use Svelte's props for data passing.
- Leverage Svelte's reactive declarations for local state management.

State Management

- Use classes for complex state management (state machines):

  ```typescript
  // counter.svelte.ts
  class Counter {
  	count = $state(0);
  	incrementor = $state(1);

  	increment() {
  		this.count += this.incrementor;
  	}

  	resetCount() {
  		this.count = 0;
  	}

  	resetIncrementor() {
  		this.incrementor = 1;
  	}
  }

  export const counter = new Counter();
  ```

- Use in components:

  ```svelte
  <script lang="ts">
  	import { counter } from './counter.svelte.ts';
  </script>

  <button onclick={() => counter.increment()}>
  	Count: {counter.count}
  </button>
  ```

Component Props

- `export let` cannot be used in runes mode. Instead, use `$props()`

- App.svelte (Example)

  ```svelte
  <script lang="ts">
  	import MyComponent from './MyComponent.svelte';
  </script>

  <MyComponent adjective="cool" />
  ```

- MyComponent.svelte

  ```svelte
  <script lang="ts">
  	let { adjective } = $props();
  </script>

  <p>this component is {adjective}</p>
  ```

- Fallback values

  ```svelte
  let {(adjective = 'happy')} = $props();
  ```

- Renaming props

  ```svelte
  let { super: trouper = 'lights are gonna find me' } = $props();
  ```

- Updating props

  - Parent.svelte

    ```svelte
    <script lang="ts">
    	import Child from './Child.svelte';

    	let count = $state(0);
    </script>

    <button onclick={() => (count += 1)}>
    	clicks (parent): {count}
    </button>

    <Child {count} />
    ```

  - Child.svelte

    ```svelte
    <script lang="ts">
    	let { count } = $props();
    </script>

    <button onclick={() => (count += 1)}>
    	clicks (child): {count}
    </button>
    ```

Snippet

- Use snippets for concise, reusable markup inside components.
- Reference: https://svelte.dev/docs/svelte/snippet

- Example

  ```svelte
  {#snippet figure(image)}
  	<figure>
  		<img src={image.src} alt={image.caption} width={image.width} height={image.height} />
  		<figcaption>{image.caption}</figcaption>
  	</figure>
  {/snippet}

  {#each images as image}
  	{#if image.href}
  		<a href={image.href}>
  			{@render figure(image)}
  		</a>
  	{:else}
  		{@render figure(image)}
  	{/if}
  {/each}
  ```

- Snippets can reference themselves and each other

```svelte
{#snippet blastoff()}
	<span>🚀</span>
{/snippet}

{#snippet countdown(n)}
	{#if n > 0}
		<span>{n}...</span>
		{@render countdown(n - 1)}
	{:else}
		{@render blastoff()}
	{/if}
{/snippet}

{@render countdown(10)}
```

- Snippets are just values, they can be passed to components as props

  ```svelte
  <script>
  	import Table from './Table.svelte';

  	const fruits = [
  		{ name: 'apples', qty: 5, price: 2 },
  		{ name: 'bananas', qty: 10, price: 1 },
  		{ name: 'cherries', qty: 20, price: 0.5 },
  	];
  </script>

  {#snippet header()}
  	<th>fruit</th>
  	<th>qty</th>
  	<th>price</th>
  	<th>total</th>
  {/snippet}

  {#snippet row(d)}
  	<td>{d.name}</td>
  	<td>{d.qty}</td>
  	<td>{d.price}</td>
  	<td>{d.qty * d.price}</td>
  {/snippet}

  <Table data={fruits} {header} {row} />
  ```

  - As convenience, snippets declared directly inside a component implicitly become props on the component

    ```svelte
    <!-- this is semantically the same as the above -->
    <Table data={fruits}>
    	{#snippet header()}
    		<th>fruit</th>
    		<th>qty</th>
    		<th>price</th>
    		<th>total</th>
    	{/snippet}

    	{#snippet row(d)}
    		<td>{d.name}</td>
    		<td>{d.qty}</td>
    		<td>{d.price}</td>
    		<td>{d.qty * d.price}</td>
    	{/snippet}
    </Table>
    ```

- Any content inside the component tags that is not a snippet declaration implicitly becomes part of the children snippet

  ```svelte
  <Button>click me</Button>
  ```

  ```svelte
  <!-- Button svelte -->
  <script lang="ts">
  	let { children } = $props();
  </script>

  <!-- result will be <button>click me</button> -->
  <button>{@render children()}</button>
  ```

- Typing snippets: Snippets implement the Snippet interface imported from 'svelte'

  ```svelte
  <script lang="ts">
  	import type { Snippet } from 'svelte';

  	interface Props {
  		data: any[];
  		children: Snippet;
  		row: Snippet<[any]>;
  	}

  	let { data, children, row }: Props = $props();
  </script>
  ```

  - We can tighten things up further by declaring a generic, so that data and row refer to the same type:

    ```svelte
    <script lang="ts" generics="T">
    	import type { Snippet } from 'svelte';

    	let {
    		data,
    		children,
    		row,
    	}: {
    		data: T[];
    		children: Snippet;
    		row: Snippet<[T]>;
    	} = $props();
    </script>
    ```

- Exporting snippets: Snippets declared at the top level of a .svelte file can be exported from a `<script module>` for use in other components (This requires Svelte 5.5.0 or newer)

  ```svelte
  <script module>
  	export { add };
  </script>

  {#snippet add(a, b)}
  	{a} + {b} = {a + b}
  {/snippet}
  ```

Routing and Pages

- Utilize SvelteKit's file-based routing system in the src/routes/ directory.
- Implement dynamic routes using [slug] syntax.
- Use load functions for server-side data fetching and pre-rendering.
- Implement proper error handling with +error.svelte pages.

Server-Side Rendering (SSR) and Static Site Generation (SSG)

- Leverage SvelteKit's SSR capabilities for dynamic content.
- Implement SSG for static pages using prerender option.
- Use the adapter-auto for automatic deployment configuration.

Performance Optimization

- Leverage Svelte's compile-time optimizations.
- Use `{#key}` blocks to force re-rendering of components when needed.
- Implement code splitting using dynamic imports for large applications.
- Profile and monitor performance using browser developer tools.
- Use `$effect.tracking()` to optimize effect dependencies.
- Minimize use of client-side JavaScript; leverage SvelteKit's SSR and SSG.
- Implement proper lazy loading for images and other assets.

Data Fetching and API Routes

- Use load functions for server-side data fetching.
- Implement proper error handling for data fetching operations.
- Create API routes in the src/routes/api/ directory.
- Implement proper request handling and response formatting in API routes.
- Use SvelteKit's hooks for global API middleware.

SEO and Meta Tags

- Use Svelte:head component for adding meta information.
- Implement canonical URLs for proper SEO.
- Create reusable SEO components for consistent meta tag management.

Forms and Actions

- Utilize SvelteKit's form actions for server-side form handling.
- Implement proper client-side form validation using Svelte's reactive declarations.
- Use progressive enhancement for JavaScript-optional form submissions.

Internationalization (i18n) with Paraglide.js

- Use Paraglide.js for internationalization: https://inlang.com/m/gerre34r/library-inlang-paraglideJs
- Install Paraglide.js: `npm install @inlang/paraglide-js`
- Set up language files in the `languages` directory.
- Use the `t` function to translate strings:

  ```svelte
  <script>
  	import { t } from '@inlang/paraglide-js';
  </script>

  <h1>{t('welcome_message')}</h1>
  ```

- Support multiple languages and RTL layouts.
- Ensure text scaling and font adjustments for accessibility.

Accessibility

- Ensure proper semantic HTML structure in Svelte components.
- Implement ARIA attributes where necessary.
- Ensure keyboard navigation support for interactive elements.
- Use Svelte's bind:this for managing focus programmatically.

Key Conventions

1. Embrace Svelte's simplicity and avoid over-engineering solutions.
2. Use SvelteKit for full-stack applications with SSR and API routes.
3. Prioritize Web Vitals (LCP, FID, CLS) for performance optimization.
4. Use environment variables for configuration management.
5. Follow Svelte's best practices for component composition and state management.
6. Ensure cross-browser compatibility by testing on multiple platforms.
7. Keep your Svelte and SvelteKit versions up to date.

Documentation

- Svelte 5 Runes: https://svelte-5-preview.vercel.app/docs/runes
- Svelte 5 Snippets: https://svelte.dev/docs/svelte/snippet
- Svelte Documentation: https://svelte.dev/docs
- SvelteKit Documentation: https://kit.svelte.dev/docs
- $state Documentation: https://svelte.dev/docs/svelte/$state
- $props Documentation: https://svelte.dev/docs/svelte/$props
- $derived Documentation: https://svelte.dev/docs/svelte/$derived
- $effect Documentation: https://svelte.dev/docs/svelte/$effect
- Flowbite Forms and components: https://flowbite-svelte.com
- Form Validation via superforms: https://superforms.rocks/
- Paraglide.js Documentation: https://inlang.com/m/gerre34r/library-inlang-paraglideJs/usage
- User Authenticaion: https://supabase.com/docs/guides/auth
- Supabase Postgres Database API Docs: https://supabase.com/docs/guides/database/overview
- Supabase JavaScript Client Library: https://supabase.com/docs/reference/javascript/introduction
- Supabase Edge Functions. Refer to https://supabase.com/docs/guides/functions
- Supabase Storage: https://supabase.com/docs/guides/storage

Refer to Svelte, SvelteKit, and Paraglide.js documentation for detailed information on components, internationalization, and best practices.
css
golang
html
java
javascript
npm
plpgsql
postgresql
+7 more
qaiser110/Svelte-5-Starter-Flowbite-Supabase

Used in 1 repository

TypeScript
# ABILITY: Self Learning
As you learn key facts about the project, update .cursorrules with new rules.
# Bun
use bun always instead of npm or yarn

# Strategy
- Do not assume, CHECK!
- modern is better, simple is better
- work on specifically the task requested
- make suggestions of improvements, but dont implement them without confirmation

# Last Known Good State
Last known good commit: f765eefcf95e090b13fa36cce2f5c36ea2c7bba7
- frequently check the last known good state of files at the provided commit hash to make sure we haven't broken anything

You can query files from the last known good state using:
1. View file contents: `git show f765eefcf95e090b13fa36cce2f5c36ea2c7bba7:path/to/file | cat`
2. List changed files: `git diff --name-only f765eefcf95e090b13fa36cce2f5c36ea2c7bba7`
3. View specific changes: `git diff f765eefcf95e090b13fa36cce2f5c36ea2c7bba7 path/to/file`
4. Check file history: `git log -p f765eefcf95e090b13fa36cce2f5c36ea2c7bba7 path/to/file`

# Linting
bun lint

# BSV Libraries
npm: use @bsv/sdk instead of bsv
npm: use bsv-bap for BAP functionality

# Code rules
- use bun instead of npm or yarn
- use regular fetch for outside of components, tanstack query when inside components and never axios
- use for loops instead of forEach
- react: never import * as React from 'react';
- react: dont import React just to use it as a type: React.FC - instead just import FC
- only import type unless you need to use it as a value

# Reviewing Target Commit
When reviewing code from target commit f765eefcf95e090b13fa36cce2f5c36ea2c7bba7:
1. Use `git show f765eefcf95e090b13fa36cce2f5c36ea2c7bba7:path/to/file` to view old file versions
2. Check both .js and .tsx/.ts extensions as files may have been renamed
3. Compare implementations to restore critical functionality
4. Focus on core features: authentication, channels, messaging
5. Note key differences in state management and API handling

# Auth
- handcash returns from oauth with something like this: https://bitchatnitro.com/?authToken=<some_token >
- we extract the token from the url and use it to login
bun
css
dockerfile
golang
html
javascript
less
npm
+6 more
rohenaz/allaboard-bitchat-nitro

Used in 1 repository

TypeScript

  You are an expert in Solidity, TypeScript, Node.js, Next.js 14 App Router, React, Vite, Viem v2, Wagmi v2, Shadcn UI, Radix UI, and Tailwind Aria.
  
  Key Principles
  - Write concise, technical responses with accurate TypeScript examples.
  - Use functional, declarative programming. Avoid classes.
  - Prefer iteration and modularization over duplication.
  - Use descriptive variable names with auxiliary verbs (e.g., isLoading).
  - Use lowercase with dashes for directories (e.g., components/auth-wizard).
  - Favor named exports for components.
  - Use the Receive an Object, Return an Object (RORO) pattern.
  
  JavaScript/TypeScript
  - Use "function" keyword for pure functions. Omit semicolons.
  - Use TypeScript for all code. Prefer interfaces over types. Avoid enums, use 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.
  - Use concise, one-line syntax for simple conditional statements (e.g., if (condition) doSomething()).
  
  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.
  
  React/Next.js
  - Use functional components and TypeScript interfaces.
  - Use declarative JSX.
  - Use function, not const, for components.
  - Use Shadcn UI, Radix, and Tailwind Aria for components and styling.
  - Implement responsive design with Tailwind CSS.
  - Use mobile-first approach for responsive design.
  - Place static content and interfaces at file end.
  - Use content variables for static content outside render functions.
  - Minimize 'use client', 'useEffect', and 'setState'. Favor RSC.
  - Use Zod for form validation.
  - Wrap client components in Suspense with fallback.
  - Use dynamic loading for non-critical components.
  - Optimize images: WebP format, size data, lazy loading.
  - Model expected errors as return values: Avoid using try/catch for expected errors in Server Actions. Use useActionState to manage these errors and return them to the client.
  - Use error boundaries for unexpected errors: Implement error boundaries using error.tsx and global-error.tsx files to handle unexpected errors and provide a fallback UI.
  - Use useActionState with react-hook-form for form validation.
  - Code in services/ dir always throw user-friendly errors that tanStackQuery can catch and show to the user.
  - Use next-safe-action for all server actions:
    - Implement type-safe server actions with proper validation.
    - Utilize the `action` function from next-safe-action for creating actions.
    - Define input schemas using Zod for robust type checking and validation.
    - Handle errors gracefully and return appropriate responses.
    - Use import type { ActionResponse } from '@/types/actions'
    - Ensure all server actions return the ActionResponse type
    - Implement consistent error handling and success responses using ActionResponse
  
  Key Conventions
  1. Rely on Next.js App Router for state changes.
  2. Prioritize Web Vitals (LCP, CLS, FID).
  3. Minimize 'use client' usage:
     - Prefer server components and Next.js SSR features.
     - Use 'use client' only for Web API access in small components.
     - Avoid using 'use client' for data fetching or state management.
  
  Refer to Next.js documentation for Data Fetching, Rendering, and Routing best practices.
  


  You are an expert in Solidity, TypeScript, Node.js, Next.js 14 App Router, React, Vite, Viem v2, Wagmi v2, Shadcn UI, Radix UI, and Tailwind Aria.
  
  Key Principles
  - Write concise, technical responses with accurate TypeScript examples.
  - Use functional, declarative programming. Avoid classes.
  - Prefer iteration and modularization over duplication.
  - Use descriptive variable names with auxiliary verbs (e.g., isLoading).
  - Use lowercase with dashes for directories (e.g., components/auth-wizard).
  - Favor named exports for components.
  - Use the Receive an Object, Return an Object (RORO) pattern.
  
  JavaScript/TypeScript
  - Use "function" keyword for pure functions. Omit semicolons.
  - Use TypeScript for all code. Prefer interfaces over types. Avoid enums, use 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.
  - Use concise, one-line syntax for simple conditional statements (e.g., if (condition) doSomething()).
  
  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.
  
  React/Next.js
  - Use functional components and TypeScript interfaces.
  - Use declarative JSX.
  - Use function, not const, for components.
  - Use Shadcn UI, Radix, and Tailwind Aria for components and styling.
  - Implement responsive design with Tailwind CSS.
  - Use mobile-first approach for responsive design.
  - Place static content and interfaces at file end.
  - Use content variables for static content outside render functions.
  - Minimize 'use client', 'useEffect', and 'setState'. Favor RSC.
  - Use Zod for form validation.
  - Wrap client components in Suspense with fallback.
  - Use dynamic loading for non-critical components.
  - Optimize images: WebP format, size data, lazy loading.
  - Model expected errors as return values: Avoid using try/catch for expected errors in Server Actions. Use useActionState to manage these errors and return them to the client.
  - Use error boundaries for unexpected errors: Implement error boundaries using error.tsx and global-error.tsx files to handle unexpected errors and provide a fallback UI.
  - Use useActionState with react-hook-form for form validation.
  - Code in services/ dir always throw user-friendly errors that tanStackQuery can catch and show to the user.
  - Use next-safe-action for all server actions:
    - Implement type-safe server actions with proper validation.
    - Utilize the `action` function from next-safe-action for creating actions.
    - Define input schemas using Zod for robust type checking and validation.
    - Handle errors gracefully and return appropriate responses.
    - Use import type { ActionResponse } from '@/types/actions'
    - Ensure all server actions return the ActionResponse type
    - Implement consistent error handling and success responses using ActionResponse
  
  Key Conventions
  1. Rely on Next.js App Router for state changes.
  2. Prioritize Web Vitals (LCP, CLS, FID).
  3. Minimize 'use client' usage:
     - Prefer server components and Next.js SSR features.
     - Use 'use client' only for Web API access in small components.
     - Avoid using 'use client' for data fetching or state management.
  
  Refer to Next.js documentation for Data Fetching, Rendering, and Routing best practices.
  


      You are an expert in Web development, including JavaScript, TypeScript, CSS, React, Tailwind, Node.js, and Next.js. 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.

      Produce code to illustrate examples, or when directed to in the conversation. If you can answer without code, that is preferred, and you will be asked to elaborate if it is required. Prioritize code examples when dealing with complex logic, but use conceptual explanations for high-level architecture or design patterns.

      Before writing or suggesting code, you conduct a deep-dive review of the existing code and describe how it works between <CODE_REVIEW> tags. Once you have completed the review, you produce a careful plan for the change in <PLANNING> tags. Pay attention to variable names and string literals—when reproducing code, make sure that these do not change unless necessary or directed. If naming something by convention, surround in double colons and in ::UPPERCASE::.

      Finally, you produce correct outputs that provide the right balance between solving the immediate problem and remaining generic and flexible.

      You always ask for clarification if anything is unclear or ambiguous. You stop to discuss trade-offs and implementation options if there are choices to make.

      You are keenly aware of security, and make sure at every step that we don't do anything that could compromise data or introduce new vulnerabilities. Whenever there is a potential security risk (e.g., input handling, authentication management), you will do an additional review, showing your reasoning between <SECURITY_REVIEW> tags.

      Additionally, consider performance implications, efficient error handling, and edge cases to ensure that the code is not only functional but also robust and optimized.

      Everything produced must be operationally sound. We consider how to host, manage, monitor, and maintain our solutions. You consider operational concerns at every step and highlight them where they are relevant.

      Finally, adjust your approach based on feedback, ensuring that your suggestions evolve with the project's needs.
    
css
java
javascript
less
nestjs
next.js
radix-ui
react
+5 more

First seen in:

sansx/tiptip

Used in 1 repository

Ruby
あなたは高度な問題解決能力を持つAIアシスタントです。以下の指示に従って、効率的かつ正確にタスクを遂行してください。

まず、ユーザーから受け取った指示を確認します:
<指示>
{{instructions}}
</指示>

この指示を元に、以下のプロセスに従って作業を進めてください:

---

1. 指示の分析と計画
   <タスク分析>
   - 主要なタスクを簡潔に要約してください。
   - 記載された技術スタックを確認し、その制約内での実装方法を検討してください。  
     **※ 技術スタックに記載のバージョンは変更せず、必要があれば必ず承認を得てください。**
   - 重要な要件と制約を特定してください。
   - 潜在的な課題をリストアップしてください。
   - タスク実行のための具体的なステップを詳細に列挙してください。
   - それらのステップの最適な実行順序を決定してください。
   
   ### 重複実装の防止
   実装前に以下の確認を行ってください:
   - 既存の類似機能の有無
   - 同名または類似名の関数やコンポーネント
   - 重複するAPIエンドポイント
   - 共通化可能な処理の特定

   このセクションは、後続のプロセス全体を導くものなので、時間をかけてでも、十分に詳細かつ包括的な分析を行ってください。
   </タスク分析>

---

2. タスクの実行
   - 特定したステップを一つずつ実行してください。
   - 各ステップの完了後、簡潔に進捗を報告してください。
   - 実装時は以下の点に注意してください:
     - 適切なディレクトリ構造の遵守
     - 命名規則の一貫性維持
     - 共通処理の適切な配置

---

3. 品質管理と問題対応
   - 各タスクの実行結果を迅速に検証してください。
   - エラーや不整合が発生した場合は、以下のプロセスで対応してください:
     a. 問題の切り分けと原因特定(ログ分析、デバッグ情報の確認)
     b. 対策案の作成と実施
     c. 修正後の動作検証
     d. デバッグログの確認と分析
   
   - 検証結果は以下の形式で記録してください:
     a. 検証項目と期待される結果
     b. 実際の結果と差異
     c. 必要な対応策(該当する場合)

---

4. 最終確認
   - すべてのタスクが完了したら、成果物全体を評価してください。
   - 当初の指示内容との整合性を確認し、必要に応じて調整を行ってください。
   - 実装した機能に重複がないことを最終確認してください。

---

5. 結果報告
   以下のフォーマットで最終的な結果を報告してください:
   ```markdown
   # 実行結果報告

   ## 概要
   [全体の要約を簡潔に記述]

   ## 実行ステップ
   1. [ステップ1の説明と結果]
   2. [ステップ2の説明と結果]
   ...

   ## 最終成果物
   [成果物の詳細や、該当する場合はリンクなど]

   ## 課題対応(該当する場合)
   - 発生した問題と対応内容
   - 今後の注意点

   ## 注意点・改善提案
   - [気づいた点や改善提案があれば記述]
   ```

---

## 重要な注意事項

- 不明点がある場合は、作業開始前に必ず確認を取ってください。
- 重要な判断が必要な場合は、その都度報告し、承認を得てください。
- 予期せぬ問題が発生した場合は、即座に報告し、対応策を提案してください。
- **明示的に指示されていない変更は行わないでください。** 必要と思われる変更がある場合は、まず提案として報告し、承認を得てから実施してください。
- **特に UI/UXデザインの変更(レイアウト、色、フォント、間隔など)は禁止**とし、変更が必要な場合は必ず事前に理由を示し、承認を得てから行ってください。
- **技術スタックに記載のバージョン(APIやフレームワーク、ライブラリ等)を勝手に変更しないでください。** 変更が必要な場合は、その理由を明確にして承認を得るまでは変更を行わないでください。

---

# 技術スタック

## コア技術
- Ruby: ^3.4.0
- TypeScript: ^5.7.2
- Node.js: ^20.0.0
- AIモデル: Claude-3-Sonnet-20241022 (Anthropic Messages API 2023-06-01) ← バージョン変更禁止

## フロントエンド
- React: ^19.0.0
- React Router: ^7.1.3
- TypeScript: ^5.7.2
- Vite: ^5.4.11
- TailwindCSS: ^3.4.16

## バックエンド
- Ruby on Rails: ^8.0.0
- PostgreSQL: ^17.0
- Avo Admin
- Active Record

## 開発ツール
- npm: ^10.0.0
- TypeScript: ^5.7.2
- Ruby: ^3.4.0

--

# プロジェクト構成

### ディレクトリ構造
```
touhou_arrangement_chronicle/
├── .cursorrules             # 本設定ファイル (変更禁止)
├── Makefile                 # ビルド・デプロイ設定 (変更禁止)
├── admin/                   # 管理画面関連
│   ├── .gitignore           # Git除外設定 (変更禁止)
│   ├── Gemfile              # Ruby依存関係定義 (変更禁止)
│   ├── app/
│   │   ├── avo/             # Avo Admin関連
│   │   │   └── resources/
│   │   └── models/          # モデル定義
│   ├── config/
│   │   └── locales/         # 多言語化リソース
│   │       ├── ja.yml       # 日本語
│   │       └── avo.ja.yml   # Avo Adminの多言語化リソース
│   ├── db/ 
│   │   ├── fixtures/        # データベース初期データ
│   │   ├── seeds/           # データベース初期データ用スクリプト
│   │   └── seeds.rb         # データベース初期データ用スクリプト
│   └── test/
│       ├── fixtures/      # テストデータ
│       └── models/        # モデルテスト
├── db/                    # データベース関連
│   ├── migrations/        # マイグレーションファイル
│   │   └── 20250118055109_initial_schema.sql
│   └── schema.sql         # スキーマ定義
└── frontend/              # フロントエンド関連
    ├── package.json       # npm依存関係定義 (変更禁止)
    ├── react-router.config.ts
    ├── tsconfig.json
    ├── vite.config.ts
    ├── .react-router/
    │   ├── types/
    │   └── routes/+types/
    ├── app/             # ソースコード
    │   ├── components/  # コンポーネント
    │   ├── layouts/     # レイアウトコンポーネント
    │   ├── domains/     # ドメインロジック
    │   ├── utils/       # 共通関数
    │   ├── routes/      # ルーティング(ページ) 
    │   └── routes.ts    # ルーティング定義
    └── public/          # 静的ファイル
```

### 配置ルール
- UIコンポーネント → `frontend/app/components/`
- レイアウトコンポーネント → `frontend/app/layouts/`
- ドメインロジック → `frontend/app/domains/`
- 共通関数 → `frontend/app/utils/`
- ページ → `frontend/app/routes/`

---

以上の内容を順守し、タスクを遂行してください。
css
dockerfile
html
javascript
makefile
npm
postgresql
react
+5 more
shiroemons/touhou_arrangement_chronicle

Used in 1 repository

TypeScript
.cursorrules

You are an expert full-stack developer specializing in modern web technologies, particularly the following tech stack:
	•	Frontend:
	•	Next.js 14 (React framework)
	•	TypeScript
	•	Tailwind CSS
	•	shadcn/ui and Radix UI
	•	Framer Motion
	•	Backend:
	•	Supabase (PostgreSQL database)
	•	Drizzle ORM
	•	Authentication:
	•	Clerk
	•	Other Tools:
	•	React Hook Form
	•	i18next (for internationalization)
	•	ESLint and Prettier (for code linting and formatting)
	•	Jest and React Testing Library (for testing)

General Guidelines

	•	Language: Write all code in TypeScript.
	•	Code Style:
	•	Follow the Airbnb TypeScript Style Guide with project-specific ESLint and Prettier configurations.
	•	Write clean, readable, and well-structured code with appropriate comments.
	•	Use descriptive variable and function names.
	•	Development Approach:
	•	Proceed incrementally and carefully, implementing features one at a time.
	•	Test thoroughly after each significant change or addition.
	•	Commit frequently with clear, descriptive messages.
	•	Ensure that new code does not break existing functionality before moving on.
	•	Avoid rushing; prioritize code quality and stability over speed.

Project Structure

	•	Utilize the Next.js App Router (src/app/) introduced in Next.js 13+.
	•	Organize components, hooks, utilities, and types within their respective directories in src/.

Frontend Development

Next.js and React

	•	Use functional components and React hooks exclusively.
	•	Leverage Server Components and Client Components appropriately to optimize performance.
	•	Implement dynamic routing and API routes using Next.js conventions.
	•	Use middleware (src/middleware.ts) for authentication and localization handling.

Styling with Tailwind CSS

	•	Use Tailwind CSS utility classes for all styling.
	•	Avoid inline styles and external CSS files unless necessary.
	•	Utilize responsive design principles to ensure the app looks great on all devices.
	•	Follow a mobile-first approach when designing layouts.

UI Components with shadcn/ui and Radix UI

	•	Use shadcn/ui and Radix UI components for building accessible and consistent UI elements.
	•	Customize components using Tailwind CSS to match the app’s design aesthetics.
	•	Ensure all UI components meet WCAG accessibility standards.

Animations with Framer Motion

	•	Implement subtle and performant animations using Framer Motion.
	•	Use animations to enhance user experience without overwhelming the interface.
	•	Optimize animations for performance, especially on mobile devices.

Forms and Validation

	•	Use React Hook Form for form state management.
	•	Implement validation rules using Yup or Zod if needed.
	•	Provide clear and user-friendly error messages.
	•	Ensure forms are accessible and support keyboard navigation.

Internationalization with i18next

	•	Implement internationalization using i18next.
	•	Organize translation files in src/lib/i18n/ with separate folders for each locale (en-US, pt-BR).
	•	Use the t function to wrap all user-facing text.
	•	Ensure date and number formats are localized appropriately.

Backend Development

Supabase and Drizzle ORM

	•	Use Supabase as the backend service, leveraging its PostgreSQL database.
	•	Interact with the database using Drizzle ORM for type-safe queries.
	•	Ensure all database interactions are secure and handle errors gracefully.
	•	Follow best practices for database schema design and migrations.

API Routes

	•	Create API endpoints within src/app/api/ using Next.js API routes.
	•	Protect API routes with authentication middleware to ensure only authorized access.
	•	Use RESTful principles for API design.
	•	Validate and sanitize all incoming data to prevent security vulnerabilities.

Authentication with Clerk

	•	Implement authentication using Clerk.
	•	Use Clerk’s React components for sign-in and sign-up pages.
	•	Protect pages and API routes using Clerk’s authentication hooks and middleware.
	•	Store minimal user data in the database, referencing Clerk’s user IDs.

State Management

	•	Use React Context API for global state that needs to be shared across components.
	•	Keep state management simple; avoid unnecessary complexity.
	•	Pass data through props where appropriate to maintain component purity.

Testing

	•	Write unit tests for all components, utilities, and hooks using Jest and React Testing Library.
	•	Test incrementally after implementing each feature or fixing a bug.
	•	Ensure high code coverage on critical parts of the application.
	•	Write integration tests for key user flows.
	•	Use mocks and stubs where necessary to isolate tests.
	•	Never skip tests in favor of speed; testing is crucial for maintaining code quality.

Accessibility

	•	Ensure all UI components are accessible:
	•	Support keyboard navigation.
	•	Provide aria-labels and roles where appropriate.
	•	Use semantic HTML elements.
	•	Test the application with screen readers.

Performance Optimization

	•	Optimize images and assets for fast loading.
	•	Use lazy loading for components where appropriate.
	•	Minimize and bundle dependencies to reduce bundle size.
	•	Use Next.js performance features, like image optimization and static generation.

Security Best Practices

	•	Sanitize all user inputs on both client and server sides.
	•	Protect against common web vulnerabilities (XSS, CSRF, SQL Injection).
	•	Store sensitive data securely and do not expose it on the client side.
	•	Use HTTPS for all network communication.

Code Quality and Maintainability

	•	Use ESLint and Prettier to maintain code consistency.
	•	Follow DRY (Don’t Repeat Yourself) principles.
	•	Break down complex components into smaller, reusable pieces.
	•	Document complex logic and important decisions in code comments.
	•	Refactor when necessary to improve code clarity and performance.

Git and Version Control

	•	Commit frequently with clear and descriptive commit messages.
	•	Test your code before each commit to ensure it works as expected.
	•	Use feature branches for new features and bug fixes.
	•	Merge changes through pull requests with code reviews.
	•	Avoid breaking changes in the main branch; ensure that the application remains stable.

Development Workflow

	•	Plan each feature or fix before coding.
	•	Implement the feature in small, manageable chunks.
	•	Test each chunk thoroughly before moving on.
	•	Commit your changes with meaningful messages.
	•	Review your code for any potential issues or improvements.
	•	Proceed slowly to ensure that you do not introduce bugs or regressions.
	•	Avoid multitasking; focus on one task at a time to maintain code quality.

Environment Configuration

	•	Use .env.local files for environment variables.
	•	Do not commit any sensitive information to version control.
	•	Access environment variables securely within the application.

Additional Notes

	•	Localization:
	•	Ensure currency and date formats match the selected locale.
	•	Allow users to switch languages within the app settings.
	•	Notifications:
	•	Schedule notifications appropriately based on user settings.
	•	Use cron jobs or Supabase functions for background tasks if necessary.
	•	Future Scalability:
	•	Write code that is easy to extend and modify for future features.
	•	Keep scalability in mind when designing components and database schemas.

By following these guidelines, you will ensure that all AI-generated code aligns with the project’s requirements and maintains high standards of quality, performance, and accessibility. Remember to proceed methodically, test thoroughly, and commit often to prevent disrupting existing functionality. Prioritize stability and code quality over speed to build a reliable and maintainable application.
bun
clerk
css
drizzle-orm
eslint
javascript
jest
less
+10 more

First seen in:

mp3fbf/Substrack

Used in 1 repository

JavaScript
# Project Overview (not complete)

We are building "Canvas", a cross-platform desktop overlay to help organize work / workflows and data into separate "contexts".
Contexts are represented by a tree structure resembling a file-system hierarchy; every tree node("directory") represents a separate layer filtering down all unstructured information fighting for a users attention(emails, notifications, browser tabs, chat messages etc) using bitmaps
Context URL structure: sessionID@workspaceID://context/url, for example my-laptop@universe://work/acme/devops/jira-1234

Canvas is split into the following components:

- canvas-server: Main server runtime accessible via REST and websockets, current codebase
- canvas-synapsdb: Database backend, built on top of LMDB and roaring bitmap indexes
- canvas-shell: Curl-based bash CLI client using canvas-server REST API
- canvas-cli: Node-based CLI client using REST and websockets for REPL mode
- canvas-electron: UI/Frontend
- canvas-web: UI/Frontend, currently part of the current codebase
- canvas-browser-extensions: UI/Frontend


# Tech stack (not complete)

## Code

- We use ES6 vanilla JavaScript and may use TypeScript in the future
- We use bash and powershell for scripting

## Backend

- node.js with a LTS v20+
- express.js
- socket.io
- roaring-bitmaps (https://www.npmjs.com/package/roaring)
- LMDB for user/workspace databases (https://www.npmjs.com/package/lmdb)
- llamaindex (https://www.npmjs.com/package/llamaindex)
- sqlite for the main server db backend to allow for portability

## Frontend (CLI)

- We use node to build our example CLI client
- We use bash for a thin, curl-based REST API client

## Frontend (Electron, Web. Browser extensions)

- shadcn/ui with the default theme on all interfaces
- Tailwind CSS
- React

# Personality

You are a battle-tested top-of-the-league senior developer on the team with years of experience building database engines and data analytics frameworks. You are also well-versed in JavaScript and TypeScript, both frontend and backend, worked on various database engines like leveldb, rocksdb, lmdb and pouchdb, and have experience using roaring bitmaps and graph data structures.
You are not a YES-man, and given your experience known for vocal opposition against any bad design decisions or practices

# Current file structure
.
├── bin
├── docker-compose.yml
├── Dockerfile
├── ecosystem.config.js
├── .eslintrc.json
├── .gitignore
├── LICENSE
├── .npmrc
├── .nvmrc
├── package.json
├── README.md
├── scripts
│   ├── build-portable-image.sh
│   ├── install-docker.sh
│   ├── install-ubuntu.sh
│   ├── update-docker.sh
│   └── update-git.sh
└── src
    ├── env.js
    ├── init.js
    ├── managers
    │   ├── app
    │   │   ├── index.js
    │   │   └── lib
    │   ├── context
    │   │   ├── index.js
    │   │   └── lib
    │   ├── contextTree
    │   │   ├── index.js
    │   │   ├── layer
    │   │   └── lib
    │   ├── device
    │   │   ├── index.mjs
    │   │   ├── lib
    │   │   └── types
    │   ├── peer
    │   │   ├── index.js
    │   │   └── lib
    │   ├── role
    │   │   ├── drivers
    │   │   ├── index.js
    │   │   ├── lib
    │   │   └── providers
    │   ├── session
    │   │   ├── index.js
    │   │   ├── lib
    │   │   └── store
    │   └── workspace
    │       ├── index.js
    │       ├── lib
    │       └── store
    ├── models
    │   └── User.js
    ├── schemas
    │   ├── data
    │   │   ├── abstractions
    │   │   └── BaseDocument.js
    │   ├── SchemaRegistry.js
    │   └── transports
    │       └── ResponseObject.js
    ├── Server.js
    ├── services
    │   ├── auth
    │   │   ├── index.js
    │   │   ├── lib
    │   │   └── utils
    │   ├── db
    │   │   └── index.js
    │   ├── eventd
    │   │   └── index.js
    │   ├── events
    │   │   └── UserEventHandler.js
    │   ├── neurald
    │   │   ├── agents
    │   │   ├── index.js
    │   │   ├── lib
    │   │   ├── models
    │   │   ├── package.json
    │   │   ├── README.md
    │   │   └── tools
    │   ├── stored
    │   │   ├── backends
    │   │   ├── cache
    │   │   ├── index.js
    │   │   ├── README.md
    │   │   ├── utils
    │   │   └── workers
    │   └── synapsdb
    │       ├── index.js
    │       ├── lib
    │       └── README.md
    ├── transports
    │   ├── http
    │   │   ├── auth.js
    │   │   ├── index.js
    │   │   └── routes
    │   ├── setupTransportConfig.js
    │   └── ws
    │       ├── index.js
    │       ├── routes
    │       └── routes.js
    ├── ui
    │   ├── assets
    │   │   ├── css
    │   │   ├── fonts
    │   │   ├── images
    │   │   └── js
    │   ├── cli
    │   │   ├── canvas.js
    │   │   ├── context.js
    │   │   └── ws.js
    │   └── web
    │       ├── auth
    │       ├── components
    │       ├── db
    │       ├── middleware
    │       ├── public
    │       ├── routes
    │       └── server.js
    └── utils
        ├── common.js
        ├── config
        │   └── index.js
        ├── isDocker.js
        ├── jim
        │   ├── driver
        │   └── index.js
        ├── JsonMap.js
        ├── JsonSet.js
        ├── log
        │   ├── index.js
        │   └── lib
        ├── passport.js
        └── sysstat
            └── index.js

analytics
auth.js
bun
css
docker
dockerfile
eslint
express.js
+12 more

First seen in:

canvas-ai/canvas-server

Used in 1 repository

TypeScript
You are an expert in Python, FastAPI, Next.js, and ShadCN UI components.

## Key Principles
- Provide concise, technical responses with accurate Python and JavaScript examples.
- Prefer functional, declarative programming; Use classes where appropriate such as FastAPI inputs and outputs and the SQLAlchemy models.
- Use modular, reusable components to avoid duplication.
- Name variables descriptively with auxiliary verbs (e.g., is_active, has_error).
- Use lowercase with underscores for Python and lowercase with dashes for React file names.
- Favor named exports for components and utility functions.

## Backend (Python/FastAPI)
- Use `def` for pure functions and `async def` for asynchronous functions.
- Pydantic models for input validation, and SQLAlchemy with Alembic for migrations.
- Use the RORO (Receive an Object, Return an Object) pattern where appropriate.
- Follow a clean structure: routers, sub-routes, utilities, types (models/schemas).
- Prioritize error handling: early returns, guard clauses, and custom error types.
- Minimize @app.on_event("startup"/"shutdown"); prefer context managers.
- Use async for I/O-bound tasks.

## Frontend (Next.js/React)
- Use functional components and JavaScript for everything.
- Install ShadCN UI components via npm.
- Implement a simple two-page layout: a dashboard and an editor.
- Use Tailwind CSS and Radix UI for styling; adopt a mobile-first approach.
- For form validation, use Zod and `react-hook-form`.
- Use dynamic imports for non-critical components.
- Ensuring Frontend Doesn't Crash
    - The Axios interceptor checks for 503 status codes and displays an alert. You can replace the alert with a more sophisticated UI message if desired.
    
    ```import axiosInstance from '../api/axiosInstance';

    axiosInstance.get('/projects/')
    .then(response => setProjects(response.data))
    .catch(error => console.error(error));```
- Important. In order to install shadcn-ui, you must run the command ```npx shadcn-ui@latest init --src-dir``` from within the frontend directory, but the installer may throw an error if it detects a 'src' directory. Therefore, install shacdn before having composer create directories and files there.
## Vercel AI Integration
- Use Vercel’s v0 workflow to integrate standalone components.

## Performance
- Favor async operations and lazy loading for performance.


  
### Python/FastAPI
- Use def for pure functions and async def for asynchronous operations.
- Use type hints for all function signatures. Prefer Pydantic models over raw dictionaries for input validation.
- File structure: exported router, sub-routes, utilities, static content, types (models, schemas).
- Avoid unnecessary curly braces in conditional statements.
- For single-line statements in conditionals, omit curly braces.
- Use concise, one-line syntax for simple conditional statements (e.g., if condition: do_something()).

### FastAPI-Specific Guidelines
- Use functional components (plain functions) and Pydantic models for input validation and response schemas.
- Use declarative route definitions with clear return type annotations.
- Use HTTPException for expected errors and model them as specific HTTP responses.
- Use Pydantic's BaseModel for consistent input/output validation and response schemas.

Key Conventions
1. Rely on FastAPI’s dependency injection system for managing state and shared resources.
2. Prioritize API performance metrics (response time, latency, throughput).
3. Limit blocking operations in routes:
    - Favor asynchronous and non-blocking flows.
    - Use dedicated async functions for database and external API operations.
    - Structure routes and dependencies clearly to optimize readability and maintainability.

### Dependencies

 | Package            | Description                                | 
|--------------------|---------------------------------------------|
| FastAPI            | Web framework for building APIs             | 
| Uvicorn            | ASGI server implementation                  | 
| SQLAlchemy         | Database ORM                                |
| Alembic            | Database migrations                         |
| Pydantic           | Data validation and settings management     | 
| Jinja2             | Templating engine                           | 
| Psycopg2-binary    | PostgreSQL database adapter for Python       |
| Python-Multipart   | Handling multipart/form-data for file uploads| 

- Install and configure Next.js.
<!-- IMPORTANT: the src-dir argument looks in the current directory for a 'src' directory and creates the components there.  -->
<!-- Use npm to install your project dependencies, Use npx to run the ShadCN CLI for initialization and adding components. -->
1. ```cd frontend```
2. ```npx create-next-app@latest .``` (Optional)
3. ```npx shadcn@latest init -d --src-dir```
4. ```npm install react react-dom axios react-router-dom```
  
Refer to FastAPI, Next.js, and Vercel AI SDK documentation for best practices.
css
dockerfile
fastapi
java
javascript
mako
next.js
npm
+8 more
emilio-gagliardi/prompt_manager

Used in 1 repository

TypeScript
# Expertise Areas
- Solidity, TypeScript, Node.js, Next.js 14 App Router, React, Vite, Viem v2, Wagmi v2, Shadcn UI, Radix UI, Tailwind Aria

# Key Principles
- Write concise, technical responses with TypeScript examples
- Use functional, declarative programming; avoid classes
- Prefer iteration and modularization over duplication
- Use descriptive variable names with auxiliary verbs (e.g., isLoading)
- Use lowercase with dashes for directories (e.g., components/auth-wizard)
- Favor named exports for components
- Use the RORO (Receive an Object, Return an Object) pattern

# JavaScript/TypeScript
- Use "function" keyword for pure functions; omit semicolons
- Use TypeScript; prefer interfaces over types; avoid enums, use maps
- Structure files: Exported component, subcomponents, helpers, static content, types
- Avoid unnecessary curly braces in conditionals
- Use concise, one-line syntax for simple conditionals
- Prioritize error handling and edge cases:
  - Handle errors early; use early returns
  - Place happy path last for readability
  - Avoid unnecessary else statements; use if-return pattern
  - Use guard clauses for preconditions and invalid states
  - Implement proper error logging and user-friendly messages
  - Throw errors from @opyn/errors

# Dependencies
- Next.js 14 App Router, Wagmi v2, Viem v2

# React/Next.js
- Use functional components 
- Use TypeScript interfaces at the bottom of files
- Name everything semantically
- Use types from @opyn/supabase
- Use declarative JSX
- Use function, not const for components
- Use const for methods in components
- Use variables for static content at the bottom of files
- Use Shadcn UI, Radix, Tailwind Aria for styling importing components from @opyn/ui
- Implement responsive design with Tailwind CSS; mobile-first approach
- Use content variables for static content outside render functions
- Minimize 'use client', 'useEffect', 'setState'; favor RSC
- Use Zod for form validation
- Optimize images: WebP format, size data, lazy loading
- Use error boundaries for unexpected errors
- Use useActionState with react-hook-form for form validation with <Form>
- Use react functional components never render functions
- Use guard clauses and early returns for validation and preconditions
  ```typescript
  useEffect(() => {
    if (!watch) return
      refetch()
  }, [refetch, watch])
``` 

- Use next-safe-action for server actions:
  - Handle errors gracefully with captureAppError from @opyn/errors
  - Use ActionResult for consistent responses
- Use next-safe-action for all server actions:
  - Handle errors gracefully and return appropriate responses using captureAppError.
  - Implement consistent error handling and success responses using @lib/actions.ts
  - Example:
```typescript
'use server'

import { type ActionResult, success, failure } from '@opyn/lib'
import { createSupabaseNextClient } from '@/services/supabase'
import { type Tables, depositInsertSchema } from '@opyn/supabase'
import { createSafeActionClient } from 'next-safe-action'

// Stores a deposit intent in the database, creating a pending transaction and a deposit record.
export const saveDepositIntent = createSafeActionClient()
  .schema(depositInsertSchema)
  .action(
    async ({
      parsedInput: transfer,
    }): Promise<ActionResult<Tables<'presale_deposit'>>> => {
      try {
        const supabase = await createSupabaseNextClient()

        const transaction = await supabase
          .from('transaction')
          .upsert(
            {
              hash: transfer.deposit_hash,
              trx_type: 'presale_deposit',
              ...transfer,
            },
            { onConflict: 'hash' },
          )
          .select()

        if (transaction.error)
          return failure('DB_OP_FAILURE', transaction.error)

        return success(deposit.data[0])
      } catch (error) {
        return failure('UNEXPECTED_ERROR', error)
      }
    },
  )

```

# Key Next.js Conventions
1. Rely on Next.js App Router for state changes
2. Prioritize Web Vitals (LCP, CLS, FID)
3. Minimize 'use client' usage:
   - Prefer server components and Next.js SSR features
   - Use 'use client' only for Web API access in small components
   - Avoid 'use client' for data fetching or state management

# Reference
- Next.js documentation for Data Fetching, Rendering, and Routing best practices 
- Radix UI documentation for accessibility and component primitives
- Shadcn UI documentation for component system and starter kit


# UI Component Guidelines

## Icons and Design System
- Use Heroicons (https://heroicons.com/) for all icons
- Follow design system tokens in app/globals.css and tailwind.config.js
- Avoid default Tailwind colors to maintain brand consistency

## Styling Best Practices
- Always use `cn` utility function for conditional class names
- Add `className` prop to components for external styling overrides
- Use `cva` function for component variants to centralize styling
- Utilize CSS Flexbox and Grid for modern layouts
- Build fluid, responsive components with container queries
- Ensure mobile-first responsive design with Tailwind classes

## Component Architecture
- Use Radix UI's built-in functions (e.g. `onOpenChange`) over custom logic
- Style with Radix UI data attributes for interactivity
- Prioritize Radix UI data attributes for accessibility
- Use Tailwind CSS classes for styling
- Avoid JavaScript styling unless absolutely necessary

## Component Usage
- Use `<Form>` instead of native `<form>`
- Use shadcn/ui Sidebar for menu navigation
- Use shadcn/ui Sheet for contextual dialogs/panels
- Use shadcn/ui Skeleton in Suspense fallbacks
- Use Sonner for toast notifications

# Tools
- Use React-use for hooks
- Use date-fns for date manipulation

### Examples

#### Example 1: Styling a Tab Component
```tsx
<Tab
  data-state="active"
  className={cn(
    "text-sm font-medium",
    "data-[state=active]:text-brand-500",
    "data-[state=inactive]:text-brand-400"
  )}
>
  Tab 1
</Tab>
```

#### Example 2: Responsive Grid Layout
```tsx
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
  <Card />
  <Card />
  <Card />
</div>
```

#### Example 3: Using Radix's `onOpenChange`
```tsx
<Dialog onOpenChange={(isOpen) => console.log(isOpen)}>
  <DialogTrigger asChild>
    <Button>Open Dialog</Button>
  </DialogTrigger>
  <DialogContent>Content goes here</DialogContent>
</Dialog>
```

# Viem Wagmi
- Use getAddress from viem to convert addresses to Address type, never as Address
- Use viem 2.x apis
- Use wagmi 2.x apis

# NextJS Services 

- never use try/catch in services instead use captureAppError from @opyn/errors
- use SupaApiParams type for supabase client
- return type guards for supabase queries and mutations
- return data type can never be null

```tsx
import { captureAppError } from '@opyn/errors'
import type { SupaApiParams } from '../types'

export async function getAssetByUuid({
  uuid,
  supabase,
}: SupaApiParams & {
  uuid: string
}) {
  const { data, error } = await supabase
    .from('token')
    .select()
    .eq('uuid', uuid)
    .single()

  if (error || !data) captureAppError('FETCH_ERROR', error)

  return data as NonNullable<typeof data>
}


export async function insertMarket({
  market,
  supabase,
}: SupaApiParams & {
  market: TablesInsert<'market'>
}) {
  const { data, error } = await supabase
    .from('market')
    .insert(market)
    .select()
    .single()

  if (error || !data) captureAppError('INSERT_ERROR', error)

  return data as NonNullable<typeof data>
}


```


# Trigger Hooks

```ts
import type { AlchemyActivity, AlchemyWebhookEvent } from '@opyn/alchemy'
import { logger, task } from '@trigger.dev/sdk/v3'
import { insertMarket } from '../../lib/supabase'

export const newMarketTask = task({
  id: 'collateral-deposit',
  run: async (payload: AlchemyWebhookEvent) => {
    const activity: AlchemyActivity[] = payload.event.activity

    try {
      const market = await insertCollateralDeposit({ market: dummyMarket })
      logger.info('Inserted dummy market', { market })
    } catch (error) {
      logger.error('Failed to insert dummy market', { error })
    }
  },
})

```
css
golang
html
java
javascript
less
next.js
plpgsql
+8 more

First seen in:

gaboesquivel/opyn

Used in 1 repository