Skip to content

Latest commit

Β 

History

26 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

castbrick-js

Official JavaScript/TypeScript SDK for the CastBrick API.

Installation

npm install castbrick-js

Requirements

  • Node.js 18+ (uses native fetch)
  • Any modern browser, Next.js, SvelteKit, or Vite project

Quick Start

import { CastBrick } from "castbrick-js";

const cb = new CastBrick({ apiKey: "your_api_key_here" });

// Send an SMS
await cb.sms.send({
  recipients: ["+244923000000"],
  content: "Hello from CastBrick!",
});

Get your API key from the CastBrick dashboard.


SMS

Send an SMS

const result = await cb.sms.send({
  recipients: ["+244923000000", "+244912000000"],
  content: "Your verification code is 1234",
  senderId: "MyApp",                   // optional β€” your approved Sender ID
  scheduledAt: "2026-04-01T10:00:00Z", // optional β€” schedule for later
  fallback: true,                      // optional β€” fall back to CastBrick sender if senderId unavailable
});

console.log(result.messageId, result.recipientCount);

Send to a Contact List

await cb.sms.send({
  recipients: [],
  content: "Promo: 50% off this weekend!",
  contactListId: "list-uuid-here",
});

List messages

// Simple
const { items, totalCount } = await cb.sms.list();

// With filters
const { items } = await cb.sms.list({
  page: 1,
  pageSize: 20,
  status: "delivered",       // pending | sent | delivered | failed | scheduled
  phone: "+244923000000",
  from: "2026-01-01T00:00:00Z",
  to: "2026-06-01T00:00:00Z",
});

Cancel a scheduled SMS

await cb.sms.cancelScheduled("message-id");

Contacts

List contacts

const { items } = await cb.contacts.list(1, 20, "search term");

Create contacts

// Comma or newline-separated phone numbers
await cb.contacts.create({
  phoneNumbers: "+244923000000\n+244912000000",
});

Delete a contact

await cb.contacts.delete("contact-id");

Contact Lists

// List all contact lists
const { items } = await cb.contacts.listLists();

// Create a list β€” returns the new list ID
const listId = await cb.contacts.createList("VIP Customers");

// Add / remove a contact from a list
await cb.contacts.addToList(listId, "contact-id");
await cb.contacts.removeFromList(listId, "contact-id");

Broadcasts

Create and send a broadcast

const id = await cb.broadcasts.create({
  name: "Weekend Promo",
  message: "50% off this weekend!",
  contactListId: "list-uuid-here", // optional
  senderId: "MyApp",               // optional
});

await cb.broadcasts.send(id);

Schedule a broadcast

await cb.broadcasts.update(id, {
  name: "Weekend Promo",
  message: "50% off this weekend!",
  scheduleAt: "2026-04-05T08:00:00Z",
});

await cb.broadcasts.send(id);

Other broadcast operations

await cb.broadcasts.cancel(id);
await cb.broadcasts.duplicate(id);
await cb.broadcasts.delete(id);

const { items } = await cb.broadcasts.list();
const broadcast = await cb.broadcasts.get(id);

Push & Realtime API

CastBrick Push & Realtime API lets you deliver Web & Mobile push notifications and stream realtime events via SSE channels.

Server-side: issue token + publish

// Issue a short-lived channel token for the client
const { token } = await cb.push.issueToken({
  channels: ["orders", "user-42"],
  userId: "user-123",   // optional
  ttlSeconds: 3600,     // optional, default 3600
});

// Publish an event to a channel
const result = await cb.push.publish({
  channel: "orders",
  event: "order.created",
  data: { orderId: "abc123", total: 5000 },
});

console.log(result.delivered, result.creditsUsed);

Browser-side: subscribe to channels

import { CastBrickPushClient } from "castbrick-js";

// token comes from your backend (via the issueToken call above)
const push = new CastBrickPushClient(token, {
  onConnected: (channels) => console.log("connected to", channels),
  onStatusChange: (status) => console.log("status:", status),
});

// Listen to events on a specific channel
const unsubscribe = push.on("orders", (event) => {
  console.log(event.event, event.data); // "order.created" { orderId: "abc123" }
});

// Later
unsubscribe();       // stop receiving events on this channel
push.disconnect();   // close the SSE connection

Push Notifications (Web & Mobile)

Better than OneSignal: unlimited free subscribers, 5,000 free pushes every month, with zero manual Service Worker configuration.

Client-side (Browser / Web Push): Zero-Config Subscription

One line handles browser permission, service worker registration, and device subscription:

import { CastBrickWebPush } from "castbrick-js";

const result = await CastBrickWebPush.subscribe({
  appId: "app_7a8b9c",
  externalUserId: "user_42",        // optional
  tags: { plan: "pro", lang: "pt" }  // optional
});

if (result.success) {
  console.log("Subscribed device ID:", result.subscriptionId);
}

Server-side: Send Push Notifications

const response = await cb.push.send({
  appId: "app_7a8b9c",
  title: "Flash Sale πŸš€",
  body: "Get 30% off today only!",
  iconUrl: "https://yourapp.com/icon.png",
  actionUrl: "https://yourapp.com/sale",
  target: {
    all: true, // or subscriptionIds: ["sub_..."], or externalUserIds: ["user_42"]
  }
});

console.log(`Delivered: ${response.deliveredCount}, Remaining Free: ${response.freePushesRemaining}`);

Billing

// Get current credit balance
const balance = await cb.billing.getBalance();

// List available credit packages
const packages = await cb.billing.listPackages();

// List credit consumption/transaction history
const { items } = await cb.billing.listTransactions();

Segments, Templates & Webhooks

The SDK also provides native access to cb.segments, cb.templates, and cb.webhooks.

// Example: Create a Webhook
await cb.webhooks.create({
  endpoint: "https://yourapp.com/webhooks/castbrick",
  eventType: "sms.delivered"
});

Error Handling

import { CastBrick, CastBrickApiError } from "castbrick-js";

try {
  await cb.sms.send({ recipients: ["+244923000000"], content: "Hello!" });
} catch (err) {
  if (err instanceof CastBrickApiError) {
    console.error(`API error ${err.status}:`, err.message);
    // 401 β†’ invalid or revoked API key
    // 402 β†’ insufficient credits
    // 422 β†’ validation error
  }
}

TypeScript

The SDK is written in TypeScript and exports all types:

import type {
  SendSmsRequest,
  SmsListParams,
  SmsMessage,
  Broadcast,
  Contact,
  ContactList,
  PagedResult,
  IssuePushTokenRequest,
  IssuePushTokenResponse,
  PublishEventRequest,
  PublishEventResponse,
  PushEvent,
  PushClientStatus,
} from "castbrick-js";

Publishing

Releases are published by GitHub Actions when a v* tag is pushed. The workflow uses npm Trusted Publishing through OIDC, so no NPM_TOKEN secret is required.

In npmjs.com package settings for castbrick-js, add a trusted publisher with:

  • Publisher: GitHub Actions
  • Owner: IldySilva
  • Repository: castbrick-js
  • Workflow: .github/workflows/publish.yml

License

MIT

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages