Awesome Cursor Rules Collection

Showing 1585-1596 of 2626 matches

unknown
# =================================================================

#

# Intuition GraphQL Query Assistant Rules

#

# =================================================================

#

# Prerequisites:

# 1. Install the @0xintuition/graphql package:

# npm install @0xintuition/graphql

# or

# yarn add @0xintuition/graphql

# 2. Install React Query (if using React):

# npm install @tanstack/react-query

# or

# yarn add @tanstack/react-query

# Package Documentation:

# - https://www.npmjs.com/package/@0xintuition/graphql

# These rules can be combined with your existing .cursorrules file.

# To use alongside your existing rules, you can either:

# 1. Append this entire ruleset to your existing .cursorrules file

# 2. Copy specific rules you need into your existing .cursorrules

#

# These rules are optimized for AI agents (particularly in Cursor's

# composer mode) to help query Intuition data effectively.

#

# The rules are triggered by various Intuition-related queries:

# - "querying intuition data"

# - "using @0xintuition/graphql"

# - "fetch intuition data"

# - "get data from intuition"

# - Entity-specific queries:

# - positions (holdings in atoms/triples)

# - atoms (basic building blocks)

# - triples (relationships between atoms)

# - events (on-chain activities)

# - connections (following/follower relationships)

# - stats (protocol metrics)

#

# Each rule provides:

# - Clear explanation of the data type

# - Framework-specific implementation (Next.js, Remix, Node.js)

# - Both React hooks and raw query examples

# - Common filtering patterns with type information

# - Error handling and optimization guidance

#

# Note: These rules won't conflict with existing rules as they only

# activate when specifically asking about Intuition data querying.

# =================================================================

# Framework Detection Rules

when user asks about "querying intuition data" or "using @0xintuition/graphql" or "fetch intuition data" or "get data from intuition" or "how to use intuition graphql" or "how to query intuition" or "get intuition data" or "retrieve intuition data" or "access intuition data" or "work with intuition data" or "intuition graphql queries" or "intuition api" or "intuition graphql api":
suggest "I'll help you query Intuition data. First, I need to know what framework you're using to provide the most appropriate implementation. The implementation will differ based on whether you're using:

- Next.js (React with server-side rendering)
- Remix (React with server-side rendering and loaders)
- Express/Node.js (Server-side only with raw queries)

Each framework has its own optimal patterns for data fetching, error handling, and state management."
ask "What framework are you using? (Next.js, Remix, Express/Node.js)"
remember framework_type as response

# Framework-Specific Setup Rules

when framework_type is "Next.js":
suggest "For Next.js apps, you'll want to use the React Query hooks with prefetching in your pages. This approach ensures optimal data loading and SEO."
show example "```typescript
// In your page:
import { dehydrate, QueryClient } from '@tanstack/react-query';
import { useGetPositions, fetcher, GetPositionsDocument } from '@0xintuition/graphql';

// Types for better type safety
interface PageProps {
dehydratedState: unknown;
}

interface QueryParams {
limit: number;
offset: number;
orderBy?: Array<{ [key: string]: 'asc' | 'desc' }>;
}

// Server-side prefetching
export async function getServerSideProps() {
const queryClient = new QueryClient();

// Define query parameters
const queryParams: QueryParams = {
limit: 10,
offset: 0,
orderBy: [{ created_at: 'desc' }]
};

// Prefetch data
await queryClient.prefetchQuery({
queryKey: ['get-positions', queryParams],
queryFn: () => fetcher(GetPositionsDocument, queryParams)()
});

return {
props: {
dehydratedState: dehydrate(queryClient)
}
};
}

// In your component:
export default function YourComponent() {
// Use the hook with proper typing
const { data, isLoading, error } = useGetPositions({
variables: {
limit: 10,
offset: 0
}
});

// Handle loading state
if (isLoading) return <div>Loading...</div>;

// Handle error state
if (error) return <div>Error: {error.message}</div>;

// Render data
return (

<div>
{data?.positions.map(position => (
<div key={position.id}>
{/_ Position details _/}
</div>
))}
</div>
);
}```"

when framework_type is "Remix":
suggest "For Remix apps, you can use React Query with our loader pattern for prefetching. This approach provides optimal server-side rendering and hydration."
show example "```typescript
import { json, type LoaderFunctionArgs } from '@remix-run/node';
import { useLoaderData, useRouteError, isRouteErrorResponse } from '@remix-run/react';
import { QueryClient, dehydrate } from '@tanstack/react-query';
import { useGetPositions, fetcher, GetPositionsDocument } from '@0xintuition/graphql';

// Types for better type safety
interface QueryParams {
limit: number;
offset: number;
orderBy?: Array<{ [key: string]: 'asc' | 'desc' }>;
}

interface LoaderData {
dehydratedState: unknown;
initialParams: QueryParams;
}

// Loader with error handling
export async function loader({ request }: LoaderFunctionArgs) {
try {
const queryClient = new QueryClient();

    // Define query parameters
    const queryParams: QueryParams = {
      limit: 10,
      offset: 0,
      orderBy: [{ created_at: 'desc' }]
    };

    // Prefetch data
    await queryClient.prefetchQuery({
      queryKey: ['get-positions', queryParams],
      queryFn: () => fetcher(GetPositionsDocument, queryParams)()
    });

    return json<LoaderData>({
      dehydratedState: dehydrate(queryClient),
      initialParams: queryParams
    });

} catch (error) {
throw json(
{ message: 'Failed to load positions' },
{ status: 500 }
);
}
}

// Error boundary component
export function ErrorBoundary() {
const error = useRouteError();

if (isRouteErrorResponse(error)) {
return (

<div>
<h1>Error {error.status}</h1>
<p>{error.data.message}</p>
</div>
);
}

return (

<div>
<h1>Error</h1>
<p>An unexpected error occurred</p>
</div>
);
}

// Main component with proper typing
export default function YourComponent() {
const { initialParams } = useLoaderData<typeof loader>();

const { data, isLoading, error } = useGetPositions({
variables: initialParams
});

// Handle loading state
if (isLoading) return <div>Loading...</div>;

// Handle error state
if (error) return <div>Error: {error.message}</div>;

// Render data
return (

<div>
{data?.positions.map(position => (
<div key={position.id}>
{/_ Position details _/}
</div>
))}
</div>
);
}```"

when framework_type is "Express" or framework_type is "Node.js":
suggest "For server-side Node.js applications, you'll want to use the raw GraphQL queries. Here's how to set up type-safe queries with error handling:"
show example "```typescript
import { createServerClient, GetClaimsByAddress, type GetClaimsByAddressQuery, type GetClaimsByAddressQueryVariables } from '@0xintuition/graphql';
import { GraphQLError } from 'graphql';

// Execute query with type safety
const data = await graphQLClient.request<GetPositionsQuery, GetPositionsQueryVariables>(
  GetClaimsByAddress,
  queryParams
);
console.log(data)

// Types for better error handling
interface GraphQLErrorResponse {
message: string;
locations?: { line: number; column: number }[];
path?: string[];
}

// Helper to handle GraphQL errors
function handleGraphQLError(error: unknown) {
if (error instanceof GraphQLError) {
console.error('GraphQL Error:', error.message);
return { error: error.message };
}
if (error instanceof Error) {
console.error('Network/Runtime Error:', error.message);
return { error: 'An unexpected error occurred' };
}
return { error: 'Unknown error occurred' };
}

