New projects created: - michangarrito (marketplace mobile) - template-saas (SaaS template) - clinica-dental (dental ERP) - clinica-veterinaria (veterinary ERP) Architecture updates: - Move catalog from core/ to shared/ - Add MCP servers structure and templates - Add git management scripts - Update SUBREPOSITORIOS.md with 15 new repos - Update .gitignore for new projects Repository infrastructure: - 4 main repositories - 11 subrepositorios - Gitea remotes configured 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
286 lines
11 KiB
Markdown
286 lines
11 KiB
Markdown
# Utils - Core Module
|
|
|
|
**Modulo:** shared/modules/utils/
|
|
**Version:** 1.0.0
|
|
**Fecha:** 2026-01-03
|
|
**Owner:** Tech-Leader
|
|
**Estado:** production-ready
|
|
|
|
---
|
|
|
|
## Descripcion
|
|
|
|
Modulo de utilidades genericas framework-agnostic que provee funciones para manipulacion de fechas, strings y validaciones. Puede ser usado en cualquier proyecto del workspace (NestJS, Express, React, etc.) sin dependencias externas.
|
|
|
|
---
|
|
|
|
## Instalacion
|
|
|
|
### Prerequisitos
|
|
|
|
No requiere dependencias npm adicionales. Usa solo APIs nativas de JavaScript/TypeScript.
|
|
|
|
### Configuracion de Paths
|
|
|
|
Agregar en `tsconfig.json` del proyecto consumidor:
|
|
|
|
```json
|
|
{
|
|
"compilerOptions": {
|
|
"paths": {
|
|
"@shared/modules/*": ["../../shared/modules/*"]
|
|
}
|
|
}
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## API Publica
|
|
|
|
### Funciones de Fecha (date.util.ts)
|
|
|
|
| Funcion | Descripcion | Parametros | Retorno |
|
|
|---------|-------------|------------|---------|
|
|
| `formatToISO` | Formatea a ISO string | `(date: Date)` | `string` |
|
|
| `formatToDate` | Formatea a YYYY-MM-DD | `(date: Date)` | `string` |
|
|
| `formatToDateTime` | Formatea a YYYY-MM-DD HH:mm:ss | `(date: Date)` | `string` |
|
|
| `formatDate` | Formatea con patron custom | `(date: Date, pattern: string)` | `string` |
|
|
| `addDays` | Agrega dias a fecha | `(date: Date, days: number)` | `Date` |
|
|
| `addHours` | Agrega horas a fecha | `(date: Date, hours: number)` | `Date` |
|
|
| `addMinutes` | Agrega minutos a fecha | `(date: Date, minutes: number)` | `Date` |
|
|
| `addMonths` | Agrega meses a fecha | `(date: Date, months: number)` | `Date` |
|
|
| `isPast` | Verifica si fecha ya paso | `(date: Date)` | `boolean` |
|
|
| `isFuture` | Verifica si fecha es futura | `(date: Date)` | `boolean` |
|
|
| `startOfDay` | Obtiene inicio del dia | `(date: Date)` | `Date` |
|
|
| `endOfDay` | Obtiene fin del dia | `(date: Date)` | `Date` |
|
|
| `startOfMonth` | Obtiene inicio del mes | `(date: Date)` | `Date` |
|
|
| `endOfMonth` | Obtiene fin del mes | `(date: Date)` | `Date` |
|
|
| `diffInDays` | Diferencia en dias | `(date1: Date, date2: Date)` | `number` |
|
|
| `diffInHours` | Diferencia en horas | `(date1: Date, date2: Date)` | `number` |
|
|
| `diffInMinutes` | Diferencia en minutos | `(date1: Date, date2: Date)` | `number` |
|
|
| `isSameDay` | Verifica si es mismo dia | `(date1: Date, date2: Date)` | `boolean` |
|
|
| `parseISO` | Parsea ISO string a Date | `(isoString: string)` | `Date` |
|
|
| `isValidDate` | Verifica si string es fecha valida | `(dateString: string)` | `boolean` |
|
|
| `getRelativeTime` | Obtiene tiempo relativo | `(date: Date)` | `string` |
|
|
| `toUnixTimestamp` | Convierte a Unix timestamp | `(date: Date)` | `number` |
|
|
| `fromUnixTimestamp` | Crea Date desde Unix | `(timestamp: number)` | `Date` |
|
|
| `isToday` | Verifica si es hoy | `(date: Date)` | `boolean` |
|
|
| `isYesterday` | Verifica si es ayer | `(date: Date)` | `boolean` |
|
|
| `getAge` | Calcula edad desde fecha nacimiento | `(birthDate: Date)` | `number` |
|
|
|
|
### Funciones de String (string.util.ts)
|
|
|
|
| Funcion | Descripcion | Parametros | Retorno |
|
|
|---------|-------------|------------|---------|
|
|
| `slugify` | Genera slug URL-friendly | `(text: string)` | `string` |
|
|
| `capitalize` | Capitaliza primera letra | `(text: string)` | `string` |
|
|
| `capitalizeWords` | Capitaliza cada palabra | `(text: string)` | `string` |
|
|
| `truncate` | Trunca con ellipsis | `(text: string, maxLength: number)` | `string` |
|
|
| `stripHtml` | Remueve tags HTML | `(html: string)` | `string` |
|
|
| `sanitize` | Sanitiza caracteres especiales | `(text: string)` | `string` |
|
|
| `isEmpty` | Verifica si string es vacio | `(text: string \| null \| undefined)` | `boolean` |
|
|
| `isNotEmpty` | Verifica si string NO es vacio | `(text: string \| null \| undefined)` | `boolean` |
|
|
| `randomString` | Genera string aleatorio | `(length?: number, charset?: string)` | `string` |
|
|
| `randomNumeric` | Genera string numerico aleatorio | `(length?: number)` | `string` |
|
|
| `maskString` | Enmascara string | `(text: string, visibleChars?: number)` | `string` |
|
|
| `maskEmail` | Enmascara email | `(email: string)` | `string` |
|
|
| `toCamelCase` | Convierte a camelCase | `(text: string)` | `string` |
|
|
| `toSnakeCase` | Convierte a snake_case | `(text: string)` | `string` |
|
|
| `toKebabCase` | Convierte a kebab-case | `(text: string)` | `string` |
|
|
| `toConstantCase` | Convierte a CONSTANT_CASE | `(text: string)` | `string` |
|
|
| `toPascalCase` | Convierte a PascalCase | `(text: string)` | `string` |
|
|
| `escapeRegex` | Escapa caracteres regex | `(text: string)` | `string` |
|
|
| `wordCount` | Cuenta palabras | `(text: string)` | `number` |
|
|
| `reverse` | Invierte string | `(text: string)` | `string` |
|
|
| `padLeft` | Padding izquierdo | `(text: string, length: number, char?: string)` | `string` |
|
|
| `padRight` | Padding derecho | `(text: string, length: number, char?: string)` | `string` |
|
|
| `removeAccents` | Remueve acentos | `(text: string)` | `string` |
|
|
| `getInitials` | Extrae iniciales | `(name: string, maxChars?: number)` | `string` |
|
|
| `formatCurrency` | Formatea como moneda | `(amount: number, currency?: string, locale?: string)` | `string` |
|
|
| `formatNumber` | Formatea con separadores | `(num: number, locale?: string)` | `string` |
|
|
| `parseQueryString` | Parsea query string a objeto | `(queryString: string)` | `Record<string, string>` |
|
|
| `buildQueryString` | Construye query string | `(params: Record<string, ...>)` | `string` |
|
|
|
|
### Funciones de Validacion (validation.util.ts)
|
|
|
|
| Funcion | Descripcion | Parametros | Retorno |
|
|
|---------|-------------|------------|---------|
|
|
| `isEmail` | Valida email | `(email: string)` | `boolean` |
|
|
| `isUUID` | Valida UUID v4 | `(uuid: string)` | `boolean` |
|
|
| `isURL` | Valida URL | `(url: string)` | `boolean` |
|
|
| `isStrongPassword` | Valida password fuerte | `(password: string)` | `boolean` |
|
|
| `getPasswordStrength` | Obtiene fuerza de password (0-4) | `(password: string)` | `number` |
|
|
| `isPhoneNumber` | Valida telefono internacional | `(phone: string)` | `boolean` |
|
|
| `isNumeric` | Valida si es numerico | `(value: string)` | `boolean` |
|
|
| `isInteger` | Valida si es entero | `(value: string \| number)` | `boolean` |
|
|
| `isAlphanumeric` | Valida alfanumerico | `(value: string)` | `boolean` |
|
|
| `isAlphabetic` | Valida solo letras | `(value: string)` | `boolean` |
|
|
| `isInRange` | Valida rango numerico | `(value: number, min: number, max: number)` | `boolean` |
|
|
| `hasRequiredFields` | Valida campos requeridos | `(obj: T, fields: (keyof T)[])` | `boolean` |
|
|
| `isValidJSON` | Valida JSON string | `(value: string)` | `boolean` |
|
|
| `isPositive` | Valida numero positivo | `(value: number)` | `boolean` |
|
|
| `isNonNegative` | Valida numero >= 0 | `(value: number)` | `boolean` |
|
|
| `isCreditCard` | Valida tarjeta (Luhn) | `(cardNumber: string)` | `boolean` |
|
|
| `isIPv4` | Valida IP v4 | `(ip: string)` | `boolean` |
|
|
| `isHexColor` | Valida color hex | `(color: string)` | `boolean` |
|
|
| `isSlug` | Valida slug | `(slug: string)` | `boolean` |
|
|
| `isValidUsername` | Valida username | `(username: string)` | `boolean` |
|
|
| `isEmptyObject` | Valida objeto vacio | `(obj: object)` | `boolean` |
|
|
| `isEmptyArray` | Valida array vacio | `(arr: T[])` | `boolean` |
|
|
| `isNullOrUndefined` | Valida null/undefined | `(value: unknown)` | `boolean` |
|
|
| `isDefined` | Valida definido | `(value: T \| null \| undefined)` | `boolean` |
|
|
| `isMexicanRFC` | Valida RFC mexicano | `(rfc: string)` | `boolean` |
|
|
| `isMexicanCURP` | Valida CURP mexicano | `(curp: string)` | `boolean` |
|
|
| `createValidator` | Crea cadena de validacion | `(value: T)` | `Validator<T>` |
|
|
|
|
---
|
|
|
|
## Ejemplos de Uso
|
|
|
|
### Ejemplo 1: Formateo de Fechas
|
|
|
|
```typescript
|
|
import { formatDate, addDays, isPast, getRelativeTime } from '@shared/modules/utils';
|
|
|
|
// Formatear fecha
|
|
const fecha = new Date();
|
|
console.log(formatDate(fecha, 'YYYY-MM-DD')); // "2026-01-03"
|
|
console.log(formatDate(fecha, 'DD/MM/YYYY')); // "03/01/2026"
|
|
|
|
// Manipular fechas
|
|
const enUnaSemana = addDays(fecha, 7);
|
|
console.log(isPast(enUnaSemana)); // false
|
|
|
|
// Tiempo relativo
|
|
const ayer = addDays(new Date(), -1);
|
|
console.log(getRelativeTime(ayer)); // "1 day ago"
|
|
```
|
|
|
|
### Ejemplo 2: Manipulacion de Strings
|
|
|
|
```typescript
|
|
import { slugify, capitalize, maskEmail, formatCurrency } from '@shared/modules/utils';
|
|
|
|
// Generar slug
|
|
const slug = slugify('Hello World 2026!'); // "hello-world-2026"
|
|
|
|
// Capitalizar
|
|
const nombre = capitalize('john'); // "John"
|
|
|
|
// Enmascarar email
|
|
const emailMasked = maskEmail('john.doe@example.com'); // "jo***@example.com"
|
|
|
|
// Formatear moneda
|
|
const precio = formatCurrency(1234.50, 'USD'); // "$1,234.50"
|
|
const precioMXN = formatCurrency(1234.50, 'MXN', 'es-MX'); // "$1,234.50"
|
|
```
|
|
|
|
### Ejemplo 3: Validaciones
|
|
|
|
```typescript
|
|
import { isEmail, isStrongPassword, hasRequiredFields, createValidator } from '@shared/modules/utils';
|
|
|
|
// Validaciones simples
|
|
console.log(isEmail('test@example.com')); // true
|
|
console.log(isStrongPassword('Abc123!@')); // true
|
|
|
|
// Validar campos requeridos
|
|
const user = { name: 'John', email: 'john@example.com' };
|
|
console.log(hasRequiredFields(user, ['name', 'email'])); // true
|
|
|
|
// Cadena de validacion
|
|
const result = createValidator('john@example.com')
|
|
.validate(isEmail('john@example.com'), 'Email invalido')
|
|
.validate(true, 'Otro check')
|
|
.result();
|
|
|
|
console.log(result); // { isValid: true, errors: [] }
|
|
```
|
|
|
|
---
|
|
|
|
## Dependencias
|
|
|
|
### Internas (otros modulos de core/)
|
|
|
|
Ninguna. Este modulo es standalone.
|
|
|
|
### Externas (npm)
|
|
|
|
Ninguna. Solo usa APIs nativas de JavaScript.
|
|
|
|
---
|
|
|
|
## Proyectos Consumidores
|
|
|
|
| Proyecto | Desde Version | Funciones Usadas |
|
|
|----------|---------------|------------------|
|
|
| gamilit | 1.0.0 | `formatDate`, `slugify`, `isEmail` |
|
|
| trading-platform | 1.0.0 | `formatCurrency`, `toUnixTimestamp` |
|
|
| erp-suite | 1.0.0 | `isMexicanRFC`, `formatNumber`, validaciones |
|
|
|
|
---
|
|
|
|
## Estructura de Archivos
|
|
|
|
```
|
|
shared/modules/utils/
|
|
+-- index.ts # Punto de entrada, re-exporta todo
|
|
+-- date.util.ts # 25 funciones de fecha
|
|
+-- string.util.ts # 30 funciones de string
|
|
+-- validation.util.ts # 35 funciones de validacion
|
|
+-- README.md # Esta documentacion
|
|
```
|
|
|
|
---
|
|
|
|
## Changelog
|
|
|
|
### v1.0.0 (2026-01-03)
|
|
- Release inicial
|
|
- 25 funciones de fecha
|
|
- 30 funciones de string
|
|
- 35 funciones de validacion
|
|
- Validaciones mexicanas (RFC, CURP)
|
|
- Cadena de validacion con createValidator
|
|
|
|
---
|
|
|
|
## Contribuir
|
|
|
|
### Proceso
|
|
|
|
1. Crear branch desde `main`
|
|
2. Implementar cambios con ejemplos en JSDoc
|
|
3. Verificar que no rompe consumidores existentes
|
|
4. Crear PR hacia `main`
|
|
5. Solicitar review del owner (Tech-Leader)
|
|
|
|
### Reglas
|
|
|
|
- Funciones deben ser puras (sin side effects)
|
|
- No agregar dependencias externas
|
|
- Mantener retrocompatibilidad
|
|
- Documentar con JSDoc
|
|
- Agregar ejemplos en comentarios
|
|
|
|
---
|
|
|
|
## Checklist de Completitud
|
|
|
|
```markdown
|
|
- [x] Descripcion clara del modulo
|
|
- [x] Instalacion documentada
|
|
- [x] API publica completa con tipos (90 funciones)
|
|
- [x] Ejemplos de uso funcionales
|
|
- [x] Dependencias listadas (ninguna)
|
|
- [x] Proyectos consumidores documentados
|
|
- [ ] Tests existentes y pasando
|
|
- [x] Changelog actualizado
|
|
```
|
|
|
|
---
|
|
|
|
**Modulo:** shared/modules/utils/ | **Owner:** Tech-Leader | **90 funciones**
|