UNPKG

@toast-studios/asset-manager

Version:

A React Native asset management library with intelligent caching and loading strategies

366 lines (365 loc) 10.2 kB
/// <reference types="node" /> /// <reference types="node" /> /** * Asset types supported by the manager */ export declare enum AssetType { LOTTIE = "lottie", IMAGE = "image", VIDEO = "video" } /** * Asset quality levels for prioritization */ export declare enum AssetQuality { MEDIUM = "720p", HIGH = "1080p" } /** * Download priorities */ export declare enum DownloadPriority { CRITICAL = 0, HIGH = 1, MEDIUM = 2, LOW = 3, BACKGROUND = 4 } /** * Network connection types */ export declare enum NetworkType { WIFI = "wifi", CELLULAR = "cellular", ETHERNET = "ethernet", UNKNOWN = "unknown" } /** * Download strategies */ export declare enum DownloadStrategy { DEFAULT = "default", NETWORK_AWARE = "network-aware", DEVICE_AWARE = "device-aware", HYBRID = "hybrid", BANDWIDTH_OPTIMIZED = "bandwidth-optimized" } /** * Strategy configuration for hybrid/composite strategies */ export interface StrategyConfig { /** Primary strategy to use */ primary: DownloadStrategy; /** Secondary strategy to combine with primary (for hybrid mode) */ secondary?: DownloadStrategy; /** Strategy-specific configurations */ networkAware?: { enableMeteredDownloads?: boolean; lowEndDeviceSizeThreshold?: number; maxConcurrentDownloads?: { low: number; medium: number; high: number; }; }; deviceAware?: { enableBatteryAwareness?: boolean; enableThermalManagement?: boolean; enableMemoryManagement?: boolean; batteryThreshold?: number; memoryThreshold?: number; }; /** Weight for primary strategy when combining (0-1, default 0.7) */ primaryWeight?: number; } /** * Individual asset definition */ export interface Asset { /** Unique identifier for the asset */ id: string; /** Asset type (lottie, image, video) */ type: AssetType; /** Asset quality level */ quality: AssetQuality; /** Download priority */ priority: DownloadPriority; /** ETag for cache validation */ etag: string; /** Download URL */ url: string; /** Sub-path where asset should be stored */ key: string; /** File size in bytes */ size: number; /** Is this asset required for game launch? */ isDefault: boolean; /** Expected file hash for integrity validation */ hash?: string; /** Additional metadata */ metadata?: Record<string, any>; } /** * Asset bundle/zip definition */ export interface AssetBundle { /** Bundle identifier */ id: string; /** Bundle version */ version: string; /** Bundle ETag */ etag: string; /** Download URL for the zip */ url: string; /** List of assets contained in this bundle */ assets: Asset[]; /** Bundle size in bytes */ size: number; /** Is this bundle critical for game launch? */ isCritical: boolean; /** Bundle hash for integrity validation */ hash?: string; } /** * Complete asset manifest */ export interface AssetManifest { /** Manifest version */ version: string; /** List of asset bundles */ bundles: AssetBundle[]; /** Default assets required for game launch */ defaultAssets: string[]; /** Manifest metadata */ metadata?: { totalSize: number; bundleCount: number; assetCount: number; [key: string]: any; }; } /** * Network conditions */ export interface NetworkConditions { /** Connection type */ type: NetworkType; /** Is connected to internet */ isConnected: boolean; /** Connection speed in Mbps */ speed?: number; /** Network ping in milliseconds */ ping?: number; /** Is connection metered */ isMetered?: boolean; } /** * Download progress information */ export interface DownloadProgress { /** Asset or bundle ID */ id: string; /** Download type */ type: 'asset' | 'bundle'; /** Progress percentage (0-100) */ progress: number; /** Downloaded bytes */ downloadedBytes: number; /** Total bytes */ totalBytes: number; /** Download speed in bytes/sec */ speed: number; /** Estimated time remaining in seconds */ eta?: number; /** Current status */ status: DownloadStatus; /** Error message if failed */ error?: string; } /** * Download status */ export declare enum DownloadStatus { PENDING = "pending", DOWNLOADING = "downloading", EXTRACTING = "extracting", COMPLETED = "completed", FAILED = "failed", CANCELLED = "cancelled", PAUSED = "paused" } /** * Asset manager configuration */ export interface AssetManagerConfig { /** Base path for asset storage */ basePath: string; /** Download strategy configuration */ strategy: DownloadStrategy | StrategyConfig; /** Maximum concurrent downloads (can be overridden by strategy) */ maxConcurrentDownloads: number; /** Enable automatic network condition detection */ enableNetworkDetection: boolean; /** Network ping timeout in milliseconds */ pingTimeout: number; /** Ping target URLs for network latency measurement */ pingTargets?: string[]; /** Retry attempts for failed downloads */ retryAttempts: number; /** Retry delay in milliseconds */ retryDelay: number; /** Enable integrity validation */ enableIntegrityCheck: boolean; /** Auto-cleanup old assets */ enableAutoCleanup: boolean; /** App version for manifest fetching */ appVersion?: string; /** Manifest URL for dynamic loading */ manifestUrl?: string; /** App language for localized manifest */ appLanguage?: string; /** Cache size limit in bytes */ cacheLimit?: number; /** Custom headers for downloads */ customHeaders?: Record<string, string>; /** Enable logging */ enableLogging: boolean; } /** * Asset download queue item */ export interface QueueItem { /** Bundle to download */ bundle: AssetBundle; /** Priority level */ priority: DownloadPriority; /** Retry count */ retryCount: number; /** Added to queue timestamp */ queuedAt: number; /** Download started timestamp */ startedAt?: number; /** Download completed timestamp */ completedAt?: number; } /** * Memory statistics */ export interface MemoryStats { /** Total memory used by asset manager */ totalMemory: number; /** Memory used by downloads */ downloadMemory: number; /** Memory used by extracted assets */ assetMemory: number; /** Memory used by cache */ cacheMemory: number; /** Number of active downloads */ activeDownloads: number; /** Queue size */ queueSize: number; } /** * Asset validation result */ export interface ValidationResult { /** Is asset valid */ isValid: boolean; /** Validation error message */ error?: string; /** Asset size */ size?: number; /** Asset hash */ hash?: string; } /** * Storage information and statistics */ export interface StorageInfo { /** Total number of assets managed */ totalAssets: number; /** Number of unique files stored (after deduplication) */ uniqueFiles: number; /** Original total size if no deduplication was used */ totalOriginalSize: number; /** Actual storage space used after deduplication */ actualStorageUsed: number; /** Space saved through deduplication */ spaceSaved: number; /** Deduplication ratio as percentage */ deduplicationRatio: number; } /** * Event types for asset manager */ export declare enum AssetManagerEvent { DOWNLOAD_STARTED = "download_started", DOWNLOAD_PROGRESS = "download_progress", DOWNLOAD_COMPLETED = "download_completed", DOWNLOAD_FAILED = "download_failed", EXTRACTION_STARTED = "extraction_started", EXTRACTION_COMPLETED = "extraction_completed", EXTRACTION_FAILED = "extraction_failed", GAME_READY = "game_ready", MANIFEST_LOADED = "manifest_loaded", MANIFEST_FAILED = "manifest_failed", NETWORK_CHANGED = "network_changed", STORAGE_WARNING = "storage_warning", CLEANUP_COMPLETED = "cleanup_completed" } /** * Event listener callback type */ export type EventCallback<T = any> = (data: T) => void; /** * Download strategy interface */ export interface IDownloadStrategy { /** Strategy name */ name: string; /** Determine optimal asset quality based on network conditions */ getOptimalQuality(conditions: NetworkConditions): AssetQuality; /** Sort bundles by download priority */ prioritizeBundles(bundles: AssetBundle[], conditions: NetworkConditions): AssetBundle[]; /** Determine if download should proceed based on conditions */ shouldDownload(bundle: AssetBundle, conditions: NetworkConditions): boolean; /** Get maximum concurrent downloads for current conditions */ getMaxConcurrentDownloads(conditions: NetworkConditions): number; } /** * Network monitor interface */ export interface INetworkMonitor { /** Get current network conditions */ getCurrentConditions(): Promise<NetworkConditions>; /** Start monitoring network changes */ startMonitoring(callback: (conditions: NetworkConditions) => void): void; /** Stop monitoring */ stopMonitoring(): void; /** Measure network ping */ measurePing(): Promise<number>; /** Cleanup resources */ destroy?(): void; } /** * Storage manager interface */ export interface IStorageManager { /** Get storage information */ getStorageInfo(): Promise<StorageInfo>; /** Check if asset exists locally */ assetExists(assetPath: string, etag?: string): Promise<boolean>; /** Save asset to storage */ saveAsset(data: Buffer, path: string): Promise<void>; /** Delete asset from storage */ deleteAsset(path: string): Promise<void>; /** Cleanup old/unused assets */ cleanup(options?: { maxAge?: number; maxSize?: number; }): Promise<number>; /** Validate asset integrity */ validateAsset(path: string, expectedHash?: string): Promise<ValidationResult>; /** Cleanup resources */ destroy?(): void; }