# @shopkit/asset-cache Architecture

## Overview

The `@shopkit/asset-cache` package provides a comprehensive browser-side asset caching solution with service worker integration, intelligent caching strategies, and Next.js components. This document outlines the architecture, data flow, and component interactions.

## High-Level Architecture

```mermaid
graph TB
    subgraph Browser["Browser Environment"]
        A[Next.js Application] --> B[Asset Cache Components]
        B --> C[AssetLoader]
        C --> D[CacheManager]
        C --> E[VersionManager]
        C --> F[Service Worker]
        
        D --> G[Cache Storage API]
        D --> H[IndexedDB]
        F --> I[Network Cache]
        
        J[Caching Strategies] --> C
        K[Cache Helpers] --> C
        L[Hash Generator] --> C
    end
    
    subgraph External["External Services"]
        M[CDN/Server] --> F
        M --> C
    end
    
    classDef appLayer fill:#4CAF50,stroke:#2E7D32,stroke-width:2px,color:#fff
    classDef cacheLayer fill:#2196F3,stroke:#1565C0,stroke-width:2px,color:#fff
    classDef storageLayer fill:#FF9800,stroke:#E65100,stroke-width:2px,color:#fff
    classDef serviceLayer fill:#9C27B0,stroke:#6A1B9A,stroke-width:2px,color:#fff
    classDef externalLayer fill:#607D8B,stroke:#37474F,stroke-width:2px,color:#fff
    
    class A appLayer
    class B,C,D,E cacheLayer
    class G,H,I storageLayer
    class F serviceLayer
    class M externalLayer
```

## Core Components

### 1. AssetLoader (Core Engine)

The central orchestrator for all asset caching operations.

```mermaid
graph LR
    A[AssetLoader] --> B["preload()"]
    A --> C["load()"]
    A --> D["isCached()"]
    A --> E["invalidate()"]
    A --> F["invalidateByTag()"]
    
    B --> G[CacheManager]
    C --> G
    D --> G
    E --> G
    F --> G
    
    B --> H[Service Worker]
    C --> H
    E --> H
    F --> H
    
    classDef coreClass fill:#FFB74D,stroke:#F57C00,stroke-width:2px,color:#fff
    classDef managerClass fill:#4CAF50,stroke:#2E7D32,stroke-width:2px,color:#fff
    classDef workerClass fill:#9C27B0,stroke:#6A1B9A,stroke-width:2px,color:#fff
    
    class A coreClass
    class G managerClass
    class H workerClass
```

**Responsibilities:**
- Asset loading with cache-first strategy
- Preloading and background revalidation
- Cache invalidation by URL or tags
- Service worker communication
- Content-based versioning

### 2. CacheManager (Storage Layer)

Manages cache storage, metadata, and manifest operations.

```mermaid
graph TB
    A[CacheManager] --> B[Cache Storage API]
    A --> C[IndexedDB Manifest]
    
    subgraph Operations["Cache Operations"]
        D["addToManifest()"]
        E["getAssetMetadata()"]
        F["removeFromManifest()"]
        G["getAssetsByTag()"]
    end
    
    A --> D
    A --> E
    A --> F
    A --> G
    
    B --> H[Cached Responses]
    C --> I[Asset Metadata]
    
    classDef managerClass fill:#4CAF50,stroke:#2E7D32,stroke-width:2px,color:#fff
    classDef storageClass fill:#2196F3,stroke:#1565C0,stroke-width:2px,color:#fff
    classDef dataClass fill:#FF9800,stroke:#E65100,stroke-width:2px,color:#fff
    
    class A managerClass
    class B,H storageClass
    class C,I dataClass
```

**Responsibilities:**
- Cache manifest management
- Asset metadata storage and retrieval
- Tag-based asset organization
- Storage quota monitoring

### 3. VersionManager (Invalidation Control)

Handles asset versioning and cache invalidation strategies.

