npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

gufi-cli

v0.1.25

Published

CLI for developing Gufi Marketplace views locally with Claude Code

Downloads

1,439

Readme

Gufi CLI

CLI para desarrollo de Gufi ERP. Gestiona módulos, automations, vistas del Marketplace y datos.

Instalación

npm install -g gufi-cli

Entornos (Local vs Producción)

El CLI soporta múltiples entornos con credenciales separadas. Cada entorno mantiene su propia sesión.

# Ver entornos configurados
gufi config

# Salida:
#   🟣 Gufi CLI - Entornos
#   ─────────────────────────────────────────────────
#   prod   https://gogufi.com
#          ● ✓ [email protected]
#
#   local  http://localhost:3000
#          ○ (no login)
#   ─────────────────────────────────────────────────
#   📍 Entorno actual: PROD

# Cambiar a LOCAL (desarrollo)
gufi config:local

# Cambiar a PRODUCCIÓN
gufi config:prod

# URL personalizada
gufi config:set https://staging.gogufi.com

Flujo de trabajo típico

# 1. Trabajar en producción
gufi config:prod
gufi login                    # Credenciales se guardan para prod
gufi modules 146

# 2. Cambiar a local para desarrollo
gufi config:local
gufi login                    # Credenciales separadas para local
gufi modules 146              # Ahora consulta localhost:3000

# 3. Volver a prod (sesión sigue activa)
gufi config:prod
gufi companies                # Ya está logueado en prod

Autenticación

gufi login          # Login interactivo (guarda credenciales)
gufi logout         # Cerrar sesión del entorno actual
gufi whoami         # Ver usuario y entorno actual

Las credenciales se guardan por entorno en ~/.gufi/config.json. El auto-login funciona automáticamente cuando el token expira.

Context (Para Claude/AI)

Genera contexto inteligente para que Claude entienda tu proyecto:

gufi context                  # Auto-detecta proyecto del directorio actual
gufi context -v 13            # Contexto de vista específica
gufi context -p 14            # Contexto de package completo
gufi context -c 116           # Contexto de company
gufi context --full           # Incluir explicaciones de conceptos Gufi
gufi context -o context.md    # Guardar a archivo

El contexto incluye:

  • Para vistas: dataSources, viewSpec, estructura de archivos
  • Para packages: módulos, entidades, automations vinculadas
  • Para companies: módulos, tablas, scripts, variables de entorno

Ideal para copiar/pegar a Claude cuando trabajas en un proyecto Gufi.

Doctor (Diagnóstico)

Verifica que todo esté correctamente configurado:

gufi doctor                   # Diagnóstico del directorio actual
gufi doctor -p 14             # Diagnosticar package
gufi doctor -v 13             # Diagnosticar vista
gufi doctor -c 116 --verbose  # Diagnosticar company con detalles

Verifica:

  • Configuración CLI: Token, entorno, credenciales
  • Estructura de vista: featureConfig, dataSources, exports
  • Errores comunes: IDs hardcodeados, imports incorrectos
  • Package: Vistas, módulos, estado de publicación
  • Company: Módulos, automations, variables de entorno
💜 Gufi Doctor - Diagnóstico del Sistema
───────────────────────────────────────────────────────

┌─ Configuración CLI ─────────────────────────────────┐
  ✓ Entorno actual: PROD
  ✓ Token presente
  ✓ Usuario: [email protected]
└─────────────────────────────────────────────────────┘

┌─ Vista: Stock Overview ─────────────────────────────┐
  ✓ export default presente
  ✓ featureConfig exportado
  ✗ IDs de tabla hardcodeados detectados
└─────────────────────────────────────────────────────┘

Resumen:
  ✓ 3 verificaciones OK
  ✗ 1 errores

Companies y Módulos

gufi companies                  # Listar companies
gufi company:create "Nombre"    # Crear company

gufi modules <company_id>       # Listar módulos
gufi module <module_id>         # Ver JSON (auto-detecta company)
gufi module <id> --edit         # Editar con $EDITOR
gufi module <id> --file m.json  # Exportar a archivo

gufi module:update <id> <file>  # Actualizar desde JSON
gufi module:create <file> -c 146  # Crear módulo nuevo

Automations

# Scripts (código JavaScript)
gufi automations -c 116           # Listar scripts
gufi automation <id>              # Ver código
gufi automation <id> --edit       # Editar con $EDITOR
gufi automation:create <name> <file> -c 116

# Triggers por entidad
gufi entity:automations <entity_id>        # Ver triggers
gufi entity:automations <id> --edit        # Editar triggers

