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

@gatekeeperx/events-client

v0.1.2

Published

Cliente oficial TypeScript para consumir la API de Eventos de GatekeeperX. Funciona en Node 18+/AWS Lambda y cualquier bundler moderno.

Readme

@gatekeeperx/events-client

Cliente oficial en TypeScript/JavaScript para consumir la API de Eventos de GatekeeperX. Envía eventos (login, transacción, onboarding, etc.) y recibe la decisión de riesgo del servicio.

Funciona en Node 18+/AWS Lambda y en cualquier proyecto TypeScript moderno. Compilado en ESM + CJS, sin dependencias de runtime.

Instalación

npm install @gatekeeperx/events-client

Requiere Node 18+ (usa el fetch global). En runtimes sin fetch, puedes pasar una implementación en la configuración (fetch).

Qué necesitas

Para conectarte, GatekeeperX te entrega:

  • tenant — identificador de tu organización.
  • apiKey — tu API key (secreta).
  • environmentsandbox para pruebas o production.

Uso

Inicializar con el builder

import { EventsApiClient } from '@gatekeeperx/events-client';

const client = EventsApiClient.builder()
  .sandbox()                          // o .production()
  .tenant('tu-tenant')
  .apiKey(process.env.GKX_API_KEY!)   // nunca lo hardcodees
  .build();

Inicializar con objeto de configuración

const client = new EventsApiClient({
  environment: 'sandbox',
  tenant: 'tu-tenant',
  apiKey: process.env.GKX_API_KEY!,
});

Enviar un evento y leer la decisión

const res = await client.processEvent(
  {
    eventType: 'login',
    customer: { customerId: '123' },
    device: { deviceId: 'abc' },
  },
  { returnScore: true, returnFeatures: true },
);

console.log(res.decision);          // p.ej. "APPROVED"
console.log(res.evaluation?.score); // score de riesgo (si pediste returnScore)
console.log(res.requestId);         // id de la evaluación

Cada evento debe incluir al menos una entidad (customer, device, transaction, order, paymentMethod, merchant, o uno de sus *Id). El timestamp se completa automáticamente si no lo envías.

Parámetros configurables

| Builder | Objeto de config | Default | Descripción | | --- | --- | --- | --- | | .tenant(t) | tenant | — (requerido) | Tu identificador de organización. | | .apiKey(k) | apiKey | — (requerido) | Tu API key. | | .organizationId(o) | organizationId | = tenant | Solo si GatekeeperX te indica un valor distinto al tenant. | | .sandbox()/.production()/.environment(e) | environment | sandbox | Ambiente: sandbox o production. | | .baseUrl(u) | baseUrl | — | URL base personalizada (p.ej. para un proxy propio). | | .timeout(ms) | timeoutMs | 30000 | Timeout por request en ms (0 lo desactiva). | | .maxRetries(n) | maxRetries | 3 | Reintentos automáticos ante fallos transitorios. | | .retryBackoff(ms) | retryBackoffMs | 500 | Espera base entre reintentos. | | .retryMultiplier(m) | retryMultiplier | 2.0 | Factor de crecimiento de la espera. | | .maxBackoff(ms) | maxBackoffMs | 10000 | Tope de la espera entre reintentos. | | .defaults(d) | defaults | false | Flags por defecto (returnScore, returnFeatures, pointInTimeEvaluation). | | .headers(h) | headers | {} | Headers adicionales para cada request. | | .fetch(f) | fetch | globalThis.fetch | Implementación de fetch (testing / edge). |

processEvent(event, returnScoreOrOptions?)

  • processEvent(event) — envía el evento.
  • processEvent(event, true) — además pide el score de riesgo.
  • processEvent(event, { returnScore, returnFeatures, pointInTimeEvaluation, timeoutMs, skipValidation, headers, signal }) — control fino por llamada.

Manejo de errores

Todos los errores extienden GatekeeperXException (con statusCode, errorCode, requestId):

| Excepción | Cuándo ocurre | | --- | --- | | ConfigurationException | Configuración inválida (tenant/apiKey faltante, URL inválida). | | ValidationException | Evento inválido, o el servicio rechazó el payload (400/422). | | AuthenticationException | API key inválida (401). | | AuthorizationException | Sin permisos (403). | | NotFoundException | Recurso no encontrado (404). | | RateLimitException | Límite de tasa alcanzado (429); incluye retryAfter. | | ServerException | Error del servidor (5xx). | | NetworkException | Fallo de red o cancelación. | | TimeoutException | La request superó el timeout. |

import { GatekeeperXException, RateLimitException } from '@gatekeeperx/events-client';

try {
  await client.processEvent({ customer: { customerId: '1' } }, true);
} catch (err) {
  if (err instanceof RateLimitException) {
    console.error('rate limited, reintenta en', err.retryAfter, 's');
  } else if (err instanceof GatekeeperXException) {
    console.error(err.statusCode, err.requestId, err.message);
  }
}

El cliente reintenta automáticamente los fallos transitorios (timeouts, errores de red, 429 y 5xx) con backoff exponencial.

Uso en AWS Lambda

import { EventsApiClient } from '@gatekeeperx/events-client';

// Crea el cliente a nivel de módulo para reutilizarlo entre invocaciones.
const client = EventsApiClient.builder()
  .production()
  .tenant(process.env.GKX_TENANT!)
  .apiKey(process.env.GKX_API_KEY!)
  .build();

export async function handler(event: { customerId: string }) {
  const res = await client.processEvent(
    { eventType: 'login', customer: { customerId: event.customerId } },
    { returnScore: true },
  );
  return { decision: res.decision, score: res.evaluation?.score };
}

Ver más en examples/lambda-handler.ts.

Seguridad

⚠️ La apiKey es un secreto. Úsala en entornos de servidor (Lambda, backend) y léela desde variables de entorno o un gestor de secretos. No la expongas en código de navegador en producción.