### Basic Comms SDK Setup and Notification Sending (TypeScript) Source: https://github.com/cryptventure/comms/blob/main/docs/FRAMEWORKS.md Demonstrates the fundamental setup of the Comms SDK with multiple providers for email and SMS, and an example function to send a welcome notification to a user via both channels. Requires environment variables for API keys and credentials. ```typescript // server.ts import CommsSdk from '@webventures/comms' const comms = new CommsSdk({ channels: { email: { multiProviderStrategy: 'fallback', providers: [ { type: 'sendgrid', apiKey: process.env.SENDGRID_API_KEY! }, { type: 'ses', region: 'us-east-1', accessKeyId: '...', secretAccessKey: '...' }, ], }, sms: { providers: [{ type: 'twilio', accountSid: '...', authToken: '...' }], }, }, }) // Send notification async function sendWelcomeNotification(user: User) { return await comms.send({ email: { from: 'noreply@example.com', to: user.email, subject: 'Welcome!', html: '

Welcome to our platform!

', }, sms: { from: '+1234567890', to: user.phone, text: 'Welcome to our platform!', }, }) } ``` -------------------------------- ### Install and Start Notification Catcher Source: https://github.com/cryptventure/comms/blob/main/docs/README.md Shows the npm commands to install the 'notification-catcher' development dependency and start the catcher service. This tool is used for local testing to intercept notifications. ```bash # Install npm install --save-dev notification-catcher # Start catcher npx notification-catcher ``` -------------------------------- ### Mock HTTP Client Setup - TypeScript Source: https://github.com/cryptventure/comms/blob/main/CLAUDE.md TypeScript example illustrating the setup of a mocked HTTP client for testing the WebVentures Comms SDK. It includes capturing request details and queuing mock responses. ```typescript const mockRequest = vi.fn(); function mockResponse(statusCode, body) { // Logic to queue mock responses } const mockHttp = { // Proxy to access captured request body via .body property }; // All tests use mockHttp instead of the real HTTP client ``` -------------------------------- ### Comms SDK Usage Examples Source: https://github.com/cryptventure/comms/blob/main/docs/MIGRATION.md Demonstrates how to initialize and use the Comms SDK. This includes sending a message and interacting with the logger. The example shows the instantiation of the CommsSdk with a configuration object and subsequent method calls. ```typescript const comms = new CommsSdk(config) await comms.send(request) comms.logger.mute() comms.logger.configure([...]) ``` -------------------------------- ### Install and Start Notification Catcher using Bash Source: https://github.com/cryptventure/comms/blob/main/README.md Installs the 'notification-catcher' package as a development dependency and starts the catcher service. This tool intercepts and displays notifications in a web UI for local development. ```bash # Install npm install --save-dev notification-catcher # Start catcher (runs on port 1080) npx notification-catcher ``` -------------------------------- ### Start Notification Catcher with Custom Settings Source: https://github.com/cryptventure/comms/blob/main/docs/README.md Provides an example of starting the Notification Catcher with custom settings via environment variables, specifically targeting a custom SMTP port. This allows for flexible local testing configurations. ```bash # Custom port COMMS_CATCHER_OPTIONS=smtp://127.0.0.1:3025?ignoreTLS=true node your-app.js ``` -------------------------------- ### Development Setup Commands Source: https://github.com/cryptventure/comms/blob/main/README.md A set of bash commands for setting up the development environment for the Comms SDK. This includes cloning the repository, installing dependencies using pnpm, running tests, performing type checks, building the project, and linting/formatting code. ```bash # Clone repository git clone https://github.com/CryptVenture/Comms.git cd comms # Install dependencies pnpm install # Run tests pnpm test # Run tests in watch mode pnpm test:watch # Type check pnpm type-check # Build pnpm build # Lint & format pnpm lint:fix ``` -------------------------------- ### Multi-Provider Fallback Strategy Example Source: https://github.com/cryptventure/comms/blob/main/docs/MIGRATION.md Illustrates the configuration of email channels with multiple providers using a fallback strategy. This example is identical for both v1.x and v2.0.2, highlighting the backward compatibility of this feature. ```javascript const CommsSdk = require('webventures-comms') new CommsSdk({ channels: { email: { multiProviderStrategy: 'fallback', providers: [ { type: 'sendgrid', apiKey: 'key1' }, { type: 'mailgun', apiKey: 'key2', domainName: 'example.com' }, ], }, }, }) ``` ```typescript import CommsSdk from '@webventures/comms' new CommsSdk({ channels: { email: { multiProviderStrategy: 'fallback', providers: [ { type: 'sendgrid', apiKey: 'key1' }, { type: 'mailgun', apiKey: 'key2', domainName: 'example.com' }, ], }, }, }) ``` -------------------------------- ### Email Sending Migration Example (v1.x to v2.0.2) Source: https://github.com/cryptventure/comms/blob/main/docs/MIGRATION.md Compares the code for sending basic emails using the Comms SDK between v1.x (CommonJS) and v2.0.2 (ESM with async/await). It shows the initialization of the SDK and the `send` method invocation. ```javascript const CommsSdk = require('webventures-comms') const comms = new CommsSdk({ channels: { email: { providers: [ { type: 'smtp', host: 'smtp.example.com', port: 587, auth: { user: 'user', pass: 'pass' }, }, ], }, }, }) comms .send({ email: { from: 'noreply@example.com', to: 'user@example.com', subject: 'Hello', text: 'World', }, }) .then(console.log) ``` ```typescript import CommsSdk from '@webventures/comms' const comms = new CommsSdk({ channels: { email: { providers: [ { type: 'smtp', host: 'smtp.example.com', port: 587, auth: { user: 'user', pass: 'pass' }, }, ], }, }, }) const result = await comms.send({ email: { from: 'noreply@example.com', to: 'user@example.com', subject: 'Hello', text: 'World', }, }) console.log(result) ``` -------------------------------- ### Clone and Setup Comms SDK Repository Source: https://github.com/cryptventure/comms/blob/main/CONTRIBUTING.md Steps to clone the WebVentures Comms SDK repository, add the upstream remote, and install project dependencies using pnpm. ```bash git clone https://github.com/YOUR_USERNAME/Comms.git cd comms git remote add upstream https://github.com/CryptVenture/Comms.git pnpm install ``` -------------------------------- ### Install WebVentures Comms SDK for Next.js Source: https://github.com/cryptventure/comms/blob/main/docs/FRAMEWORKS.md Installs the WebVentures Comms SDK using npm. This is the initial step for integrating the SDK into a Next.js project. ```bash npm install @webventures/comms ``` -------------------------------- ### Installing WebVentures Comms SDK Package Source: https://github.com/cryptventure/comms/blob/main/docs/MIGRATION.md Shows the change in the npm package name required for installation between v1.x and v2.0.2. ```bash npm install webventures-comms ``` ```bash npm install @webventures/comms ``` -------------------------------- ### CommsSdk Configuration Example Source: https://github.com/cryptventure/comms/blob/main/docs/API.md Provides an example of the CommsSdkConfig interface, demonstrating how to set up different notification channels like email and SMS, including multiple providers and multi-provider strategies. ```typescript const config: CommsSdkConfig = { useNotificationCatcher: false, channels: { email: { multiProviderStrategy: 'fallback', providers: [ { type: 'sendgrid', apiKey: 'xxx' }, { type: 'ses', region: 'us-east-1', accessKeyId: 'xxx', secretAccessKey: 'xxx' }, ], }, sms: { multiProviderStrategy: 'roundrobin', providers: [ { type: 'twilio', accountSid: 'xxx', authToken: 'xxx' }, { type: 'nexmo', apiKey: 'xxx', apiSecret: 'xxx' }, ], }, }, } ``` -------------------------------- ### Fallback Provider Strategy Example (TypeScript) Source: https://github.com/cryptventure/comms/blob/main/docs/EXAMPLES.md This example demonstrates configuring the CommsSdk to use a 'fallback' strategy for email providers. If the primary provider (SendGrid) fails, the SDK automatically attempts to use the next provider in the list (SES), and then the subsequent one (SMTP). This ensures message delivery by trying alternative services. ```typescript const comms = new CommsSdk({ channels: { email: { multiProviderStrategy: 'fallback', providers: [ { type: 'sendgrid', apiKey: process.env.SENDGRID_API_KEY! }, { type: 'ses', region: 'us-east-1', accessKeyId: process.env.AWS_KEY!, secretAccessKey: process.env.AWS_SECRET!, }, { type: 'smtp', host: 'smtp.backup.com', port: 587, auth: { user: '...', pass: '...' } }, ], }, }, }) // If SendGrid fails, tries SES, then SMTP const result = await comms.send({ email: { from: 'noreply@example.com', to: 'user@example.com', subject: 'Important Email', text: 'This email will be delivered even if primary provider fails', }, }) ``` -------------------------------- ### Utilizing Framework Adapters for Comms SDK Source: https://github.com/cryptventure/comms/blob/main/docs/MIGRATION.md Provides examples of how to import and use framework-specific adapters for Next.js, React Native, Expo, and Node.js environments in v2.0.2. ```typescript // Next.js 16+ import { createNextJSComms, withComms } from '@webventures/comms/adapters' // React Native import { createReactNativeComms } from '@webventures/comms/adapters' // Expo import { createExpoComms } from '@webventures/comms/adapters' // Node.js with env config import { createNodeCommsFromEnv } from '@webventures/comms/adapters' ``` -------------------------------- ### Install @webventures/comms SDK Source: https://github.com/cryptventure/comms/blob/main/docs/README.md Installs the WebVentures Comms SDK using different package managers (npm, yarn, pnpm). ```bash # Using npm npm install @webventures/comms # Using yarn yarn add @webventures/comms # Using pnpm pnpm add @webventures/comms ``` -------------------------------- ### Environment-Based Comms SDK Configuration (TypeScript & Bash) Source: https://github.com/cryptventure/comms/blob/main/docs/FRAMEWORKS.md Shows how to configure the Comms SDK dynamically based on environment variables using `createNodeCommsFromEnv`. This allows for flexible configuration without hardcoding credentials. The example includes a `.env` file for setting up email and SMS providers, along with other environment-specific settings. ```typescript // config/comms.ts import { createNodeCommsFromEnv } from '@webventures/comms/adapters' export const comms = createNodeCommsFromEnv() ``` ```bash # .env COMMS_EMAIL_PROVIDER=sendgrid SENDGRID_API_KEY=your_key COMMS_SMS_PROVIDER=twilio TWILIO_ACCOUNT_SID=your_sid TWILIO_AUTH_TOKEN=your_token NODE_ENV=development USE_NOTIFICATION_CATCHER=true ``` -------------------------------- ### JSDoc Example for EmailSendGridProvider Source: https://github.com/cryptventure/comms/blob/main/CLAUDE.md Illustrates comprehensive JSDoc comments for a TypeScript class, including descriptions, `@see` links to external documentation, and an `@example` block demonstrating realistic usage. ```typescript /** * SendGrid Email Provider * * Sends transactional emails via the SendGrid v3 API. Supports attachments, * CC/BCC, custom headers, and reply-to addresses. * * @see https://docs.sendgrid.com/api-reference/mail-send/mail-send * * @example * ```typescript * const provider = new EmailSendGridProvider({ * apiKey: process.env.SENDGRID_API_KEY * }) * * const result = await provider.send({ * from: 'noreply@example.com', * to: 'user@example.com', * subject: 'Welcome', * html: '

