npm package: @glossaai/chat-sdk
Description: Glossa AI Chat SDK for web applications - Support for Angular, React, Vue, PHP (Laravel, Symfony, CodeIgniter), and Vanilla JavaScript
Author: Glossa AI Team
Latest version: 1.7.7

# Glossa Chat SDK

JavaScript/TypeScript SDK for embedding Glossa AI chat widgets in your web applications. Supports React, Vue, Angular, PHP (Laravel, Symfony, CodeIgniter), and Vanilla JavaScript.

> **⚠️ IMPORTANT: This is a Paid Service**  
> To use the Glossa Chat SDK, you must first purchase a bot subscription through the [Glossa website](https://glossaai.ir) to obtain your unique `botCode`. The SDK requires an active subscription and valid bot credentials to function.

## Features

- 🚀 Easy integration with any web framework
- 💬 Real-time AI-powered chat with RAG (Retrieval-Augmented Generation)
- 🎨 Customizable appearance and branding
- 📱 Responsive and mobile-friendly
- 🔒 Secure session management
- 🌐 Multi-language support (RTL included)
- 📦 Both ESM and UMD builds
- 📘 Built-in TypeScript type definitions (no manual declarations needed)
- 🤖 AI-powered responses with document knowledge base
- 📚 Document upload and knowledge base integration
- 📊 Analytics and conversation tracking
- 🔄 Multi-platform support (Web, Telegram, WhatsApp, Bale, Eitaa)

## Prerequisites

Before installing the SDK, you need:

1. **Active Subscription**: Purchase a bot subscription at [glossaai.ir](https://glossaai.ir)
2. **Bot Code**: Obtain your unique 11-character `botCode` from the Glossa customer panel
3. **Allowed Origins**: Configure allowed domains in your bot settings for CORS security

## Installation

### NPM

```bash
npm install @glossaai/chat-sdk
```

### Yarn

```bash
yarn add @glossaai/chat-sdk
```

### CDN

```html
<script src="https://unpkg.com/@glossaai/chat-sdk/dist/@glossaai/chat-sdk.umd.js"></script>
<link rel="stylesheet" href="https://unpkg.com/@glossaai/chat-sdk/dist/@glossaai/chat-sdk.css">
```

## Quick Start

### Vanilla JavaScript

```html
<script src="https://unpkg.com/@glossaai/chat-sdk/dist/glossa-chat-sdk.umd.js"></script>
<script>
  window.GlossaChat.init({
    botCode: 'your-bot-code',
    chatServiceUrl: 'https://panel.glossaai.ir'
  });
</script>
```

### React

```jsx
import { useEffect } from 'react';
import '@glossaai/chat-sdk/styles';

declare global {
  interface Window {
    GlossaChat: any;
  }
}

function App() {
  useEffect(() => {
    import('@glossaai/chat-sdk').then(() => {
      window.GlossaChat?.initReact({
        botCode: 'your-bot-code',
        chatServiceUrl: 'https://panel.glossaai.ir'
      });
    });

    return () => {
      if (window.GlossaChat?.isOpen) {
        window.GlossaChat.closeChat();
      }
    };
  }, []);

  return <div>Your App</div>;
}
```

### Vue

```vue
<template>
  <div>Your App</div>
</template>

<script>
import '@glossaai/chat-sdk/styles';

export default {
  mounted() {
    import('@glossaai/chat-sdk').then(() => {
      window.GlossaChat?.initVue({
        botCode: 'your-bot-code',
        chatServiceUrl: 'https://panel.glossaai.ir'
      });
    });
  },
  beforeUnmount() {
    if (window.GlossaChat?.isOpen) {
      window.GlossaChat.closeChat();
    }
  }
};
</script>
```

### Angular

#### Angular 18+ (Standalone Component)

```typescript
import { Component, OnInit, OnDestroy } from '@angular/core';
import '@glossaai/chat-sdk/styles';

declare global {
  interface Window {
    GlossaChat: any;
    GlossaAngularService: any;
  }
}

@Component({
  selector: 'app-root',
  standalone: true,
  template: '<router-outlet />'  // SDK automatically adds the widget
})
export class AppComponent implements OnInit, OnDestroy {
  ngOnInit() {
    // SDK automatically adds the widget to document.body
    import('@glossaai/chat-sdk').then(() => {
      window.GlossaChat?.initAngular({
        botCode: 'your-bot-code',  // Required: 11-character bot code
        chatServiceUrl: 'https://panel.glossaai.ir'  // Optional: defaults to this
      });
    });
  }

  ngOnDestroy() {
    if (window.GlossaChat?.isOpen) {
      window.GlossaChat.closeChat();
    }
  }
}
```

#### Angular (Classic Module-based)

```typescript
import { Component, OnInit, OnDestroy } from '@angular/core';
import '@glossaai/chat-sdk/styles';

declare global {
  interface Window {
    GlossaChat: any;
    GlossaAngularService: any;
  }
}

@Component({
  selector: 'app-root',
  template: '<router-outlet></router-outlet>'
})
export class AppComponent implements OnInit, OnDestroy {
  ngOnInit() {
    import('@glossaai/chat-sdk').then(() => {
      window.GlossaChat?.initAngular({
        botCode: 'your-bot-code',
        chatServiceUrl: 'https://panel.glossaai.ir'
      });
    });
  }

  ngOnDestroy() {
    if (window.GlossaChat?.isOpen) {
      window.GlossaChat.closeChat();
    }
  }
}
```

**Important:** The SDK automatically adds the chat widget to the corner of the page. No special template is needed for the widget.

### PHP (Laravel)

```php
<!-- resources/views/layouts/app.blade.php -->
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://unpkg.com/@glossaai/chat-sdk/src/styles/chat-widget.css">
</head>
<body>
    @yield('content')
    
    <script src="https://unpkg.com/@glossaai/chat-sdk/dist/glossa-chat-sdk.umd.js"></script>
    <script>
        window.GlossaChat.init({
            botCode: '{{ config("chat.bot_code") }}',
            chatServiceUrl: '{{ config("chat.service_url") }}'
            // primaryColor and other bot settings are loaded from API automatically
        }).then(function(result) {
            if (result.success) {
                console.log('Chat SDK initialized');
            }
        });
    </script>
</body>
</html>
```

## Configuration

### Options

```typescript
{
  // Required
  botCode: string;              // Your bot code (11 characters, obtained from Glossa panel)
  
  // Optional
  chatServiceUrl?: string;      // Chat service URL (default: 'https://panel.glossaai.ir')
  
  // Note: The following settings are loaded from bot API automatically:
  // - primaryColor: Bot's primary color (from bot settings in panel)
  // - position: Widget position (from bot settings)
  // - welcomeMessage: Welcome message (from bot settings)
  // - showAvatar: Show/hide avatar (from bot settings)
  // - avatarUrl: Bot avatar URL (from bot settings)
  // - name: Bot name (from bot settings)
}
```

**Important**: Your `botCode` must be valid and associated with an active subscription. Invalid or expired bot codes will result in initialization errors.

### Methods

```typescript
// Initialize (use framework-specific method)
await window.GlossaChat.initAngular(config);   // Angular
await window.GlossaChat.initReact(config);      // React
await window.GlossaChat.initVue(config);        // Vue
await window.GlossaChat.init(config);           // Vanilla JS

// Control chat
window.GlossaChat.openChat();
window.GlossaChat.closeChat();
window.GlossaChat.toggleChat();

// Send message
window.GlossaChat.sendMessage('Hello!');

// Get info
const sessionId = window.GlossaChat.getSessionId();
const isInit = window.GlossaChat.isInitialized;
const isOpen = window.GlossaChat.isOpen;
```

### Events

Monitor chat state through properties:

```typescript
if (window.GlossaChat.isInitialized) {
  console.log('SDK is ready');
}
if (window.GlossaChat.isOpen) {
  console.log('Chat is open');
}
```

## Styling

### Importing Styles

The SDK includes all styles and fonts bundled. Simply import the styles:

```javascript
// ✅ Recommended: Import styles (includes fonts automatically)
import '@glossaai/chat-sdk/styles';

// ✅ Alternative: Import CSS file directly
import '@glossaai/chat-sdk/styles.css';
```

**Important:** 
- ✅ **No manual font setup needed** - Vazirmatn fonts are automatically included as base64 inline fonts
- ✅ **No need to copy font files** - Everything is bundled in the CSS
- ✅ **Works with all bundlers** - Webpack, Vite, Rollup, etc.

### Customizing Styles

You can override default styles:

```css
/* Override default styles */
.glossa-chat-container {
  /* Your custom styles */
}

.glossa-chat-button {
  background-color: your-color !important;
}

.glossa-chat-panel {
  /* Custom chat panel styles */
}
```

### Fonts

The SDK uses **Vazirmatn** font for Persian/Arabic text support. Fonts are:
- ✅ Automatically bundled as base64 inline fonts
- ✅ No external font files needed
- ✅ No @font-face declarations needed
- ✅ Works offline

## Examples

Check the `/examples` directory for complete examples:

- [Vanilla JavaScript](./examples/vanilla/index.html)
- [React](./examples/react/index.html)
- [Vue](./examples/vue/index.html)
- [Angular](./examples/angular/index.html)
- [PHP Laravel](./examples/php/laravel-example.php)
- [PHP Symfony](./examples/php/symfony-example.php)
- [PHP CodeIgniter](./examples/php/codeigniter-example.php)

## Development

### Setup

```bash
npm install
```

### Build

```bash
# Production build (both UMD and ESM)
npm run build

# Development build
npm run build:dev

# Watch mode
npm run dev
```

### Test

```bash
npm test
```

### Lint

```bash
npm run lint
```

## Browser Support

- Chrome (latest)
- Firefox (latest)
- Safari (latest)
- Edge (latest)
- Mobile browsers (iOS Safari, Chrome Mobile)

## API Integration

This SDK works with the Glossa Chat Service and integrates with the full Glossa AI Platform.

### Chat Service URL

Set the `chatServiceUrl` to your chat service endpoint:

```javascript
{
  chatServiceUrl: 'https://panel.glossaai.ir'  // Production (default)
  // or
  chatServiceUrl: 'http://localhost:3001'      // Development
}
```

### Platform Architecture

The Glossa platform consists of:

1. **Customer Panel**: Bot management, configuration, and analytics
2. **Chat Service**: Real-time messaging service (port 3001)
3. **Chat SDK**: This package for embedding chat widgets
4. **RAG API**: AI-powered response generation service
5. **Multi-Platform Connectors**: Telegram, WhatsApp, Bale, Eitaa integrations

### Backend Services

- **WhatsApp**: Direct connection via Baileys (no third-party API required)
- **Telegram**: Webhook-based integration
- **Bale & Eitaa**: Native bot API integration
- **RAG API**: Document-based AI responses with context awareness

### CORS Configuration

**Critical**: You must configure allowed domains in your bot settings:

1. Log in to the [Glossa Customer Panel](https://panel.glossaai.ir)
2. Navigate to your bot settings
3. Add your website domain(s) to the "Allowed Origins" list
   - Example: `https://example.com` (no trailing slash)
   - You can add up to 2 domains per bot
   - Wildcard (`*`) is not allowed for security
4. Save your settings

Requests from domains not in your allowed list will be blocked by CORS policy.

## TypeScript Support

The SDK includes built-in TypeScript type definitions. **No manual type declarations needed!**

### Automatic Type Support

When you install the SDK, TypeScript automatically recognizes the types:

```typescript
// ✅ Just import - types are automatically available
import GlossaChatSDK from '@glossaai/chat-sdk';

const sdk = new GlossaChatSDK();
// ✅ Full autocomplete and type checking
await sdk.init({ botCode: 'your-bot-code' });
```

### Type Definitions Included

The SDK provides complete type definitions for:

- **SDKConfig**: Configuration interface
- **BotConfig**: Bot settings interface
- **InitResult**: Initialization result interface
- **BotConfigResult**: Bot config API response interface
- **GlossaChatSDK**: Main SDK class with all methods

### Example with TypeScript

```typescript
import GlossaChatSDK, { SDKConfig, InitResult } from '@glossaai/chat-sdk';

const config: SDKConfig = {
  botCode: 'your-bot-code',
  chatServiceUrl: 'https://panel.glossaai.ir'
};

const sdk = new GlossaChatSDK();
const result: InitResult = await sdk.init(config);

if (result.success) {
  console.log('SDK initialized:', result.message);
} else {
  console.error('Initialization failed:', result.error);
}
```

### Global Window Types (Optional)

If you're using the global `window.GlossaChat` instance, you can optionally extend the Window interface:

```typescript
declare global {
  interface Window {
    GlossaChat: InstanceType<typeof import('@glossaai/chat-sdk').default>;
    GlossaAngularService?: any;
    GlossaReactHook?: any;
    GlossaVuePlugin?: any;
  }
}
```

**Note**: This is optional. The SDK's built-in types work automatically when importing the module.

## Troubleshooting

### Chat widget not appearing

1. Check console for errors
2. Verify `botCode` is correct (11 characters)
3. Ensure your bot subscription is active
4. Verify domain is added to allowed origins in bot settings
5. Check if SDK script is loaded: `console.log(window.GlossaChat)`

### Initialization errors

1. **Invalid bot code**: Verify your bot code in the customer panel
2. **Expired subscription**: Check if your subscription is still active
3. **Bot not found**: Ensure bot exists and is not deleted
4. **Inactive bot**: Make sure bot is enabled in settings
5. Check browser console for detailed error messages

### CORS errors (blocked by CORS policy)

**Most common issue!** If you see:
```
Access to fetch has been blocked by CORS policy
```

**Solutions**:
1. Add your domain to "Allowed Origins" in bot settings (customer panel)
2. Remove trailing slashes from your domain (use `https://example.com` not `https://example.com/`)
3. Use exact domain match (protocol + domain, no wildcards)
4. Wait 5 minutes for cache to clear after updating origins
5. Verify you're testing from the same domain you configured

### Connection errors

1. Check network connectivity
2. Verify chat service URL is correct (`https://panel.glossaai.ir`)
3. Check browser DevTools Network tab for failed requests
4. Ensure you're not behind a firewall blocking the API
5. Verify your subscription payment is up to date
6. Check if RAG API is accessible and configured correctly
7. Verify bot is active and enabled in customer panel

### Platform-specific issues

**WhatsApp Integration:**
- Ensure QR code is scanned successfully
- Check session files are not corrupted
- Verify Baileys connection is stable

**Telegram/Bale/Eitaa:**
- Verify bot token is correct
- Check webhook URL is configured properly
- Ensure bot is active in platform settings

## License

MIT License - see [LICENSE](./LICENSE) file for details

## Platform Features

Glossa AI Platform provides comprehensive multi-platform support:

### 🌐 Web Integration
- Chat SDK for embedding in websites
- Customizable widget appearance
- Real-time messaging
- Session management

### 📱 Messaging Platforms
- **Telegram**: Full bot integration with webhook support
- **WhatsApp**: Direct connection via Baileys library with QR code authentication
- **Bale**: Complete bot integration
- **Eitaa**: Full bot support

### 🤖 AI Capabilities
- **RAG API Integration**: Retrieval-Augmented Generation for context-aware responses
- **Document Knowledge Base**: Upload and manage documents for AI training
- **Multiple AI Providers**: Support for various AI models
- **Conversation History**: Persistent chat history across sessions
- **Smart Responses**: Context-aware and intelligent responses

### 🔧 Technical Features
- **Internal Webhook System**: Clean separation of connection management and message processing
- **Session Management**: Secure session handling for all platforms
- **Rate Limiting**: Built-in rate limiting per user
- **Error Handling**: Robust error handling and reconnection logic
- **Analytics**: Comprehensive analytics and reporting

## Pricing & Subscription

Glossa Chat SDK is a **paid service** with the following features:

- ✅ Unlimited messages (subject to rate limits per user)
- ✅ AI-powered responses with RAG (Retrieval-Augmented Generation)
- ✅ Document upload and knowledge base integration
- ✅ Multi-platform support (Web, Telegram, WhatsApp, Bale, Eitaa)
- ✅ Analytics and conversation tracking
- ✅ Custom branding and styling
- ✅ Webhook support for all messaging platforms
- ✅ WhatsApp direct connection (no third-party API required)
- ✅ Real-time message processing
- ✅ Conversation history and context management

Visit [glossaai.ir](https://glossaai.ir) for:
- Pricing plans
- Feature comparison
- Free trial information
- Subscription management

## Support

- 🌐 Website: [glossaai.ir](https://glossaai.ir)
- 👤 Customer Panel: [panel.glossaai.ir](https://panel.glossaai.ir)
- 📧 Email: support@glossaai.ir

## Changelog

### Version 1.6.16 (Latest)
- ✅ Multi-platform messaging support (Telegram, WhatsApp, Bale, Eitaa)
- ✅ WhatsApp Baileys integration with QR code authentication
- ✅ Internal webhook system for clean message processing
- ✅ RAG API integration for intelligent responses
- ✅ Document knowledge base support
- ✅ Enhanced error handling and reconnection logic
- ✅ Improved session management
- ✅ Better performance and reliability

See [CHANGELOG.md](./CHANGELOG.md) for complete version history.

## Auto-Configuration (Recommended)

You can configure the SDK without writing any JavaScript code. The SDK will automatically detect and initialize using one of these methods:

### Method 1: Data Attributes (Easiest)
```html
<script 
  src="https://unpkg.com/@glossaai/chat-sdk/dist/glossa-chat-sdk.umd.js"
  data-bot-code="your-bot-code"
  data-chat-service-url="https://panel.glossaai.ir">
</script>
<!-- Note: Bot settings (primaryColor, welcomeMessage, etc.) are loaded from API -->
```

### Method 2: Meta Tags
```html
<head>
  <meta name="glossa-bot-code" content="your-bot-code">
  <meta name="glossa-chat-service-url" content="https://panel.glossaai.ir">
  <!-- Note: primaryColor and other bot settings come from API, not from meta tags -->
</head>
```

### Method 3: Global Config
```html
<script>
  window.GLOSSA_CONFIG = {
    botCode: 'your-bot-code',
    chatServiceUrl: 'https://panel.glossaai.ir'
    // Note: primaryColor is loaded from bot API, not from this config
  };
</script>
<script src="...glossa-chat-sdk.umd.js"></script>
```

**Important Notes**:
- If botCode is found using any of these methods, the SDK will automatically initialize. You don't need to call `init()` manually.
- Bot settings like `primaryColor`, `welcomeMessage`, `position`, `avatarUrl`, etc. are **automatically loaded from the bot API** based on the botCode. You don't need to configure them manually.
- Only `botCode` and `chatServiceUrl` can be configured. All other settings come from your bot configuration in the Glossa panel.