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

@noctamble/synapse

v1.0.0

Published

Validador de contratos y arquitectura de servicios por casuísticas y roles

Readme

⚡ @noctamble/synapse

Validador de contratos y arquitectura de servicios por casuísticas y roles con Zod, resiliencia (SLAs/reintentos) y dashboards ejecutivos.

npm version License: MIT


🎯 ¿Por qué Synapse?

En arquitecturas modernas (Next.js, Microservicios, APIs REST/GraphQL), un mismo endpoint suele responder diferente según la casuística o rol del usuario:

  • Un visitante anónimo / invitado recibe menús básicos sin acceso a herramientas privadas.
  • Un usuario regular (B2C) recibe puntos de lealtad, membresías y ofertas individuales.
  • Un cliente corporativo (B2B) recibe tarifas mayoristas, líneas de crédito, identificadores tributarios y portales dedicados.

Synapse permite orquestar flujos continuos que simulan y auditan estas casuísticas, asegurando que tus contratos de datos, latencias (SLAs) y tolerancia a fallos se cumplan rigurosamente.


✨ Características Principales

  • 🎭 Casuísticas y Roles Nativos: Etiqueta pasos por rol (role: "PUBLICO" | "REGULAR" | "B2B") para visualizar con exactitud qué contrato se evaluó.
  • ⏱️ SLAs y Control de Latencia: Define maxDurationMs por paso. Si el servicio responde más lento de lo pactado, Synapse reportará una advertencia de SLA sin romper la ejecución de contratos.
  • 🔄 Resiliencia y Reintentos: Configura retries y retryDelayMs para tolerar fluctuaciones temporales de red o picos de carga.
  • ⏱️ Timeouts: Define timeoutMs para cancelar peticiones colgadas de forma segura.
  • 💻 Consola Rápida por Defecto: En local o en CI/CD corre en consola con formato limpio y cero overhead.
  • 📊 Dashboard HTML con un Flag: Agrega --ui o { ui: true } y Synapse abrirá automáticamente un informe visual interactivo con diseño Glassmorphism, métricas por módulo y explorador de errores Zod.
  • 🐙 Soporte Nativo para GitHub Actions: Genera tablas en Markdown listas para $GITHUB_STEP_SUMMARY mediante writeGitHubStepSummary().
  • 🔁 Compatibilidad Total: Exporta SynapseRunner y SynapseSuite como nombres principales, manteniendo ArchTraceRunner y ArchTraceSuite como alias compatibles.

📦 Instalación

# npm
npm install @noctamble/synapse zod

# pnpm
pnpm add @noctamble/synapse zod

# bun
bun add @noctamble/synapse zod

Nota: Requiere zod >= 3.22.0 o zod 4.x instalado en tu proyecto.


🚀 Inicio Rápido: Evaluando Casuísticas por Rol

Crea tu prueba en un archivo TypeScript (ej. test-navigation.ts):

import { SynapseRunner, SynapseSuite } from "@noctamble/synapse";
import { z } from "zod";

// 1. Define contratos esperados por rol
const GuestMenuSchema = z.object({
  items: z.array(z.object({ label: z.string(), path: z.string() })),
  userRole: z.literal("GUEST"),
  hasEnterprisePortal: z.literal(false),
});

const B2BMenuSchema = z.object({
  items: z.array(z.object({ label: z.string(), path: z.string() })),
  userRole: z.literal("B2B_ENTERPRISE"),
  hasEnterprisePortal: z.literal(true),
  companyTaxId: z.string(),
});

async function run() {
  // 2. Runner para Invitado
  const guestRunner = new SynapseRunner();
  guestRunner.addStep({
    module: "Navigation",
    name: "getMenu",
    role: "PUBLICO",
    action: async () => fetch("/api/menu").then(r => r.json()),
    schema: GuestMenuSchema,
    maxDurationMs: 250, // SLA: Menos de 250ms
  });

  // 3. Runner para Cliente Corporativo B2B
  const b2bRunner = new SynapseRunner();
  b2bRunner.addStep({
    module: "Navigation",
    name: "getMenu",
    role: "EMPRESARIAL",
    action: async () => fetch("/api/menu", {
      headers: { Authorization: "Bearer token_b2b_corp" }
    }).then(r => r.json()),
    schema: B2BMenuSchema,
    retries: 2, // Reintenta 2 veces si falla
    maxDurationMs: 350,
  });

  // 4. Suite Global
  const suite = new SynapseSuite({
    title: "Auditoría de Menús por Casuística",
    environment: "Staging",
  });

  suite.addRunner("Invitado", guestRunner);
  suite.addRunner("Corporativo B2B", b2bRunner);

  // Corre en consola por defecto
  await suite.runAll();
}

run();

🖥️ Ejecución en Consola vs Interfaz Gráfica (UI)

1. Solo Consola (Rápido)

bun test-navigation.ts
# o con Node:
npx tsx test-navigation.ts

2. Abrir Dashboard Gráfico en el Navegador

Pasa el flag --ui directamente en tu comando de terminal:

bun test-navigation.ts --ui

Synapse detectará el flag, creará el dashboard HTML (synapse-dashboard.html) y lo abrirá en tu navegador por defecto.

También puedes habilitarlo programáticamente:

await suite.runAll({ ui: true });

🤖 Integración en CI/CD (GitHub Actions)

En tu pipeline de GitHub Actions, puedes activar la salida a $GITHUB_STEP_SUMMARY:

name: Contract Validation
on: [push, pull_request]

jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
      - run: npm ci
      - run: npx tsx test-navigation.ts --ci --exit-on-failure
        env:
          GITHUB_STEP_SUMMARY: $GITHUB_STEP_SUMMARY

O programáticamente:

await suite.runAll({
  exitOnFailure: true,
  githubStepSummary: true
});

📖 Opciones del Paso (StepDefinition)

| Propiedad | Tipo | Descripción | | :--- | :--- | :--- | | name | string | Nombre del paso o método. | | module | string | Módulo o servicio al que pertenece (ej. AuthService, Catalog). | | role | string | (Opcional) Rol asociado ("PUBLICO", "REGULAR", "EMPRESARIAL", "B2B"). | | action | (ctx) => Promise<any> | Función asíncrona que invoca el servicio o API. | | schema | ZodType<any> | Esquema de Zod contra el cual se validará el resultado. | | maxDurationMs | number | (Opcional) SLA de latencia esperada en milisegundos. | | retries | number | (Opcional) Cantidad de reintentos antes de marcar como fallido. | | retryDelayMs | number | (Opcional) Espera entre reintentos en ms (por defecto: 100ms). | | timeoutMs | number | (Opcional) Tiempo límite máximo de ejecución en ms. |


📄 Licencia

MIT © 2026