{"_id":"@codexpro.ai/ai-chatbot","_rev":"2-8a97191bd78888dcd2aff251df78a311","name":"@codexpro.ai/ai-chatbot","dist-tags":{"latest":"2.0.3"},"versions":{"2.0.2":{"name":"@codexpro.ai/ai-chatbot","version":"2.0.2","keywords":["react","chatbot","ai","chat-widget","typescript","ai-assistant","chat-ui"],"author":{"name":"CodexPro AI"},"license":"ISC","_id":"@codexpro.ai/ai-chatbot@2.0.2","maintainers":[{"name":"codexpro.ai","email":"techsupport@smalldaytech.com"}],"dist":{"shasum":"803d640ff8b088c703862bfd31428e44f643927a","tarball":"https://registry.npmjs.org/@codexpro.ai/ai-chatbot/-/ai-chatbot-2.0.2.tgz","fileCount":23,"integrity":"sha512-biIzIy7eNqwCzipBnooj45P6n3MbfDlPbcmv9Cx4EjOscR2B+Rx3zoMcCCv2o8gr0qiQyIZEkUZ5kUCGuR+xgQ==","signatures":[{"sig":"MEYCIQC40K0n1l/5lV3Kc5PD2rKlgiBgxbXwsoTKYNBRo8dnNwIhAPQ1Qslp/Iigt7NQ8sVRT08637BSJJz1RX4KenLMu3HR","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":467141},"main":"./dist/index.umd.js","types":"./dist/index.d.ts","module":"./dist/index.es.js","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.es.js","require":"./dist/index.umd.js"}},"gitHead":"37f0892b7ef30ce70fb102c82128ed6649867a8d","scripts":{"dev":"vite dev/index.html --config vite.config.dev.ts","test":"vitest --run","build":"vite build && tsc --emitDeclarationOnly","dev:lib":"vite build --watch","test:watch":"vitest"},"_npmUser":{"name":"codexpro.ai","email":"techsupport@smalldaytech.com"},"_npmVersion":"10.8.2","description":"A production-ready React chat widget for AI assistants with enterprise-grade architecture","directories":{},"_nodeVersion":"20.20.2","dependencies":{"nanoid":"^5.1.6","lucide-react":"^0.575.0","react-markdown":"^9.0.1"},"_hasShrinkwrap":false,"devDependencies":{"vite":"^7.3.1","jsdom":"^28.1.0","react":"^18.2.0","vitest":"^1.0.4","react-dom":"^18.2.0","@vitest/ui":"^1.0.4","typescript":"^5.9.3","tailwindcss":"^4.2.1","@types/react":"^19.2.14","@types/react-dom":"^19.2.3","@tailwindcss/vite":"^4.2.1","vite-tsconfig-paths":"^6.1.1","@vitejs/plugin-react":"^5.1.4","@testing-library/react":"^14.1.2","vite-plugin-css-injected-by-js":"^4.0.1"},"peerDependencies":{"react":"^16.8.0 || ^17.0.0 || ^18.0.0","react-dom":"^16.8.0 || ^17.0.0 || ^18.0.0"},"_npmOperationalInternal":{"tmp":"tmp/ai-chatbot_2.0.2_1776145641575_0.6922439466628323","host":"s3://npm-registry-packages-npm-production"}},"2.0.3":{"name":"@codexpro.ai/ai-chatbot","version":"2.0.3","description":"A production-ready React chat widget for AI assistants with enterprise-grade architecture","main":"./dist/index.umd.js","module":"./dist/index.es.js","types":"./dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.es.js","require":"./dist/index.umd.js"}},"scripts":{"build":"vite build && tsc --emitDeclarationOnly","test":"vitest --run","test:watch":"vitest","dev":"vite dev/index.html --config vite.config.dev.ts","dev:lib":"vite build --watch"},"keywords":["react","chatbot","ai","chat-widget","typescript","ai-assistant","chat-ui"],"author":{"name":"CodexPro AI"},"license":"ISC","devDependencies":{"@tailwindcss/vite":"^4.2.1","@testing-library/react":"^16.3.2","@types/react":"^19.2.14","@types/react-dom":"^19.2.3","@vitejs/plugin-react":"^5.1.4","@vitest/ui":"^1.0.4","jsdom":"^28.1.0","react":"^19.2.0","react-dom":"^19.2.0","tailwindcss":"^4.2.1","typescript":"^5.9.3","vite":"^7.3.1","vite-plugin-css-injected-by-js":"^4.0.1","vite-tsconfig-paths":"^6.1.1","vitest":"^1.0.4"},"peerDependencies":{"react":"^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0","react-dom":"^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"},"dependencies":{"lucide-react":"^0.575.0","nanoid":"^5.1.6","react-markdown":"^9.0.1"},"_id":"@codexpro.ai/ai-chatbot@2.0.3","gitHead":"37f0892b7ef30ce70fb102c82128ed6649867a8d","_nodeVersion":"20.20.2","_npmVersion":"10.8.2","dist":{"integrity":"sha512-2AAqkXwFvaYFJpTfk5Y8+IHPYbTzYYbnErkdYn0Qz16omoqcOt+/zAlB9J3/SS7/fjRMIiHv9uCJ48zZtvlW0A==","shasum":"38b940fa5c97dc278abd275beb288d17c154e00f","tarball":"https://registry.npmjs.org/@codexpro.ai/ai-chatbot/-/ai-chatbot-2.0.3.tgz","fileCount":23,"unpackedSize":467549,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEYCIQCuXiVvF1/Dh+GXnSZbf/VSZFzJV9GLCGE2dcKrLEcVsQIhAIMY542LXSs/bqnoEFuZicW54bOsAfallYF9vp+E0MEp"}]},"_npmUser":{"name":"codexpro.ai","email":"techsupport@smalldaytech.com"},"directories":{},"maintainers":[{"name":"codexpro.ai","email":"techsupport@smalldaytech.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/ai-chatbot_2.0.3_1776161313523_0.28239131344472246"},"_hasShrinkwrap":false}},"time":{"created":"2026-04-14T05:47:21.510Z","modified":"2026-04-14T10:08:34.091Z","2.0.2":"2026-04-14T05:47:21.723Z","2.0.3":"2026-04-14T10:08:33.680Z"},"author":{"name":"CodexPro AI"},"license":"ISC","keywords":["react","chatbot","ai","chat-widget","typescript","ai-assistant","chat-ui"],"description":"A production-ready React chat widget for AI assistants with enterprise-grade architecture","maintainers":[{"name":"codexpro.ai","email":"techsupport@smalldaytech.com"}],"readme":"# AI ChatBot Library v2.0.2\n\nA production-ready React library for building AI chatbot interfaces with enterprise-grade architecture. Built with TypeScript, featuring service layer architecture, comprehensive error handling, and full customization support.\n\n**✨ Tailwind CSS v4 is bundled** - No need to install Tailwind separately! The library includes all necessary styles.\n\n## Features\n\n- 🏗️ Enterprise-grade architecture with service layer\n- 🎨 Fully customizable UI (colors, branding, themes)\n- 📝 Markdown rendering for rich text responses (bold, lists, code blocks, links)\n- 📎 File attachments (images, videos, audio)\n- 🎤 Voice recording with WhatsApp-style interface\n- 💬 Real-time chat with typing indicators\n- 🔄 Automatic retry with exponential backoff\n- 💾 Conversation persistence\n- 📱 Responsive design\n- 🌐 Full TypeScript support with enums\n- ⚡ Lightweight and performant\n- 🛡️ Robust error handling with typed errors\n- 📊 Structured logging for debugging\n- ✅ Configuration validation\n\n## Installation\n\n```bash\nnpm install ai-chatbot\n# or\nyarn add ai-chatbot\n# or\npnpm add ai-chatbot\n```\n\n## Quick Start\n\n### EchoMind Integration\n\nFor EchoMind projects, you can use the simplified props instead of constructing the full endpoint:\n\n```tsx\n<AiChatWidget\n  apiBase=\"http://localhost:3030/api\"\n  projectId=\"your-project-uuid\"\n  userId=\"user-123\"\n  branding={{\n    name: \"Support Bot\"\n  }}\n/>\n```\n\nThis automatically constructs the endpoint as `{apiBase}/{projectId}/query` and handles conversation persistence.\n\n### Basic Usage\n\n```tsx\nimport { AiChatWidget } from 'ai-chatbot'\n\nexport default function App() {\n  return (\n    <AiChatWidget\n      apiEndpoint=\"https://your-api.com/chat\"\n      branding={{\n        name: \"Support Bot\",\n        companyName: \"Your Company\"\n      }}\n    />\n  )\n}\n```\n\n### Next.js Usage (App Router)\n\nCreate a client component wrapper:\n\n```tsx\n// components/ChatWidget.tsx\n'use client'\n\nimport { AiChatWidget } from 'ai-chatbot'\n\nexport default function ChatWidget() {\n  return (\n    <AiChatWidget\n      apiEndpoint=\"https://your-api.com/chat\"\n      branding={{\n        name: \"Support Bot\"\n      }}\n      theme={{\n        primaryColor: \"#3b82f6\",\n        headerBackground: \"#1e40af\"\n      }}\n    />\n  )\n}\n```\n\nThen use it in your layout or page:\n\n```tsx\n// app/layout.tsx\nimport ChatWidget from '@/components/ChatWidget'\n\nexport default function RootLayout({ children }) {\n  return (\n    <html>\n      <body>\n        {children}\n        <ChatWidget />\n      </body>\n    </html>\n  )\n}\n```\n\n## Backend API Integration\n\nYour backend needs to handle POST requests to the `apiEndpoint` you configure. The widget sends structured data and expects a specific response format.\n\n### API Endpoint\n\nThe widget makes POST requests to your configured endpoint:\n\n```tsx\n<AiChatWidget apiEndpoint=\"https://your-api.com/chat\" />\n```\n\n### Request Payload\n\nThe widget sends a POST request with the following structure:\n\n#### JSON Request (Text Messages)\n\n```json\n{\n  \"message\": \"User's message text\",\n  \"conversationId\": \"conv-abc123\",\n  \"history\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Previous question\"\n    },\n    {\n      \"role\": \"assistant\", \n      \"content\": \"Previous answer\"\n    }\n  ],\n  \"sessionId\": \"session-xyz\",\n  \"userMetadata\": {\n    \"Authorization\": \"Bearer token\"\n  }\n}\n```\n\n#### FormData Request (With File Attachments)\n\nWhen users upload files, the request is sent as `multipart/form-data`:\n\n```\nmessage: \"Check this image\"\nconversationId: \"conv-abc123\"\nhistory: \"[{...}]\" (JSON stringified)\nsessionId: \"session-xyz\"\nuserMetadata: \"{...}\" (JSON stringified)\nfile_0: <File object>\nfile_1: <File object>\nattachments: \"[{id, type, name, size, mimeType}]\" (JSON stringified)\n```\n\n### Request Fields\n\n| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n| `message` | string | Yes | The user's message text |\n| `conversationId` | string | Yes | Unique conversation identifier (auto-generated) |\n| `history` | Array<{role, content}> | Yes | Simplified message history with role and content only |\n| `sessionId` | string | No | Session identifier (from config or userId) |\n| `userMetadata` | object | No | Custom headers/metadata from config |\n| `attachments` | array | No | File metadata when files are uploaded |\n\n### Expected Response Format\n\nYour API must return a JSON response with at minimum a `message` field:\n\n#### Minimal Response\n\n```json\n{\n  \"message\": \"This is the AI assistant's response\"\n}\n```\n\n#### Full Response (Optional Fields)\n\n```json\n{\n  \"message\": \"This is the AI assistant's response\",\n  \"id\": \"msg-response-123\",\n  \"timestamp\": 1234567890,\n  \"role\": \"assistant\",\n  \"attachments\": [\n    {\n      \"id\": \"att-1\",\n      \"type\": \"image\",\n      \"url\": \"https://cdn.example.com/image.jpg\",\n      \"name\": \"result.jpg\",\n      \"size\": 12345,\n      \"mimeType\": \"image/jpeg\"\n    }\n  ],\n  \"metadata\": {\n    \"model\": \"gpt-4\",\n    \"confidence\": 0.95\n  }\n}\n```\n\n### Response Fields\n\n| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n| `message` | string | **Yes** | The assistant's response text |\n| `id` | string | No | Message ID (auto-generated if omitted) |\n| `timestamp` | number | No | Unix timestamp in ms (auto-generated if omitted) |\n| `role` | string | No | Message role, defaults to \"assistant\" |\n| `attachments` | array | No | Files/media to display with response |\n| `metadata` | object | No | Additional data to store with message |\n\n**Note:** If your response includes `metadata.conversation_id`, the widget will automatically use this for subsequent requests in the same session. This is useful for server-managed conversation tracking.\n\n### Quick Backend Example\n\n```javascript\n// Node.js/Express\napp.post('/chat', async (req, res) => {\n  const { message, conversationId, history } = req.body;\n  \n  // Your AI logic here\n  const response = await yourAI.chat(message, history);\n  \n  res.json({\n    message: response.text,\n    timestamp: Date.now()\n  });\n});\n```\n\n### Error Handling\n\nReturn appropriate HTTP status codes for errors:\n- `400` - Bad Request (invalid input)\n- `401` - Unauthorized (authentication failed)  \n- `429` - Too Many Requests (rate limit exceeded)\n- `500` - Internal Server Error\n\nThe widget automatically retries failed requests (500, 429) with exponential backoff.\n\n**📖 For complete API documentation with more examples, see [docs/API.md](./docs/API.md)**\n\n## Markdown Support\n\nThe chat widget automatically renders markdown in AI responses, supporting:\n\n- **Bold text** with `**text**` or `__text__`\n- *Italic text* with `*text*` or `_text_`\n- Lists (ordered and unordered)\n- `Inline code` with backticks\n- Code blocks with triple backticks\n- Links with `[text](url)`\n- Headings with `#`, `##`, `###`\n- Blockquotes with `>`\n\nYour AI responses can include markdown formatting and it will be rendered beautifully:\n\n```json\n{\n  \"message\": \"**Here's the pricing:**\\n\\n* Free: $0\\n* Standard: $200\\n* Premium: $350\\n\\nVisit [our website](https://example.com) for details.\"\n}\n```\n\nThis will display with proper formatting, bold text, bullet points, and clickable links.\n\n## Configuration\n\n### Full Configuration Example\n\n```tsx\n<AiChatWidget\n  // Required\n  apiEndpoint=\"https://your-api.com/chat\"\n  \n  // Position\n  position=\"bottom-right\" // 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left'\n  \n  // Branding\n  branding={{\n    name: \"Support Bot\",\n    companyName: \"Your Company\",\n    logoUrl: \"https://your-cdn.com/logo.png\",\n    tagline: \"We're here to help!\"\n  }}\n  \n  // Theme\n  theme={{\n    primaryColor: \"#3b82f6\",\n    headerBackground: \"#1e40af\",\n    headerTextColor: \"#ffffff\",\n    userBubbleColor: \"#3b82f6\",\n    botBubbleColor: \"#f3f4f6\",\n    userTextColor: \"#ffffff\",\n    botTextColor: \"#1f2937\",\n    borderRadius: \"0.75rem\"\n  }}\n  \n  // Features\n  features={{\n    enableImageUpload: true,\n    enableAudioUpload: true,\n    enableVideoUpload: true,\n    enableFileUpload: false,\n    enableTypingIndicator: true\n  }}\n  \n  // File Constraints\n  fileConstraints={{\n    maxFileSize: 10 * 1024 * 1024, // 10MB\n    maxImageSize: 5 * 1024 * 1024,  // 5MB\n    maxAudioSize: 10 * 1024 * 1024, // 10MB\n    maxVideoSize: 50 * 1024 * 1024, // 50MB\n    allowedImageTypes: ['image/jpeg', 'image/png', 'image/gif'],\n    allowedAudioTypes: ['audio/mpeg', 'audio/wav', 'audio/webm'],\n    allowedVideoTypes: ['video/mp4', 'video/webm']\n  }}\n  \n  // Session Management\n  sessionId=\"user-123\"\n  conversationId=\"conv-456\"\n  persistConversation={true}\n  \n  // API Configuration\n  headers={{\n    'Authorization': 'Bearer YOUR_TOKEN',\n    'X-Custom-Header': 'value'\n  }}\n  retryAttempts={3}\n  retryDelay={1000}\n  \n  // Callbacks\n  onMessageSent={(message) => console.log('Sent:', message)}\n  onMessageReceived={(message) => console.log('Received:', message)}\n  onError={(error) => console.error('Error:', error)}\n  onStatusChange={(status) => console.log('Status:', status)}\n/>\n```\n\n## Development\n\n### Build\n\n```bash\nnpm run build\n```\n\nOutputs to `dist/` with both ESM and UMD formats.\n\n### Testing\n\n```bash\n# Run tests once\nnpm test\n\n# Watch mode\nnpm run test:watch\n```\n\n### Dev Server\n\n```bash\nnpm run dev\n```\n\n## Project Structure\n\n```\nsrc/\n├── components/\n│   └── ChatBot.tsx          # Main React component\n├── hooks/\n│   └── useChat.ts           # Chat state management hook\n├── types/\n│   └── index.ts             # TypeScript type definitions\n├── __tests__/\n│   ├── ChatBot.test.tsx     # Component tests\n│   └── useChat.test.ts      # Hook tests\n└── index.ts                 # Library entry point\n```\n\n## Next Steps\n\n1. Install dependencies: `npm install`\n2. Run tests: `npm test`\n3. Build library: `npm run build`\n4. Use in your project or publish to npm\n\n## License\n\nISC\n\n\n## API Props Reference\n\n### AiChatWidget Props\n\n| Prop | Type | Required | Default | Description |\n|------|------|----------|---------|-------------|\n| `apiEndpoint` | string | Yes | - | Your backend API endpoint |\n| `apiBase` | string | No | - | EchoMind API base URL (e.g., http://localhost:3030/api) |\n| `projectId` | string | No | - | EchoMind project UUID |\n| `userId` | string | No | - | Unique identifier for end user (for chat history) |\n| `position` | string | No | 'bottom-right' | Widget position on screen |\n| `branding` | BrandingConfig | No | - | Branding customization |\n| `theme` | ChatWidgetTheme | No | - | Color and style customization |\n| `launcher` | LauncherConfig | No | - | Launcher button customization |\n| `features` | FeaturesConfig | No | - | Feature toggles |\n| `fileConstraints` | FileConstraints | No | - | File upload limits |\n| `sessionId` | string | No | - | User session identifier |\n| `conversationId` | string | No | auto-generated | Conversation identifier |\n| `persistConversation` | boolean | No | false | Save conversation to localStorage |\n| `headers` | object | No | - | Custom HTTP headers |\n| `retryAttempts` | number | No | 3 | Number of retry attempts |\n| `retryDelay` | number | No | 1000 | Initial retry delay (ms) |\n| `onMessageSent` | function | No | - | Callback when user sends message |\n| `onMessageReceived` | function | No | - | Callback when bot responds |\n| `onError` | function | No | - | Callback on error |\n| `onStatusChange` | function | No | - | Callback on status change |\n\n### useChat Hook\n\nFor advanced use cases, you can use the `useChat` hook directly:\n\n```tsx\nimport { useChat } from 'ai-chatbot'\n\nfunction CustomChat() {\n  const {\n    messages,\n    isLoading,\n    error,\n    conversationId,\n    sendMessage,\n    clearHistory,\n    stopGeneration\n  } = useChat({\n    apiEndpoint: 'https://your-api.com/chat'\n  })\n\n  return (\n    <div>\n      {messages.map(msg => (\n        <div key={msg.id}>{msg.content}</div>\n      ))}\n      <button onClick={() => sendMessage('Hello')}>\n        Send\n      </button>\n    </div>\n  )\n}\n```\n\n## TypeScript Support\n\nThe library is written in TypeScript with full type safety using enums:\n\n```tsx\nimport { \n  AiChatWidget,\n  MessageRole,\n  ChatStatus,\n  AttachmentType,\n  LauncherPosition\n} from 'ai-chatbot'\n\nimport type { \n  ChatMessage, \n  ChatWidgetConfig, \n  BrandingConfig, \n  ChatWidgetTheme,\n  FeaturesConfig,\n  FileConstraints,\n  ChatApiError\n} from 'ai-chatbot'\n\n// Use enums for type safety\nconst status: ChatStatus = ChatStatus.CONNECTED\nconst role: MessageRole = MessageRole.ASSISTANT\n```\n\n## Development\n\n### Build\n\n```bash\nnpm run build\n```\n\nOutputs to `dist/` with both ESM and UMD formats plus TypeScript declarations.\n\n### Testing\n\n```bash\n# Run tests once\nnpm test\n\n# Watch mode\nnpm run test:watch\n```\n\n### Dev Server\n\n```bash\nnpm run dev\n```\n\n## Architecture\n\nBuilt with a layered architecture for maintainability and scalability:\n\n```\nsrc/\n├── components/           # Presentation Layer\n│   ├── ChatHeader.tsx\n│   ├── ChatInput.tsx\n│   ├── ChatLauncher.tsx\n│   ├── ChatMessage.tsx\n│   ├── ChatMessages.tsx\n│   ├── ChatWindow.tsx\n│   ├── TypingIndicator.tsx\n│   └── index.tsx        # Main AiChatWidget component\n├── hooks/               # Business Logic Layer\n│   ├── useChat.ts       # State management with service integration\n│   └── useLocalStorage.ts\n├── services/            # Service Layer (NEW in v2.0)\n│   └── chatApi.service.ts  # API communication with retry logic\n├── utils/               # Utility Layer\n│   ├── config.validator.ts # Configuration validation (NEW)\n│   ├── logger.ts           # Structured logging (NEW)\n│   ├── fileValidation.ts\n│   └── sanitize.ts\n├── constants/           # Constants Layer (NEW in v2.0)\n│   └── index.ts         # All constants and defaults\n├── types/               # Type Layer\n│   └── index.ts         # TypeScript definitions with enums\n├── styles/\n│   └── defaultTheme.ts\n└── index.ts             # Library entry point\n```\n\nSee [ARCHITECTURE.md](./ARCHITECTURE.md) for detailed architecture documentation.\n\n## What's New in v2.0.0\n\n### Breaking Changes\n- Component renamed from `ChatBot` to `AiChatWidget`\n- String literals replaced with type-safe enums (`MessageRole`, `ChatStatus`, etc.)\n- New service layer architecture\n\n### New Features\n- ✅ Service layer for API communication\n- ✅ Configuration validation\n- ✅ Structured logging with `logger` utility\n- ✅ Typed errors with `ChatApiError`\n- ✅ Enhanced retry logic with exponential backoff\n- ✅ Better error handling throughout\n\n### Migration from v1.x\n```tsx\n// Before (v1.x)\nimport { ChatBot } from 'ai-chatbot'\n<ChatBot apiEndpoint=\"...\" />\n\n// After (v2.0)\nimport { AiChatWidget } from 'ai-chatbot'\n<AiChatWidget apiEndpoint=\"...\" />\n```\n\nSee [ARCHITECTURE.md](./ARCHITECTURE.md) for complete migration guide.\n\n## Documentation\n\n- 📖 [Architecture Guide](./ARCHITECTURE.md) - Detailed architecture and design patterns\n- 🔌 [API Documentation](./API.md) - Backend API integration guide\n- 💻 [Backend Examples](./BACKEND_EXAMPLES.md) - Ready-to-use backend implementations\n- 🚀 [Integration Guide](./INTEGRATION_GUIDE.md) - Step-by-step integration instructions\n\n## Browser Support\n\n- Chrome (latest)\n- Firefox (latest)\n- Safari (latest)\n- Edge (latest)\n\n## Contributing\n\nContributions are welcome! Please follow the architecture guidelines in [ARCHITECTURE.md](./ARCHITECTURE.md).\n\n## License\n\nISC\n\n## Support\n\nFor issues and questions, please open an issue on GitHub.\n","readmeFilename":"README.md"}