# Debugging
gufi automations:meta -c 116               # Ver índice del worker
gufi automations:executions -c 116         # Historial de ejecuciones
gufi automations:executions -c 116 --limit 50 --script sync_nayax

api.query() en Automations

⚠️ IMPORTANTE: api.query() devuelve rows directamente (NO { rows }):

// ✅ CORRECTO
const rows = await api.query("SELECT * FROM table WHERE id = $1", [id]);

// ❌ INCORRECTO
const { rows } = await api.query(...);  // ERROR!

Llamar automations desde vistas

await dataProvider.runClickAutomation?.({
  company_id, module_id, table_id: entityId,
  function_name: "my_automation",
  input: { record_id: 123 },
});

Row CRUD (Datos)

gufi rows <table>                 # Listar (auto-detecta company)
gufi rows m360_t16192 -l 50       # Últimos 50 registros
gufi rows m360_t16192 -f estado=activo

gufi row <table> <id>             # Ver registro
gufi row:create <table> --data '{"nombre":"Test"}'
gufi row:update <table> <id> --data '{"estado":"done"}'
gufi row:delete <table> <id>
gufi row:duplicate <table> <id>

gufi rows:create <table> --file datos.json  # Bulk create

Variables de Entorno

gufi env                    # Listar variables
gufi env:set KEY value      # Crear/actualizar
gufi env:delete KEY         # Eliminar

Desarrollo de Vistas (Marketplace)

# Crear vista nueva desde template
gufi view:templates                    # Ver templates disponibles
gufi view:create "Mi Vista" --template tabla-filtros

# Editar vista existente
gufi view:pull <viewId>                # Descargar vista a ~/gufi-dev/view_<id>/
gufi view:push                         # Subir cambios (detecta directorio actual)
gufi view:watch                        # Auto-sync al guardar
gufi view:logs                         # Ver console.log del LivePreview
gufi view:status                       # Ver estado de sincronización

Migraciones de Base de Datos

Cuando publicas una nueva versión, puedes incluir migraciones SQL que se ejecutan automáticamente al actualizar.

1. Crear metadata/migrations.ts:

export const migrations = [
  {
    description: "Add status column",
    up: `ALTER TABLE {tableName} ADD COLUMN IF NOT EXISTS status VARCHAR(50);`,
    down: `ALTER TABLE {tableName} DROP COLUMN IF EXISTS status;`
  },
  {
    description: "Make email unique",
    up: `ALTER TABLE {tableName} ADD CONSTRAINT uq_email UNIQUE (email);`,
    down: `ALTER TABLE {tableName} DROP CONSTRAINT IF EXISTS uq_email;`
  }
];

2. Placeholders disponibles:

| Placeholder | Valor | |-------------|-------| | {tableName} | Tabla física (ej: company_147.m360_t4589) | | {entityId} | ID de la entidad | | {companyId} | ID de la company |

3. Flujo:

  • Al publicar versión → migraciones se guardan automáticamente
  • Cliente ve "Update available" con lista de migraciones
  • Click "Update" → ejecuta en transacción con rollback si falla

SDK para Vistas (@/sdk)

Las vistas del Marketplace deben usar el SDK centralizado. Importar desde @/sdk:

import {
  // Hooks
  useViewPreferences,  // Persistir filtros/ordenación por usuario
  useDebouncedValue,   // Debounce para búsquedas
  useViewData,         // Carga de datos con seedData/dataProvider

  // Utils
  cn,                  // tailwind-merge para classnames
  formatNumber,
  formatCurrency,
  groupBy, sumBy, sortBy,

  // Notifications
  toastSuccess, toastError, toastInfo,

  // Translations
  tUI, getLang,

  // Types
  type FeatureProps,
  type GufiContext,
} from '@/sdk';