```mermaid
graph LR
    A[VersionManager] --> B["createVersionedUrl()"]
    A --> C["hasVersion()"]
    A --> D["extractVersion()"]
    
    B --> E[Content Hash]
    B --> F[Deployment ID]
    B --> G[Query Parameters]
    
    classDef managerClass fill:#FF5722,stroke:#D84315,stroke-width:2px,color:#fff
    classDef versionClass fill:#795548,stroke:#5D4037,stroke-width:2px,color:#fff
    
    class A managerClass
    class E,F,G versionClass
```

**Responsibilities:**
- URL versioning with content hashes
- Deployment-based invalidation
- Version extraction and validation

### 4. Service Worker Integration

Provides offline support and background caching capabilities.

```mermaid
graph TB
    A[Main Thread] --> B[Service Worker Messages]
    B --> C[Service Worker]
    
    subgraph Operations["Service Worker Operations"]
        D[CACHE_ASSET]
        E[INVALIDATE_ASSET]
        F[INVALIDATE_TAG]
        G[CHECK_ASSET]
        H[UPDATE_MANIFEST]
    end
    
    C --> D
    C --> E
    C --> F
    C --> G
    C --> H
    
    C --> I[Network Cache]
    C --> J[Background Sync]
    
    classDef threadClass fill:#E3F2FD,stroke:#1976D2,stroke-width:2px,color:#000
    classDef workerClass fill:#9C27B0,stroke:#6A1B9A,stroke-width:2px,color:#fff
    classDef cacheClass fill:#4CAF50,stroke:#2E7D32,stroke-width:2px,color:#fff
    classDef syncClass fill:#FF9800,stroke:#E65100,stroke-width:2px,color:#fff
    
    class A,B threadClass
    class C workerClass
    class I cacheClass
    class J syncClass
```

**Message Types:**
- `CACHE_ASSET`: Cache a specific asset
- `INVALIDATE_ASSET`: Remove asset from cache
- `INVALIDATE_TAG`: Remove assets by tag
- `CHECK_ASSET`: Check if asset is cached
- `UPDATE_MANIFEST`: Update cache manifest

## Caching Strategies

### 1. Cache-First Strategy

```mermaid
sequenceDiagram
    participant App as Application
    participant AC as AssetLoader
    participant Cache as Cache Storage
    participant Network as Network
    
    App->>AC: load(url)
    AC->>Cache: check cache
    
    alt Asset in cache and not expired
        Cache-->>AC: return cached asset
        AC-->>App: return from cache
    else Asset not in cache or expired
        AC->>Network: fetch(url)
        Network-->>AC: return asset
        AC->>Cache: store asset
        AC-->>App: return from network
    end
```

### 2. Network-First Strategy

```mermaid
sequenceDiagram
    participant App as Application
    participant AC as AssetLoader
    participant Network as Network
    participant Cache as Cache Storage
    
    App->>AC: load(url)
    AC->>Network: fetch(url)
    
    alt Network success
        Network-->>AC: return asset
        AC->>Cache: store asset
        AC-->>App: return from network
    else Network failure
        AC->>Cache: check cache
        Cache-->>AC: return cached asset
        AC-->>App: return from cache
    end
```

### 3. Stale-While-Revalidate Strategy

```mermaid
sequenceDiagram
    participant App as Application
    participant AC as AssetLoader
    participant Cache as Cache Storage
    participant Network as Network
    
    App->>AC: load(url, {revalidate: true})
    AC->>Cache: check cache
    
    alt Asset in cache
        Cache-->>AC: return cached asset
        AC-->>App: return from cache
        
        Note over AC,Network: Background revalidation
        AC->>Network: fetch(url)
        Network-->>AC: return fresh asset
        AC->>Cache: update cache
    else Asset not in cache
        AC->>Network: fetch(url)
        Network-->>AC: return asset
        AC->>Cache: store asset
        AC-->>App: return from network
    end
```

