Ir al contenido
Reks.
Guías y referencia

Ejemplos verificados

Los quickstarts y esta referencia usan una sola fuente. Sustituye los marcadores y conserva una política revisada; los ejemplos no habilitan un entorno real.

En esta página

Navegador

Instalar el archivo privado del SDK frontend
@reks/sdk-browser 0.4.0 · sh
# Recibe el archivo y su SHA-256 por el canal autorizado de tu equipo.
# Guarda el archivo verificado en ./distribuciones/.
npm install --ignore-scripts ./distribuciones/reks-sdk-browser-0.4.0.tgz
Instalación mínima en el navegador
@reks/sdk-browser 0.4.0 · typescript
import { installBugSDK } from "@reks/sdk-browser";

// Sustituye estos identificadores y orígenes por tu configuración pública aprobada.
export function startReks() {
  return installBugSDK({
    organizationId: "TU_ORGANIZACION",
    projectId: "TU_PROYECTO",
    publicKey: "TU_CLAVE_PUBLICA_DE_PROYECTO",
    environment: "preview",
    serviceId: "web",
    releaseId: "TU_RELEASE",
    collectorOrigin: "https://collector.example.test",
    privacyPolicy: {
      policyVersion: 1,
      projectId: "TU_PROYECTO",
      allowedRouteTemplates: ["/panel"],
      prohibitedRoutePrefixes: ["/privado"],
      allowedActionSelectors: [],
      prohibitedSelectors: ["[data-reks-private]", "[data-client-signal-private]"],
    },
    currentRouteTemplate: () => location.pathname === "/panel" ? "/panel" : null,
    requestRouteTemplate: () => null, // Sin capturas de red no revisadas.
  });
}

const sdk = startReks();
// Conecta el router real si necesitas registrar una navegación permitida.
sdk.recordNavigation();
// Función local: el host DEBE llamarla antes de cambiar sesión/organización
// y al desmontar; no se ejecuta inmediatamente al instalar.
export function stopReks() { sdk.stop(); }
React: instalar y desmontar por identidad
@reks/sdk-browser 0.4.0 + React · typescript
import { useEffect } from "react";
import { installBugSDK, type BugSDKConfig } from "@reks/sdk-browser";

type Props = {
  config: BugSDKConfig;
  // Función de tu aplicación: avisa ANTES del cambio real de identidad.
  subscribeBoundary: (stop: () => void) => () => void;
};
export function ReksCapture({ config, subscribeBoundary }: Props) {
  useEffect(() => {
    const sdk = installBugSDK(config);
    const unsubscribe = subscribeBoundary(() => sdk.stop());
    return () => { unsubscribe(); sdk.stop(); };
  }, [config, subscribeBoundary]);
  return null;
}
// Mantén ambas props estables para la misma identidad. El callback síncrono
// de tu auth/org detiene captura antes del cambio, aunque la URL no cambie.
// El cleanup de React es adicional; no sustituye ese límite real.
Política instalada de logs estructurados
@reks/sdk-browser 0.4.0 · typescript
export const structuredLogs = {
  schemaVersion: 1,
  minLevel: "info",
  definitions: [{
    code: "panel_saved",
    category: "system",
    attributes: { result: { values: ["ok", "failed"] } },
  }],
} as const;
// Añade esta política revisada a privacyPolicy.structuredLogs.
// No se habilitan logs si esa política no existe.
Emitir un código aprobado
@reks/sdk-browser 0.4.0 · typescript
import type { BugSDK } from "@reks/sdk-browser";

export async function recordSaved(sdk: BugSDK) {
  sdk.logger.info("panel_saved", { result: "ok" });
  // Un intento acotado. "sent" no significa salud de la aplicación.
  const result = await sdk.flush();
  return result; // "empty" | "sent" | "failed" | "closed"
}
Reducir captura desde un canal confiable del host
@reks/sdk-browser 0.4.0 · typescript
import type { BugSDK } from "@reks/sdk-browser";
export function pauseCapture(sdk: BugSDK, revision: number) {
  return sdk.applyCaptureConfig({
    schemaVersion: 1,
    revision,
    captureEnabled: false,
    sampleRate: 0,
  });
}
// Reduce-only. No amplía rutas, selectores ni permisos; no reactiva un handle
// detenido. El host aporta la configuración por un canal confiable.

