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

pulsesocketdb

v1.2.2

Published

Client SDK for PulseSocketDB — a self-hosted real-time BaaS built on Fastify, Socket.io and Redis.

Readme

pulsesocketdb

English | Português (Brasil)


English

A lightweight, fully-typed real-time Client SDK for PulseSocketDB — a pioneering Control Plane Real-Time Backend-as-a-Service (BaaS) engineered for 100% Data Sovereignty and sub-millisecond event synchronization.

🚀 Key Advantages

  • 🛡️ Data Sovereignty: Managed Control Plane with 100% data custody on your own VPS Redis instance (LGPD/GDPR Native Compliance).
  • Sub-Millisecond Sync: Real-time event propagation powered by Socket.io and Redis Pub/Sub.
  • 🌐 Pure WebSocket Architecture: Initial snapshot data and live events arrive 100% over WebSockets with zero HTTP requests.
  • 🔄 Automatic Reconnection: Seamlessly re-establishes all active subscriptions and initial data on network reconnect.
  • 💰 Predictable Pricing: No per-operation read/write surcharges. Fixed monthly Control Plane rates.
  • 🔒 Zero Vendor Lock-in: Standard Redis Hash data structures.

📦 Installation

Install the official SDK via npm, yarn, or pnpm:

npm install pulsesocketdb

🔌 Getting Started

Initialize the client with your project environment API Key (pk_dev_..., pk_staging_..., or pk_prod_...):

import { PulseSocketDB } from 'pulsesocketdb';

const db = new PulseSocketDB({
  apiKey: 'YOUR_PULSESOCKETDB_API_KEY',
  apiBase: 'https://api.pulsesocketdb.com' // or your custom Core API host
});

1. Fetching Documents (GET) & Checking Existence

To read all documents inside a collection or check if a single document exists:

// Fetch all documents in a collection
const docs = await db.collection('messages').get();

// Check if a document exists
const exists = await db.collection('messages').doc('my-custom-id').exists();
console.log('Document exists?', exists); // true / false

2. Auto-generating Stable IDs (POST)

To create a document with an auto-generated unique, stable ID:

const response = await db.collection('messages').add({
  text: 'Hello world!',
  timestamp: new Date().toISOString()
});
console.log('New Document ID:', response.id);

3. Setting/Overwriting by ID (PUT)

To write or completely overwrite a document with a specific ID:

await db.collection('messages').doc('my-custom-id').set({
  text: 'Updated text content!',
  timestamp: new Date().toISOString()
});

4. Partial Merging / Updating (PATCH)

To update specific fields of a document without erasing existing fields (Firebase-style shallow merge):

await db.collection('messages').doc('my-custom-id').update({
  status: 'read' // Only updates 'status', keeping text and timestamp intact
});

5. Deleting by ID (DELETE)

To delete a document by its ID:

await db.collection('messages').doc('my-custom-id').delete();

6. Real-Time Synchronization (WebSockets)

Listen to live document updates (inserts, updates, deletes) in real-time. Initial state and real-time events are transmitted purely over WebSockets (0 HTTP requests). Subscriptions auto-reconnect on network drops.

Collection-Level Subscription

Listens to updates for all documents in a collection:

const unsubscribe = db.collection('messages').onSnapshot(
  (change) => {
    if (change.deleted) {
      console.log(`Document ${change.id} was deleted!`);
    } else {
      console.log(`Document ${change.id} was added/updated:`, change.data);
    }
  },
  (error) => {
    console.error('Subscription error:', error);
  }
);

// Stop listening later (also notifies server to clean up subscription room):
// unsubscribe();
Document-Level Subscription

Subscribe to changes on a single document specifically:

const unsubscribe = db.collection('messages').doc('message-123').onSnapshot(
  (change) => {
    if (change.deleted) {
      console.log('Document was deleted!');
    } else {
      console.log('Document updated:', change.data);
    }
  },
  (error) => {
    console.error('Document subscription error:', error);
  }
);

7. Connection State & Lifecycle Management

Monitor connection status or control the connection lifecycle manually:

// Listen to connection state changes
const unsubscribeState = db.onConnectionStateChange((state) => {
  // 'disconnected' | 'connecting' | 'connected' | 'reconnecting'
  console.log('Connection state:', state);
});

// Access current state synchronously
console.log('Is connected?', db.connectionState === 'connected');

// Manually disconnect (preserves subscription definitions)
db.disconnect();

// Reconnect (automatically re-subscribes all listeners with fresh data)
db.connect();

Português (Brasil)

SDK leve, totalmente tipado em TypeScript e em tempo real para o PulseSocketDB — um motor pioneiro de Backend-as-a-Service (BaaS) em tempo real no modelo Control Plane projetado para 100% de Soberania de Dados e sincronização sub-milissegundo.