Welcome!

' * }) * ``` */ export default class EmailSendGridProvider implements Provider { // ... } ``` -------------------------------- ### Custom Email Provider Implementation Source: https://github.com/cryptventure/comms/blob/main/docs/MIGRATION.md Demonstrates how to implement a custom email provider for the Comms SDK. The example shows the structure required for a custom provider, including its type, ID, and the `send` method, adapted for v1.x (callback-based) and v2.0.2 (async/await with TypeScript). ```javascript { type: 'custom', id: 'my-email-service', send: (request) => { return myEmailService.send(request) .then(response => response.id) } } ``` ```typescript import type { EmailRequest } from '@webventures/comms' { type: 'custom', id: 'my-email-service', send: async (request: EmailRequest): Promise => { const response = await myEmailService.send(request) return response.id } } ``` -------------------------------- ### CLI Application for Sending Notifications (TypeScript) Source: https://github.com/cryptventure/comms/blob/main/docs/FRAMEWORKS.md Illustrates building a command-line interface (CLI) application using the `commander` library to send notifications. This example specifically shows how to create a command to send emails with options for recipient, subject, and body. It initializes the Comms SDK with SMTP provider details. ```typescript #!/usr/bin/env node // bin/send-notification.ts import CommsSdk from '@webventures/comms' import { Command } from 'commander' const program = new Command() program .name('send-notification') .description('Send notifications via CLI') .version('1.0.0') program .command('email') .description('Send email') .requiredOption('-t, --to ', 'Recipient email') .requiredOption('-s, --subject ', 'Email subject') .requiredOption('-b, --body ', 'Email body') .action(async (options) => { const comms = new CommsSdk({ channels: { email: { providers: [{ type: 'smtp', host: '...', port: 587, auth: {...} }] } } }) const result = await comms.send({ email: { from: 'cli@example.com', to: options.to, subject: options.subject, html: options.body } }) console.log('Result:', result) }) program.parse() ``` -------------------------------- ### Configure Sendmail Email Provider (Basic) Source: https://github.com/cryptventure/comms/blob/main/docs/PROVIDERS.md Utilizes the local sendmail binary for email delivery. Requires sendmail to be installed and configured on the server. Supports basic configuration with path and newline settings. ```typescript { type: 'sendmail', sendmail: true, path: '/usr/sbin/sendmail', newline: 'unix' } ``` -------------------------------- ### Testing: Mocking SDK in Tests (TypeScript/Vitest) Source: https://github.com/cryptventure/comms/blob/main/docs/FRAMEWORKS.md Provides an example of mocking the '@webventures/comms' SDK using Vitest for testing purposes. It mocks the default export and its 'send' method to return a successful response. ```typescript import { vi } from 'vitest' vi.mock('@webventures/comms', () => ({ default: vi.fn().mockImplementation(() => ({ send: vi.fn().mockResolvedValue({ status: 'success', channels: { email: { id: 'test-id', providerId: 'test' } }, }), })), })) ``` -------------------------------- ### Round-Robin Provider Strategy Example (TypeScript) Source: https://github.com/cryptventure/comms/blob/main/docs/EXAMPLES.md This example shows how to configure the CommsSdk for SMS providers using a 'roundrobin' strategy. The SDK will cycle through the provided SMS providers (Twilio, Nexmo, Plivo) for each message sent. This method helps distribute the load across multiple services and can prevent hitting rate limits on a single provider. ```typescript const comms = new CommsSdk({ channels: { sms: { multiProviderStrategy: 'roundrobin', providers: [ { type: 'twilio', accountSid: '...', authToken: '...' }, { type: 'nexmo', apiKey: '...', apiSecret: '...' }, { type: 'plivo', authId: '...', authToken: '...' }, ], }, }, }) // Distributes load across providers for (let i = 0; i < 100; i++) { await comms.send({ sms: { from: '+1234567890', to: `+098765432${i.toString().padStart(2, '0')}`, text: `Message ${i}`, }, }) // Cycles through: Twilio → Nexmo → Plivo → Twilio → ... } ``` -------------------------------- ### Send Email with Custom Headers and Tracking Source: https://github.com/cryptventure/comms/blob/main/docs/EXAMPLES.md Shows how to send marketing emails with custom headers for unsubscribing and tracking, as well as including a tracking pixel. This example utilizes the Comms SDK with an email provider. ```typescript async function sendMarketingEmail(subscriber: Subscriber, campaign: Campaign) { const unsubscribeUrl = `https://example.com/unsubscribe?id=${subscriber.id}` const trackingPixel = `` const result = await comms.send({ email: { from: 'newsletter@example.com', to: subscriber.email, subject: campaign.subject, html: ` ${campaign.content} ${trackingPixel}