Servidor

Instalar el archivo privado del SDK backend
@reks/sdk-node 0.2.0 · sh
# Node.js 22 o superior. Verifica antes el SHA-256 recibido.
npm install --ignore-scripts ./distribuciones/reks-sdk-node-0.2.0.tgz
Contexto técnico explícito y cierre acotado
@reks/sdk-node 0.2.0 · typescript
import { installNodeSDK } from "@reks/sdk-node";

export function createObservability() {
  return installNodeSDK({
    scope: {
      organizationId: "TU_ORGANIZACION",
      projectId: "TU_PROYECTO",
      environment: "preview",
      serviceId: "api",
      releaseId: "TU_RELEASE",
    },
    collectorOrigin: "https://collector.example.test",
    credential: process.env.REKS_SERVER_EVIDENCE_CREDENTIAL,
    privacyPolicy: {
      policyVersion: 1,
      projectId: "TU_PROYECTO",
      allowedRouteTemplates: ["/panel"],
      prohibitedRoutePrefixes: ["/privado"],
      allowedActionSelectors: [],
      prohibitedSelectors: [],
      structuredLogs: {
        schemaVersion: 1,
        minLevel: "info",
        definitions: [{
          code: "panel_saved",
          category: "system",
          attributes: { result: { values: ["ok", "failed"] } },
        }],
      },
    },
  });
}

export async function runExample() {
  const sdk = createObservability();
  try {
    await sdk.run("/panel", async () => {
      sdk.logger.info("panel_saved", { result: "ok" });
    });
  } finally {
    await sdk.shutdown(1500);
  }
}
// REKS_SERVER_EVIDENCE_CREDENTIAL es una variable de TU servidor en este
// ejemplo, no una credencial incluida ni un endpoint ya habilitado.
Fastify: adaptar antes de registrar rutas
@reks/sdk-node 0.2.0 · typescript
import { instrumentFastify } from "@reks/sdk-node/fastify";
import type { NodeSDK } from "@reks/sdk-node";

type FastifyTarget = Parameters<typeof instrumentFastify>[0];
export function attachReksToFastify(app: FastifyTarget, sdk: NodeSDK) {
  instrumentFastify(app, sdk); // Una vez, antes de registrar rutas.
}
// En Nest + Fastify, úsalo sobre el adaptador antes de init()/listen().
// No es un adaptador Express ni instala un proveedor OpenTelemetry global.

Integración manual según contrato

No universal

La fábrica gestionada actual tiene un contrato específico y no admite perfiles sensibles. El bootstrap local exige su propio adaptador/transporte aprobado.

Distribución privada del bridge y relay
host-bridge 0.2.1 / relay 0.2.0 · sh
# Bridge: dependencia de la aplicación host, nunca JS remoto en su página.
npm install --ignore-scripts ./distribuciones/reks-host-bridge-0.2.1.tgz
# Relay: sólo en el servidor que autentica a tus usuarios.
npm install --ignore-scripts ./distribuciones/reks-relay-0.2.0.tgz
Conectar el bridge con el adaptador de tu aplicación
@reks/host-bridge 0.2.1 · typescript
import { mountFeedbackIntegration } from "@reks/host-bridge";

type Bindings = Pick<Parameters<typeof mountFeedbackIntegration>[0],
  "currentToken" | "currentBoundary" | "subscribe" |
  "configure" | "send" | "status">;