// Example Express route handler with error handling
app.get('/positions', async (req, res) => {
try {
// Type-safe query parameters
const queryParams: GetPositionsQueryVariables = {
limit: Number(req.query.limit) || 10,
offset: Number(req.query.offset) || 0,
orderBy: [{ created_at: 'desc' }],
where: req.query.accountId ? {
account: {
id: { \_eq: req.query.accountId }
}
} : undefined
};

    // Execute query with type safety
    const data = await graphQLClient.request<GetPositionsQuery, GetPositionsQueryVariables>(
      GetPositionsDocument,
      queryParams
    );

    // Return successful response
    return res.json({
      success: true,
      data: data.positions,
      total: data.total?.aggregate?.count || 0
    });

} catch (error) {
// Handle different types of errors
const errorResponse = handleGraphQLError(error);
return res.status(500).json({
success: false,
...errorResponse
});
}
});```"

# Query Type Rules

when user asks about "positions" or "getting positions" or "query positions" or "fetch positions" or "position data" or "position queries" or "holdings" or "get holdings" or "find positions" or "search positions" or "list positions" or "position details" or "position information" or "get account positions" or "fetch account holdings" or "vault positions" or "account holdings" or "wallet positions" or "wallet holdings" or "position balance" or "holding balance" or "position amount" or "holding amount" or "position ownership" or "holding ownership" or "who owns" or "ownership details" or "vault ownership" or "atom holdings" or "triple holdings":
suggest "Positions represent holdings in atoms or triples. They are the core data structure that:

- Links accounts to vaults (either atom vaults or triple vaults)
- Contains share amounts showing ownership levels
- Tracks creation and modification timestamps
- Provides relationships to the underlying atoms or triples

Available Queries:

1. Basic Position Queries:
   - GetPositions: Paginated list with total shares
   - GetPosition: Single position by ID
   - GetPositionsCount: Just the counts and sums
   - GetPositionsCountByType: Counts separated by atom/triple type

2. Advanced Position Queries:
   - GetPositionsWithAggregates: Combined data with aggregates
   - GetTriplePositionsByAddress: Specialized triple position lookup

Common Parameters:
- limit: Number of results (pagination)
- offset: Starting point (pagination)
- orderBy: Sort order (e.g., [{ created_at: 'desc' }])
- where: Filter conditions
- address: Account address (MUST be lowercase)

IMPORTANT: Any address parameter MUST be lowercase. The GraphQL API will not match addresses with uppercase characters.

Would you like to use React hooks (for Next.js/Remix) or raw queries (for Node.js/server-side)?"

when user asks about "atoms" or "getting atoms" or "query atoms" or "fetch atoms" or "atom data" or "atom queries" or "entities" or "get entities" or "find atoms" or "search atoms" or "list atoms" or "atom details" or "atom information" or "get atom by id" or "fetch atom details" or "atom relationships" or "atom metadata" or "atom properties" or "atom search" or "find entities" or "entity search" or "search entities" or "find items" or "search items" or "get items" or "fetch items" or "item details" or "entity details" or "atom label" or "entity label" or "atom name" or "entity name" or "atom creator" or "entity creator" or "created atoms" or "created entities" or "atom image" or "entity image":
suggest "Atoms are the foundational entities in Intuition that can be connected through relationships (triples). They have:

Properties:
- Unique identifier
- Label (display name)
- Optional image URL
- Creation timestamp
- Creator information (with lowercase address)
- Type and metadata

Available Queries:

1. Basic Atom Queries:
   - GetAtoms: Paginated list with basic metadata
   - GetAtom: Single atom by ID
   - GetAtomsCount: Just the counts

2. Advanced Atom Queries:
   - GetAtomsWithPositions: Includes position data for an address
   - GetAtomsWithAggregates: Combined data with aggregates
   - GetAtomTriplesWithPositions: Related triples with position data

Common Parameters:
- limit: Number of results (pagination)
- offset: Starting point (pagination)
- orderBy: Sort order (e.g., [{ created_at: 'desc' }])
- where: Filter conditions
- address: Account address for position data (MUST be lowercase)

IMPORTANT: Any address parameter MUST be lowercase. The GraphQL API will not match addresses with uppercase characters.

Would you like to use React hooks (for Next.js/Remix) or raw queries (for Node.js/server-side)?"

when user asks about "triples" or "getting triples" or "query triples" or "fetch triples" or "triple data" or "triple queries" or "relationships" or "get relationships" or "find triples" or "search triples" or "list triples" or "triple details" or "triple information" or "get triple by id" or "fetch triple details" or "triple relationships" or "triple metadata" or "triple properties" or "triple search" or "find relationships" or "relationship search" or "semantic relationships" or "atom connections" or "entity relationships" or "connection details" or "relationship details" or "relationship type" or "connection type" or "relationship metadata" or "connection metadata" or "subject object pairs" or "subject predicate object" or "relationship direction" or "connection direction" or "relationship structure" or "semantic structure" or "semantic link" or "semantic connection":
suggest "Triples are semantic relationships between atoms, following a Subject -> Predicate -> Object structure. They provide:

Structure:
- Subject (the atom doing something)
- Predicate (the action or relationship type)
- Object (the target of the action/relationship)
- Creator information (with lowercase address)

Properties:
- Unique identifier
- Creation timestamp
- Two vaults (main and counter) for positions
- Metadata and relationship context

Available Queries:

1. Basic Triple Queries:
   - GetTriples: Paginated list with basic metadata
   - GetTriple: Single triple by ID
   - GetTriplesCount: Just the counts

2. Advanced Triple Queries:
   - GetTriplesWithPositions: Includes position data for an address
   - GetTriplesWithAggregates: Combined data with aggregates
   - GetTriplePositionsByAddress: Detailed position information

Common Parameters:
- limit: Number of results (pagination)
- offset: Starting point (pagination)
- orderBy: Sort order (e.g., [{ created_at: 'desc' }])
- where: Filter conditions
- address: Account address for position data (MUST be lowercase)

IMPORTANT: Any address parameter MUST be lowercase. The GraphQL API will not match addresses with uppercase characters.

Would you like to use React hooks (for Next.js/Remix) or raw queries (for Node.js/server-side)?"

when user asks about "events" or "getting events" or "query events" or "fetch events" or "event data" or "event queries" or "activities" or "get activities" or "find events" or "search events" or "list events" or "event details" or "event information" or "get event by id" or "fetch event details" or "event history" or "activity history" or "transaction history" or "on-chain events" or "protocol events" or "user activity" or "account activity" or "recent events" or "latest events" or "event timeline" or "activity timeline" or "transaction timeline" or "event log" or "activity log" or "transaction log" or "event type" or "activity type" or "transaction type" or "event filter" or "activity filter" or "transaction filter":
suggest "Events track on-chain activities in Intuition. They represent:

Types of Events:
- Mints (new atom/triple creation)
- Transfers (position transfers)
- Protocol actions (system events)
- Deposits and redemptions

Properties:
- Event type
- Block timestamp and number
- Transaction hash
- From/to addresses (MUST be lowercase)
- Additional metadata
- Related atom or triple data

Available Queries:

1. Basic Event Queries:
   - GetEvents: Paginated list with position data
   - GetEventsCount: Just the counts
   - GetEventsData: Specialized data query

2. Advanced Event Queries:
   - GetEventsWithAggregates: Combined data with aggregates
   - GetDebugEvents: Detailed event information with positions

Common Parameters:
- limit: Number of results (pagination)
- offset: Starting point (pagination)
- orderBy: Sort order (e.g., [{ block_timestamp: 'desc' }])
- where: Filter conditions
- addresses: Array of account addresses (MUST be lowercase)

IMPORTANT: Any address parameter MUST be lowercase. The GraphQL API will not match addresses with uppercase characters.

Would you like to use React hooks (for Next.js/Remix) or raw queries (for Node.js/server-side)?"

when user asks about "connections" or "getting connections" or "query connections" or "fetch connections" or "connection data" or "connection queries" or "social" or "get social" or "find connections" or "search connections" or "list connections" or "connection details" or "connection information" or "get followers" or "get following" or "follower list" or "following list" or "social graph" or "social connections" or "social relationships" or "followers" or "following" or "social network" or "network connections" or "network graph" or "follower count" or "following count" or "social stats" or "network stats" or "connection strength" or "relationship strength" or "social influence" or "network influence":
suggest "Connections represent social relationships between accounts in Intuition. They are built using special predicates and provide:

Structure:

- Following relationships (who follows whom)
- Follower relationships (who is followed by whom)
- Share amounts (strength of connection)

Properties:

- Connection direction
- Share amount
- Timestamp
- Account details

Common Use Cases:

1. Social Graph

   - Get followers
   - Get following
   - Calculate connection strength

2. Discovery

   - Find mutual connections
   - Explore network
   - Suggest connections

3. Analytics
   - Connection counts
   - Network growth
   - Engagement metrics

Would you like to use React hooks (for Next.js/Remix) or raw queries (for Node.js/server-side)?"

when user asks about "stats" or "getting stats" or "query stats" or "fetch stats" or "statistics" or "metrics" or "protocol stats" or "get metrics" or "find stats" or "search stats" or "list stats" or "stat details" or "stat information" or "get statistics" or "fetch metrics" or "analytics" or "protocol metrics" or "user stats" or "account stats" or "position stats" or "usage stats" or "growth stats" or "trend stats" or "historical stats" or "time-based stats" or "aggregate stats" or "summary stats" or "total stats" or "count stats" or "metric trends" or "stat trends" or "usage trends" or "growth trends":
suggest "Stats provide aggregate metrics about the Intuition protocol. They include:

Types of Stats:

- Protocol-wide metrics
- Account-specific stats
- Position-type counts
- Time-based analytics

Properties:

- Total counts
- Aggregate sums
- Growth metrics
- Usage statistics

Common Use Cases:

1. Protocol Overview

   - Total atoms/triples
   - Total positions
   - Active accounts

2. Account Analytics

   - Position counts
   - Creation stats
   - Activity metrics

3. Growth Tracking
   - Time-series data
   - Usage trends
   - Network growth

Would you like to use React hooks (for Next.js/Remix) or raw queries (for Node.js/server-side)?"

# Combined Query Patterns

when user asks about "combining queries" or "multiple queries" or "query combination" or "fetch multiple" or "combined data" or "related data" or "query relationships" or "fetch related" or "connected data" or "data relationships" or "query together" or "fetch together" or "joint queries" or "related queries" or "profile data" or "full profile" or "complete data" or "all data" or "everything about" or "full details" or "complete details" or "related information" or "connected information" or "linked data" or "data connections" or "data links" or "data associations" or "associated data":
suggest "You can combine multiple Intuition queries to fetch related data efficiently. Common patterns include:

1. Entity with Relationships

   - Fetch atom details
   - Get related triples
   - Include positions
     Example use case: Profile page with user's content and connections

2. Social Graph with Activity

   - Get connections
   - Fetch recent events
   - Include position details
     Example use case: Social feed with activity

3. Stats with Details
   - Fetch aggregate stats
   - Get specific entities
   - Include latest activity
     Example use case: Dashboard with metrics and recent activity

Would you like to see examples of combining queries using React hooks or raw queries?"

# Client Configuration Rules

when user asks about "configuring client" or "api url" or "graphql endpoint":
suggest "The GraphQL package comes pre-configured with our production API endpoint, so you typically don't need to configure anything. However, if you need to override the default API URL (for example, for development or testing), you can use configureClient. Make sure to do this at the top level of your application:"
show example "```typescript
// For Remix: in your root.tsx
// For Next.js: in your top-level layout or \_app.tsx
// For Node.js/Express: at the top of your app entry point (e.g., app.ts)

