JSPM

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

Client library for Imagenai image generation API with comprehensive loading state support and usage tracking

Package Exports

  • imagenai
  • imagenai/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (imagenai) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

imagenai

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 comprehensive loading state support.

🚀 Features

  • AI Image Generation: Generate high-quality images using OpenAI's GPT Image 1 model
  • Flexible Options: Support for custom sizes (1024x1024, 1024x1536, 1536x1024) and quality levels (low, medium, high)
  • 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
  • Usage Tracking: Built-in usage monitoring and subscription status checking
  • Loading State Support: Comprehensive examples for proper loading state management

📦 Installation

npm install imagenai

🌐 Compatibility

Environment ImagenaiClient Notes
Node.js ✅ Full Support Server-side image generation
React ✅ Full Support Client-side with hooks
Next.js ✅ Full Support SSR + Client-side
Vanilla JS ✅ Full Support Browser environments
Deno ✅ Full Support Server-side only

🔑 Quick Start

import { createImagenaiClient } from 'imagenai';

// Initialize the client
const client = createImagenaiClient({
  apiKey: 'your-api-key-here'
});

// 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);
console.log('Remaining quota:', image.usage?.remaining);

🎯 Core Features

Image Generation

// 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: '1024x1536',  // Portrait orientation
  quality: 'medium'    // Balance of quality and speed
});

Usage Monitoring

// Check your current usage and subscription status
const usage = await client.getUsage();

console.log(`Images generated: ${usage.imagesGenerated}`);
console.log(`Images remaining: ${usage.imagesRemaining}`);
console.log(`Monthly limit: ${usage.subscriptionLimit}`);
console.log(`Can generate: ${usage.canGenerate}`);

⚙️ Configuration Options

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

🛡️ Error Handling

The library provides comprehensive error handling with detailed information:

try {
  const image = await client.generateImage({
    prompt: 'A beautiful landscape'
  });
} catch (error: any) {
  if (error.details?.status === 'active' && error.details?.current >= error.details?.limit) {
    console.log('Quota exceeded - 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);
    console.log('Error details:', error.details);
  }
}

📊 Response Types

GeneratedImage

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
  quality: string;      // Image quality level
  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

interface UsageInfo {
  imagesGenerated: number;    // Images generated in current period
  imagesRemaining: number;    // Images remaining in current period
  subscriptionTier: string;   // Subscription tier (free, basic, pro, etc.)
  subscriptionStatus: string; // Subscription status (active, inactive, etc.)
  subscriptionLimit: number;  // Total monthly limit
  canGenerate: boolean;       // Whether user can generate images
  isLimitExceeded: boolean;   // Whether monthly limit is exceeded
  resetDate: string;          // When usage resets (ISO timestamp)
  subscriptionPrice: number;  // Monthly subscription price
  pricePerImage: number;      // Price per individual image
}

🎨 Loading State Best Practices

AI image generation takes time (usually 10-30 seconds). Here's how to provide the best user experience:

React Example with Loading States

import React, { useState } from 'react';
import { createImagenaiClient } from 'imagenai';

export function ImageGenerator() {
  const [imageUrl, setImageUrl] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');

  const generateImage = async (prompt: string) => {
    setIsLoading(true);
    setError('');
    
    try {
      const client = createImagenaiClient({ apiKey: 'your-api-key' });
      const result = await client.generateImage({ prompt });
      setImageUrl(result.url);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div>
      {/* Loading State */}
      {isLoading && (
        <div className="loading-container">
          <div className="spinner"></div>
          <p>Generating your image...</p>
          <p>This usually takes 10-30 seconds</p>
        </div>
      )}

      {/* Error State */}
      {error && (
        <div className="error-container">
          <p>{error}</p>
          <button onClick={() => generateImage('A beautiful landscape')}>
            Retry
          </button>
        </div>
      )}

      {/* Generated Image */}
      {imageUrl && !isLoading && (
        <img src={imageUrl} alt="Generated image" />
      )}
    </div>
  );
}

Vanilla JavaScript Example

<!DOCTYPE html>
<html>
<head>
    <title>Imagenai Demo</title>
    <style>
        .loading { display: none; }
        .spinner { /* Add your spinner styles */ }
    </style>
</head>
<body>
    <div id="loading" class="loading">
        <div class="spinner"></div>
        <p>Creating your image...</p>
        <p>Usually takes 10-30 seconds</p>
    </div>
    
    <div id="result"></div>

    <script type="module">
        import { createImagenaiClient } from 'https://esm.sh/imagenai';
        
        async function generateImage() {
            document.getElementById('loading').style.display = 'block';
            document.getElementById('result').innerHTML = '';
            
            try {
                const client = createImagenaiClient({
                    apiKey: 'your-api-key-here'
                });
                
                const result = await client.generateImage({
                    prompt: 'A cyberpunk city at night'
                });
                
                document.getElementById('loading').style.display = 'none';
                document.getElementById('result').innerHTML = 
                    `<img src="${result.url}" alt="Generated image" />`;
                    
            } catch (error) {
                document.getElementById('loading').style.display = 'none';
                document.getElementById('result').innerHTML = 
                    `<p>Error: ${error.message}</p>`;
            }
        }
        
        generateImage();
    </script>
</body>
</html>

🚀 Advanced Usage

Custom Retry Logic

const client = createImagenaiClient({
  apiKey: 'your-key',
  retries: 5,
  timeout: 60000
});

Multiple Image Generation

const prompts = [
  'A cyberpunk city at night',
  'A peaceful forest scene',
  'A futuristic robot'
];

const results = [];
for (const prompt of prompts) {
  try {
    const result = await client.generateImage({ prompt });
    results.push({ prompt, success: true, result });
  } catch (error: any) {
    results.push({ prompt, success: false, error: error.message });
  }
}

console.log(`Generated ${results.filter(r => r.success).length}/${prompts.length} images`);

🔧 Development

Building the Package

npm run build

Running Tests

npm test

Linting

npm run lint

📝 Examples

See the examples/ directory for comprehensive usage examples:

  • basic-usage.ts - Complete image generation examples with error handling

🤝 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

  • @imagenai/react - React components for image generation
  • @imagenai/node - Node.js utilities and CLI tools
  • @imagenai/web - Web components and vanilla JS utilities