Unsubscribe

`, headers: { 'List-Unsubscribe': `<${unsubscribeUrl}>`, 'X-Campaign-ID': campaign.id, 'X-Subscriber-ID': subscriber.id, }, }, }) return result } ``` -------------------------------- ### Custom Multi-Provider Strategy Implementation Source: https://github.com/cryptventure/comms/blob/main/docs/MIGRATION.md Shows how to implement a custom multi-provider strategy for communication channels. The example demonstrates a random provider selection strategy, adapted for both v1.x (using a function expression) and v2.0.2 (using TypeScript with explicit types). ```javascript const customStrategy = (providers) => async (request) => { const provider = providers[Math.floor(Math.random() * providers.length)] try { const id = await provider.send(request) return { id, providerId: provider.id } } catch (error) { error.providerId = provider.id throw error } } ``` ```typescript import type { StrategyFunction } from '@webventures/comms' const customStrategy: StrategyFunction = (providers) => { return async (request) => { const provider = providers[Math.floor(Math.random() * providers.length)] if (!provider) throw new Error('No providers available') try { const id = await provider.send(request) return { id, providerId: provider.id } } catch (error) { if (error instanceof Error) { ;(error as Error & { providerId?: string }).providerId = provider.id } throw error } } } ``` -------------------------------- ### Custom Email Provider Implementation Source: https://github.com/cryptventure/comms/blob/main/docs/PROVIDERS.md Provides an example of implementing a custom provider for sending emails. This involves defining an object with `type: 'custom'`, a unique `id`, and an asynchronous `send` function that accepts an `EmailRequest` and handles the email sending logic, returning a message ID. ```typescript { type: 'custom', id: 'my-email-service', send: async (request: EmailRequest) => { // Your custom implementation const response = await myEmailApi.send({ from: request.from, to: request.to, subject: request.subject, html: request.html }) return response.messageId } } ``` -------------------------------- ### Expo Backend Client Setup for Comms Source: https://github.com/cryptventure/comms/blob/main/docs/FRAMEWORKS.md Initializes a backend client for Expo applications using '@webventures/comms/adapters'. It checks for the Expo environment and logs platform details. The `sendNotification` function is exported to facilitate sending data via the configured comms client. ```typescript // src/services/notifications.ts import { createExpoBackendClient, isExpo, getExpoInfo } from '@webventures/comms/adapters' export const commsClient = createExpoBackendClient('https://api.example.com') // Check Expo environment const expoInfo = getExpoInfo() console.log('Is Expo:', expoInfo.isExpo) console.log('Platform:', expoInfo.platform) // 'ios' | 'android' | 'web' console.log('Is Dev:', expoInfo.isExpoDev) export async function sendNotification(data: any) { return await commsClient.send(data) } ``` -------------------------------- ### Install Notification Catcher for Local Testing Source: https://github.com/cryptventure/comms/blob/main/docs/README.md Installs the notification-catcher package as a development dependency for local testing purposes. ```bash npm install --save-dev notification-catcher ``` -------------------------------- ### Example Custom Email Provider Configuration (TypeScript) Source: https://github.com/cryptventure/comms/blob/main/docs/API.md An example demonstrating how to configure a custom email provider using the CustomProviderConfig interface. It specifies the 'custom' type, a unique ID, and an async function to handle sending emails via a custom service. ```typescript const customEmailProvider: CustomProviderConfig = { type: 'custom', id: 'my-email-service', send: async (request) => { // Custom implementation const response = await myEmailService.send(request) return response.messageId }, } ``` -------------------------------- ### Install @webventures/comms with npm, yarn, or pnpm Source: https://github.com/cryptventure/comms/blob/main/README.md This snippet shows how to install the @webventures/comms package using popular Node.js package managers. Ensure you have Node.js v18.0.0 or higher installed. ```bash npm install @webventures/comms ``` ```bash yarn add @webventures/comms ``` ```bash pnpm add @webventures/comms ``` -------------------------------- ### JSDoc Documentation Example for TypeScript Source: https://github.com/cryptventure/comms/blob/main/CONTRIBUTING.md Example of a JSDoc comment block for an exported TypeScript class, including a description, see link, and a runnable code example. ```typescript /** * SendGrid Email Provider * * Sends transactional emails via the SendGrid v3 API. Supports attachments, * CC/BCC, custom headers, and reply-to addresses. * * @see https://docs.sendgrid.com/api-reference/mail-send/mail-send * * @example * ```typescript * const provider = new EmailSendGridProvider({ * apiKey: process.env.SENDGRID_API_KEY * }) * * const result = await provider.send({ * from: 'noreply@example.com', * to: 'user@example.com', * subject: 'Welcome', * html: '