import { configureClient } from '@0xintuition/graphql';

// Only use this if you need to override the default API URL
configureClient({
apiUrl: 'https://your-custom-endpoint.com/graphql'
});

// The default configuration is already set up for production use,
// so you don't need to call configureClient unless you have a specific reason

// Example for Remix root.tsx:
export default function App() {
// Configure client once at the app root
useEffect(() => {
if (process.env.CUSTOM_GRAPHQL_URL) {
configureClient({
apiUrl: process.env.CUSTOM_GRAPHQL_URL
});
}
}, []);

return (

<html>
{/_ Your app content _/}
</html>
);
}

// Example for Next.js \_app.tsx or layout.tsx:
export default function RootLayout({ children }) {
// Configure client once at the app root
useEffect(() => {
if (process.env.CUSTOM_GRAPHQL_URL) {
configureClient({
apiUrl: process.env.CUSTOM_GRAPHQL_URL
});
}
}, []);

return <>{children}</>;
}

// Example for Node.js/Express app.ts:
import express from 'express';
import { configureClient } from '@0xintuition/graphql';

// Configure client at app startup
if (process.env.CUSTOM_GRAPHQL_URL) {
configureClient({
apiUrl: process.env.CUSTOM_GRAPHQL_URL
});
}

const app = express();
// ... rest of your Express app setup```"

# Schema Validation Rules

when user asks about "schema" or "types" or "fields" or "available queries" or "query fields" or "available mutations" or "mutation fields" or "type definitions" or "graphql schema":
suggest "The GraphQL package provides type-safe queries based on the Intuition schema. Here are the key types and fields available:

1. Positions

   - id: ID
   - amount: String
   - created_at: DateTime
   - account: Account
   - vault: Vault

2. Atoms

   - id: ID
   - label: String
   - image_url: String (optional)
   - created_at: DateTime
   - creator: Account

3. Triples

   - id: ID
   - subject: Atom
   - predicate: Atom
   - object: Atom
   - created_at: DateTime
   - creator: Account

4. Events

   - id: ID
   - type: EventType
   - block_timestamp: DateTime
   - block_number: Int
   - transaction_hash: String
   - from_address: String
   - to_address: String

5. Accounts
   - id: ID
   - address: String
   - created_at: DateTime

Would you like to see example queries using these types?"

# Query Validation Rules

when user asks about "query validation" or "type checking" or "schema validation" or "validate query" or "check types":
suggest "To ensure your queries use valid fields from the schema:

1. Use the generated types from @0xintuition/graphql:

   ```typescript
   import {
     GetAtomsQuery,
     GetAtomsQueryVariables,
     GetPositionsQuery,
     GetPositionsQueryVariables,
     // etc...
   } from '@0xintuition/graphql'
   ```

2. Use the provided hooks which are already typed:

   ```typescript
   import {
     useGetAtoms,
     useGetPositions,
     useGetTriples,
     // etc...
   } from '@0xintuition/graphql'
   ```

3. For raw queries, use the provided documents:
   ```typescript
   import {
     GetAtomsDocument,
     GetPositionsDocument,
     GetTriplesDocument,
     // etc...
   } from '@0xintuition/graphql'
   ```

The package provides complete type safety and will show TypeScript errors if you try to access fields that don't exist in the schema."

# Provider Setup Rules

when user asks about "setting up providers" or "react query provider" or "query client provider":
suggest "To use our hooks with React Query, you'll need to set up the QueryClientProvider at the root of your app. Here's how to do it:"
show example "```typescript
// providers.tsx (or .client/providers.tsx for Remix)
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';

// Create a client
const queryClient = new QueryClient({
defaultOptions: {
queries: {
// Default options for all queries
staleTime: 1000 _ 60, // 1 minute
cacheTime: 1000 _ 60 \* 5, // 5 minutes
refetchOnWindowFocus: false,
retry: 1
}
}
});

// For Next.js: In your \_app.tsx or layout.tsx
export default function App({ children }) {
return (
<QueryClientProvider client={queryClient}>
{children}
{process.env.NODE_ENV === 'development' && <ReactQueryDevtools />}
</QueryClientProvider>
);
}

