coding-standards
Convenciones de codificación base entre proyectos para nomenclatura, legibilidad, inmutabilidad y revisión de calidad de código. Usar skills de frontend o backend para patrones específicos de frameworks.
What this skill does
# Estándares de Codificación y Buenas Prácticas
Convenciones de codificación base aplicables en todos los proyectos.
Este skill es el suelo compartido, no el manual detallado de frameworks.
- Usar `frontend-patterns` para React, estado, formularios, renderizado y arquitectura UI.
- Usar `backend-patterns` o `api-design` para capas de repositorio/servicio, diseño de endpoints, validación y aspectos específicos del servidor.
- Usar `rules/common/coding-style.md` cuando necesites la capa de reglas reutilizables más corta en lugar de un recorrido completo del skill.
## Cuándo Activar
- Iniciar un nuevo proyecto o módulo
- Revisar código para calidad y mantenibilidad
- Refactorizar código existente para seguir convenciones
- Hacer cumplir consistencia en nomenclatura, formato o estructura
- Configurar reglas de linting, formato o verificación de tipos
- Incorporar nuevos colaboradores a las convenciones de codificación
## Límites de Alcance
Activar este skill para:
- nomenclatura descriptiva
- valores predeterminados de inmutabilidad
- legibilidad, KISS, DRY y aplicación de YAGNI
- expectativas de manejo de errores y revisión de code smells
No usar este skill como fuente principal para:
- Composición, hooks o patrones de renderizado de React
- Arquitectura backend, diseño de API o capas de base de datos
- Orientación específica de frameworks cuando ya existe un skill ECC más específico
## Principios de Calidad de Código
### 1. Legibilidad Primero
- El código se lee más de lo que se escribe
- Nombres claros para variables y funciones
- Código auto-documentado preferido sobre comentarios
- Formato consistente
### 2. KISS (Keep It Simple, Stupid)
- La solución más simple que funcione
- Evitar sobreingeniería
- Sin optimización prematura
- Fácil de entender > código inteligente
### 3. DRY (Don't Repeat Yourself)
- Extraer lógica común en funciones
- Crear componentes reutilizables
- Compartir utilidades entre módulos
- Evitar programación por copiar y pegar
### 4. YAGNI (You Aren't Gonna Need It)
- No construir features antes de que sean necesarias
- Evitar generalidad especulativa
- Agregar complejidad solo cuando sea requerido
- Empezar simple, refactorizar cuando sea necesario
## Estándares TypeScript/JavaScript
### Nomenclatura de Variables
```typescript
// PASS: BIEN: Nombres descriptivos
const marketSearchQuery = 'election'
const isUserAuthenticated = true
const totalRevenue = 1000
// FAIL: MAL: Nombres poco claros
const q = 'election'
const flag = true
const x = 1000
```
### Nomenclatura de Funciones
```typescript
// PASS: BIEN: Patrón verbo-sustantivo
async function fetchMarketData(marketId: string) { }
function calculateSimilarity(a: number[], b: number[]) { }
function isValidEmail(email: string): boolean { }
// FAIL: MAL: Poco claro o solo sustantivo
async function market(id: string) { }
function similarity(a, b) { }
function email(e) { }
```
### Patrón de Inmutabilidad (CRÍTICO)
```typescript
// PASS: SIEMPRE usar el operador spread
const updatedUser = {
...user,
name: 'New Name'
}
const updatedArray = [...items, newItem]
// FAIL: NUNCA mutar directamente
user.name = 'New Name' // MAL
items.push(newItem) // MAL
```
### Manejo de Errores
```typescript
// PASS: BIEN: Manejo de errores comprensivo
async function fetchData(url: string) {
try {
const response = await fetch(url)
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
}
return await response.json()
} catch (error) {
console.error('Fetch failed:', error)
throw new Error('Failed to fetch data')
}
}
// FAIL: MAL: Sin manejo de errores
async function fetchData(url) {
const response = await fetch(url)
return response.json()
}
```
### Buenas Prácticas de Async/Await
```typescript
// PASS: BIEN: Ejecución paralela cuando sea posible
const [users, markets, stats] = await Promise.all([
fetchUsers(),
fetchMarkets(),
fetchStats()
])
// FAIL: MAL: Secuencial cuando no es necesario
const users = await fetchUsers()
const markets = await fetchMarkets()
const stats = await fetchStats()
```
### Seguridad de Tipos
```typescript
// PASS: BIEN: Tipos apropiados
interface Market {
id: string
name: string
status: 'active' | 'resolved' | 'closed'
created_at: Date
}
function getMarket(id: string): Promise<Market> {
// Implementación
}
// FAIL: MAL: Usar 'any'
function getMarket(id: any): Promise<any> {
// Implementación
}
```
## Buenas Prácticas de React
### Estructura de Componentes
```typescript
// PASS: BIEN: Componente funcional con tipos
interface ButtonProps {
children: React.ReactNode
onClick: () => void
disabled?: boolean
variant?: 'primary' | 'secondary'
}
export function Button({
children,
onClick,
disabled = false,
variant = 'primary'
}: ButtonProps) {
return (
<button
onClick={onClick}
disabled={disabled}
className={`btn btn-${variant}`}
>
{children}
</button>
)
}
// FAIL: MAL: Sin tipos, estructura poco clara
export function Button(props) {
return <button onClick={props.onClick}>{props.children}</button>
}
```
### Custom Hooks
```typescript
// PASS: BIEN: Custom hook reutilizable
export function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value)
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value)
}, delay)
return () => clearTimeout(handler)
}, [value, delay])
return debouncedValue
}
// Uso
const debouncedQuery = useDebounce(searchQuery, 500)
```
### Gestión de Estado
```typescript
// PASS: BIEN: Actualizaciones de estado correctas
const [count, setCount] = useState(0)
// Actualización funcional para estado basado en el estado previo
setCount(prev => prev + 1)
// FAIL: MAL: Referencia de estado directa
setCount(count + 1) // Puede estar obsoleta en escenarios async
```
### Renderizado Condicional
```typescript
// PASS: BIEN: Renderizado condicional claro
{isLoading && <Spinner />}
{error && <ErrorMessage error={error} />}
{data && <DataDisplay data={data} />}
// FAIL: MAL: Infierno de ternarios
{isLoading ? <Spinner /> : error ? <ErrorMessage error={error} /> : data ? <DataDisplay data={data} /> : null}
```
## Estándares de Diseño de API
### Convenciones de API REST
```
GET /api/markets # Listar todos los markets
GET /api/markets/:id # Obtener market específico
POST /api/markets # Crear nuevo market
PUT /api/markets/:id # Actualizar market (completo)
PATCH /api/markets/:id # Actualizar market (parcial)
DELETE /api/markets/:id # Eliminar market
# Parámetros de consulta para filtrado
GET /api/markets?status=active&limit=10&offset=0
```
### Formato de Respuesta
```typescript
// PASS: BIEN: Estructura de respuesta consistente
interface ApiResponse<T> {
success: boolean
data?: T
error?: string
meta?: {
total: number
page: number
limit: number
}
}
// Respuesta exitosa
return NextResponse.json({
success: true,
data: markets,
meta: { total: 100, page: 1, limit: 10 }
})
// Respuesta de error
return NextResponse.json({
success: false,
error: 'Invalid request'
}, { status: 400 })
```
### Validación de Entrada
```typescript
import { z } from 'zod'
// PASS: BIEN: Validación con esquema
const CreateMarketSchema = z.object({
name: z.string().min(1).max(200),
description: z.string().min(1).max(2000),
endDate: z.string().datetime(),
categories: z.array(z.string()).min(1)
})
export async function POST(request: Request) {
const body = await request.json()
try {
const validated = CreateMarketSchema.parse(body)
// Proceder con datos validados
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json({
success: false,
error: 'Validation failed',
details: error.errors
}, { status: 400 })
}
}
}
```
## ORelated in Web Dev
generating-lwc-components
IncludedLightning Web Components with PICKLES methodology and 165-point scoring. Use this skill when the user creates or edits LWC components, builds wire service patterns, or writes Jest tests for LWC. TRIGGER when: user creates/edits LWC components, touches lwc/**/*.js, .html, .css, .js-meta.xml files, or asks about wire service, SLDS, or Jest LWC tests. DO NOT TRIGGER when: Apex classes (use generating-apex), Aura components, or Visualforce.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Set up queries with useQuery, mutations with useMutation, configure QueryClient caching strategies, implement optimistic updates, and handle infinite scroll with useInfiniteQuery. Use when: setting up data fetching in React projects, migrating from v4 to v5, or fixing object syntax required errors, query callbacks removed issues, cacheTime renamed to gcTime, isPending vs isLoading confusion, keepPreviousData removed problems.
document-processor-api
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
nutrient-document-processing
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Covers useMutationState, simplified optimistic updates, throwOnError, network mode (offline/PWA), and infiniteQueryOptions. Use when setting up data fetching, fixing v4→v5 migration errors (object syntax, gcTime, isPending, keepPreviousData), or debugging SSR/hydration issues with streaming server components.
accelint-nextjs-best-practices
IncludedNext.js performance optimization and best practices. Use when writing Next.js code (App Router or Pages Router); implementing Server Components, Server Actions, or API routes; optimizing RSC serialization, data fetching, or server-side rendering; reviewing Next.js code for performance issues; fixing authentication in Server Actions; or implementing Suspense boundaries, parallel data fetching, or request deduplication.