🚀 Vantagens Exclusivas

  • 🛡️ Soberania de Dados: Control Plane gerenciado com 100% da custódia dos dados de produção na sua própria VPS Redis (Conformidade nativa com a LGPD e GDPR).
  • Sincronização Sub-Milissegundo: Propagação de eventos em tempo real com Socket.io e Redis Pub/Sub.
  • 🌐 Arquitetura 100% WebSocket: Snapshots iniciais e eventos ao vivo trafegam via WebSocket com zero requisições HTTP.
  • 🔄 Reconexão Automática: Restaura automaticamente todas as assinaturas e atualiza os dados ao reconectar à rede.
  • 💰 Previsibilidade Financeira: Sem taxas absurdas por leitura/escrita. Valor mensal fixo de capacidade.
  • 🔒 Zero Vendor Lock-in: Dados armazenados em estruturas padrão Redis Hash.

📦 Instalação

Instale o SDK oficial via npm, yarn ou pnpm:

npm install pulsesocketdb

🔌 Como Começar

Inicialize o cliente utilizando a chave de API do ambiente do seu projeto (pk_dev_..., pk_staging_... ou pk_prod_...):

import { PulseSocketDB } from 'pulsesocketdb';

const db = new PulseSocketDB({
  apiKey: 'SUA_CHAVE_API_PULSESOCKETDB',
  apiBase: 'https://api.pulsesocketdb.com' // ou a URL do seu servidor Core API
});

1. Buscando Documentos (GET) e Checando Existência

Para ler todos os documentos dentro de uma coleção ou verificar se um documento existe:

// Buscar todos os documentos de uma coleção
const docs = await db.collection('mensagens').get();

// Verificar se um documento existe sem erro 404
const existe = await db.collection('mensagens').doc('meu-id-customizado').exists();
console.log('Documento existe?', existe); // true / false

2. Criando Documentos com ID Automático (POST)

Para criar um documento com um ID estável e único gerado automaticamente:

const resposta = await db.collection('mensagens').add({
  texto: 'Olá mundo!',
  dataCriacao: new Date().toISOString()
});
console.log('ID do novo documento:', resposta.id);

3. Salvando/Sobrescrevendo por ID (PUT)

Para gravar ou sobrescrever completamente um documento com um ID específico:

await db.collection('mensagens').doc('meu-id-customizado').set({
  texto: 'Conteúdo atualizado!',
  dataAtualizacao: new Date().toISOString()
});

4. Atualização Parcial / Merge (PATCH)

Para atualizar apenas campos específicos de um documento preservando os outros (merge rasa estilo Firebase):

await db.collection('mensagens').doc('meu-id-customizado').update({
  lida: true // Atualiza apenas o campo 'lida', mantendo o texto e data intactos
});

5. Excluindo por ID (DELETE)

Para remover um documento pelo seu ID:

await db.collection('mensagens').doc('meu-id-customizado').delete();

6. Sincronização em Tempo Real (WebSockets)

Escute atualizações ao vivo de documentos (inserções, edições, exclusões) em tempo real via WebSockets. Snapshots iniciais e eventos chegam 100% via WebSocket (0 requisições HTTP). Re-assinatura automática em quedas de conexão.

Assinatura em Nível de Coleção

Escuta alterações de todos os documentos em uma coleção:

const cancelarInscricao = db.collection('mensagens').onSnapshot(
  (mudanca) => {
    if (mudanca.deleted) {
      console.log(`O documento ${mudanca.id} foi excluído!`);
    } else {
      console.log(`O documento ${mudanca.id} foi atualizado:`, mudanca.data);
    }
  },
  (erro) => {
    console.error('Erro na assinatura:', erro);
  }
);

// Para cancelar a inscrição (libera também a sala no servidor):
// cancelarInscricao();
Assinatura em Nível de Documento

Escute atualizações de um único documento específico:

const cancelarInscricao = db.collection('mensagens').doc('mensagem-123').onSnapshot(
  (mudanca) => {
    if (mudanca.deleted) {
      console.log('O documento foi excluído!');
    } else {
      console.log('Documento atualizado:', mudanca.data);
    }
  },
  (erro) => {
    console.error('Erro na assinatura do documento:', erro);
  }
);

7. Gerenciamento de Conexão e Ciclo de Vida

Monitore o status da conexão ou controle o ciclo de vida manualmente:

// Monitorar mudanças no status da conexão
const cancelarStatus = db.onConnectionStateChange((estado) => {
  // 'disconnected' | 'connecting' | 'connected' | 'reconnecting'
  console.log('Status da conexão:', estado);
});

// Consultar o status atual de forma síncrona
console.log('Está conectado?', db.connectionState === 'connected');

// Desconectar manualmente (preserva as definições de assinatura)
db.disconnect();

// Reconectar (re-assina automaticamente todos os listeners com dados atualizados)
db.connect();

📝 Licença / License

Distribuído sob a licença MIT. Consulte LICENSE para obter mais detalhes.