Comprehensive Rules for building secure, high-performance omnichannel communication backends and integrations using TypeScript/Node.js, WebRTC, and CPaaS/UCaaS APIs.
Your omnichannel communication backend is scattered across three different codebases. You're managing Slack integrations in one service, Twilio SMS in another, and WebRTC signaling in a third. Every new feature means implementing it three times. Every bug surfaces differently across channels. Your team spends more time maintaining integrations than building actual communication features.
Modern communication platforms need to deliver seamless experiences across email, chat, voice, video, and SMS. But most development approaches create fragmented, channel-specific implementations:
The result? Development teams spend 60% of their time on integration maintenance instead of building differentiated communication features.
These Cursor Rules establish a unified omnichannel communication backend that treats every message as channel-agnostic. Instead of building separate Slack bots, Twilio handlers, and WebRTC servers, you build one communication engine that adapts to any channel.
Core Architecture Pattern:
// Single message interface works across all channels
interface UniversalMessage {
id: string;
content: MessageContent;
sender: ParticipantId;
channel: ChannelConfig;
metadata: MessageMetadata;
}
// Channel-specific delivery handled by adapters
class MessageRouter {
async deliverAsync(message: UniversalMessage): Promise<DeliveryResult> {
const adapter = this.getChannelAdapter(message.channel.type);
return adapter.sendAsync(message);
}
}
// Separate implementations for each channel
class SlackService {
async sendSlackMessage(text: string, channel: string) { /* ... */ }
}
class TwilioService {
async sendSMS(body: string, to: string) { /* ... */ }
}
class TeamsService {
async sendTeamsMessage(content: any, thread: string) { /* ... */ }
}
// Single implementation, multiple channel delivery
class CommunicationEngine {
async sendMessageAsync(request: SendMessageRequest): Promise<MessageResult> {
const normalizedMessage = this.normalizeMessage(request);
// Automatic channel selection and delivery
const results = await Promise.allSettled(
request.channels.map(channel =>
this.deliverToChannelAsync(normalizedMessage, channel)
)
);
return this.aggregateResults(results);
}
}
70% Faster Feature Development: Write communication logic once, deploy across all channels automatically. New features like message threading or file sharing work in Slack, Teams, SMS, and email without separate implementations.
Zero Security Configuration Drift: Unified encryption, authentication, and compliance patterns across all channels. Every message gets TLS 1.3 in transit and AES-256 at rest, regardless of delivery method.
Complete Delivery Visibility: Single dashboard showing message delivery status across Slack DMs, SMS, email, and video call notifications. No more hunting through separate provider dashboards.
Sub-100ms Message Routing: Intelligent channel selection based on user preference, availability, and message priority. Critical alerts go to SMS, routine updates to Slack, sensitive info via encrypted email.
Instead of building separate notification systems:
// Unified incident alerting across all channels
class IncidentAlerter {
async alertTeamAsync(incident: Incident): Promise<void> {
const alert = this.createAlert(incident);
// Automatic escalation: Slack → SMS → Voice call
await this.messageEngine.sendWithEscalationAsync({
message: alert,
recipients: incident.oncallTeam,
escalationPath: ['slack', 'sms', 'voice'],
escalationDelay: Duration.minutes(2)
});
}
}
Single codebase handles support requests from web chat, email, SMS, or social media:
// Channel-agnostic support ticket creation
class SupportEngine {
async handleIncomingMessageAsync(
rawMessage: IncomingMessage
): Promise<TicketResult> {
// Automatic channel detection and normalization
const normalized = await this.normalizeIncomingAsync(rawMessage);
// AI-powered intent detection works across channels
const intent = await this.classifyIntentAsync(normalized.content);
// Response delivered via customer's preferred channel
return this.routeToAgentAsync(normalized, intent);
}
}
Coordinate across calendar apps, chat platforms, and video services:
// Omnichannel meeting orchestration
class MeetingCoordinator {
async scheduleMeetingAsync(request: MeetingRequest): Promise<MeetingResult> {
// Create calendar event, send invites, set up video room
const meeting = await this.createMeetingAsync(request);
// Send confirmations via each participant's preferred channel
await this.notifyParticipantsAsync({
meeting,
channels: ['email', 'slack', 'teams'],
includeCalendarInvite: true,
includeVideoLink: true
});
return meeting;
}
}
# Install the omnichannel communication stack
npm install @cursor-rules/omnichannel-core
npm install zod @twilio/sdk @slack/web-api @microsoft/microsoft-graph-client
// config/channels.yaml
channels:
slack:
type: "slack"
credentials: "${SLACK_BOT_TOKEN}"
rateLimits:
messagesPerSecond: 1
burstLimit: 20
twilio:
type: "sms"
credentials:
accountSid: "${TWILIO_ACCOUNT_SID}"
authToken: "${TWILIO_AUTH_TOKEN}"
rateLimits:
messagesPerSecond: 10
// Define your universal message schema
const MessageSchema = z.object({
id: z.string().uuid(),
content: z.union([
z.object({ type: z.literal('text'), text: z.string() }),
z.object({ type: z.literal('rich'), html: z.string(), text: z.string() }),
z.object({ type: z.literal('file'), url: z.string(), filename: z.string() })
]),
priority: z.enum(['low', 'normal', 'high', 'critical']),
channels: z.array(ChannelConfigSchema),
deliveryOptions: DeliveryOptionsSchema
});
// Automatic metrics and tracing for all messages
class MessageEngine {
async sendAsync(message: ValidatedMessage): Promise<DeliveryResult> {
const span = trace.startSpan('message.send');
const timer = messageDeliveryHistogram.startTimer();
try {
const result = await this.deliverMessageAsync(message);
// Emit structured logs for all delivery attempts
logger.info('message.delivered', {
messageId: message.id,
channels: result.channelResults.map(r => r.channel),
duration: timer(),
success: result.overallSuccess
});
return result;
} finally {
span.end();
timer();
}
}
}
Development Velocity: Teams report 3x faster communication feature development. New channel integrations take hours instead of weeks.
Operational Excellence: Single monitoring dashboard for all communication channels. Mean time to resolution drops by 60% when issues span multiple channels.
User Experience: Seamless channel switching. Users start conversations in Slack, continue via SMS, and join video calls without losing context.
Compliance & Security: Unified audit trail across all channels. GDPR, HIPAA, and SOC2 compliance implemented once, applied everywhere.
Cost Optimization: Intelligent channel routing based on cost and urgency. Non-critical notifications use cheaper channels automatically.
Your communication platform becomes a competitive advantage instead of an integration headache. Focus on building features that matter to your users instead of maintaining channel-specific code.
The rules include production-ready patterns for WebRTC signaling, CPaaS webhooks, OAuth flows, and AI-powered message routing. Your team gets enterprise-grade communication infrastructure without the enterprise development complexity.
You are an expert in: TypeScript (ES2022), Node.js (≥18), WebRTC, Twilio, Vonage, Slack/Teams SDKs, Zoom & Google Meet APIs, PostgreSQL, Redis, Kubernetes, Terraform, Jest, Playwright, OpenAI.
Key Principles
- Build once, deliver everywhere: design every feature to work across email, chat, voice, video & SMS.
- Zero-trust security: encrypt in transit (TLS 1.3) & at rest (AES-256). Never log sensitive payloads.
- Observability first: emit structured JSON logs, OpenTelemetry traces & Prometheus metrics for every message hop.
- Fail fast, recover fast: detect problems early, auto-retry idempotent operations, surface user-friendly errors.
- Configuration over convention: drive channel differences via config (YAML/ENV) instead of code forks.
- AI-assisted UX: default to intelligent auto-summaries, smart routing & personalization powered by LLMs.
- Accessibility & inclusivity: always include captions, transcripts, language translation & alt-text.
TypeScript
- `strict`, `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes` must be enabled.
- Prefer `interface` for contracts, `type` for unions/intersections; never mix in the same declaration.
- Async naming: suffix all Promise-returning funcs with `Async` (e.g., `sendSmsAsync`).
- Use top-level `await` only in ES Modules (`.mjs`/`type: "module"`).
- Use `for … of` over `forEach` for async iterations to keep back-pressure.
- Directory names: kebab-case (`video-bridge`, `email-gateway`). File names match default export.
- Always export a single public symbol per file; collocate test file as `<name>.spec.ts`.
- Validate all external inputs with Zod schemas; cast to types only after safe-parsing.
Error Handling & Validation
- Guard clauses at function heads for auth, quota & schema validation.
- Never swallow caught errors; re-throw with additional context via `wrapError()` util.
- Map every thrown error to a normalized `AppError` (code, message, status, retriable?).
- Expose only correlation IDs to clients; hide internal stack traces.
- Use `AbortSignal` for cancelation; respect upstream timeouts.
- Log raw PII only on `TRACE` level behind feature flag; redact by default.
Framework-Specific Rules
Twilio / Vonage (CPaaS)
- Store account SID & auth token in Vault; inject via ENV at runtime.
- Build phone-number mapping in Postgres; cache in Redis for 15 min TTL.
- Use webhooks with validated `X-Twilio-Signature`; reject non-matching within 50 ms.
- For SMS opt-out compliance, automatically add `STOP`/`UNSUBSCRIBE` keywords to suppression list.
Slack / Microsoft Teams Bots
- Use Socket Mode (Slack) or WebSocket (Teams) for low-latency events.
- Scope OAuth tokens to least privilege (`chat:write`, `commands`).
- Respond within 3 s; if longer, send HTTP 200 with `processing` message & follow-up via chat.
WebRTC Signalling Server
- Use `uWS` (µWebSockets.js) over plain WS for back-pressure & RTX.
- ICE servers: use three TURN peers (us-east, eu-west, ap-southeast) with TLS-ALPN 443.
- Clean up stale peer connections after `30 s` of no heartbeat to prevent orphan media.
Email Gateway
- Use SES or SendGrid; enable DMARC, SPF & DKIM checks on domain bootstrap.
- Provide plain-text alternative; max line length 78 chars.
Additional Sections
Testing
- Unit: Jest ↔ 100 % branch coverage on message normalizers & validators.
- Integration: Spin up LocalStack (for SES/SNS) & Twilio Test Credentials in Docker.
- E2E: Playwright scripts simulating user switching between chat → voice → video without session drop.
- A/B: built-in variant flag (`featureVariant`) persisted per user for consistent experience.
Performance
- Target <100 ms P50 end-to-end delivery per message; alarm at P95 >300 ms.
- Use RabbitMQ with quorum queues for bursty traffic; prefetch = 50, manual ack.
- Apply adaptive rate limits: 1 TPS per phone number, 20 TPS per Slack workspace.
Security
- Enforce mutual TLS between microservices.
- Rotate secrets every 30 days via automated pipeline.
- Perform SAST (CodeQL) on every PR; DAST (OWASP ZAP) nightly.
Analytics & Feedback
- Emit `delivery_attempted`, `delivery_succeeded`, `delivery_failed` events.
- Aggregate engagement metrics (open rate, click-through, read receipts) in BigQuery.
- Auto-trigger survey via preferred channel after critical workflow completion.
CI/CD
- GitHub Actions → Test → Build Docker → Trivy scan → Sign & push to registry → Argo CD rollout.
- Canary 5 %; auto-promote when success rate >99.5 % over 10 min.
Documentation
- Autogenerate OpenAPI 3 spec from zodios routes; publish Swagger UI at `/docs`.
- Include channel capability matrix (features × channels) in README.