UNPKG

imagenai

Version:

Core client library for Imagenai image generation API

282 lines (206 loc) 7.52 kB
# @imagenai/core A powerful TypeScript client library for the Imagenai image generation API. Generate stunning AI images using OpenAI's GPT Image 1 model with enterprise-grade features like quota management, API key management, and alt tag processing. ## 🚀 Features - **AI Image Generation**: Generate high-quality images using OpenAI's GPT Image 1 model - **Flexible Options**: Support for custom sizes and quality levels - **Alt Tag Processing**: Automatically generate images from HTML alt attributes (Browser only) - **Universal Compatibility**: Works in Node.js, React, Next.js, and vanilla JavaScript - **Enterprise Ready**: Built-in retry logic, timeout handling, and error management - **TypeScript First**: Full TypeScript support with comprehensive type definitions ## 📦 Installation ```bash npm install @imagenai/core ``` ## 🌐 Compatibility | Environment | ImagenaiClient | Alt Tag Processor | Notes | |-------------|----------------|-------------------|-------| | **Node.js** | ✅ Full Support | ❌ Not Available | Server-side image generation | | **React** | ✅ Full Support | ✅ Full Support | Client-side with hooks | | **Next.js** | ✅ Full Support | ✅ Full Support | SSR + Client-side | | **Vanilla JS** | ✅ Full Support | ✅ Full Support | Browser environments | | **Deno** | ✅ Full Support | ❌ Not Available | Server-side only | ## 🔑 Quick Start ```typescript import { createImagenaiClient } from '@imagenai/core'; // Initialize the client const client = createImagenaiClient({ apiKey: 'your-api-key-here', baseUrl: 'https://your-domain.com' }); // Generate your first image const image = await client.generateImage({ prompt: 'A beautiful sunset over mountains, digital art style', size: '1024x1024', quality: 'high' }); console.log('Generated image URL:', image.url); ``` ## 🎯 Core Features ### Image Generation ```typescript // Basic image generation const image = await client.generateImage({ prompt: 'A cyberpunk city at night with neon lights', size: '1024x1024', quality: 'high' }); // Advanced options const advancedImage = await client.generateImage({ prompt: 'A logo for a tech company', size: '1024x1024', quality: 'high' }); ``` ### Alt Tag Processing Automatically generate images from HTML alt text using the `[IMAGENAI:...]` syntax: ```typescript import { ImagenaiAltTagProcessor } from '@imagenai/core'; // Create processor const processor = new ImagenaiAltTagProcessor(client, { autoProcess: true, // Process images automatically showLoading: true, // Show loading states onImageGenerated: (img, result) => { console.log('Generated:', result.prompt); } }); ``` **HTML Usage:** ```html <!-- Simple usage --> <img src="placeholder.jpg" alt="[IMAGENAI] A beautiful sunset over mountains" /> <!-- With custom parameters --> <img src="placeholder.jpg" alt="[IMAGENAI:size=1024x1536,quality=high] A portrait of a cat" /> <!-- With custom parameters --> <img src="placeholder.jpg" alt="[IMAGENAI:size=1024x1024,quality=high] A logo design" /> ``` ## ⚙️ Configuration Options ```typescript const client = createImagenaiClient({ apiKey: 'your-api-key', // Required: Your Imagenai API key baseUrl: 'https://api.example.com', // Optional: API base URL timeout: 30000, // Optional: Request timeout in ms (default: 30000) retries: 3 // Optional: Number of retry attempts (default: 3) }); ``` ## 🎨 Image Generation Options | Option | Type | Default | Description | |--------|------|---------|-------------| | `prompt` | `string` | Required | Text description of the image to generate | | `size` | `'1024x1024' \| '1024x1536' \| '1536x1024'` | `'1024x1024'` | Image dimensions | | `quality` | `'low' \| 'medium' \| 'high'` | `'medium'` | Rendering quality | ## 🔄 Alt Tag Processing The alt tag processor automatically generates images from HTML using the `[IMAGENAI:...]` syntax: ### **Basic Usage:** ```html <img src="placeholder.jpg" alt="[IMAGENAI] A beautiful sunset over mountains" /> ``` ### **Advanced Parameters:** ```html <img src="placeholder.jpg" alt="[IMAGENAI:size=1024x1536,quality=high,background=transparent] A logo design" /> ``` ### **JavaScript Integration:** ```typescript import { ImagenaiAltTagProcessor } from '@imagenai/core'; const processor = new ImagenaiAltTagProcessor(client, { autoProcess: true, // Process images automatically showLoading: true, // Show loading states onImageGenerated: (img, result) => { console.log('Generated:', result.prompt); }, onError: (img, error) => { console.error('Failed:', error.message); } }); // Manual processing await processor.processAltTags(); // Get statistics const stats = processor.getStats(); console.log(`Processed ${stats.totalProcessed} images`); ``` ### **Supported Parameters:** - `size`: `1024x1024`, `1024x1536`, `1536x1024` - `quality`: `low`, `medium`, `high` ## 🛡️ Error Handling The library provides comprehensive error handling: ```typescript try { const image = await client.generateImage({ prompt: 'A beautiful landscape' }); } catch (error) { if (error.message.includes('quota exceeded')) { console.log('Upgrade your subscription for more images'); } else if (error.message.includes('invalid prompt')) { console.log('Please provide a valid prompt'); } else { console.log('An error occurred:', error.message); } } ``` ## 📊 Response Types ### GeneratedImage ```typescript interface GeneratedImage { id: string; // Unique image identifier url: string; // CDN URL for the generated image prompt: string; // The prompt used to generate the image size: string; // Image dimensions cached: boolean; // Whether the image was served from cache createdAt: string; // ISO timestamp of creation usage?: { // Usage information (if available) remaining: number; // Remaining images in quota limit: number; // Total quota limit tier: string; // Subscription tier }; } ``` ### UsageInfo ```typescript interface UsageInfo { remaining: number; // Images remaining in current period limit: number; // Total monthly limit tier: string; // Subscription tier (free, basic, pro, etc.) status: string; // Subscription status (active, inactive, etc.) } ``` ## 🚀 Advanced Usage ### Custom Retry Logic ```typescript const client = createImagenaiClient({ apiKey: 'your-key', retries: 5, timeout: 60000 }); ``` ## 🔧 Development ### Building the Package ```bash npm run build ``` ### Running Tests ```bash npm test ``` ### Linting ```bash npm run lint ``` ## 📝 Examples See the `examples/` directory for comprehensive usage examples: - `alt-tag-usage.ts` - Alt tag processing examples ## 🤝 Contributing 1. Fork the repository 2. Create a feature branch 3. Make your changes 4. Add tests if applicable 5. Submit a pull request ## 📄 License MIT License - see LICENSE file for details ## 🆘 Support - **Documentation**: [https://docs.imagenai.com](https://docs.imagenai.com) - **Issues**: [GitHub Issues](https://github.com/yourusername/imagenai/issues) - **Discord**: [Join our community](https://discord.gg/imagenai) ## 🔗 Related Packages - `@imagenai/react` - React components for image generation - `@imagenai/node` - Node.js utilities and CLI tools - `@imagenai/web` - Web components and vanilla JS utilities