## Data Flow

### Asset Loading Flow

```mermaid
graph TD
    A[Request Asset] --> B{Check Cache}
    B -->|Hit| C[Check Expiration]
    B -->|Miss| D[Fetch from Network]
    
    C -->|Valid| E[Return Cached Asset]
    C -->|Expired| F[Remove from Cache]
    F --> D
    
    D --> G{Network Success?}
    G -->|Yes| H[Process Response]
    G -->|No| I[Return Error]
    
    H --> J{Should Cache?}
    J -->|Yes| K[Generate Content Hash]
    J -->|No| L[Return Asset]
    
    K --> M[Create Cache Entry]
    M --> N[Store in Cache]
    N --> O[Update Manifest]
    O --> P[Notify Service Worker]
    P --> L
    
    E --> Q{Revalidate?}
    Q -->|Yes| R[Background Revalidation]
    Q -->|No| S[End]
    
    R --> T[Fetch Latest]
    T --> U[Compare Versions]
    U -->|Different| V[Update Cache]
    U -->|Same| S
    V --> S
    
    classDef startClass fill:#2196F3,stroke:#1565C0,stroke-width:2px,color:#fff
    classDef successClass fill:#4CAF50,stroke:#2E7D32,stroke-width:2px,color:#fff
    classDef errorClass fill:#F44336,stroke:#C62828,stroke-width:2px,color:#fff
    classDef processClass fill:#FF9800,stroke:#E65100,stroke-width:2px,color:#fff
    classDef endClass fill:#9E9E9E,stroke:#616161,stroke-width:2px,color:#fff
    
    class A startClass
    class E,L,V successClass
    class I errorClass
    class H,K,M,N,O,P,R,T,U processClass
    class S endClass
```

### Cache Invalidation Flow

```mermaid
graph TD
    A[Invalidation Request] --> B{By URL or Tag?}
    
    B -->|URL| C[Find Asset in Manifest]
    B -->|Tag| D[Find Assets by Tag]
    
    C --> E[Remove from Cache Storage]
    D --> F[Remove Multiple Assets]
    
    E --> G[Update Manifest]
    F --> G
    
    G --> H[Notify Service Worker]
    H --> I[Background Cleanup]
    I --> J[End]
    
    classDef requestClass fill:#FF9800,stroke:#E65100,stroke-width:2px,color:#fff
    classDef findClass fill:#2196F3,stroke:#1565C0,stroke-width:2px,color:#fff
    classDef removeClass fill:#F44336,stroke:#C62828,stroke-width:2px,color:#fff
    classDef updateClass fill:#4CAF50,stroke:#2E7D32,stroke-width:2px,color:#fff
    classDef cleanupClass fill:#9C27B0,stroke:#6A1B9A,stroke-width:2px,color:#fff
    classDef endClass fill:#9E9E9E,stroke:#616161,stroke-width:2px,color:#fff
    
    class A requestClass
    class C,D findClass
    class E,F removeClass
    class G updateClass
    class H,I cleanupClass
    class J endClass
```

## Next.js Integration Architecture

```mermaid
graph TB
    subgraph NextJS["Next.js Application"]
        A[App Layout] --> B[AssetCacheInitializer]
        C[Page Components] --> D[BaseCachedImage]
        C --> E[BaseCachedVideo]
        
        D --> F[useBaseCachedImage]
        E --> G[useBaseCachedVideo]
        
        H[Preload Hook] --> I[useBasePreloadAssets]
    end
    
    subgraph Core["Asset Cache Core"]
        B --> J[initAssetCache]
        F --> K[AssetLoader]
        G --> K
        I --> K
        
        J --> L[Service Worker Registration]
        J --> M[Cache Initialization]
    end
    
    classDef appClass fill:#4CAF50,stroke:#2E7D32,stroke-width:2px,color:#fff
    classDef initClass fill:#FF9800,stroke:#E65100,stroke-width:2px,color:#fff
    classDef componentClass fill:#2196F3,stroke:#1565C0,stroke-width:2px,color:#fff
    classDef coreClass fill:#FFB74D,stroke:#F57C00,stroke-width:2px,color:#fff
    
    class A appClass
    class B initClass
    class D,E,F,G,I componentClass
    class K coreClass
```

