# @toast-studios/asset-manager

A powerful React Native asset management library with intelligent caching, network-aware downloading, and dynamic manifest loading.

## 🚀 Features

- **Dynamic Manifest Loading** - Fetch manifests from URLs with app versioning and localization
- **Network-Aware Downloads** - Intelligent downloading based on network conditions
- **Smart Caching** - Automatic cache management (default 500MB)
- **High-Performance Batching** - 90%+ reduction in I/O operations through intelligent batching
- **Asset Validation** - SHA-256 hash verification
- **Auto Cleanup** - Automatic cleanup of old assets
- **TypeScript Support** - Full type definitions included
- **Production Ready** - Battle-tested in production

## 📦 Installation

```bash
npm install @toast-studios/asset-manager react-native-fs @react-native-community/netinfo react-native-device-info @react-native-async-storage/async-storage
```

## 🔧 Quick Start

```typescript
import { ToastAssetManager } from '@toast-studios/asset-manager';

const assetManager = new ToastAssetManager({
  basePath: '/assets',
  manifestUrl: 'https://api.yourapp.com/manifest',
  appVersion: '1.2.3',
  appLanguage: 'en'
});

// Single method does everything: initialize + load manifest + start downloads
await assetManager.start();

// Get asset path
const assetPath = await assetManager.getAsset('my-video.mp4');
```

## 📖 Configuration

```typescript
interface AssetManagerConfig {
  basePath: string;
  appVersion?: string;           // For manifest fetching
  manifestUrl?: string;          // Dynamic manifest URL
  appLanguage?: string;          // Localization
  maxConcurrentDownloads?: number; // Default: 3
  retryAttempts?: number;        // Default: 3
  retryDelay?: number;           // Default: 1000ms
  cacheLimit?: number;           // Default: 500MB
  customHeaders?: Record<string, string>;
  enableLogging?: boolean;       // Default: false
}
```

## 🌐 Dynamic Manifest Loading

```typescript
// Configuration generates: GET https://api.yourapp.com/manifest?appVersion=1.2.3&language=en
const assetManager = new ToastAssetManager({
  basePath: '/assets',
  manifestUrl: 'https://api.yourapp.com/manifest',
  appVersion: '1.2.3',
  appLanguage: 'en'
});
```

**Manifest Format:**
```json
{
  "version": "1.0.0",
  "bundles": [{
    "id": "essential-assets",
    "url": "https://cdn.yourapp.com/assets/essential.zip",
    "size": 1024000,
    "isCritical": true,
    "hash": "sha256-abc123...",
    "assets": [{
      "id": "logo.png",
      "filename": "logo.png",
      "type": "image",
      "size": 5000,
      "hash": "sha256-def456..."
    }]
  }]
}
```

## 📱 React Native Example

```typescript
import React, { useState, useEffect } from 'react';
import { ToastAssetManager } from '@toast-studios/asset-manager';

const AssetComponent = () => {
  const [progress, setProgress] = useState(0);
  const [assetManager, setAssetManager] = useState(null);

  useEffect(() => {
    const manager = new ToastAssetManager({
      basePath: '/assets',
      manifestUrl: 'https://api.yourapp.com/manifest',
      appVersion: '1.0.0'
    });

    manager.onProgress((progress) => setProgress(progress.progress));
    
    // Single call to start everything
    manager.start().then(() => setAssetManager(manager));
  }, []);

  return (
    <View>
      <Text>Progress: {progress}%</Text>
    </View>
  );
};
```

## 🔧 Production Configurations

**Enterprise:**
```typescript
new ToastAssetManager({
  basePath: '/assets',
  manifestUrl: 'https://cdn.yourapp.com/manifest',
  appVersion: '2.1.0',
  cacheLimit: 1024 * 1024 * 1024, // 1GB
  retryAttempts: 5,
  customHeaders: { 'Authorization': 'Bearer token' }
});
```

**High-Performance:**
```typescript
new ToastAssetManager({
  basePath: '/assets',
  manifestUrl: 'https://api.yourapp.com/manifest',
  maxConcurrentDownloads: 5,
  cacheLimit: 2048 * 1024 * 1024, // 2GB
  retryDelay: 500
});
```

## 🛠 Key Methods

```typescript
// Main method - does everything in one call
await assetManager.start();              // Initialize + load manifest + start downloads
await assetManager.start(manifest);     // Or pass manifest directly

// Asset access
const path = await assetManager.getAsset('id'); // Get asset path
const asset = assetManager.getAsset('id');      // Get asset object

// Utility methods
const count = await assetManager.cleanup();     // Manual cleanup
await assetManager.destroy();                   // Clean up resources

// Progress monitoring
assetManager.onProgress((progress) => {
  console.log(`${progress.progress}% - ${progress.status}`);
});

// Performance optimization methods
await assetManager.flushStorage();           // Force immediate save to disk
const stats = assetManager.getStorageBatchingStats(); // Monitor batching performance
```

## ⚡ Performance Optimization

The asset manager uses intelligent **batching** to dramatically reduce disk I/O operations:

**Before (v1.1):** Every asset save = 2 disk writes  
**After (v1.2):** Multiple saves batched into 2 disk writes within 1-second windows

**Performance Impact:**
- **10 assets:** 90% fewer I/O operations
- **100 assets:** 99% fewer I/O operations  
- **1000 assets:** 99.9% fewer I/O operations

```typescript
// Automatic batching (default behavior)
await assetManager.start(); // All downloads are automatically batched

// Manual control for critical operations
await assetManager.flushStorage(); // Force immediate save before app shutdown

// Monitor batching performance
const stats = assetManager.getStorageBatchingStats();
console.log(`Pending updates: ${stats.pendingAssetUpdates}`);
console.log(`Batching active: ${stats.hasPendingTimer}`);
```

## 🔒 Enterprise Features

- **CDN Integration** - Optimized for global content delivery
- **Multi-language Support** - Localization through language parameters  
- **Version Management** - App version-based manifest fetching
- **HTTPS Security** - Secure downloads with hash verification
- **Memory Management** - Intelligent cache limits
- **Background Processing** - Non-blocking operations

## 📄 License

**Commercial License** - © Toast Studios

## 🤝 Support

**Technical Support:** Implementation assistance and documentation  
**Enterprise Services:** Priority support, custom features, training  
**Contact:** Toast Studios team for licensing and support

---

**Powered by Toast Studios** 