JSPM

apptise-types

1.0.3
    • ESM via JSPM
    • ES Module Entrypoint
    • Export Map
    • Keywords
    • License
    • Repository URL
    • TypeScript Types
    • README
    • Created
    • Published
    • Downloads 5
    • Score
      100M100P100Q61594F
    • License MIT

    TypeScript interfaces and types for Apptise notification plugins

    Package Exports

    • apptise-types
    • apptise-types/example-plugin
    • apptise-types/plugin-interface

    Readme

    Apptise Plugin Interface

    This package provides TypeScript interfaces and base classes for creating notification plugins in the Apptise ecosystem.

    Overview

    The INotificationPlugin interface defines the contract that all notification plugins must implement. It provides a standardized way to:

    • Send notifications to various services (Discord, Slack, Email, etc.)
    • Handle different notification types and formats
    • Support file attachments
    • Parse and validate service URLs
    • Manage plugin metadata and configuration

    Key Components

    Core Interface

    • INotificationPlugin: Main interface that all plugins must implement
    • NotificationPluginBase: Abstract base class with common functionality

    Supporting Types

    • NotifyType: Notification severity levels (INFO, SUCCESS, WARNING, FAILURE)
    • NotifyFormat: Message formats (TEXT, MARKDOWN, HTML)
    • OverflowMode: How to handle message length limits (UPSTREAM, TRUNCATE, SPLIT)
    • PersistentStoreMode: Storage behavior (NEVER, FLUSH, MEMORY, AUTO)

    Template System

    • TemplateToken: URL path parameters (required for service connection)
    • TemplateArg: URL query parameters (optional configuration)

    Error Handling

    • NotificationError: Base error for notification failures
    • URLParseError: Specific error for URL parsing issues

    Quick Start

    1. Install the Package

    pnpm add @apptise/types

    2. Implement a Plugin

    import { NotificationPluginBase, NotifyType, AttachBase } from '@apptise/types';
    
    export class MyServicePlugin extends NotificationPluginBase {
      // Required metadata
      readonly service_name = 'myservice';
      readonly service_url = 'https://myservice.com';
      readonly protocol = 'myservice';
      readonly protocols = ['myservice'];
      
      // Feature support
      readonly attachment_support = true;
      readonly body_maxlen = 1000;
      
      // URL templates
      readonly templates = [
        'myservice://{api_key}',
        'myservice://{api_key}?channel={channel}'
      ];
      
      // Template tokens (required URL parameters)
      readonly template_tokens = {
        api_key: {
          name: 'API Key',
          type: 'string' as const,
          required: true,
          private: true
        }
      };
      
      // Template args (optional URL parameters)
      readonly template_args = {
        channel: {
          name: 'Channel',
          type: 'string' as const,
          default: 'general'
        }
      };
      
      constructor(private apiKey: string, private options: any = {}) {
        super(options);
      }
      
      // Implement required methods
      send(body: string, title?: string, notify_type?: NotifyType, attach?: AttachBase[]): boolean {
        // Your synchronous send logic here
        console.log(`Sending to MyService: ${title} - ${body}`);
        return true;
      }
      
      async async_send(body: string, title?: string, notify_type?: NotifyType, attach?: AttachBase[]): Promise<boolean> {
        // Your asynchronous send logic here
        console.log(`Async sending to MyService: ${title} - ${body}`);
        return true;
      }
      
      parse_url(url: string): ParsedURL | null {
        // Your URL parsing logic here
        try {
          const parsed = new URL(url);
          return {
            schema: parsed.protocol.slice(0, -1),
            host: parsed.hostname,
            path: parsed.pathname,
            params: Object.fromEntries(parsed.searchParams),
            url
          };
        } catch {
          return null;
        }
      }
    }

    3. Use the Plugin

    // Create plugin instance
    const plugin = new MyServicePlugin('your-api-key');
    
    // Send a notification
    try {
      const success = plugin.send(
        'Hello World!',
        'Test Notification',
        NotifyType.INFO
      );
      console.log('Sent:', success);
    } catch (error) {
      console.error('Failed:', error);
    }
    
    // Send async notification
    const success = await plugin.async_send(
      'Async message',
      'Async Test',
      NotifyType.SUCCESS
    );

    Plugin Requirements

    Every plugin must implement:

    Required Properties

    • service_name: Unique identifier for the service
    • service_url: Official website of the service
    • protocol: Primary URL protocol (e.g., 'discord', 'slack')
    • protocols: Array of supported protocols
    • templates: Array of URL template strings
    • template_tokens: Required URL path parameters
    • template_args: Optional URL query parameters

    Required Methods

    • send(): Synchronous notification sending
    • async_send(): Asynchronous notification sending
    • parse_url(): Parse and validate service URLs

    Optional Properties

    • setup_url: Link to service setup documentation
    • attachment_support: Whether attachments are supported
    • body_maxlen: Maximum message body length
    • title_maxlen: Maximum title length
    • request_rate_per_sec: Rate limiting information

    Advanced Features

    Message Formatting

    Use the formatMessage() method from the base class to handle different formats:

    const formatted = this.formatMessage(title, body, notify_type, NotifyFormat.MARKDOWN);

    Attachment Support

    Handle file attachments in your send methods:

    send(body: string, title?: string, notify_type?: NotifyType, attach?: AttachBase[]): boolean {
      if (attach && attach.length > 0) {
        // Process attachments
        for (const file of attach) {
          console.log(`Attachment: ${file.name}, Size: ${file.size}`);
        }
      }
      // Send logic...
    }

    Error Handling

    Use the provided error classes for consistent error reporting:

    import { NotificationError, URLParseError } from '@apptise/types';
    
    // In your send method
    if (!response.ok) {
      throw new NotificationError(
        `API error: ${response.status}`,
        this.service_name,
        response.status
      );
    }
    
    // In your parse_url method
    if (!isValidUrl) {
      throw new URLParseError('Invalid URL format', url);
    }

    Example Plugins

    See example-plugin.ts for a complete Discord webhook plugin implementation that demonstrates:

    • Full interface implementation
    • URL parsing and validation
    • Error handling
    • Attachment support
    • Configuration management
    • Factory methods for URL-based instantiation

    Type Safety

    This package is fully typed with TypeScript, providing:

    • Compile-time type checking
    • IntelliSense support
    • Clear interface contracts
    • Runtime type validation helpers

    Contributing

    When creating new plugins:

    1. Extend NotificationPluginBase for common functionality
    2. Implement all required interface methods
    3. Follow the naming conventions for services
    4. Include comprehensive error handling
    5. Add unit tests for your plugin
    6. Document any service-specific requirements

    License

    This package is part of the Apptise project and follows the same licensing terms.