Welcome!

' * }) * ``` */ ``` -------------------------------- ### Development and Demo Commands - Bash Source: https://github.com/cryptventure/comms/blob/main/CLAUDE.md Bash commands for running the SDK in development mode and starting a local notification catcher for testing. These commands facilitate local development and debugging. ```bash pnpm run dev pnpm run demo ``` -------------------------------- ### Comms SDK Singleton Pattern Implementation (TypeScript) Source: https://github.com/cryptventure/comms/blob/main/docs/FRAMEWORKS.md Implements a singleton pattern for the Comms SDK to ensure a single instance is used throughout the application, simplifying state management and resource usage. It provides functions to get and reset the singleton instance. Usage examples are included. ```typescript // services/comms.ts import { getCommsSingleton, resetCommsSingleton } from '@webventures/comms/adapters' export const getComms = () => { return getCommsSingleton({ channels: { email: { providers: [{ type: 'sendgrid', apiKey: process.env.SENDGRID_API_KEY! }] } } }) } // For testing export const resetComms = resetCommsSingleton // Usage import { getComms } from './services/comms' const comms = getComms() await comms.send({...}) ``` -------------------------------- ### Send Basic Email with SMTP Source: https://github.com/cryptventure/comms/blob/main/docs/EXAMPLES.md Demonstrates sending a simple welcome email using the Comms SDK with an SMTP provider. It requires email credentials and recipient details. The output logs the unique ID of the sent email. ```typescript import CommsSdk from '@webventures/comms' const comms = new CommsSdk({ channels: { email: { providers: [ { type: 'smtp', host: 'smtp.gmail.com', port: 587, auth: { user: process.env.EMAIL_USER!, pass: process.env.EMAIL_PASS!, }, }, ], }, }, }) async function sendWelcomeEmail(email: string, name: string) { const result = await comms.send({ email: { from: 'noreply@example.com', to: email, subject: `Welcome ${name}!`, html: `