## Storage Architecture

### Cache Storage Structure

```
Cache Storage
├── asset-cache-v1/
│   ├── /images/product-1.jpg?v=abc123
│   ├── /images/product-2.jpg?v=def456
│   ├── /videos/demo.mp4?v=ghi789
│   └── /fonts/custom.woff2?v=jkl012
```

### IndexedDB Manifest Structure

```typescript
interface CacheManifest {
  version: string;
  generatedAt: string;
  assets: {
    [url: string]: {
      type: AssetType;
      version: string;
      lastModified: string;
      size?: number;
      tags?: string[];
    }
  }
}
```

## Performance Optimizations

### 1. Lazy Loading Integration

```mermaid
graph LR
    A[Intersection Observer] --> B[Asset Enters Viewport]
    B --> C[Check Cache Status]
    C -->|Cached| D[Load Immediately]
    C -->|Not Cached| E[Preload Asset]
    E --> F[Show Placeholder]
    F --> G[Asset Ready]
    G --> D
    
    classDef observerClass fill:#4CAF50,stroke:#2E7D32,stroke-width:2px,color:#fff
    classDef loadClass fill:#2196F3,stroke:#1565C0,stroke-width:2px,color:#fff
    classDef preloadClass fill:#FF9800,stroke:#E65100,stroke-width:2px,color:#fff
    
    class A observerClass
    class D loadClass
    class E preloadClass
```

### 2. Priority-Based Loading

```mermaid
graph TD
    A[Asset Requests] --> B{Priority Level}
    
    B -->|High| C[Immediate Processing]
    B -->|Medium| D[Queue for Processing]
    B -->|Low| E[Background Processing]
    
    C --> F[Network Request]
    D --> G[Wait for High Priority]
    E --> H[Idle Time Processing]
    
    G --> F
    H --> F
    
    classDef requestClass fill:#2196F3,stroke:#1565C0,stroke-width:2px,color:#fff
    classDef highClass fill:#4CAF50,stroke:#2E7D32,stroke-width:2px,color:#fff
    classDef mediumClass fill:#FF9800,stroke:#E65100,stroke-width:2px,color:#fff
    classDef lowClass fill:#9C27B0,stroke:#6A1B9A,stroke-width:2px,color:#fff
    classDef networkClass fill:#607D8B,stroke:#37474F,stroke-width:2px,color:#fff
    
    class A requestClass
    class C highClass
    class D mediumClass
    class E lowClass
    class F,G,H networkClass
```

### 3. Memory Management

```mermaid
graph TB
    A[Cache Size Monitor] --> B{Storage Quota}
    
    B -->|< 80%| C[Continue Caching]
    B -->|80-95%| D[Selective Caching]
    B -->|> 95%| E[Cleanup Old Assets]
    
    D --> F[Cache High Priority Only]
    E --> G[LRU Eviction]
    G --> H[Update Manifest]
    
    classDef monitorClass fill:#2196F3,stroke:#1565C0,stroke-width:2px,color:#fff
    classDef okClass fill:#4CAF50,stroke:#2E7D32,stroke-width:2px,color:#fff
    classDef warningClass fill:#FF9800,stroke:#E65100,stroke-width:2px,color:#fff
    classDef criticalClass fill:#F44336,stroke:#C62828,stroke-width:2px,color:#fff
    
    class A monitorClass
    class C okClass
    class D,F warningClass
    class E,G,H criticalClass
```

## Error Handling

### Network Failure Recovery