// For Remix: In your root.tsx
import { withReactQuery } from './providers';

// Wrap your app with the provider
export default withReactQuery(
function App() {
return (

<html>
<head>
<Meta />
<Links />
</head>
<body>
<Outlet />
<ScrollRestoration />
<Scripts />
<LiveReload />
</body>
</html>
);
}
);

// providers.tsx helper for Remix
import { useState } from 'react';

export function withReactQuery(Component: React.ComponentType) {
return function WithReactQuery() {
const [queryClient] = useState(
() =>
new QueryClient({
defaultOptions: {
queries: {
staleTime: 1000 _ 60,
cacheTime: 1000 _ 60 \* 5,
refetchOnWindowFocus: false,
retry: 1
}
}
})
);

    return (
      <QueryClientProvider client={queryClient}>
        <Component />
        {process.env.NODE_ENV === 'development' && <ReactQueryDevtools />}
      </QueryClientProvider>
    );

};
}

// For Node.js/Express:
// No provider needed since you'll be using raw document queries```"

# Error Handling Rules

when user mentions "error" or "handling errors":
suggest "Here's how to handle errors with the GraphQL queries:"
show example "```typescript
// Using schema-valid fields
const { data, error, isError } = useGetPositions({
variables: {
where: {
account: {
id: { \_eq: 'account-id' }
}
}
},
onError: (error) => {
// Handle specific error types
if (error.message.includes('not found')) {
console.error('Account not found:', error);
} else if (error.message.includes('unauthorized')) {
console.error('Authorization error:', error);
} else {
console.error('Error fetching positions:', error);
}
}
});

// Type-safe error handling
if (error) {
return <div>Error: {error.message}</div>;
}

// Type-safe data access
return (

  <div>
    {data?.positions.map(position => (
      <div key={position.id}>
        <p>Amount: {position.amount}</p>
        <p>Created: {position.created_at}</p>
      </div>
    ))}
  </div>
);
```"

# Optimization Rules

when user asks about "caching" or "optimizing queries":
suggest "The GraphQL package uses React Query for built-in caching. Here's how to configure it with schema-valid fields:"
show example "```typescript
// Using schema-valid fields
const { data } = useGetAtoms({
variables: {
where: {
label: { \_ilike: '%search%' }
}
},
// Configure caching
staleTime: 1000 _ 60, // Data stays fresh for 1 minute
cacheTime: 1000 _ 60 \* 5, // Cache persists for 5 minutes
// Configure refetching
refetchOnWindowFocus: false,
refetchOnMount: false,
refetchOnReconnect: false
});

// Type-safe data access
return (

  <div>
    {data?.atoms.map(atom => (
      <div key={atom.id}>
        <p>Label: {atom.label}</p>
        {atom.image_url && <img src={atom.image_url} alt={atom.label} />}
        <p>Created: {atom.created_at}</p>
      </div>
    ))}
  </div>
);
```"

# Real-time Updates Rules

when user asks about "real-time" or "live updates":
suggest "You can use React Query's refetch and polling capabilities with schema-valid fields:"
show example "```typescript
// Using schema-valid fields
const { data } = useGetEvents({
variables: {
where: {
block_timestamp: { \_gte: 'timestamp' }
}
},
// Configure polling
refetchInterval: 5000, // Poll every 5 seconds
refetchIntervalInBackground: false // Only poll when tab is focused
});

// Type-safe data access
return (

  <div>
    {data?.events.map(event => (
      <div key={event.id}>
        <p>Type: {event.type}</p>
        <p>Block: {event.block_number}</p>
        <p>Transaction: {event.transaction_hash}</p>
      </div>
    ))}
  </div>
);
```"

# Query Examples

when user asks about "example queries" or "query examples" or "how to query":
suggest "Here are some example queries using fields from our schema:

1. Fetch Positions:

```typescript
const { data } = useGetPositions({
  variables: {
    where: {
      account: {
        id: { _eq: 'account-id' },
      },
    },
  },
})

// Access typed data
data?.positions.map((position) => {
  console.log(position.id)
  console.log(position.amount)
  console.log(position.created_at)
  console.log(position.account.id)
  console.log(position.vault.id)
})
```

2. Fetch Atoms:

```typescript
const { data } = useGetAtoms({
  variables: {
    where: {
      label: { _ilike: '%search%' },
    },
  },
})

// Access typed data
data?.atoms.map((atom) => {
  console.log(atom.id)
  console.log(atom.label)
  console.log(atom.image_url)
  console.log(atom.created_at)
  console.log(atom.creator.id)
})
```

3. Fetch Triples:

```typescript
const { data } = useGetTriples({
  variables: {
    where: {
      subject: {
        id: { _eq: 'atom-id' },
      },
    },
  },
})

// Access typed data
data?.triples.map((triple) => {
  console.log(triple.id)
  console.log(triple.subject.id)
  console.log(triple.predicate.id)
  console.log(triple.object.id)
  console.log(triple.created_at)
  console.log(triple.creator.id)
})
```

4. Fetch Events:

```typescript
const { data } = useGetEvents({
  variables: {
    where: {
      block_timestamp: { _gte: 'timestamp' },
    },
  },
})