Welcome ${name}!

Thanks for joining us.

`, }, }) console.log('Email sent:', result.channels?.email?.id) } await sendWelcomeEmail('user@example.com', 'John') ``` -------------------------------- ### Updating Comms SDK Dependencies (npm) Source: https://github.com/cryptventure/comms/blob/main/docs/MIGRATION.md Commands to uninstall the old 'webventures-comms' package and install the new '@webventures/comms' package using npm. Includes installing TypeScript if necessary. ```bash # Remove old package npm uninstall webventures-comms # Install new package npm install @webventures/comms # If using TypeScript npm install --save-dev typescript@^5.0.0 ``` -------------------------------- ### Initialize Comms SDK for Node.js Source: https://github.com/cryptventure/comms/blob/main/docs/README.md Illustrates the standard initialization of the Comms SDK for a Node.js environment using the main CommsSdk class. Configuration options should be passed as per the SDK documentation. ```typescript import CommsSdk from '@webventures/comms' const comms = new CommsSdk({ // Standard configuration }) ``` -------------------------------- ### Send SMS using Twilio Source: https://github.com/cryptventure/comms/blob/main/docs/PROVIDERS.md Example of sending an SMS message using the Twilio provider. Requires 'from' and 'to' phone numbers and the message 'text'. ```typescript await comms.send({ sms: { from: '+1234567890', to: '+0987654321', text: 'Your verification code: 123456', }, }) ``` -------------------------------- ### Channel Provider Implementation Example (TypeScript) Source: https://github.com/cryptventure/comms/blob/main/CLAUDE.md This snippet demonstrates a typical implementation of a channel provider. It includes initialization with configuration, a 'send' method that handles request customization, transformation, HTTP requests with specific headers, error handling via ProviderError, and result extraction. It relies on an external 'request' utility and defines provider-specific constants. ```typescript import request from '@/util/request' import { ProviderError } from '@/types/errors' /** * ProviderName Provider * * Detailed description of what this provider does, any limitations, * and links to official documentation. * * @example * ```typescript * const provider = new ProviderNameProvider({ * apiKey: 'your-api-key', * // other config * }) * ``` */ export default class ChannelProviderNameProvider implements Provider { readonly id: string = '{channel}-{provider-name}-provider' constructor(config: ProviderConfig) { // Validate required config if (!config.apiKey) { throw new Error('ProviderName requires apiKey') } this.apiKey = config.apiKey } async send(request: ChannelRequest): Promise { // 1. Apply customize function if provided const customized = request.customize ? await request.customize(this.id, request) : request // 2. Transform to provider API format const payload = this.transformRequest(customized) // 3. Make HTTP request with User-Agent header const response = await request('https://api.provider.com/endpoint', { method: 'POST', headers: { Authorization: `Bearer ${this.apiKey}`, 'Content-Type': 'application/json', 'User-Agent': 'webventures-comms/v2 (+https://github.com/cryptventure/comms)', }, body: JSON.stringify(payload), }) // 4. Handle errors with ProviderError if (!response.ok) { const errorBody = await response.text() throw new ProviderError( `ProviderName API error: ${errorBody}`, this.id, '{channel}', 'API_ERROR', { statusCode: response.status, response: errorBody } ) } // 5. Extract and return message ID const result = await response.json() return { id: result.messageId } } } ``` -------------------------------- ### Expo Custom Push Notification Provider Setup Source: https://github.com/cryptventure/comms/blob/main/docs/FRAMEWORKS.md Configures a custom push notification provider for Expo using the Comms SDK. This setup integrates with Expo's push notification service, defining a 'send' function that chunks and sends notifications asynchronously via Expo's server SDK. ```typescript // Backend: Expo Push Notifications import CommsSdk from '@webventures/comms' import { Expo } from 'expo-server-sdk' const comms = new CommsSdk({ channels: { push: { providers: [ { type: 'custom', id: 'expo-push', send: async (request) => { const expo = new Expo() const messages = [ { to: request.registrationToken, sound: 'default', title: request.title, body: request.body, data: request.custom, }, ] const chunks = expo.chunkPushNotifications(messages) const tickets = await Promise.all( chunks.map((chunk) => expo.sendPushNotificationsAsync(chunk)) ) return tickets[0]?.[0]?.id ?? 'unknown' }, }, ], }, }, }) ``` -------------------------------- ### Importing SMS Provider Types (TypeScript) Source: https://github.com/cryptventure/comms/blob/main/docs/MIGRATION.md Imports type definitions for various SMS gateway providers compatible with the Comms SDK, ensuring accurate type checking during provider setup. ```typescript // SMS providers import type { SmsProviderTwilio, SmsProviderNexmo, SmsProviderPlivo, // ... etc } from '@webventures/comms' ``` -------------------------------- ### Send Push Notification using FCM Source: https://github.com/cryptventure/comms/blob/main/docs/PROVIDERS.md Example of sending a push notification via FCM. Includes registration token, title, body, optional icon, color, priority, and custom data payload. ```typescript await comms.send({ push: { registrationToken: 'fcm-device-token', title: 'Notification Title', body: 'Notification body text', icon: 'notification_icon', color: '#FF0000', priority: 'high', custom: { userId: '123', action: 'open_chat', }, }, }) ``` -------------------------------- ### TypeScript Code Style Examples Source: https://github.com/cryptventure/comms/blob/main/CONTRIBUTING.md Illustrative TypeScript code snippets demonstrating recommended practices for type definitions, checking optional fields, using optional chaining, and prefixing unused variables. ```typescript // Use type for unions and utility types type ProviderConfig = SendGridConfig | MailgunConfig | SESConfig // Check for undefined before accessing if (config.optionalField !== undefined) { processField(config.optionalField) } // Use optional chaining const value = config.nested?.property?.value // Prefix unused variables with underscore const [first, , third] = array const { needed, _unused } = object ``` -------------------------------- ### Provider Lifecycle Steps Source: https://github.com/cryptventure/comms/blob/main/docs/ARCHITECTURE.md Illustrates the lifecycle of a provider, from initial configuration to execution. This includes user-provided configuration, factory instantiation, registry storage, and eventual use by a strategy. ```plaintext Configuration → Factory → Registration → Execution 1. User provides config: { type: 'sendgrid', apiKey: 'xxx' } 2. Factory creates instance: const provider = new SendGridProvider(config) 3. Registry stores instance: Registry.set('sendgrid-default', provider) 4. Strategy uses provider: const id = await provider.send(request) ``` -------------------------------- ### Initialize CommsSdk with Single Provider per Channel Source: https://context7.com/cryptventure/comms/llms.txt Demonstrates initializing the CommsSdk with a single provider for email, SMS, and push notifications. This setup uses environment variables for sensitive credentials like API keys and tokens. ```typescript import CommsSdk from '@webventures/comms' // Single provider per channel const comms = new CommsSdk({ channels: { email: { providers: [ { type: 'sendgrid', apiKey: process.env.SENDGRID_API_KEY, }, ], }, sms: { providers: [ { type: 'twilio', accountSid: process.env.TWILIO_ACCOUNT_SID, authToken: process.env.TWILIO_AUTH_TOKEN, }, ], }, push: { providers: [ { type: 'fcm', id: process.env.FCM_SERVER_KEY, }, ], }, }, }) ``` -------------------------------- ### Cost Optimization Strategy for Comms SDK Source: https://github.com/cryptventure/comms/blob/main/docs/EXAMPLES.md Implements a strategy that selects the most cost-effective provider for sending messages. It sorts providers by 'costPerMessage' and attempts to send the message starting with the cheapest. Dependencies include the 'StrategyFunction' and 'Provider' types from '@webventures/comms'. ```typescript import type { StrategyFunction, Provider } from '@webventures/comms' interface ProviderWithCost extends Provider { costPerMessage: number } const costOptimizedStrategy: StrategyFunction = (providers: Provider[]) => { const sortedProviders = [...providers].sort((a, b) => { const costA = (a as ProviderWithCost).costPerMessage || 0 const costB = (b as ProviderWithCost).costPerMessage || 0 return costA - costB }) return async (request) => { for (const provider of sortedProviders) { try { const id = await provider.send(request) return { id, providerId: provider.id } } catch (error) { // Try next provider continue } } throw new Error('All providers failed') } } const comms = new CommsSdk({ channels: { sms: { multiProviderStrategy: costOptimizedStrategy, providers: [ { type: 'twilio', accountSid: '...', authToken: '...', costPerMessage: 0.0075 } as any, { type: 'nexmo', apiKey: '...', apiSecret: '...', costPerMessage: 0.005 } as any, { type: 'plivo', authId: '...', authToken: '...', costPerMessage: 0.006 } as any, ], }, }, }) ``` -------------------------------- ### Initialize Comms SDK for React Native Source: https://github.com/cryptventure/comms/blob/main/docs/README.md Provides an example of initializing the Comms SDK for a React Native application using the createReactNativeComms adapter. Specific configuration details are omitted and should be provided based on project needs. ```typescript import { createReactNativeComms } from '@webventures/comms/adapters' const comms = createReactNativeComms({ // Configuration }) ``` -------------------------------- ### Send Push Notification using APNs Source: https://github.com/cryptventure/comms/blob/main/docs/PROVIDERS.md Example of sending a push notification to an iOS device via APNs. Includes registration token, title, body, badge count, sound, and topic (app's bundle ID). ```typescript await comms.send({ push: { registrationToken: 'device-token-here', title: 'New Message', body: 'You have a new message', badge: 1, sound: 'default', topic: 'com.example.app', // Bundle ID }, }) ``` -------------------------------- ### Initialize Comms SDK with Telegram Provider Source: https://github.com/cryptventure/comms/blob/main/docs/PROVIDERS.md Demonstrates how to initialize the Comms SDK with a Telegram channel provider. The configuration specifies the channel type and includes an array of providers, where each provider object contains the `type` and `botToken` for Telegram. The `botToken` is typically loaded from environment variables. ```typescript const comms = new CommsSdk({ channels: { telegram: { providers: [ { type: 'telegram', botToken: process.env.TELEGRAM_BOT_TOKEN, }, ], }, }, }) ``` -------------------------------- ### Importing Comms SDK Helper Functions (TypeScript) Source: https://github.com/cryptventure/comms/blob/main/docs/MIGRATION.md Imports utility functions for checking response status, retrieving errors, getting channel IDs, and detecting the environment. These helpers simplify common operations when working with the Comms SDK. ```typescript import { isSuccessResponse, isErrorResponse, getErrors, getChannelIds, detectEnvironment } from '@webventures/comms' const result = await comms.send({...}) if (isSuccessResponse(result)) { const ids = getChannelIds(result) console.log('Email ID:', ids.email) } ``` -------------------------------- ### Initialize CommsSdk with Multi-Provider Failover Strategies Source: https://context7.com/cryptventure/comms/llms.txt Illustrates configuring the CommsSdk for high availability using multiple providers per channel with automatic failover. Supports 'fallback' (sequential) and 'round-robin' (load balancing) strategies. ```typescript import CommsSdk from '@webventures/comms' // Multi-provider with automatic failover const highAvailabilityComms = new CommsSdk({ channels: { email: { multiProviderStrategy: 'fallback', // Try sequentially until success providers: [ { type: 'sendgrid', apiKey: 'primary-key' }, { type: 'ses', region: 'us-east-1', accessKeyId: 'xxx', secretAccessKey: 'xxx' }, { type: 'mailgun', apiKey: 'backup-key', domainName: 'mg.example.com' }, ], }, sms: { multiProviderStrategy: 'round-robin', // Load balance across providers providers: [ { type: 'twilio', accountSid: 'xxx', authToken: 'xxx' }, { type: 'vonage', apiKey: 'xxx', apiSecret: 'xxx' }, ], }, }, }) ``` -------------------------------- ### Input Validation: Email Validation Function (TypeScript) Source: https://github.com/cryptventure/comms/blob/main/docs/FRAMEWORKS.md A TypeScript function to validate email addresses using a regular expression. It checks if the provided string conforms to a standard email format. An example demonstrates how to use this function to throw an error for invalid email addresses. ```typescript function validateEmail(email: string): boolean { return /^[^s@]+@[^s@]+.[^s@]+$/.test(email) } if (!validateEmail(to)) { throw new Error('Invalid email address') } ``` -------------------------------- ### Send Welcome Email with Next.js Server Actions Source: https://github.com/cryptventure/comms/blob/main/docs/README.md Demonstrates sending a welcome email using Next.js 16+ Server Components and Server Actions. It utilizes the createNextJSComms adapter and requires SendGrid API key for email delivery. ```typescript import { createNextJSComms } from '@webventures/comms/adapters' export async function sendWelcomeEmail(email: string) { 'use server' const comms = createNextJSComms({ channels: { email: { providers: [{ type: 'sendgrid', apiKey: process.env.SENDGRID_API_KEY! }], }, }, }) return await comms.send({ email: { from: 'noreply@example.com', to: email, subject: 'Welcome!', text: 'Thanks for signing up!', }, }) } ``` -------------------------------- ### Configure Logger Provider for Notifications Source: https://github.com/cryptventure/comms/blob/main/docs/PROVIDERS.md This configuration shows how to set up the 'logger' provider for various notification channels. The logger provider is useful for development and testing as it logs notifications instead of sending them externally. This setup ensures that all messages sent through email, SMS, and push channels will be logged for inspection. ```typescript const comms = new CommsSdk({ channels: { email: { providers: [{ type: 'logger' }], }, sms: { providers: [{ type: 'logger' }], }, push: { providers: [{ type: 'logger' }], }, }, }) ``` -------------------------------- ### Basic Email Sending with Comms SDK Source: https://github.com/cryptventure/comms/blob/main/docs/README.md Demonstrates how to initialize the Comms SDK with SMTP email provider and send a basic HTML email. Requires email credentials and recipient details. ```typescript import CommsSdk from '@webventures/comms' // Initialize SDK const comms = new CommsSdk({ channels: { email: { providers: [ { type: 'smtp', host: 'smtp.gmail.com', port: 587, auth: { user: 'your-email@gmail.com', pass: 'your-password', }, }, ], }, }, }) // Send email const result = await comms.send({ email: { from: 'noreply@example.com', to: 'user@example.com', subject: 'Welcome to WebVentures!', html: '

