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

chatbot-sdk-integro

v1.0.2

Published

SDK de chatbot con inteligencia artificial listo para integrar en cualquier proyecto React o sitio web mediante CDN. Se conecta a un backend NestJS que utiliza **Google Gemini** como motor de IA.

Readme

chatbot-sdk-integro

SDK de chatbot con inteligencia artificial listo para integrar en cualquier proyecto React o sitio web mediante CDN. Se conecta a un backend NestJS que utiliza Google Gemini como motor de IA.


📦 Instalación

npm install chatbot-sdk-integro

Requisitos: react >= 19 y react-dom >= 19 como peer dependencies.


🚀 Uso en React (NPM)

import { Chatbot } from 'chatbot-sdk-integro';
import 'chatbot-sdk-integro/style.css';

function App() {
  return (
    <Chatbot
      projectApiKey="TU_API_KEY_DEL_PROYECTO"
      hostUrl="https://tu-backend.com"
    />
  );
}

Props del componente

| Prop | Tipo | Requerido | Descripción | |------|------|-----------|-------------| | projectApiKey | string | ✅ | API Key única del proyecto, generada desde el backend. | | hostUrl | string | ✅ | URL base del backend (ej: https://tu-backend.com). |


🌐 Uso mediante CDN (sin NPM)

Si no usas React en tu proyecto, puedes incluir el chatbot directamente con un <script>:

<div
  id="ai-chatbot-integro"
  data-project="TU_API_KEY_DEL_PROYECTO"
  data-host="https://tu-backend.com"
></div>

<script src="https://tu-cdn.com/chatbot.umd.js"></script>

El SDK detectará automáticamente el <div> con id="ai-chatbot-integro" y renderizará el chatbot dentro de un Shadow DOM aislado.


⚙️ Configuración del Backend

El SDK se comunica con un backend NestJS que gestiona la IA y la autenticación. A continuación se detalla la configuración necesaria.

Variables de entorno (.env)

Crea un archivo .env en la raíz del proyecto backend con las siguientes variables:

# Clave de API de Google Gemini (obligatoria)
GEMINI_API_KEY=tu_clave_de_gemini_aqui

# Configuración de la base de datos PostgreSQL
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_USER=postgres
POSTGRES_PASSWORD=postgres
POSTGRES_DB=chatbot

| Variable | Descripción | |----------|-------------| | GEMINI_API_KEY | Clave de API de Google AI Studio. Es la clave que el backend usa internamente para comunicarse con el modelo Gemini. No se expone al cliente. | | POSTGRES_* | Credenciales de conexión a la base de datos PostgreSQL donde se almacenan usuarios y proyectos. |

[!IMPORTANT] La GEMINI_API_KEY es una variable del servidor y nunca se envía al navegador. El SDK del cliente solo necesita la projectApiKey del proyecto, que es un UUID diferente generado por el backend.

Ejecución con Docker

cd backend-chatbot
docker-compose up -d

Esto levanta:

  • PostgreSQL en el puerto 5432
  • API NestJS en el puerto 3000

🔑 Flujo de autenticación (API Key)

┌─────────────┐         x-api-key header          ┌──────────────┐
│   Chatbot   │ ──────────────────────────────────▶│   Backend    │
│   (SDK)     │   POST /api/chat/stream            │   (NestJS)   │
└─────────────┘                                    └──────┬───────┘
                                                          │
                                                   ApiKeyGuard
                                                          │
                                                   ┌──────▼───────┐
                                                   │  PostgreSQL  │
                                                   │  (projects)  │
                                                   └──────────────┘
  1. El SDK envía cada mensaje al endpoint POST /api/chat/stream incluyendo el header x-api-key.
  2. El ApiKeyGuard del backend valida la API Key contra la tabla Project en PostgreSQL.
  3. Opcionalmente, el guard verifica el Origin del request contra la lista blanca de dominios (domainWhitelist) configurada en el proyecto.
  4. Si la validación es exitosa, el backend procesa el mensaje con Google Gemini usando el systemPrompt del proyecto y devuelve la respuesta como un Server-Sent Events (SSE) stream.

Crear un proyecto y obtener tu API Key

Usa el endpoint de gestión del backend para crear un proyecto:

# 1. Crear un usuario
curl -X POST https://tu-backend.com/management/users \
  -H "Content-Type: application/json" \
  -d '{"email": "[email protected]", "passwordHash": "tu_contraseña"}'

# 2. Crear un proyecto (usa el _id del usuario devuelto)
curl -X POST https://tu-backend.com/management/projects \
  -H "Content-Type: application/json" \
  -d '{
    "ownerId": "uuid-del-usuario",
    "systemPrompt": "Eres un asistente amigable que responde preguntas.",
    "name": "Mi Chatbot",
    "domainWhitelist": ["https://mi-sitio.com"]
  }'

La respuesta incluirá un campo apiKey (UUID generado automáticamente). Ese es el valor que debes pasar como projectApiKey al componente <Chatbot>.

[!TIP] Si quieres que el chatbot funcione en cualquier dominio durante desarrollo, usa "domainWhitelist": ["*"].


📁 Estructura del paquete

dist/
├── index.mjs                  # ESM para import/export
├── index.cjs                  # CommonJS para require()
├── index.d.ts                 # Declaraciones TypeScript
├── chatbot-sdk-integro.css    # Estilos del componente
└── cdn/
    └── chatbot.umd.js         # Bundle standalone para CDN (incluye React)

📄 Licencia

ISC