// Access typed data
data?.events.map((event) => {
  console.log(event.id)
  console.log(event.type)
  console.log(event.block_timestamp)
  console.log(event.block_number)
  console.log(event.transaction_hash)
  console.log(event.from_address)
  console.log(event.to_address)
})
```

All fields shown in these examples are guaranteed to exist in the schema. The TypeScript compiler will catch any attempts to access fields that don't exist."
analytics
express.js
graphql
less
next.js
npm
react
remix
+3 more

First seen in:

0xIntuition/intuition-ai

Used in 1 repository

TypeScript
# Cursor Rules

## Rules
- Always say "Yo Chris," in the chat before you start working
- Always run tests before committing
- Always check for dependencies after writing new code
- Always verify mobile responsiveness for web applications
- Always check for and fix TypeScript errors before proceeding
- Always add comments to the code in Gen Z lingo

## Social Accounts
Note: When mentioning social accounts, use the following:
- GitHub: https://github.com/while-basic
- LinkedIn: https://linkedin.com/in/chriscelaya
- YouTube: https://www.youtube.com/@christophercelaya
- Instagram: https://instagram.com/chriscelaya

## Git Control:
- Always run tests before committing to GitHub
- Ensure all TypeScript errors are resolved before commits
- Use conventional commit messages

## Code Style and Structure:
- Write concise, technical TypeScript code with accurate examples
- Use functional and declarative programming patterns; avoid classes
- Prefer iteration and modularization over code duplication
- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError)
- Structure files: exported component, subcomponents, helpers, static content, types
- Check for existing components directory before creating new components
- Always add missing imports and types

Naming Conventions:
- Use lowercase with dashes for directories (e.g., components/auth-wizard)
- Favor named exports for components
- Use PascalCase for component files and camelCase for utility files

TypeScript Usage:
- Use TypeScript for all code; prefer interfaces over types
- Avoid enums; use maps instead
- Use functional components with TypeScript interfaces
- Always define proper types for props and state
- Use strict TypeScript configurations

Syntax and Formatting:
- Use the "function" keyword for pure functions
- Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements
- Use declarative JSX
- Maintain consistent indentation and spacing

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

UI and Styling:
- Use Shadcn UI, Radix, and Tailwind Aria for components and styling
- Implement responsive design with Tailwind CSS; use a mobile-first approach
- Ensure all components are fully mobile responsive
- Test on multiple viewport sizes
- Follow accessibility best practices

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 proper code splitting
- Use proper caching strategies

Key Conventions:
- Use 'nuqs' for URL search parameter state management
- Optimize Web Vitals (LCP, CLS, FID)
- Limit 'use client':
  - Favor server components and Next.js SSR
  - Use only for Web API access in small components
  - Avoid for data fetching or state management

Development Workflow:
- Always install dependencies after writing new code
- Check for errors before writing more code
- Ensure all web applications are fully mobile responsive
- Check if a components directory is available before creating new ones
- Add missing imports and types immediately

Follow Next.js docs for Data Fetching, Rendering, and Routing
css
golang
html
javascript
next.js
plpgsql
python
radix-ui
+4 more

First seen in:

while-basic/v1

Used in 1 repository

unknown
## Key Principles

- **Code Quality & Style**
  - Write concise, maintainable, and strongly typed code with accurate TypeScript implementations.
  - Embrace functional, declarative programming. Avoid OOP and classes.
  - Limit files to a maximum of 150 lines; refactor into smaller modules if exceeded.
  - Prefer iteration and modularization over duplication.
  - Use descriptive, semantic variable names with auxiliary verbs (e.g., `isLoading`, `hasError`).
  - Use lowercase with dashes for directories and files (e.g., `components/auth-wizard`).
  - Favor named exports for components.
  - Adopt RORO (Receive an Object, Return an Object) for function parameters/returns.
  - Always attain to use DRY (Don't Repeat Yourself) principles.
  - Conduct regular code reviews and frequent refactoring sessions to ensure consistency and quality.
  - Check and improve Web Vitals (LCP, CLS, FID) to maintain performance and user experience.

- **Create 'Build Notes':**
  - You must create a 'Build Notes' file for each task group to track the progress of the task group we work on.
  - **Clarity & Brevity:** Keep notes concise, direct, and focused on the task at hand.  
  - **Logical Naming:** Use a consistent naming convention that ties each notes file to a specific task and date.  
  - **Incremental Updates:** Update notes as plans evolve or tasks are completed. Append rather than overwrite.  
  - **Traceability:** Ensure that each decision or change in approach is recorded and easy to follow.

- **Review 'Project Contexts':**
  - You must review the `projectContext.md` as we need to ensure that the project context is up to date and accurate.
  - **Stability:** Treat context files as stable references, not daily scratchpads.  
  - **Selective Updates:** Update context files only when there are significant, approved changes to requirements or project scope.  
  - **Accessibility:** Make context files easily understandable and organized so future developers can quickly grasp the project’s core guidance.

- **Stack and Framework Conventions**
  - Target **Next.js 15+** and leverage the App Router, React Server Components (RSC), and SSR capabilities.
  - Use Zustand for state management in client components when necessary.
  - Maintain proper Shadcn UI management using `npx shadcn@latest add` for new components.
  - Follow a mobile-first approach and responsive design patterns.
  - Emphasize server-side logic, minimizing the usage of `use client` and other client-only APIs.
  - Structure project as Progressive Web App (PWA) with offline capabilities, app-like experience, and installability across devices.

- **Monorepo & Tooling**
  - If using a monorepo structure, place shared code in a `packages/` directory and app-specific code in `app/`.
  - Use `Taskfile.yml` commands for development, testing, and deployment tasks.
  - Keep environment variables and sensitive data outside of code and access them through `.env` files or similar configuration.

Below is a structured guideline to provide to the AI development agent, incorporating key principles and detailed rules for maintaining the `/ProjectDocs/Build_Notes/` and `/ProjectDocs/contexts/` directories.

---

### Rules for Build Notes Files

1. **Location & Naming:**  
   - Store all notes files in `/ProjectDocs/Build_Notes/`.  
   - Use a logical, descriptive naming convention, e.g., `build-title_phase-#_task-group-name.md`.
   - Use the `<build-title>` to describe the build task.
   - Use the `<phase-#>` to apply the Phase # to the build task.
   - Use the `<task-group-name>` to describe the task group name.
   - Example: `supabase-schema-standardization_phase-1_preparation-and-code-analysis.md`
       - `supabase-schema-standardization` is the build title
       - `phase-1` is the phase number
       - `preparation-and-code-analysis` is the task group name

2. **Content Structure:**  
   - Begin with a brief **Task Objective** that summarizes what you aim to achieve.  
   - Provide **Current State Assessment**: a short description of the current state of the project pertaining to the build tasks.
   - Provide **Future State Goal**: a short description of the future state of the project pertaining to the build tasks.
   - Follow with a **Implementation Plan**: a numbered list of **steps** containing checklist **tasks** to achieve the future state.
   - Update the **Implementation Plan** as tasks are completed and line out not applicable tasks. NEVER DELETE TASKS FROM THE PLAN.
   - If the plan changes or evolves, add new **steps** or **tasks**, rather than overwriting previous content.

3. **When to Update:**  
   - **At Task Start:** Create or open the task-specific notes file and record the initial plan before coding.  
   - **During Task Execution:** Add updates when plans change, difficulties arise, or new insights emerge.  
   - **At Task Completion:** Append a summary of what was done and verify it aligns with the original objective.

4. **Style & Tone:**  
   - Keep notes succinct, on-topic, and free of unrelated commentary.  
   - Maintain a logical sequence so that future readers can understand the decision-making process without confusion.

5. **Completion of Build Notes:**
   - Once the build notes are complete, move the file to the `/ProjectDocs/Build_Notes/completed/` directory.
   - If build notes are deprecated and no longer needed, move the file to the `/ProjectDocs/Build_Notes/archived/` directory.

---

### Rules for Context Files

1. **Master Project Context (`projectContext.md`):**  
   - Located in `/ProjectDocs/contexts/`.  
   - Provides the overarching project scope, requirements, and design principles.  
   - Only update this file if there are major changes to the project’s fundamental direction or scope.

2. **Additional Context Files:**  
   - Supplementary files (e.g., `uiContext.md`, `featureAContext.md`) may be created for more detailed specifications on certain functionalities, designs, or areas of the application.  
   - Keep these files stable. Update them only when new, approved changes need to be documented.  
   - Reference these files frequently to ensure development aligns with established guidelines.

3. **Change Management:**  
   - Record any changes to context files within the corresponding build notes file for that task.  
   - Maintain a clear rationale for context changes to preserve transparency and alignment with the core project goals.

---

## Project Structure

Adopt a clear, modular directory structure:

```
├── app/
│   ├── (auth)/           # Auth-related routes/pages
│   ├── (dashboard)/      # Dashboard routes/pages
│   ├── api/              # API routes
│   └── layout.tsx        # Root layout
├── components/
│   ├── shared/           # Shared, reusable UI components
│   │   ├── buttons/
│   │   ├── forms/
│   │   └── layout/
│   ├── features/         # Feature-specific components
│   │   ├── auth/
│   │   └── dashboard/
│   └── ui/               # Shadcn UI components
├── lib/
│   ├── supabase/         # Supabase client and utilities
│   │   ├── current/      # Current schema and types
│   │   └── domain/       # Domain-specific schema and types
│   │       ├── user/       # User domain schema and types
│   │       │   ├── index.ts    # Exports all supabase utilities
│   │       │   ├── queries.ts  # Supabase queries
│   │       │   ├── services.ts # Supabase services
│   │       │   └── types.ts    # Supabase types
│   │       ├── roles/        # Roles domain schema and types
│   │       └── ...            # Add more domains as needed
│   ├── constants/        # Global constants and configuration
│   │   ├── auth/         # Authentication constants
│   │   └── ui/           # UI constants
│   ├── hooks/            # Custom React hooks
│   │   ├── useAuth/      # Authentication hooks
│   │   └── useUI/         # UI hooks
│   ├── middleware/       # Custom middleware
│   │   ├── auth/         # Authentication middleware
│   │   ├── rbac/         # Role-based access control middleware
│   │   └── ui/           # UI middleware
│   └── utils/            # Shared utility functions
├── public/               # Static assets
├── services/             # Business logic and data-fetching services
├── types/                # Global TypeScript types and interfaces
└── config/               # Configuration files (env, tailwind, etc.)
```

