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

@ominiflow/sdk

v1.0.0-rc.0

Published

Official TypeScript SDK for OmniFlow CPaaS platform

Downloads

61

Readme

@omniflow/sdk

SDK TypeScript oficial do OmniFlow CPaaS — envio de mensagens, gestão de conversas, contatos, caixas de entrada e webhooks com retry automático e tipagem completa.

Instalação

npm install @omniflow/sdk
# ou
bun add @omniflow/sdk

Quick Start

import { OmniFlow } from '@omniflow/sdk';

const client = new OmniFlow({ apiKey: 'omf_live_...' });

// ou OAuth Client Credentials
const oauthClient = new OmniFlow({
  oauth: {
    clientId: 'client_123',
    clientSecret: 'secret_123',
  },
});

// Enviar uma mensagem de texto
const message = await client.messages.send({
  to: '+5511999999999',
  channel: 'whatsapp_official',
  content: { type: 'text', text: 'Olá! Como posso ajudar?' },
});

console.log(message.id, message.conversationId);

Configuração

const client = new OmniFlow({
  apiKey: 'omf_live_...',          // obrigatório
  baseUrl: 'https://api.sua-instancia.com', // opcional — padrão: https://api.omniflow.com.br
  timeout: 30_000,                  // ms — padrão: 30000
  maxRetries: 3,                    // padrão: 3
});

const oauthClient = new OmniFlow({
  oauth: {
    clientId: 'client_123',
    clientSecret: 'secret_123',
    tokenPath: '/v1/oauth/token', // opcional
  },
});

Recursos

client.messages

// Enviar mensagem de texto
await client.messages.send({ to, channel, content: { type: 'text', text } });

// Enviar imagem
await client.messages.send({ to, channel, content: { type: 'image', url, caption } });

// Listar mensagens de uma conversa
const { data, nextCursor } = await client.messages.list(conversationId, { limit: 50 });

// Iterar por todas as mensagens via cursor
for await (const message of client.messages.listAll(conversationId, { limit: 100 })) {
  console.log(message.id);
}

client.conversations

// Listar conversas
const { data } = await client.conversations.list({ status: 'open', inboxId, limit: 25 });

// Iterar por todas as conversas abertas
for await (const conversation of client.conversations.listAll({ status: 'open', limit: 100 })) {
  console.log(conversation.id);
}

// Buscar por ID
const conv = await client.conversations.get(id);

// Marcar como resolvida
await client.conversations.resolve(id);

// Atribuir a um agente
await client.conversations.assign(id, { agentId: 'agent-uuid' });

// Reabrir conversa resolvida
await client.conversations.reopen(id);

client.contacts

// Criar contato
const contact = await client.contacts.create({ phoneNumber: '+5511999999999', name: 'Maria' });

// Buscar por ID
const contact = await client.contacts.get(id);

// Buscar por telefone
const contact = await client.contacts.findByPhone('+5511999999999'); // null se não encontrado

client.inboxes

// Listar caixas de entrada
const inboxes = await client.inboxes.list();

client.templates

// Listar templates aprovados
const templates = await client.templates.list({ channel: 'whatsapp_official' });

// Enviar mensagem via template
await client.templates.send({
  to: '+5511999999999',
  channel: 'whatsapp_official',
  templateId: 'boas_vindas_v1',
  params: { nome: 'João', empresa: 'Acme' },
});

client.webhooks

CRUD de endpoints

// Listar webhooks cadastrados
const webhooks = await client.webhooks.list();

// Criar webhook
const wh = await client.webhooks.create({
  url: 'https://sua-api.com/omniflow/webhook',
  events: ['message.received', 'conversation.created'],
  secret: 'seu-segredo-aqui',
});

// Remover webhook
await client.webhooks.delete(wh.id);

// Histórico de entregas
const { data } = await client.webhooks.listDeliveries(wh.id, { limit: 20 });

Verificação de assinatura

import { verifyWebhookSignature } from '@omniflow/sdk';

// Em seu servidor Express/Hono/Fastify:
app.post('/omniflow/webhook', async (req, res) => {
  const rawBody = await req.text(); // leia o body como string bruta
  const sig = req.headers['x-omniflow-signature-256'] ?? '';

  const valid = await verifyWebhookSignature({
    payload: rawBody,
    signature: sig,
    secret: process.env.WEBHOOK_SECRET!,
  });
  if (!valid) return res.status(401).send('Unauthorized');

  const event = client.webhooks.parse(rawBody);
  // event.type, event.tenantId, event.payload, event.timestamp
});

Tratamento de Erros

import { OmniFlow, OmniFlowApiError } from '@omniflow/sdk';

try {
  await client.messages.send({ ... });
} catch (err) {
  if (err instanceof OmniFlowApiError) {
    console.error(err.status);    // HTTP status code (ex: 422, 429)
    console.error(err.code);      // código de erro da API (ex: "quota_exceeded")
    console.error(err.requestId); // X-Request-Id para abertura de suporte
  }
  throw err;
}

Retry automático

O SDK faz até 3 tentativas (configurável via maxRetries) com backoff exponencial:

| Situação | Comportamento | |---|---| | 429 Too Many Requests | Aguarda Retry-After (máx. 60s) e retenta | | 5xx Server Error | Exponential backoff com jitter até o teto de 1s → 2s → 4s | | 4xx Client Error | Lança OmniFlowApiError imediatamente (sem retry) | | Timeout / rede | Exponential backoff com jitter até maxRetries |

Tipos Exportados

import type {
  Channel,
  ContactDto,
  ConversationDto,
  InboxDto,
  MessageDto,
  OmniFlowOpenApiPaths,
  TemplateDto,
  VerifyWebhookSignatureParams,
  WebhookDto,
  WebhookDeliveryDto,
  WebhookEvent,
  WebhookEventType,
  // params
  SendMessageParams,
  SendTemplateParams,
  CreateContactParams,
  CreateWebhookParams,
  AssignConversationParams,
  // paginação
  PaginatedResult,
} from '@omniflow/sdk';

Eventos de Webhook

| Tipo | Payload | |---|---| | message.received | { messageId, conversationId, channel, direction } | | conversation.created | { conversationId, contactId, inboxId } | | conversation.resolved | { conversationId, resolvedBy } | | contact.opted_out | { contactId, phoneNumber } |

Licença

MIT © OmniFlow Team