// bindings son funciones de TU adaptador, no helpers suministrados por Reks.
export function attachFeedback(target: HTMLElement, bindings: Bindings) {
  const integration = mountFeedbackIntegration({
    window,
    target,
    projectId: "TU_PROYECTO",
    widgetOrigin: "https://reportes.example.test",
    ...bindings,
  });
  return () => integration.dispose();
}
// configure/send hablan con TU backend autenticado y respetan AbortSignal.
// subscribe debe notificar cambios reales de sesión, organización y elegibilidad.
// currentBoundary devuelve una clave local estable de esa identidad; no se envía
// como telemetría. No instales un captureCeiling que no haya sido aprobado.
Punto de montaje para un transporte propio aprobado
@reks/host-bridge 0.2.1 · typescript
import { mountFeedbackWidget, type WidgetBootstrapOptions } from "@reks/host-bridge";

// options procede del adaptador específico aprobado de TU aplicación.
export function attachApprovedWidget(options: WidgetBootstrapOptions) {
  const widget = mountFeedbackWidget(options);
  return { open: () => widget.open(), dispose: () => widget.destroy() };
}
// Este ejemplo es una función local, no una API nueva de Reks.
// Valida orígenes/configuración y conecta el teardown síncrono de identidad.
// No reenvíes tokens privados al iframe ni actives un perfil no aprobado.
Proyectar sólo la configuración pública
@reks/relay 0.2.0 · typescript
import { loadFeedbackIntegration, publicFeedbackConfiguration,
  type RelayConnection } from "@reks/relay";

export async function readPublicConfiguration(connection: RelayConnection | null) {
  // connection procede de TU servidor: no serializarla al navegador.
  const config = await loadFeedbackIntegration(connection, {
    projectId: "TU_PROYECTO",
    widgetOrigin: "https://reportes.example.test",
  });
  return config ? publicFeedbackConfiguration(config) : null;
}
// Autentica y comprueba elegibilidad en TU endpoint antes de llamar esta función.
// El envío requiere FeedbackRelay + reserva durable de cuota/idempotencia.
// Este ejemplo de lectura no implementa un backend completo de reportes.

Operador local

Instalar la CLI independiente
@reks/cli 0.2.0 · Node.js 22+ · sh
# Usa una instalación de Node de tu usuario; no requiere la app cliente.
npm install --global --ignore-scripts ./distribuciones/reks-cli-0.2.0.tgz
reks --help
Archivo local privado de credenciales
@reks/cli 0.2.0 · dotenv
# reks.local.env — fuera de Git. Sustituye todos los marcadores.
REKS_CONSOLE_URL=https://console.example.test
REKS_OPERATOR_EMAIL=TU_CORREO_DE_OPERADOR
REKS_OPERATOR_PASSWORD=TU_CREDENCIAL_LOCAL
Leer y diagnosticar el alcance autorizado
@reks/cli 0.2.0 · sh
chmod 600 reks.local.env
reks doctor --origin https://console.example.test \
  --credentials ./reks.local.env --project-id TU_PROYECTO
reks signals:permissions --origin https://console.example.test \
  --credentials ./reks.local.env --project-id TU_PROYECTO
reks signals:list --origin https://console.example.test \
  --credentials ./reks.local.env --project-id TU_PROYECTO
reks signals:read --origin https://console.example.test \
  --credentials ./reks.local.env --project-id TU_PROYECTO --signal-id TU_REPORTE
nota-revisada.json
@reks/cli 0.2.0 · json
{"text":"Nota revisada del equipo con contexto no sensible."}
Una escritura revisada necesita intención explícita
@reks/cli 0.2.0 · sh
# Revisa primero el JSON, tu permiso y el alcance de la operación.
# Usa el mismo action-id sólo para esa operación idéntica revisada.
reks signals:note --origin https://console.example.test \
  --credentials ./reks.local.env --project-id TU_PROYECTO --signal-id TU_REPORTE \
  --input ./nota-revisada.json --action-id TU_ID_ESTABLE --confirm
# --confirm no sustituye autorización. No reintentes automáticamente una escritura
# cuyo resultado sea ambiguo. Este comando NO cierra ni aprueba el reporte.