```mermaid
graph TD
    A[Network Request Fails] --> B{Cache Available?}
    
    B -->|Yes| C[Serve from Cache]
    B -->|No| D[Return Error]
    
    C --> E[Mark for Retry]
    E --> F[Background Retry]
    F --> G{Retry Success?}
    
    G -->|Yes| H[Update Cache]
    G -->|No| I[Exponential Backoff]
    I --> J[Schedule Next Retry]
    
    classDef errorClass fill:#F44336,stroke:#C62828,stroke-width:2px,color:#fff
    classDef fallbackClass fill:#FF9800,stroke:#E65100,stroke-width:2px,color:#fff
    classDef successClass fill:#4CAF50,stroke:#2E7D32,stroke-width:2px,color:#fff
    classDef retryClass fill:#9C27B0,stroke:#6A1B9A,stroke-width:2px,color:#fff
    
    class A,D errorClass
    class C fallbackClass
    class H successClass
    class E,F,G,I,J retryClass
```

## Security Considerations

### Content Validation

```mermaid
graph LR
    A[Asset Response] --> B[Content-Type Check]
    B --> C[Size Validation]
    C --> D[Hash Verification]
    D --> E[Security Headers]
    E --> F[Store in Cache]
    
    B -->|Invalid| G[Reject]
    C -->|Too Large| G
    D -->|Mismatch| G
    E -->|Missing| G
    
    classDef responseClass fill:#2196F3,stroke:#1565C0,stroke-width:2px,color:#fff
    classDef validationClass fill:#FF9800,stroke:#E65100,stroke-width:2px,color:#fff
    classDef successClass fill:#4CAF50,stroke:#2E7D32,stroke-width:2px,color:#fff
    classDef rejectClass fill:#F44336,stroke:#C62828,stroke-width:2px,color:#fff
    
    class A responseClass
    class B,C,D,E validationClass
    class F successClass
    class G rejectClass
```

## Monitoring and Analytics

### Cache Performance Metrics

```mermaid
graph TB
    A[Cache Operations] --> B[Hit Rate Tracking]
    A --> C[Load Time Metrics]
    A --> D[Storage Usage]
    A --> E[Error Rates]
    
    B --> F[Performance Dashboard]
    C --> F
    D --> F
    E --> F
    
    F --> G[Optimization Insights]
    
    classDef operationsClass fill:#2196F3,stroke:#1565C0,stroke-width:2px,color:#fff
    classDef metricsClass fill:#FF9800,stroke:#E65100,stroke-width:2px,color:#fff
    classDef dashboardClass fill:#4CAF50,stroke:#2E7D32,stroke-width:2px,color:#fff
    classDef insightsClass fill:#9C27B0,stroke:#6A1B9A,stroke-width:2px,color:#fff
    
    class A operationsClass
    class B,C,D,E metricsClass
    class F dashboardClass
    class G insightsClass
```

## Deployment Considerations

### Cache Invalidation Strategy

```mermaid
graph TD
    A[New Deployment] --> B[Generate Deployment ID]
    B --> C[Update Service Worker]
    C --> D[Broadcast to Clients]
    D --> E[Client Receives Update]
    E --> F[Invalidate Old Cache]
    F --> G[Preload Critical Assets]
    G --> H[Ready for Traffic]
    
    classDef deploymentClass fill:#2196F3,stroke:#1565C0,stroke-width:2px,color:#fff
    classDef updateClass fill:#FF9800,stroke:#E65100,stroke-width:2px,color:#fff
    classDef invalidateClass fill:#F44336,stroke:#C62828,stroke-width:2px,color:#fff
    classDef readyClass fill:#4CAF50,stroke:#2E7D32,stroke-width:2px,color:#fff
    
    class A deploymentClass
    class B,C,D,E updateClass
    class F invalidateClass
    class G,H readyClass
```

This architecture provides a robust, scalable, and performant asset caching solution that integrates seamlessly with modern web applications while maintaining excellent developer experience and end-user performance.