**Naming & Organization:**
- Use semantic, descriptive names.
- Keep file names lowercase with dashes.
- Use `feature/`, `bugfix/`, `hotfix/`, `refactor/`, `docs/` prefixes for branches.
- Export from `index.ts` files in feature directories for cleaner imports.

---

## JavaScript/TypeScript Standards

- Use TypeScript everywhere. Prefer `interface` for public-facing contracts.
- Use `function` keyword for defining components and pure functions (avoid arrow functions for components).
- Omit semicolons for a cleaner look.
- Maintain a logical file order:
  1. Exported component
  2. Subcomponents
  3. Helpers/internal utilities
  4. Static content/constants
  5. Types and interfaces at the bottom
- Write concise conditionals:
  - Avoid unnecessary braces in single-line conditionals.
  - Use early returns to handle edge cases and errors upfront.
- Model expected errors as return values instead of using exceptions in server actions.

Example:

```typescript
function formatInput({ input }: { input: string }) {
  if (!input) return null
  return input.trim()
}
```

---

## Error Handling, Validation, and Services

- Handle errors at the start of functions with guard clauses and early returns.
- Keep the “happy path” visible at the bottom of the function.
- Avoid `else` statements by using if-return patterns to reduce nesting.
- Use Zod for schema validation and form validation.
- Use `react-hook-form` with `useActionState` to manage form state and submission flows.
- In `services/` directories, always throw user-friendly errors that can be caught upstream and displayed to the user.
- Implement proper error logging and user-friendly messages.
- Employ error boundaries (`error.tsx`, `global-error.tsx`) for unexpected errors.
- Use `next-safe-action` for secure and type-safe server actions.

---

## AI Integration

- Use the Vercel AI SDK UI and Core to implement streaming chat and AI-driven features.
- Handle rate limiting, quota, and model availability gracefully.
- Implement fallback logic if AI models are unavailable.
- Sanitize user inputs before sending them to the AI.
- Store API keys and sensitive information in environment variables.
- Provide clear, user-friendly error messages in case of AI service failures.

---

## React/Next.js Component Development

- **Functional Components**: Use function declarations and TypeScript interfaces for props.
- **Minimal Props & Composition**: Keep components small, focused, and composed of reusable subcomponents.
- **Server Components First**: Prefer React Server Components and SSR data fetching to minimize client overhead.
- **Zustand for State**: Use Zustand for complex local state if necessary, ensuring minimal `use client` usage.
- **Client Components**: Only use `use client` for components that require browser APIs or local user interaction.
- **Responsive Design**: Use Tailwind CSS utility classes, with a mobile-first approach.
- **UI Libraries**: Use Shadcn UI and Radix UI for base components and interactions.
- **Static Content & Types**: Place static text, constants, and types at the end of each file.
- **Dynamic Loading**: Dynamically import non-critical components to improve initial load times.
- **Optimize Images**: Use WebP format, appropriate sizing, and lazy loading for images.

---

## Supabase, Database, and GraphQL

- **Schema Management**: Keep `schema.sql` updated regularly with the latest schema changes.
- **Types Management**: Keep `database.types.ts` updated regularly with the latest schema changes.
- **Migrations**: Use Supabase CLI for local development and database migrations. Test all changes before staging/production.
- **RLS & RBAC**: Implement Row Level Security and role-based access control. Assign default roles in `handle_new_user` functions.
- **CRUD-based Policies**: Follow INSERT, UPDATE, SELECT, DELETE policies and document them.
- **Enum Tables**: Use enum tables for predefined values.
- **Relationships**: Document all table relationships and data flows.
- **Genql**: Use Genql for type-safe GraphQL queries against Supabase. Fetch only necessary data.

Example user creation:

```typescript
async function handleNewUser({ userId, email }: { userId: string; email: string }) {
  const defaultRole = await getDefaultRole()
  await supabase.from('profiles').insert({
    id: userId,
    email,
    role_id: defaultRole.id,
    created_at: new Date().toISOString(),
  })
}
```

---

## Version Control and Workflow

- **Branch Naming**: `feature/`, `bugfix/`, `hotfix/`, `refactor/`, `docs/`.
- **Commit Messages**: Use `type(scope): description` format. Common types: `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore`.
- **Pull Requests**: Use PR templates with a summary, change type, testing steps, and any database changes noted.
- **Schema Updates**: Update `schema.sql` and commit the changes after each migration.
- **Testing Before PR**: Always test changes locally before submitting PRs.

---

## Data Fetching and State Management

- **RSC for Data**: Use React Server Components for data fetching whenever possible.
- **Preload Pattern**: Implement preload patterns to avoid waterfall requests.
- **Supabase for Real-Time**: Use Supabase subscriptions for real-time data and SSR-friendly data access.
- **Zustand**: Manage local state in isolated client components when needed.
- **Vercel KV**: Use Vercel KV for chat history, rate limiting, and ephemeral storage.
- **SSR & Minimize ‘use client’**: Prefer SSR and server actions. Only use `use client` for browser-based interactions.

---

## Testing and Quality Assurance

- **Unit Tests**: Write unit tests for utilities, hooks, and business logic.
- **Integration Tests**: Test complex components, pages, and features in isolation.
- **End-to-End Tests**: Validate critical flows (login, checkout) end-to-end.
- **Local DB Testing**: Use Supabase local development for realistic database tests.
- **Coverage**: Maintain a minimum test coverage threshold for PR merges.

---

## Styling and Accessibility

- **Tailwind CSS**: Use utility classes with a mobile-first responsive approach.
- **CVA for Variants**: Employ Class Variance Authority for component variants and theme consistency.
- **Radix UI**: Utilize Radix primitives for accessible UI patterns.
- **ARIA & WCAG**: Ensure proper ARIA labels, roles, and adhere to WCAG guidelines for color contrast and keyboard navigation.
- **Shadcn UI**: Leverage shadcn UI components for design consistency and speed.

---

## Documentation

- **Comments & JSDoc**: Comment complex logic and use JSDoc for functions and components.
- **Readmes**: Keep README files updated with setup, instructions, and architectural details.
- **API & DB Docs**: Document all API endpoints, RLS policies, and database schema.
- **Edge Functions**: Document Supabase Edge Functions and their intended usage.
- **Setup Instructions**: Keep environment configuration and setup steps current for onboarding developers.

---

**Remember:**
- Regularly check file sizes; refactor when needed.
- Maintain separation of concerns and modular design.
- Reuse components and keep them composable and testable.
- Always test locally before pushing changes.
- Ensure proper error handling, user-friendly messages, and accessible interfaces.
golang
graphql
java
javascript
nestjs
next.js
radix-ui
react
+6 more

First seen in:

PatrickJS/awesome-cursorrules

Used in 1 repository

TypeScript
You are an expert in TypeScript, Node.js, Next.js App Router, React, Zustand, Supabase, Shadcn UI, Radix UI and Tailwind.
  
Code Style and Structure
  - Write concise, technical TypeScript code with accurate examples.
  - Use functional and declarative programming patterns; avoid classes.
  - Prefer iteration and modularization over code duplication.
  - Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
  - Structure files: exported component, subcomponents, helpers, static content, types.
  
Naming Conventions
  - Use lowercase with dashes for directories (e.g., components/auth-wizard).
  - Favor named exports for components.
  
TypeScript Usage
  - Use TypeScript for all code; prefer interfaces over types.
  - Avoid enums; use maps instead.
  - Use functional components with TypeScript interfaces.
  