Hello!

Welcome to our platform.

', }, }) console.log(result) // { status: 'success', channels: { email: { id: 'msg-123', providerId: 'smtp-provider' } } } ``` -------------------------------- ### Backend Server Setup for React Native Comms Source: https://github.com/cryptventure/comms/blob/main/docs/FRAMEWORKS.md Sets up an Express.js backend server to handle notification requests from React Native applications. It initializes the Comms SDK with email (SendGrid) and push (FCM) providers and exposes an API endpoint '/notifications/send' to process and send notifications. ```typescript // backend/server.ts import express from 'express' import CommsSdk from '@webventures/comms' const app = express() app.use(express.json()) const comms = new CommsSdk({ channels: { email: { providers: [{ type: 'sendgrid', apiKey: process.env.SENDGRID_API_KEY! }], }, push: { providers: [ { type: 'fcm', id: process.env.FCM_SERVER_KEY!, }, ], }, }, }) app.post('/notifications/send', async (req, res) => { try { const result = await comms.send(req.body) res.json(result) } catch (error) { res.status(500).json({ error: 'Failed to send notification' }) } }) app.listen(3000) ``` -------------------------------- ### Initializing Comms SDK from Environment Variables (Node.js Adapter - TypeScript) Source: https://github.com/cryptventure/comms/blob/main/README.md Demonstrates using an adapter function to initialize the Comms SDK by reading configuration from environment variables. This is a convenient way to manage credentials and settings in different environments without hardcoding them. The `createNodeCommsFromEnv` function automatically picks up variables like `COMMS_EMAIL_PROVIDER`, `COMMS_SMS_PROVIDER`, etc. ```typescript import { createNodeCommsFromEnv } from '@webventures/comms/adapters' // Reads COMMS_EMAIL_PROVIDER, COMMS_SMS_PROVIDER, etc. const comms = createNodeCommsFromEnv() ``` -------------------------------- ### Build and Test Commands - Bash Source: https://github.com/cryptventure/comms/blob/main/CLAUDE.md Common bash commands for building, testing, linting, and cleaning the WebVentures Comms SDK package. These commands utilize the pnpm package manager. ```bash pnpm run build pnpm run type-check pnpm run lint pnpm run lint:fix pnpm test pnpm test:watch pnpm test:ui pnpm test:coverage pnpm test __tests__/providers/email/sendgrid.test.ts pnpm run clean ``` -------------------------------- ### Build Production-Ready Email Service with Logging in TypeScript Source: https://github.com/cryptventure/comms/blob/main/docs/EXAMPLES.md This TypeScript class provides a production-ready email service using CommsSdk. It configures multiple email providers with a fallback strategy and integrates with Winston for logging errors and informational messages. Environment variables are used for API keys and sender email addresses. It also configures the SDK's internal logger to write to a dedicated file. ```typescript import CommsSdk from '@webventures/comms' import winston from 'winston' class EmailService { private comms: CommsSdk private logger: winston.Logger constructor() { this.comms = new CommsSdk({ channels: { email: { multiProviderStrategy: 'fallback', providers: [ { type: 'sendgrid', apiKey: process.env.SENDGRID_API_KEY! }, { type: 'ses', region: 'us-east-1', accessKeyId: process.env.AWS_KEY!, secretAccessKey: process.env.AWS_SECRET!, }, ], }, }, }) this.logger = winston.createLogger({ level: 'info', format: winston.format.json(), transports: [ new winston.transports.File({ filename: 'error.log', level: 'error' }), new winston.transports.File({ filename: 'combined.log' }), ], }) // Configure SDK logger this.comms.logger.configure([new winston.transports.File({ filename: 'notifications.log' })]) } async sendTransactional(to: string, subject: string, html: string) { try { const result = await this.comms.send({ email: { from: process.env.FROM_EMAIL!, to, subject, html, }, }) this.logger.info('Email sent', { to, subject, messageId: result.channels?.email?.id, provider: result.channels?.email?.providerId, }) return result } catch (error) { this.logger.error('Email failed', { to, subject, error: error instanceof Error ? error.message : 'Unknown error', }) throw error } } } export const emailService = new EmailService() ``` -------------------------------- ### Express.js Integration for Sending Emails (TypeScript) Source: https://github.com/cryptventure/comms/blob/main/docs/FRAMEWORKS.md Provides an example of integrating the Comms SDK with an Express.js application to create an API endpoint for sending emails. It demonstrates how to handle POST requests, parse JSON bodies, and send email notifications using the SDK. Error handling for API calls is also included. ```typescript // server.ts import express from 'express' import CommsSdk from '@webventures/comms' const app = express() app.use(express.json()) const comms = new CommsSdk({ channels: { email: { providers: [{ type: 'sendgrid', apiKey: process.env.SENDGRID_API_KEY! }] }, sms: { providers: [{ type: 'twilio', accountSid: '...', authToken: '...' }] }, }, }) app.post('/api/send-email', async (req, res) => { try { const { to, subject, body } = req.body const result = await comms.send({ email: { from: 'noreply@example.com', to, subject, html: body, }, }) if (result.status === 'success') { res.json({ success: true, messageId: result.channels?.email?.id }) } else { res.status(500).json({ success: false, errors: result.errors }) } } catch (error) { res.status(500).json({ success: false, error: error.message }) } }) app.listen(3000, () => { console.log('Server running on port 3000') }) ```