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

@hubmessage/connect

v1.0.0

Published

Hub Message SDK for browser applications

Downloads

281

Readme

@hubmessage/connect

SDK para conectar seus canais via HubMessage.

Funciona em qualquer projeto frontend: React, Angular, Vue, vanilla JS ou direto via <script> no HTML.


Instalacao

npm / yarn / pnpm

npm install @hubmessage/connect

CDN (script tag)

<script src="https://unpkg.com/@hubmessage/connect"></script>

Quick Start

const client = HubMessage.newClient({ publicKey: "sua-public-key" });

const response = await client.connect({
  channelId: "id-do-canal",
});

if (response.success) {
  // envie response para seu backend
  await fetch("/api/connect-channel", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(response),
  });
}

Como funciona

+-----------+        +-------------+        +-----------+        +----------------+
|  Seu App  |  --->  |  SDK Client |  --->  |  Meta/FB  |  --->  |  Seu Backend   |
| (frontend)|        | (este pkg)  |        |  (OAuth)  |        |  (POST p/ Hub) |
+-----------+        +-------------+        +-----------+        +----------------+
  1. Frontend - Voce inicializa o SDK com sua publicKey e chama connect({ channelId })
  2. SDK - Abre o fluxo OAuth da Meta (popup ou embedded signup) para o usuario autorizar
  3. Retorno - O SDK devolve um objeto com code, wabaId, phoneId etc.
  4. Backend - Voce envia esse objeto para seu backend, que chama a API de conexao da HubMessage passando os dados retornados

O SDK nao finaliza a conexao sozinho. Ele apenas coleta as credenciais OAuth do usuario. A finalizacao acontece no seu backend via API HubMessage.


Importacao

ES Modules (React, Vue, Angular, Vite, Next.js...)

import HubMessage from "@hubmessage/connect";
// ou
import { HubMessage } from "@hubmessage/connect";

CommonJS (Node SSR, Webpack 4, require)

const { HubMessage } = require("@hubmessage/connect");

Script tag (HTML puro)

<script src="https://unpkg.com/@hubmessage/connect"></script>
<script>
  // HubMessage fica disponivel como variavel global
  const client = HubMessage.newClient({ publicKey: "..." });
</script>

API

HubMessage.newClient(options)

Cria uma nova instancia do client.

| Parametro | Tipo | Obrigatorio | Descricao | | ------------------- | -------- | ----------- | ------------------------------------------------------------------ | | options.publicKey | string | Sim | Sua chave publica fornecida pela HubMessage | | options.logo | string | Nao | URL da logo da sua aplicacao, exibida no popup de conexao via proxy |

const client = HubMessage.newClient({
  publicKey: "pk_live_abc123",
  logo: "https://meuapp.com/logo.png", // opcional
});

client.connect(options)

Inicia o fluxo de conexao do canal. Retorna uma Promise que resolve quando o usuario completa (ou cancela) o fluxo OAuth.

| Parametro | Tipo | Obrigatorio | Descricao | | ------------------- | --------- | ----------- | ---------------------------------------------- | | options.channelId | string | Sim | ID do canal a ser conectado | | options.direct | boolean | Nao | Forca embedded signup direto (sem proxy popup) |

Retorno:

{
  success: boolean; // se o usuario completou o fluxo
  code: string | null; // codigo OAuth retornado pela Meta
  wabaId: string | null; // WhatsApp Business Account ID
  phoneId: string | null; // ID do numero de telefone selecionado
}

Exemplo completo

React

import { useState } from "react";
import HubMessage from "@hubmessage/connect";

const client = HubMessage.newClient({ publicKey: "pk_live_abc123" });

function ConnectButton({ channelId }: { channelId: string }) {
  const [loading, setLoading] = useState(false);

  async function handleConnect() {
    setLoading(true);

    const response = await client.connect({ channelId });

    if (response.success) {
      // envia para seu backend finalizar a conexao
      await fetch("/api/connect-channel", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(response),
      });

      alert("Canal conectado!");
    } else {
      alert("Conexao cancelada.");
    }

    setLoading(false);
  }

  return (
    <button onClick={handleConnect} disabled={loading}>
      {loading ? "Conectando..." : "Conectar WhatsApp"}
    </button>
  );
}

Angular

import { Component } from "@angular/core";
import HubMessage from "@hubmessage/connect";

@Component({
  selector: "app-connect",
  template: `
    <button (click)="handleConnect()" [disabled]="loading">
      {{ loading ? "Conectando..." : "Conectar WhatsApp" }}
    </button>
  `,
})
export class ConnectComponent {
  loading = false;

  private client = HubMessage.newClient({ publicKey: "pk_live_abc123" });

  async handleConnect() {
    this.loading = true;

    const response = await this.client.connect({
      channelId: "meu-channel-id",
    });

    if (response.success) {
      await fetch("/api/connect-channel", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(response),
      });
    }

    this.loading = false;
  }
}

HTML puro

<!DOCTYPE html>
<html>
  <body>
    <button id="connect-btn">Conectar WhatsApp</button>

    <script src="https://unpkg.com/@hubmessage/connect"></script>
    <script>
      const client = HubMessage.newClient({ publicKey: "pk_live_abc123" });

      document
        .getElementById("connect-btn")
        .addEventListener("click", async () => {
          const response = await client.connect({
            channelId: "meu-channel-id",
          });

          if (response.success) {
            // envia para seu backend
            fetch("/api/connect-channel", {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify(response),
            });
          }
        });
    </script>
  </body>
</html>

Seguranca

Allowed Origins

O canal pode ser configurado com uma lista de dominios permitidos (allowOrigins). Se o SDK detectar que esta rodando em um dominio nao autorizado, ele:

  • Loga um warning no console: [HubMessage SDK] Origin "..." is not in the allowed origins list
  • Retorna { success: false } imediatamente

Isso garante que apenas dominios autorizados possam iniciar o fluxo de conexao.

Public Key

A publicKey e usada para autenticar as requests do SDK. Nunca exponha sua secret key no frontend. A public key e segura para uso client-side.


Fluxo backend (apos o SDK)

O objeto retornado pelo client.connect() contem as credenciais OAuth necessarias. Envie-o para seu backend e chame a API de conexao da HubMessage:

POST /api/connect-channel  (seu backend)
        |
        v
   Seu backend recebe { code, wabaId, phoneId, channelId }
        |
        v
   Seu backend chama a API HubMessage passando esses dados
        |
        v
   Canal conectado!

Compatibilidade

| Ambiente | Suporte | | --------------------------------------- | -------------------- | | ES Modules (import) | Sim | | CommonJS (require) | Sim | | Script tag (<script>) | Sim | | TypeScript | Sim (tipos inclusos) | | React / Next.js | Sim | | Angular | Sim | | Vue | Sim | | Vanilla JS | Sim | | Browsers: Chrome, Firefox, Safari, Edge | Sim (ES2018+) |


License

MIT - FourPixel IT