Syntax and Formatting
  - Use the "function" keyword for pure functions.
  - Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements.
  - Use declarative JSX.
  
UI and Styling
  - Use Shadcn UI, Radix, and Tailwind for components and styling.
  - Implement responsive design with Tailwind CSS; use a mobile-first approach.
  
Performance Optimization
  - Minimize 'use client', 'useEffect', and 'setState'; favor React Server Components (RSC).
  - Wrap client components in Suspense with fallback.
  - Use dynamic loading for non-critical components.
  - Optimize images: use WebP format, include size data, implement lazy loading.

Next.js Specifics
  - Implement type-safe server actions with proper validation.
  - Define input schemas using Zod for robust type checking and validation.
  - Handle errors gracefully and return appropriate responses.

Additional Rules
  - Implement proper metadata for SEO
  - Utilize Next.js Image component for optimized image handling

Key Conventions
  - Optimize Web Vitals (LCP, CLS, FID).
  - Limit 'use client':
  - Favor server components and Next.js SSR.
  - Use only for Web API access in small components.
  - Avoid for data fetching or state management.
  
Follow Next.js docs for Data Fetching, Rendering, and Routing.
css
javascript
mdx
next.js
radix-ui
react
shadcn/ui
supabase
+3 more

First seen in:

alessiotortora/cms12

Used in 1 repository

TypeScript
You are a Senior Front-End Developer and an expert in ReactJS, NextJS, JavaScript, TypeScript, HTML, CSS, and modern UI/UX frameworks (e.g., TailwindCSS, Shadcn). You are thoughtful, provide nuanced answers, and excel at reasoning. Your responses are always accurate, factual, and detailed.

General Coding Guidelines:

1. Always use functional React components.

2. For styling, use TailwindCSS with cva. For example, the className for the root div will be className={cvaRoot()}, and the corresponding styles will be defined in another file as follows:

```ts
import { cva } from 'cva';

export const cvaRoot = cva({
  base: [
    'ExampleComponentStyles-cvaRoot',
    ''
  ]
});
```
Group tailwind classes into logical categories, for example: Layout, Background, Spacing, Flexbox, Typography, States, Transitions, etc.

3. When I ask you to create a component, always organize files and folders as follows:
-	Folders: ui, model, lib.
-	Files:
  -	/ui/ComponentName.tsx
  -	/ui/ComponentNameStyles.ts
  -	/model/types.ts

4. For widgets, place the component in src/widgets/. For shared components, use src/shared/ui/. For entities, use src/entities/.

5. Files templates:
- ComponentName.tsx:
```tsx
import { FC } from 'react';
import { cvaRoot } from './ComponentNameStyles';
import { IComponentNameProps } from '../model/types';

const ComponentName: FC<IComponentNameProps> = () => {
  return (
    <div className={cvaRoot()}>
      
    </div>
  );
};

export default ComponentName;
```

- ComponentNameStyles.ts:
```ts
import { cva } from 'cva';

export const cvaRoot = cva({
  base: [
    'ComponentNameStyles-cvaRoot',
    ''
  ]
});
```

- types.ts:
```ts
export interface IComponentNameProps {}
```

6. If the request involves creating a component from the terminal, generate only empty files without any templates.

7. Always use the Next.js Image component instead of the default <img> tag.

8. Never use inline Tailwind classes or string-based inline classNames. Always define and use cvaClassName().

9. NEVER USE INLINE TAILWIND STYLES.
css
golang
java
javascript
next.js
react
shadcn/ui
shell
+2 more
SerafimKremnev/scrum-board

Used in 1 repository

TypeScript
You are an expert in Vue.js, Vue Test Utils, TanStack Query, JavaScript, TypeScript, HTML, CSS, and SCSS.

When responding to questions, follow the Chain of Thought method. First, outline a detailed pseudocode plan step by step,
then confirm it, and proceed to write the code.

Key Coding Principles:
- simplicity.
- readability.
- performance.
- maintainability.
- testability.
- reusability.

Variables:
- use descriptive variable and function/const names, and prefix event functions with "handle" (e.g. "handleClick" for onClick and "handleKeyDown" for onKeyDown).
- import and use COPY objects instead of string literals (e.g. FINANCES_COPY).

Functions:
- prefer early returns to minimize nesting.

Imports:
- use absolute imports. Don't use relative imports.
- sort imports under "// External" and "// Internal" sections.
- internal imports should be ordered as follows: components, constants, types, services, utils, testing-related.
- add a newline between import sections.
- when importing types, include the type keyword in the parentheses (e.g. import { type MyType } from 'path').

Syntax:
- prefer the "function" keyword over 'const' function expressions.

Accessibility:
- ensure HTML elements and components are accessible.

Tests:
- use "getMountComponent" in test spec files instead of "mount". "getMountComponent" is available globally and doesn't need to be imported.
- use "test" instead of "it".
- do not begin tests with "should".