Reglas de imports (validadas en gufi push):

  • @/sdk → ✅ Preferido
  • @/shared/hooks → ✅ OK (backwards compat)
  • @/stores/* → ⚠️ Warning - usar gufi.context
  • @/shared/api/dataProvider → ⚠️ Warning - usar gufi.dataProvider
  • IDs físicos (m123_t456) → ❌ Error - usar viewSpec

Docs completos: frontend/src/sdk/README.md

Detección automática de directorio: view:push y view:status detectan automáticamente si el directorio actual tiene un archivo .gufi-view.json válido. Si lo tiene, usa esa vista; si no, usa la última vista del config.

Packages (Marketplace)

gufi packages               # Ver mis packages
gufi package <id>           # Ver detalles
gufi package:create "Nombre"
gufi package:add-module <packageId>
gufi package:add-view <packageId> <viewId>
gufi package:publish <id>
gufi package:sync <id>      # Sincronizar versión

Migraciones de Package

Las migraciones SQL se ejecutan automáticamente cuando los clientes actualizan a una nueva versión.

💜 IMPORTANTE: El código de las vistas es SIEMPRE LIVE (cambios instantáneos). Las migraciones son SOLO para cambios de esquema SQL (columnas, índices, constraints).

Comandos

# Ver entidades disponibles para target_entity
gufi package:entities 14

# Listar migraciones del package
gufi package:migrations 14

# Crear migración desde CLI
gufi package:migration:create 14 \
  -d "Add unique constraint to email" \
  -e "tareas.proyectos" \
  -u "ALTER TABLE {tableName} ADD CONSTRAINT uq_email UNIQUE (email);" \
  -D "ALTER TABLE {tableName} DROP CONSTRAINT IF EXISTS uq_email;"

# Crear migración desde archivo JSON
gufi package:migration:create 14 -f migration.json

# Eliminar migración (solo si no ha sido aplicada)
gufi package:migration:delete 14 <migrationId>

Placeholders Disponibles

| Placeholder | Valor | Ejemplo | |-------------|-------|---------| | {tableName} | Tabla física completa | company_147.m360_t4589 | | {entityId} | ID de la entidad target | 4589 | | {companyId} | ID de la company del cliente | 147 |

Formato del Archivo JSON

{
  "description": "Add status column",
  "up": "ALTER TABLE {tableName} ADD COLUMN IF NOT EXISTS status VARCHAR(50);",
  "down": "ALTER TABLE {tableName} DROP COLUMN IF EXISTS status;"
}

Ejemplos Comunes de Migraciones

-- Agregar columna
ALTER TABLE {tableName} ADD COLUMN IF NOT EXISTS phone VARCHAR(20);

-- Agregar columna NOT NULL con default
ALTER TABLE {tableName} ADD COLUMN IF NOT EXISTS active BOOLEAN DEFAULT true NOT NULL;

-- Renombrar columna
ALTER TABLE {tableName} RENAME COLUMN estado TO status;

-- Cambiar tipo de columna
ALTER TABLE {tableName} ALTER COLUMN price TYPE NUMERIC(10,2);

-- Agregar índice
CREATE INDEX IF NOT EXISTS idx_{entityId}_date ON {tableName}(created_at);

-- Agregar constraint UNIQUE
ALTER TABLE {tableName} ADD CONSTRAINT uq_{entityId}_code UNIQUE (code);

-- Agregar foreign key
ALTER TABLE {tableName} ADD CONSTRAINT fk_{entityId}_user
  FOREIGN KEY (user_id) REFERENCES core.users(id);

-- Eliminar duplicados antes de UNIQUE
DELETE FROM {tableName} a USING {tableName} b
  WHERE a.id < b.id AND a.email = b.email;

Tipos de Columna Disponibles

El paquete @gufi/column-types define todos los tipos válidos:

| Tipo | PostgreSQL | Uso | |------|------------|-----| | text | TEXT | Texto libre | | number | NUMERIC | Números | | number_int | INTEGER | Enteros | | boolean | BOOLEAN | Sí/No | | date | DATE | Fecha | | datetime | TIMESTAMP | Fecha+hora | | select | TEXT | Selector único | | multiselect | TEXT[] | Selector múltiple | | relation | INTEGER | FK a otra tabla | | currency | JSONB | {currency, amount} | | phone | JSONB | {country, number} | | location | JSONB | {address, lat, lng} | | file | JSONB | [{url, name, size}] | | users | INTEGER[] | Array de user IDs | | json | JSONB | Datos arbitrarios |

Flujo de Actualización

Developer crea migración
       │
       ▼
gufi package:publish 14
       │
       ▼
Cliente ve banner "Update available v1.0.0 → v1.1.0"
       │
       ▼
Click "Update" → ejecuta migrations en transacción
       │
       ├── ✅ Éxito → installed_view_version = 1.1.0
       │
       └── ❌ Fallo → ROLLBACK automático, nada cambia

Schema

gufi schema                 # Ver todas las tablas
gufi schema -m 360          # Filtrar por módulo

Estructura de Config

El CLI guarda configuración en ~/.gufi/config.json:

{
  "currentEnv": "prod",
  "environments": {
    "prod": {
      "apiUrl": "https://gogufi.com",
      "token": "eyJ...",
      "refreshToken": "eyJ...",
      "email": "[email protected]",
      "password": "***"
    },
    "local": {
      "apiUrl": "http://localhost:3000",
      "email": "[email protected]",
      "password": "***"
    }
  },
  "currentView": {
    "id": 13,
    "name": "Tasks Manager",
    "packageId": 14,
    "localPath": "~/gufi-dev/view_13"
  }
}

Output JSON (para Claude/scripts)

Todos los comandos de lectura soportan --json para output estructurado sin colores ni emojis:

gufi companies --json           # Lista companies en JSON
gufi modules 146 --json         # Lista módulos en JSON
gufi module 360 --json          # JSON del módulo
gufi automations --json         # Lista automations en JSON
gufi automation 15 --json       # Código y metadata del automation
gufi schema --json              # Estructura de tablas en JSON
gufi rows m360_t16192 --json    # Registros en JSON
gufi row m360_t16192 5 --json   # Registro específico en JSON
gufi packages --json            # Lista packages en JSON
gufi package 14 --json          # Detalles del package en JSON

Ideal para integración con Claude Code, scripts de automatización, o cualquier herramienta que necesite parsear el output.

MCP Server (Model Context Protocol)

El CLI incluye un servidor MCP que permite a Claude interactuar directamente con Gufi sin ejecutar comandos manualmente.

Configuración

# Añadir el MCP a Claude Code
claude mcp add --transport stdio gufi -- gufi mcp

Tools disponibles

El MCP expone todas las funcionalidades del CLI como tools que Claude puede usar directamente:

| Tool | Descripción | |------|-------------| | Contexto | | | gufi_context | Genera contexto del proyecto para Claude | | gufi_whoami | Ver usuario y entorno actual | | gufi_schema | Ver estructura de tablas | | Companies | | | gufi_companies | Listar companies del usuario | | gufi_company_create | Crear nueva company | | Módulos | | | gufi_modules | Listar módulos de una company | | gufi_module | Ver JSON de un módulo | | gufi_module_update | Actualizar módulo desde JSON | | gufi_module_create | Crear módulo nuevo | | Automations | | | gufi_automations | Listar scripts de automation | | gufi_automation | Ver código de un automation | | gufi_automation_create | Crear/actualizar automation | | gufi_entity_automations | Ver triggers de una entidad | | gufi_entity_automations_update | Actualizar triggers | | gufi_automations_executions | Ver historial de ejecuciones | | Datos | | | gufi_rows | Listar registros de una tabla | | gufi_row | Ver un registro específico | | gufi_row_create | Crear registro | | gufi_row_update | Actualizar registro | | gufi_row_delete | Eliminar registro | | Environment | | | gufi_env | Listar variables de entorno | | gufi_env_set | Crear/actualizar variable | | gufi_env_delete | Eliminar variable | | Vistas | | | gufi_view_files | Ver archivos de una vista | | gufi_view_file_update | Actualizar archivo de vista | | Packages | | | gufi_packages | Listar packages | | gufi_package | Ver detalles de package | | gufi_package_create | Crear package | | gufi_package_publish | Publicar package | | gufi_package_sync | Sincronizar versión | | gufi_package_add_module | Añadir módulo | | gufi_package_add_view | Añadir vista |

Ejemplo de uso

Una vez configurado, puedes hablar naturalmente con Claude:

"Agrega un campo 'fecha_entrega' tipo date al módulo de pedidos"
→ Claude usa gufi_module para leer, modifica, y usa gufi_module_update

"Crea un automation que envíe email cuando un pedido pase a 'enviado'"
→ Claude usa gufi_automations para ver existentes, crea código, usa gufi_automation_create

"¿Cuántos registros hay en la tabla de clientes?"
→ Claude usa gufi_rows para consultar

Seguridad

  • El MCP usa las credenciales del CLI (gufi login)
  • Solo accede a companies/packages que el usuario tiene permisos
  • No hay servidor público - todo corre localmente

Tips

  • Auto-detección: module, automation, rows detectan la company automáticamente
  • Edición rápida: Usa --edit para abrir en tu $EDITOR
  • Entornos separados: Cada entorno tiene sus propias credenciales
  • Auto-login: El CLI refresca tokens automáticamente
  • Output JSON: Usa --json cuando necesites output parseable

Links

  • Web: https://gogufi.com
  • Docs: https://github.com/juanbp23/gogufi/blob/main/docs/guide/27-gufi-cli.md