Your responses should focus on providing correct, best practice, DRY principle (Don't Repeat Yourself), bug-free, fully functional, and working code aligned with the listed rules above.
Prioritize easy and readable code over performance and fully implement all requested functionality.
Ensure that the code is complete and thoroughly verified, including all required imports and proper naming of key components.
c#
express.js
html
java
javascript
makefile
nestjs
scss
+4 more

First seen in:

Philosocode/okane

Used in 1 repository

TypeScript
{
  "rules": [
    {
      "description": "Mantener contexto de lo ya propuesto y evitar repeticiones.",
      "action": "track_previous_proposals",
      "criteria": ["review_conversation_history", "validate_against_previous_responses"],
      "output": "avoid_duplicate_suggestions",
      "confirmationMessage": "Esta sugerencia actual no se ha propuesto antes en nuestra conversación histórica."
    },
    {
      "description": "Responder siempre en español, pero escribir todo el código y comentarios en inglés.",
      "action": "enforce_language_rules",
      "responseLanguage": "es",
      "codeLanguage": "en"
    },
    {
      "description": "Incluir console logs para la mayoría de las tareas.",
      "action": "insert_console_logs",
      "criteria": ["log_major_tasks"],
      "output": "include_logs"
    },
    {
      "description": "Modificar el código lo menos posible y avanzar paso a paso.",
      "action": "minimize_code_changes",
      "criteria": ["preserve_existing_code", "step_by_step_modifications"]
    },
    {
      "description": "Actuar como un diseñador senior de extensiones para Visual Studio Code.",
      "action": "apply_senior_practices",
      "criteria": ["use_best_practices", "recommend_design_patterns"]
    },
    {
      "description": "Indicar paso a paso qué propone y qué entendió de lo solicitado.",
      "action": "provide_step_by_step_plan",
      "criteria": ["confirm_understanding", "propose_step_by_step"]
    },
    {
      "description": "Explicar detalladamente la lógica detrás de cada propuesta.",
      "action": "explain_logic_in_detail",
      "criteria": ["include_detailed_explanations"]
    },
    {
      "description": "Intentar verificar si el código tiene errores utilizando ESLint.",
      "action": "check_code_with_eslint",
      "criteria": ["validate_code_with_eslint"]
    },
    {
      "description": "Generar reglas de parseo de manera acumulativa y casos sobre casos para no perder posibles opciones.",
      "action": "generate_cumulative_parsing_rules",
      "criteria": ["build_on_existing_cases", "preserve_previous_cases"]
    },
    {
      "description": "Evitar sugerencias genéricas y alinear con el código existente.",
      "action": "avoid_generic_suggestions",
      "criteria": ["align_with_existing_code"]
    },
    {
      "description": "Proveer código completo y detallado, evitando el tipo 'any' en TypeScript.",
      "action": "enforce_strong_typing",
      "criteria": ["no_any_type"],
      "output": "detailed_and_complete_code"
    },
    {
      "description": "Leer y validar el código base antes de proponer sugerencias.",
      "action": "validate_codebase_before_suggestions",
      "criteria": ["review_codebase", "ensure_context_alignment"]
    },
    {
      "description": "Asegurar alineación con el stack tecnológico del proyecto.",
      "action": "ensure_stack_alignment",
      "criteria": [
        "Vercel",
        "Next.js 14",
        "TypeScript",
        "Drizzle ORM",
        "Supabase",
        "NextAuth V5",
        "Turborepo",
        "Shadcn/ui",
        "Sentry",
        "PostHog",
        "Tailwind CSS",
        "Resend",
        "React Email",
        "React",
        "Zod",
        "ESLint and Prettier",
        "pnpm"
      ]
    },
    {
      "description": "Proveer código concreto en lugar de bloques con numeración.",
      "action": "provide_concrete_code",
      "criteria": ["avoid_line_number_references"]
    }
  ]
}
drizzle-orm
eslint
golang
javascript
next.js
nextauth
npm
pnpm
+8 more
danilopezmella/pestd3code

Used in 1 repository

Shell
{
  "rules": [
    {
      "name": "Verify Information",
      "pattern": "(?i)\\b(assume|assumption|guess|speculate)\\b",
      "message": "Always verify information before presenting it. Do not make assumptions or speculate without clear evidence."
    },
    {
      "name": "File-by-File Changes",
      "pattern": "// MULTI-FILE CHANGE:",
      "message": "Make changes file by file and give me a chance to spot mistakes"
    },
    {
      "name": "No Apologies",
      "pattern": "(?i)\\b(sorry|apologize|apologies)\\b",
      "message": "Never use apologies"
    },
    {
      "name": "No Understanding Feedback",
      "pattern": "(?i)\\b(understand|understood|got it)\\b",
      "message": "Avoid giving feedback about understanding in comments or documentation"
    },
    {
      "name": "No Whitespace Suggestions",
      "pattern": "(?i)\\b(whitespace|indentation|spacing)\\b",
      "message": "Don't suggest whitespace changes"
    },
    {
      "name": "No Summaries",
      "pattern": "(?i)\\b(summary|summarize|overview)\\b",
      "message": "Don't summarize changes made"
    },
    {
      "name": "No Inventions",
      "pattern": "(?i)\\b(suggest|recommendation|propose)\\b",
      "message": "Don't invent changes other than what's explicitly requested"
    },
    {
      "name": "No Unnecessary Confirmations",
      "pattern": "(?i)\\b(make sure|confirm|verify|check)\\b",
      "message": "Don't ask for confirmation of information already provided in the context"
    },
    {
      "name": "Preserve Existing Code",
      "pattern": "(?i)\\b(remove|delete|eliminate|destroy)\\b",
      "message": "Don't remove unrelated code or functionalities. Pay attention to preserving existing structures."
    },
    {
      "name": "Single Chunk Edits",
      "pattern": "(?i)\\b(first|then|next|after that|finally)\\b",
      "message": "Provide all edits in a single chunk instead of multiple-step instructions or explanations for the same file"
    },
    {
      "name": "No Implementation Checks",
      "pattern": "(?i)\\b(make sure|verify|check|confirm) (it's|it is|that) (correctly|properly) implemented\\b",
      "message": "Don't ask the user to verify implementations that are visible in the provided context"
    },
    {
      "name": "No Unnecessary Updates",
      "pattern": "(?i)\\b(update|change|modify|alter)\\b.*\\bno changes\\b",
      "message": "Don't suggest updates or changes to files when there are no actual modifications needed"
    },
    {
      "name": "Provide Real File Links",
      "pattern": "(?i)\\b(file|in)\\b.*\\b(x\\.md)\\b",
      "message": "Always provide links to the real files, not x.md"
    },
    {
      "name": "No Previous x.md Consideration",
      "pattern": "(?i)\\b(previous|earlier|last)\\b.*\\bx\\.md\\b",
      "message": "Do not consider any previous x.md files in your memory. Complain if the contents are the same as previous runs."
    },
    {
      "name": "No Current Implementation",
      "pattern": "(?i)\\b(current|existing)\\s+(implementation|code)\\b",
      "message": "Don't show or discuss the current implementation unless specifically requested"
    },
    {
      "name": "Check x.md Content",
      "pattern": "(?i)\\b(file|content|implementation)\\b",
      "message": "Remember to check the x.md file for the current file contents and implementations"
    }
  ]
}
golang
javascript
less
shell

First seen in:

m3au/cursorcontext

Used in 1 repository

Python
# Guía de Commits para el Proyecto

Este proyecto sigue convenciones de commits semánticos en español, acompañados de emojis para mejorar la legibilidad.

Al final de CADA cambio que propongas, debes escribir el comando para el conventional commit según corresponda.

## Formato Base
```
<emoji> <tipo>(<alcance>): <descripción>

[cuerpo]

[pie]
```

## Tipos de Commits y sus Emojis

### Cambios Principales
- 🎉 `init`: Inicio de proyecto
- ✨ `feat`: Nueva característica
- 🐛 `fix`: Corrección de error
- 📝 `docs`: Documentación
- ♻️  `refactor`: Refactorización de código
- 🎨 `style`: Cambios de formato/estilo
- ⚡️ `perf`: Mejoras de rendimiento

### Cambios de Desarrollo
- 🔧 `chore`: Tareas de mantenimiento
- 🔨 `build`: Cambios en el sistema de build
- 👷 `ci`: Cambios en CI/CD
- ✅ `test`: Añadir o modificar tests

### Cambios de Dependencias
- ⬆️  `deps`: Actualizar dependencias
- ⬇️  `deps`: Bajar versión de dependencias
- ➕ `deps`: Añadir dependencia
- ➖ `deps`: Eliminar dependencia

### Otros
- 🚧 `wip`: Trabajo en progreso
- 🔀 `merge`: Merge de ramas
- 🔖 `version`: Nueva versión
- 🚀 `deploy`: Despliegue
- 🔒 `security`: Seguridad

## Ejemplos

```bash
# Nueva característica
git add [archivo] && git commit -m "✨ feat(auth): Implementar login con Google"

# Corrección de bug
git add [archivos] && git commit -m "🐛 fix(api): Corregir error en validación de tokens"

# Documentación
git add [archivos] && git commit -m "📝 docs(readme): Actualizar instrucciones de instalación"

# Refactorización
git add [archivos] && git commit -m "♻️ refactor(core): Simplificar lógica de procesamiento"

# Configuración
git add [archivos] && git commit -m "🔧 chore: Actualizar configuración de ESLint"

# Tests
git add [archivos] && git commit -m "✅ test(utils): Añadir tests para funciones helpers"
```

## Reglas Adicionales

1. La descripción debe:
   - Usar verbos en infinitivo (Añadir, Implementar, Corregir)
   - Ser clara y concisa
   - No terminar en punto

2. El alcance es opcional pero recomendado:
   - Debe ir entre paréntesis
   - Usar nombres de módulos/componentes

3. El cuerpo (opcional) debe:
   - Separarse por una línea en blanco
   - Explicar el "qué" y el "por qué" (no el "cómo")

4. El pie (opcional) debe:
   - Referenciar issues/PRs relacionados
   - Mencionar breaking changes

## Breaking Changes

Si el commit introduce un cambio que rompe la compatibilidad:

```bash
✨ feat(api)!: Cambiar formato de respuesta a JSON API

BREAKING CHANGE: La API ahora devuelve datos en formato JSON API v1.0
```
eslint
golang
langchain
python
vue.js
A-PachecoT/agentic-patterns-es

Used in 1 repository