<!-- markdownlint-disable MD013 MD060 -->

# HTTP Request Manager - Angular Library

[![TypeScript](https://img.shields.io/badge/TypeScript-007ACC?style=flat&logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
[![Angular](https://img.shields.io/badge/Angular-DD0031?style=flat&logo=angular&logoColor=white)](https://angular.io/)
[![RxJS](https://img.shields.io/badge/RxJS-B7178C?style=flat&logo=reactivex&logoColor=white)](https://rxjs.dev/)

> **Supported Angular:** 22.x (Angular 22 is the supported baseline. The library also retains the observable/NgRx track for older Angular 14-18 consumers and the signal track for Angular 19+ consumers, but the peer range and the toolchain target Angular 22.)

A comprehensive Angular library providing enterprise-grade HTTP request management, state management, real-time communication, and local data persistence.

This README is the main documentation hub for the library. Detailed service guides live in `src/docs/`, and this page links to the observable/ngrx services for older Angular applications and the signal-based services for newer Angular applications in parallel.

## 🚀 Features

### Core Capabilities

| Feature | Description | Angular 14-18 / Observable + NgRx | Angular 19+ / Signals |
|---------|-------------|----------------------------------|------------------------|
| **🌐 HTTP Request Management** | Retry, polling, streaming, file downloads | [`HTTPManagerService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/HTTP_MANAGER_README.md) | [`HTTPManagerSignalsService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/HTTP_SIGNALS_MANAGER_README.md) |
| **🔄 State Management** | CRUD state, persistence, derived state | [`HTTPManagerStateService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/HTTP_STATE_MANAGER_README.md) and [`StoreStateManagerService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/STORE_STATE_MANAGER_README.md) | [`StoreStateManagerSignalsService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/STORE_STATE_SIGNALS_README.md) |
| **💬 Real-Time Communication** | WebSocket channels, tracking, messaging | [`WebSocketManagerService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/WS_MANAGER_README.md), [`WebSocketMessageService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/WEBSOCKET_MESSAGE_SERVICE.md), and [`MessageTrackerService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/MESSAGE_TRACKER_README.md) | [`WebSocketSignalsManagerService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/WEBSOCKET_SIGNALS_README.md) and [`MessageTrackerSignalsService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/MESSAGE_TRACKER_SIGNALS_README.md) |
| **💾 Data Persistence** | Local/session storage and offline caching | [`LocalStorageManagerService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/LOCAL_STORAGE_README.md) and [`DatabaseManagerService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/DATABASE_README.md) | [`LocalStorageSignalsManagerService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/LOCAL_STORAGE_SIGNALS_README.md) |
| **🗄️ Database Queries** | MySQL-syntax SQL queries on IndexedDB — the recommended way to query data | [`DexieSqlService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/SQL_DIXIE_README.md) | Uses the same service |
| **⚡ Utility Functions** | JSON handling, encryption, headers, validation, logging | [`UtilsService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/UTILS_SERVICES_README.md), [`Encryption`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/ENCRYPTION_README.md), [`Logger`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/LOGGER_README.md) | Uses the same utility layer |
| **🔧 Utility Services** | Headers, path/query, merging, base request classes | [`Utility Services`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/UTILS_SERVICES_README.md) | Internal and helper services |
| **🖥️ Node.js WS Server** | Companion [`ws-request-manager`](https://www.npmjs.com/package/ws-request-manager) Node.js package — pluggable auth, IP rate limiting, channels, heartbeat, message replay | [`WebSocket Server Guide`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/WS_SERVER_README.md) | Same protocol on both sides |

### Key Benefits

- ✅ **Type-Safe** - Full TypeScript support with generics
- ✅ **Offline-First** - Built-in IndexedDB caching
- ✅ **Real-Time Ready** - Seamless WebSocket integration with companion Node.js server
- ✅ **Secure** - AES & RSA encryption support for sensitive data
- ✅ **Scalable** - ComponentStore-based architecture
- ✅ **Flexible** - Works with Observables or Signals
- ✅ **Pluggable Auth on Server** - You control auth (API key, JWT, cookie, BFF session) and rate limits on the Node.js side

### 🖥️ Server-Side Companion — `ws-request-manager`

The frontend `http-request-manager` speaks the full WebSocket protocol implemented by the Node.js package [`ws-request-manager`](https://www.npmjs.com/package/ws-request-manager). The server package is **deliberately thin** — it does **not** implement any auth strategy. Instead, you provide a `WsAuthFn` (an async function) and the library calls it on every WebSocket upgrade.

**Quick start:**

```javascript
// server.js
const express = require('express');
const http = require('http');
const { register, registerServer, destroy, noAuth } = require('ws-request-manager');

const app = express();
app.use(express.json());

async function start() {
  await register(app, noAuth);              // mounts /ws/channels, /ws/connections, /ws/broadcast
  const server = http.createServer(app);
  await registerServer(server, noAuth);      // attaches WS upgrade handler at /ws
  server.listen(3000);
  process.on('SIGTERM', async () => { await destroy(); server.close(); });
}
start();
```

Swap `noAuth` for a custom `WsAuthFn` to gate access. Common patterns:

- `createApiKeyAuth(process.env.STATIC_API_KEY)` — static API key
- `createJwtAuth(process.env.JWT_SECRET_KEY)` — JWT (re-use your HTTP API's secret)
- `createCookieAuth(validateSession)` — BFF session cookie
- `createRateLimitedAuth(authFn, { maxFailures: 10, blockDurationMs: 300_000 })` — IP-based rate limiting wrapper

👉 **Full guide:** [`WS_SERVER_README.md`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/WS_SERVER_README.md) — covers configuration (env vars), auth patterns, rate limiting, full message protocol reference, HTTP REST routes, and the end-to-end BFF setup.

Note on clearing persisted data:

- **Clear full DB (fire-and-forget)**: To wipe the entire IndexedDB for this library and its associated localStorage metadata, call `DatabaseManagerService.clearDatabase()`. This method subscribes internally and is intentionally fire-and-forget — callers should simply call `databaseManager.clearDatabase()` (no `.subscribe()` required). The method also clears related localStorage metadata via `LocalStorageManagerService`.
- **Clear a specific table (Observable)**: To remove records from a specific table, use `DatabaseManagerService.clearTableRecords(tableName)` which returns an `Observable<void>`; callers should `.subscribe()` or use RxJS operators to react to completion.

### �️ Database Access

The library provides two complementary services for working with IndexedDB data:

| Task | Service | Example |
|------|---------|---------|
| **Query data** (recommended) | `DexieSqlService` | `sql.query('SELECT * FROM orders WHERE status = "open"')` |
| **Create tables** | `DatabaseManagerService` | `db.createDatabaseTable(tableDef)` |
| **Insert / update records** | `DatabaseManagerService` | `db.createTableRecord('orders', record)` |
| **Delete records** | `DatabaseManagerService` | `db.deleteTableRecord('orders', id)` |
| **Clear / reset database** | `DatabaseManagerService` | `db.clearDatabase()` |

Use `DexieSqlService` for all read queries — it supports SELECT with WHERE, JOIN, ORDER BY, LIMIT, COUNT, DISTINCT, and more. Use `DatabaseManagerService` for table creation and write operations.

See the full SQL syntax reference: [`DexieSqlService Guide`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/SQL_DIXIE_README.md)

### �🚀 Advanced Features

| Feature | Description | Learn More |
|---------|-------------|------------|
| **🔐 Enterprise Encryption** | AES symmetric + RSA asymmetric encryption | [`Encryption Utils`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/ENCRYPTION_README.md) |
| **🗄️ Database Queries** | MySQL-syntax SQL queries on IndexedDB — the recommended way to query data (SELECT, WHERE, JOIN, ORDER BY, LIMIT, COUNT, DISTINCT) | [`DexieSqlService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/SQL_DIXIE_README.md) |
| **📡 Streaming Support** | NDJSON & Server-Sent Events (SSE) | [`HTTP Manager`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/HTTP_MANAGER_README.md#streaming) |
| **📄 File Downloads** | Progress tracking for large files | [`HTTP Manager`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/HTTP_MANAGER_README.md#file-downloads) |
| **📤 File Uploads** | Multi-file upload with progress, validation, and form-data config | [`Upload Request`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/UPLOAD_REQUEST_README.md) |
| **📊 Pagination** | Built-in pagination with page tracking | [`HTTP State Manager`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/HTTP_STATE_MANAGER_README.md#pagination) |
| **🔔 Smart Notifications** | Persistent notifications with DB storage | [`WebSocket Guide`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/ADVANCED_WEBSOCKET.md#notifications) |
| **👥 Presence Tracking** | Real-time user presence by channel | [`WebSocket Guide`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/ADVANCED_WEBSOCKET.md#presence) |
| **🔄 Message Replay** | Automatic message history on reconnect | [`WebSocket Guide`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/ADVANCED_WEBSOCKET.md#message-replay) and [`Message Tracker`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/MESSAGE_TRACKER_README.md) |
| **🏷️ Channel Architecture** | SYS-, PUB-, MES- channel prefixes | [`WebSocket Guide`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/ADVANCED_WEBSOCKET.md#channels) |
| **🔌 Singleton WebSocket** | Single connection across ALL instances | [`WebSocket Guide`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/ADVANCED_WEBSOCKET.md#singleton) |
| **✨ Unified Message Service** | Type-safe WebSocket messaging with auto prefixes | [`WebSocket Message Service`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/WEBSOCKET_MESSAGE_SERVICE.md) |
| **🖥️ Node.js WS Server** | Companion `ws-request-manager` package for Node.js — pluggable auth, rate limiting, channels, heartbeat | [`WebSocket Server Guide`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/WS_SERVER_README.md) ([npm](https://www.npmjs.com/package/ws-request-manager)) |
| **🚀 Batch Requests** | Execute multiple HTTP requests with sequential/parallel modes | [`Batch Request Guide`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/BATCH_REQUEST_README.md) |
| **📝 Message Tracking** | Guaranteed delivery with gap detection | [`Message Tracker`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/MESSAGE_TRACKER_README.md) |
| **🔍 Debug Logging** | Context-aware logging with dev/prod modes | [`Logger Service`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/LOGGER_README.md) |

## 📋 Table of Contents

- [Quick Start](#-quick-start)
- [Configuration](#️-configuration)
- [Services Overview](#-services-overview)
- [Documentation Paths](#-documentation-paths)
- [Architecture](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/ARCHITECTURE.md)
- [Interceptors](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/INTERCEPTOR_README.md)
- [Advanced Features](#-advanced-features)
- [Batch Requests](#batch-requests)
- [Detailed Documentation](#-detailed-documentation)
- [Demo Examples](#-demo-examples)
- [Migration Guide](#-migration-guide)

## 🚀 Quick Start

### Installation & Setup (2 minutes)

#### 1. Import Module

```typescript
// app.module.ts
import { HttpRequestManagerModule } from 'http-request-manager';

@NgModule({
  imports: [
    HttpRequestManagerModule.forRoot({
      httpRequestOptions: {
        server: 'http://localhost:8080',  // Your API base URL
        retry: { times: 3, delay: 2 },
        displayError: true
      }
    })
  ]
})
export class AppModule { }
```

#### 2. Provide APP_ID (if using encryption)

```typescript
// app.module.ts
import { APP_ID } from '@angular/core';

@NgModule({
  providers: [
    { provide: APP_ID, useValue: "your-unique-guid-here" }
  ]
})
export class AppModule { }
```

### Simple Examples

#### Basic HTTP Request

```typescript
import { Component, inject } from '@angular/core';
import { HTTPManagerService, ApiRequest } from 'http-request-manager';

@Component({
  selector: 'app-users',
  template: `
    <div *ngIf="isLoading$ | async">Loading...</div>
    <div *ngIf="error$ | async as error" class="error">
      Error: {{ error.message }}
    </div>
    <div *ngFor="let user of data$ | async">
      {{ user.name }}
    </div>
  `
})
export class UsersComponent {
  httpManager = inject(HTTPManagerService);
  
  data$ = this.httpManager.data$;
  isLoading$ = this.httpManager.isPending$;
  error$ = this.httpManager.error$;

  ngOnInit() {
    this.httpManager.getRequest(
      ApiRequest.adapt({ path: ['users'], displaySuccess: true, successMessage: 'Loaded users!' })
    ).subscribe();
  }
}
```

#### State Management with CRUD

```typescript
@Injectable({ providedIn: 'root' })
export class UsersStore extends HTTPManagerStateService<User> {
  
  constructor() {
    super(
      ApiRequest.adapt({
        server: 'http://localhost:8080',
        path: ['users']
      }),
      DataType.ARRAY
    );
  }

  // Public API
  loadUsers() { this.fetchRecords(); }
  addUser(user: User) { this.createRecord(user); }
  updateUser(user: User) { this.updateRecord(user); }
  deleteUser(id: number) { this.deleteRecord(id); }
}

// Component
@Component({
  selector: 'app-users',
  template: `
    <button (click)="store.loadUsers()">Load</button>
    <div *ngFor="let user of store.data$ | async">
      {{ user.name }}
      <button (click)="store.deleteUser(user.id)">Delete</button>
    </div>
  `
})
export class UsersComponent {
  store = inject(UsersStore);
}
```

### Request Tracking Options (Database Mode)

`HTTPManagerStateService` supports request tracking options for `fetchRecords` and `fetchStream` when database caching is configured (`DatabaseStorage` provided in the service constructor).

```typescript
service.fetchRecords(RequestOptions.adapt({
  path: ['ai/pagination?page=0&size=25'],
  ignoreQueryParams: ['page', 'size'],
  queryParamsExpiresIn: '10s'
}));
```

Supported request options:

- `ignoreQueryParams`: Query keys to track for request-change behavior.
- `queryParamsExpiresIn`: Expiry window for tracked values (examples: `10s`, `5mn`, `1h`).

Behavior notes:

- Database enabled (`DatabaseStorage` configured): tracker is active, repeated identical query values are blocked until expiry, then can call API again.
- Database disabled: tracker is bypassed; requests call the API directly each time.
- `forceRefresh: true` always forces an API call.

### Delta Sync (Incremental Fetch)

When `deltaSync: true` is set on `DatabaseStorage`, the store performs a **delta fetch on every call** — both the initial call and every subsequent call (after a `savedAt` cursor exists), including after a page refresh. The backend returns only records created or modified at or after the provided `X-Modified-Since: <epoch>` timestamp; the store merges them into the existing DB via upsert (IndexedDB `bulkPut`) and re-reads the merged table into state.

Both `fetchRecords` and `fetchStream` honor `deltaSync`. Each maintains its **own `savedAt` cursor** under `requestCache.GET.savedAt` and `requestCache.STREAM.savedAt` respectively; a stream delta fetch advances the STREAM cursor only and leaves the GET cursor untouched (and vice versa).

**Gating flow:**

The same gates apply to both `fetchRecords` (reads `requestCache.GET.savedAt`) and `fetchStream` (reads `requestCache.STREAM.savedAt`). Under `deltaSync` the **`savedAt` cursor owns freshness** — the TTL (`expiresIn`) never clears the table or cursor; an expired cursor still runs `deltaFetch` with `X-Modified-Since` rather than clearing.

| GATE | Condition | Behavior |
|------|-----------|----------|
| **GATE 1** (initial fetch) | `!hasInitialFetch && deltaSync=true` | If DB table missing → `initDBStorageAsync` + full fetch. Else if `savedAt` exists → `deltaFetch(savedAt, ...)` (sends `X-Modified-Since` header) — **no TTL clear**. Else → full fetch (writes fresh `savedAt`). Sets `hasInitialFetch=true` on completion. |
| **GATE 3a** (TTL expiry) | `hasExpired=true && deltaSync=false` | `clearRequestCacheMetadata(table)` → clears `savedAt` from localStorage. `clearSessionFlag()` + `hasInitialFetch=false`. `clearTable` + full fetch (resets DB + writes new `savedAt`). **Skipped when `deltaSync=true`** — the `savedAt` cursor owns freshness and the TTL never clears. |
| **GATE 3b** (schema mismatch) | Stored schema ≠ current adapter schema | Same as GATE 3a but also calls `createDatabaseTable` to recreate with new schema before full fetch. |
| **GATE 4** (subsequent fetch) | `hasInitialFetch=true && deltaSync=true` | **Delta fetch on every call** — `savedAt` exists → `deltaFetch(savedAt, ...)` (sends `X-Modified-Since`, merges into the existing DB). Table missing → `initDBStorageAsync` + full fetch. |
| **GATE 5** (deltaSync=false) | `deltaSync=false` | Tracker + DB cache flow (unchanged, no delta). |
| **forceRefresh** | `options.forceRefresh=true` | Full fetch bypasses delta and serve-from-DB paths entirely. |
| **WS push** | `fetchRecord(UPDATE/CREATE/DELETE)` | After successful DB write, `saveRequestCacheMetadata` advances the GET `savedAt` (CRUD paths) so the next delta fetch uses the latest cursor. |

**Requirements:**

- `DatabaseStorage` must be configured with a valid `table` name (database storage enabled).
- `deltaSync: true` must be set on the `DatabaseStorage` config.
- `expiresIn` does NOT trigger periodic full re-syncs when `deltaSync: true` — the `savedAt` cursor owns freshness, so the TTL never clears the table or cursor regardless of the `expiresIn` value. Use `expiresIn: '0'` for explicit "never expire" semantics. Set a non-zero `expiresIn` only for `deltaSync: false` stores to get periodic full re-fetches (corrects soft-delete drift).

```typescript
// Delta sync — never clears (TTL ignored), delta on every call
const service = new HTTPManagerStateService(
  ApiRequest.adapt({ server: 'https://api.example.com', path: ['api', 'items'] }),
  DataType.ARRAY,
  DatabaseStorage.adapt({ table: 'items', expiresIn: '0', deltaSync: true })
);

// Delta sync with a non-zero expiresIn — TTL is still ignored (cursor owns freshness)
const service2 = new HTTPManagerStateService(
  ApiRequest.adapt({ server: 'https://api.example.com', path: ['api', 'items'] }),
  DataType.ARRAY,
  DatabaseStorage.adapt({ table: 'items', expiresIn: '1d', deltaSync: true })
);
```

**How it works:**

1. **First call with no `savedAt`** (GATE 1, initial fetch): full fetch, DB populated via `createTableRecords`, `savedAt` written to localStorage as `Date.now()`, `hasInitialFetch` set to `true`.
2. **First call with `savedAt`** (GATE 1, subsequent session/page reload with valid cursor): `deltaFetch(savedAt, ...)` runs — sends `X-Modified-Since: floor(savedAt / 1000)` header.
   - **Records returned**: upserted to IndexedDB via `bulkPut`, merged into state via `mergeDeltaData$`, `savedAt` advanced.
   - **Empty response `[]`**: state/DB unchanged, `savedAt` advanced to current time.
   - **Error**: state/DB unchanged, `savedAt` NOT advanced — next call retries from the same timestamp; serves from DB.
3. **Subsequent calls with `hasInitialFetch=true`** (GATE 4): **delta fetch on every call** — `savedAt` exists → `deltaFetch(savedAt, ...)` re-checks the server and merges the delta into the existing DB.
   - **Records returned**: upserted to IndexedDB via `bulkPut`, merged set re-read and reflected in state, `savedAt` advanced.
   - **Empty response `[]`**: state and DB unchanged, `savedAt` advanced — the next call keeps delting.
4. **TTL expiry** (GATE 3a): applies only when `deltaSync=false`. With `deltaSync=true` the `savedAt` cursor owns freshness — an expired TTL does NOT clear the table or cursor (even for a non-zero `expiresIn`); delta fetch continues.
5. **Schema mismatch** (GATE 3b): same flow as TTL expiry but also calls `createDatabaseTable` to recreate the table with the current adapter's schema before `fetchFromAPI`.
6. **`forceRefresh: true`**: full fetch bypasses delta and serve-from-DB entirely (checks the flag inside the `hasInitialFetch=true` block, before GATE 4).
7. **WebSocket pushes** (`fetchRecord(UPDATE/CREATE/DELETE)`): after each successful IndexedDB write (`updateTableRecord`, `createTableRecord`, `createTableRecords` bulkPut, `deleteTableRecord`), `saveRequestCacheMetadata` advances `savedAt`. When `hasDatabase` is false (no DB configured), `saveRequestCacheMetadata` is NOT called.

### `fetchStream` delta sync

`fetchStream` mirrors the `fetchRecords` delta flow using the STREAM cursor:
1. **Init call, `deltaSync=false`**: full `fetchStreamFromAPI` (existing tracker/DB-cache flow unchanged).
2. **Init call, `deltaSync=true`, no `STREAM.savedAt`**: `fetchStreamFromAPI` full stream — populates DB and writes `requestCache.STREAM.savedAt`.
3. **Init call, `deltaSync=true`, `STREAM.savedAt` set, not expired**: `deltaFetch(streamSavedAt, ..., 'STREAM')` — sends `X-Modified-Since: floor(streamSavedAt / 1000)`, sets `requestOptions.stream=true`, upserts response via `createTableRecords` (bulkPut), calls `saveRequestCacheMetadata(tableName, 'STREAM', ...)`.
4. **Init call, `deltaSync=true`, `STREAM.savedAt` set (any TTL, including expired)**: `deltaFetch(streamSavedAt, ..., 'STREAM')` — the TTL never clears under `deltaSync`.
5. **Non-init call, `deltaSync=true`, `hasInitialFetch=true`**: `deltaFetch(..., 'STREAM')` on every call — sends `X-Modified-Since`, merges into the existing DB. An empty full-stream still persists the STREAM cursor.

**Deletion contract (Option a — WS-driven deletes):** The delta stream response contains **upserts only** — deletes are NOT conveyed in the delta payload. Use `fetchRecord(DELETE)` (or `deleteRecord$`) to remove records via WebSocket; `deleteTableRecord` advances `savedAt` so the next stream delta fetch's cursor is correct. Because the TTL never clears under `deltaSync`, soft-delete drift is NOT auto-corrected by a periodic full re-sync — deletes must flow through the WebSocket path.

**localStorage updates on DB write:**

When data is pushed to IndexedDB (full fetch, delta fetch, or WS push), the localStorage store for the table is updated with:
- `expires`: refreshed to `utils.expires(expiresIn)` — under `deltaSync` the store's own expiry is disabled (`options.expires = 0`), so it never purges the store/cursor.
- `requestCache.GET.savedAt`: set to `Date.now()` — the cursor for the next delta request's `X-Modified-Since` header.

**`DatabaseStorage` properties:**

| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `table` | `string` | `''` | IndexedDB table name (required for delta sync) |
| `expiresIn` | `string` | `''` | TTL for full re-sync (only honored when `deltaSync=false`). Use `'0'` for explicit never-expire semantics. Examples: `'1m'`, `'1h'`, `'1d'` |
| `deltaSync` | `boolean` | `false` | Enable incremental fetch with `X-Modified-Since` header |

**Notes:**

- `X-Modified-Since` is added to `volatileHeaders` so it's excluded from request signatures and cache metadata.
- With `deltaSync: true`, the TTL never expires the store — delta sync runs on every call. `expiresIn: '0'` additionally pins the store's own expiry to never.
- The `savedAt` timestamp (used as the `X-Modified-Since` value) is the last time data was successfully written to the DB — it represents the last DB sync time, not the last API call time.
- **`savedAt` is cleared alongside the DB on schema mismatch and `clearRecords`** (via `clearRequestCacheMetadata`), then rewritten by the next full `fetchFromAPI`. Under `deltaSync` it is NOT cleared by TTL expiry. Every call — initial, subsequent, and after a page reload — reads the surviving `savedAt` cursor and sends `X-Modified-Since`, so a refresh keeps delting instead of full-fetching. WS pushes advance `savedAt` so the next delta uses the latest cursor.
- **Empty-response recovery**: an empty delta against an empty DB falls back to a full fetch (both GET and STREAM), so a stale cursor can never leave the store permanently empty. An empty GET full fetch does **not** persist a `savedAt` cursor, so the next call cleanly full-fetches; STREAM keeps its existing empty-stream cursor behavior (recovery is handled by the delta fallback).
- Fully backwards compatible — existing consumers see no behavior change unless `deltaSync: true` is set.

## ⚙️ Configuration

### Module Initialization (`forRoot`)

Configure the library globally using the `forRoot` method:

```typescript
import { HttpRequestManagerModule } from 'http-request-manager';

@NgModule({
  imports: [
    HttpRequestManagerModule.forRoot({
      httpRequestOptions: {
        server: 'https://api.example.com',
        headers: { 'Authorization': 'Bearer token' },
        retry: { times: 3, delay: 2 },
        displayError: true
      },
      LocalStorageOptions: {
        storageName: 'my-app-data',
        storageSettingsName: 'my-app-settings',
        options: {
          encrypted: true,
          expiresIn: '7d'
        }
      }
    })
  ]
})
export class AppModule { }
```

### Configuration Options

#### HTTP Options (`ConfigHTTPOptions`)

| Option | Type | Description | Default |
|--------|------|-------------|---------|
| `server` | `string` | Base URL for API requests | `''` |
| `path` | `any[]` | Default path segments | `[]` |
| `headers` | `any` | Default headers | `{}` |
| `polling` | `number` | Default polling interval (seconds) | `0` |
| `retry` | `RetryOptions` | Default retry configuration | `{ times: 0, delay: 3 }` |
| `stream` | `boolean` | Enable streaming by default | `false` |
| `displayError` | `boolean` | Show toast errors by default | `false` |
| `displaySuccess` | `boolean` | Show toast on success by default | `false` |
| `successMessage` | `string` | Custom success toast message (optional) | `undefined` |
| `errorMessage` | `string` | Custom error toast message (optional, overrides default) | `undefined` |
| `suppressToastStatuses` | `number[]` | Suppress error toast for these status codes (requires `displayError: true`) | `[]` |

#### Local Storage Options (`LocalStorageOptions`)

| Option | Type | Description | Default |
|--------|------|-------------|---------|
| `storageName` | `string` | Key for storing data | `'storage'` |
| `storageSettingsName` | `string` | Key for settings metadata | `'global-storage'` |
| `options` | `SettingOptions` | Default storage settings | `{ storage: StorageType.GLOBAL, expires: 0, expiresIn: '', encrypted: false }` |

#### Retry Options (`RetryOptions`)

| Option | Type | Description | Default |
|--------|------|-------------|---------|
| `times` | `number` | Number of retry attempts | `0` |
| `delay` | `number` | Delay between retries (seconds) | `3` |

#### WebSocket Options (`WSOptions`)

| Option | Type | Description | Default |
|--------|------|-------------|---------|
| `id` | `string` | Channel identifier (used to construct channel names) | `''` |
| `wsServer` | `string` | WebSocket server URL | `''` |
| `jwtToken` | `string` | JWT token for authentication | `''` |
| `permissions` | `string[]` | Permission levels for the connection | `[]` |
| `channels` | `string[]` | Additional channels to subscribe to | `[]` |
| `user` | `any` | User information for presence tracking | `undefined` |
| `retry` | `RetryOptions` | Retry configuration for reconnection | `{ times: 0, delay: 3 }` |

### Injection Tokens

| Token | Type | Purpose | Required |
|-------|------|---------|----------|
| `CONFIG_SETTINGS_TOKEN` | `ConfigOptions` | Global library configuration (provided by `forRoot()`) | Yes (via `forRoot()`) |
| `APP_ID` | `string` | Unique application ID for encryption key generation | Yes (if using encryption) |

### Providing APP_ID

If using encryption features (localStorage encryption, AES/RSA encryption), you must provide a unique `APP_ID`:

```typescript
import { APP_ID } from '@angular/core';

@NgModule({
  providers: [
    { provide: APP_ID, useValue: 'your-unique-app-guid-here' }
  ]
})
export class AppModule { }
```

> **Important:** The `APP_ID` is used as the encryption key for `SymmetricalEncryptionService`. Use a strong, unique value per application.

## 📚 Services Overview

### Angular 14-18: Observable + NgRx Services

| Service | Description | Use Case |
|---------|-------------|----------|
| [`HTTPManagerService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/HTTP_MANAGER_README.md) | Observable-based HTTP client with retry, polling, streaming | Simple API calls with loading states |
| [`HTTPManagerStateService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/HTTP_STATE_MANAGER_README.md) | ComponentStore + HTTP + WebSocket + IndexedDB | CRUD with auto state sync and real-time updates |
| [`StoreStateManagerService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/STORE_STATE_MANAGER_README.md) | Persistent ComponentStore with localStorage sync | Application state persistence |
| [`WebSocketManagerService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/WS_MANAGER_README.md) | Singleton WebSocket connection manager | Real-time messaging and notifications |
| [`WebSocketMessageService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/WEBSOCKET_MESSAGE_SERVICE.md) | Unified type-safe message sending service | Simplified WebSocket messaging with auto prefixes |
| [`MessageTrackerService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/MESSAGE_TRACKER_README.md) | Guaranteed message delivery with gap detection | Message tracking and reconnection sync |
| [`LocalStorageManagerService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/LOCAL_STORAGE_README.md) | Secure local/session storage with encryption | User preferences and session data |
| [`DatabaseManagerService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/DATABASE_README.md) | IndexedDB wrapper via Dexie.js | Offline-first data access |

### Angular 19+: Signal-Based Services

| Service | Description | Use Case |
|---------|-------------|----------|
| [`HTTPManagerSignalsService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/HTTP_SIGNALS_MANAGER_README.md) | Signal-based HTTP client for modern reactive UI | Modern Angular with Signals |
| [`LocalStorageSignalsManagerService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/LOCAL_STORAGE_SIGNALS_README.md) | Signal-based local/session storage | Reactive persisted UI state |
| [`StoreStateManagerSignalsService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/STORE_STATE_SIGNALS_README.md) | Signal-based persistent state service | App state persistence with computed derivations |
| [`WebSocketSignalsManagerService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/WEBSOCKET_SIGNALS_README.md) | Signal-based WebSocket manager | Signal-driven real-time dashboards and messaging |
| [`MessageTrackerSignalsService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/MESSAGE_TRACKER_SIGNALS_README.md) | Signal-based channel/message tracking (deprecated — use `ChannelPresenceSignalsService`) | Presence, counters, last-message views |
| [`ChannelPresenceSignalsService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/CHANNEL_PRESENCE_SIGNALS_README.md) | Signal-based channel presence and metadata tracking | ✅ Recommended replacement for `MessageTrackerSignalsService` |

### Message Display System

| Service | Description | Use Case |
|---------|-------------|----------|
| [`MessageDisplayRouterService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/MESSAGE_DISPLAY_README.md) | Rule-based message routing to display strategies | Routing messages to snackbar, dialog, or custom displays |
| [`SnackbarStrategy`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/MESSAGE_DISPLAY_README.md) | Default toast notification display strategy | Showing toast messages via `ToastMessageDisplayService` |

### Base Request Services (Internal)

| Service | Description | Use Case |
|---------|-------------|----------|
| `RequestService` | Base HTTP request class with `BehaviorSubject` state | Internal — extended by `HTTPManagerService` |
| `RequestSignalsService` | Base HTTP request class with Angular Signals | Internal — extended by `HTTPManagerSignalsService` |

### Shared Utilities

| Service | Description | Use Case |
|---------|-------------|----------|
| [`UtilsService`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/UTILS_SERVICES_README.md) | Utilities: encryption, headers, merging, path/query | Helper functions |
| [`Utility Services`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/UTILS_SERVICES_README.md) | Headers, path/query, merging, base request classes | Internal and helper services |

### Common Use Cases

| Use Case | Service to Use | Key Features |
|----------|---------------|--------------|
| Simple API calls | `HTTPManagerService` | Observables, retry, polling |
| Modern reactive UI | `HTTPManagerSignalsService` | Angular Signals |
| CRUD operations | `HTTPManagerStateService` | Auto state updates, pagination |
| Real-time chat | `HTTPManagerStateService` + WebSocket | PUB- messaging channels |
| Persistent notifications | `HTTPManagerStateService` + WebSocket | MES- channels with DB storage |
| State synchronization | `HTTPManagerStateService` + WebSocket | SYS- private channels |
| **Unified WebSocket messaging** | **`WebSocketMessageService`** | **Type-safe, auto prefixes, validation** |
| User preferences | `LocalStorageManagerService` | Encryption, expiration |
| Offline-first | `DatabaseManagerService` | IndexedDB caching, querying |
| Large local datasets | `DatabaseManagerService` | Bulk operations, indexing |
| Secure data storage | `LocalStorageManagerService` | AES encryption |
| File transfers | `HTTPManagerService` | Download progress tracking |
| Live data streams | `HTTPManagerService` | NDJSON, SSE streaming |

## 📖 Documentation Paths

All detailed service guides live in `src/docs/`. Use this README as the entry point, then choose the track that matches the Angular version in your app.

### Angular 14-18: Observable + NgRx Track

| Category | Documentation |
|----------|---------------|
| HTTP | [HTTP Manager](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/HTTP_MANAGER_README.md) |
| State | [HTTP State Manager](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/HTTP_STATE_MANAGER_README.md) and [Store State Manager](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/STORE_STATE_MANAGER_README.md) |
| Real-Time | [WebSocket Manager](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/WS_MANAGER_README.md), [WebSocket Message Service](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/WEBSOCKET_MESSAGE_SERVICE.md), and [Message Tracker](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/MESSAGE_TRACKER_README.md) |
| Persistence | [Local Storage](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/LOCAL_STORAGE_README.md) and [Database](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/DATABASE_README.md) |
| Utilities | [Utils](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/UTILS_SERVICES_README.md), [Encryption](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/ENCRYPTION_README.md), [Logger](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/LOGGER_README.md) |
| Reference | [Models](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/MODELS_README.md), [Complete API Reference](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/COMPLETE_API_REFERENCE.md) |

### Angular 19+: Signal Track

| Category | Documentation |
|----------|---------------|
| Overview | [Signal Services Overview](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/SIGNAL_SERVICES_README.md) |
| HTTP | [HTTP Manager Signals](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/HTTP_SIGNALS_MANAGER_README.md) |
| State | [Store State Signals](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/STORE_STATE_SIGNALS_README.md) |
| Real-Time | [WebSocket Signals](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/WEBSOCKET_SIGNALS_README.md) and [Channel Presence Signals](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/CHANNEL_PRESENCE_SIGNALS_README.md) |
| Message Tracking | [Message Tracker Signals](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/MESSAGE_TRACKER_SIGNALS_README.md) (deprecated — use Channel Presence Signals) |

### Cross-Cutting

| Category | Documentation |
|----------|---------------|
| Message Display | [Message Display System](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/MESSAGE_DISPLAY_README.md) |
| Interceptors | [HTTP Interceptors](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/INTERCEPTOR_README.md) |
| Models | [Models Reference](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/MODELS_README.md) |
| Batch Requests | [Batch Request Guide](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/BATCH_REQUEST_README.md) |
| File Uploads | [Upload Request Guide](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/UPLOAD_REQUEST_README.md) |
| Encryption | [Encryption Utils](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/ENCRYPTION_README.md) |
| Logger | [Logger Service](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/LOGGER_README.md) |
| SQL Queries | [DexieSqlService Guide](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/SQL_DIXIE_README.md) |
| Persistence | [Local Storage Signals](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/LOCAL_STORAGE_SIGNALS_README.md) |

## 🏗️ Architecture

For detailed system architecture, data flows, and design patterns, see:

📋 **[Architecture Documentation](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/ARCHITECTURE.md)**

### System Overview

```text
┌─────────────────────────────────────────────────────────────────┐
│                         Angular Application                     │
├─────────────────────────────────────────────────────────────────┤
│  ┌────────────────┐  ┌────────────────┐  ┌──────────────────┐   │
│  │   Components   │  │   Components   │  │    Components    │   │
│  │   (Signals)    │  │  (Observables) │  │  (State Store)   │   │
│  └───────┬────────┘  └───────┬────────┘  └────────┬─────────┘   │
│          │                   │                     │            │
│          ▼                   ▼                     ▼            │
│  ┌──────────────┐    ┌──────────────┐    ┌──────────────────┐   │
│  │HTTPManager   │    │HTTPManager   │    │HTTPManager       │   │
│  │SignalsService│    │Service       │    │StateService      │   │
│  └──────┬───────┘    └──────┬───────┘    └────────┬─────────┘   │
│         │                   │                      │            │
│         └───────────────────┴──────────────────────┘            │
│                             │                                   │
│                             ▼                                   │
│                    ┌─────────────────┐                          │
│                    │  HttpClient     │                          │
│                    │  (Angular)      │                          │
│                    └────────┬────────┘                          │
│                             │                                   │
├─────────────────────────────┼───────────────────────────────────┤
│                             │                                   │
│  ┌──────────────────────────┼──────────────────────┐            │
│  │        Storage Layer                            │            │
│  ├──────────────────────────┼──────────────────────┤            │
│  │  ┌────────────────┐      │      ┌─────────────┐ │            │
│  │  │LocalStorage    │      │      │IndexedDB    │ │            │
│  │  │Manager Service │      │      │(Dexie.js)   │ │            │
│  │  └────────────────┘      │      └─────────────┘ │            │
│  └──────────────────────────┼──────────────────────┘            │
│                             │                                   │
│  ┌──────────────────────────┼──────────────────────┐            │
│  │        WebSocket Layer                          │            │
│  ├──────────────────────────┼──────────────────────┤            │
│  │  ┌─────────────────────────────────────┐        │            │
│  │  │   WebsocketService                  │        │            │
│  │  └─────────────────────────────────────┘        │            │
│  └─────────────────────────────────────────────────┘            │
└─────────────────────────────────────────────────────────────────┘
```

## 🔧 Interceptors

The library provides several HTTP interceptors that are automatically configured:

📋 **[Interceptors Documentation](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/INTERCEPTOR_README.md)**

### Available Interceptors

| Interceptor | Purpose | Automatically Applied |
|-------------|---------|----------------------|
| **RequestErrorInterceptor** | Handles 400/500 errors with toast notifications | ✅ Yes |
| **RequestHeadersInterceptor** | Adds Content-Type, Accept-Language, Current-Date | ✅ Yes |
| **CredentialsInterceptor** | Adds `withCredentials: true` for CORS | ✅ Yes |
| **ProxyDebuggerInterceptor** | Debug logging for development | ⚙️ Configurable |

### Manual Configuration

```typescript
// app.module.ts
providers: [
  { provide: HTTP_INTERCEPTORS, useClass: WithCredentialsInterceptor, multi: true },
  { provide: HTTP_INTERCEPTORS, useClass: RequestHeadersInterceptor, multi: true },
  { provide: HTTP_INTERCEPTORS, useClass: RequestErrorInterceptor, multi: true }
]
```

### Customization

Error handling can be customized with `ErrorSettings`:

```typescript
import { ErrorSettings } from 'http-request-manager';

const customSettings: ErrorSettings = {
  displayError: true,
  displayWarning: true,
  customHandler: (error) => {
    // Custom error handling logic
  }
};
```

## 📚 Detailed Documentation

For in-depth documentation on each service and component, refer to the following detailed guides:

### Detailed Docs for Angular 14-18

| Documentation | Description |
|---------------|-------------|
| 📖 [HTTP Manager Service](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/HTTP_MANAGER_README.md) | Observable-based HTTP client with retry, polling, streaming, and error handling |
| 📖 [HTTP Manager State Service](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/HTTP_STATE_MANAGER_README.md) | ComponentStore integration with automatic CRUD state updates and WebSocket sync |
| 📖 [Store State Manager Service](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/STORE_STATE_MANAGER_README.md) | Persistent ComponentStore synchronized with local/session storage |
| 📖 [WebSocket Manager Service](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/WS_MANAGER_README.md) | WebSocket connection management with channel-based messaging and notifications |
| 📖 [WebSocket Message Service](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/WEBSOCKET_MESSAGE_SERVICE.md) | Type-safe WebSocket message sending with channel prefix helpers |
| 📖 [Message Tracker Service](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/MESSAGE_TRACKER_README.md) | Guaranteed message delivery with gap detection and reconnection sync |
| 📖 [Local Storage Manager Service](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/LOCAL_STORAGE_README.md) | Secure local/session storage with encryption and expiration |
| 📖 [Database Manager Service](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/DATABASE_README.md) | IndexedDB wrapper via Dexie.js with Observable API for offline-first apps |
| 🚀 [Batch Request Service](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/BATCH_REQUEST_README.md) | Execute multiple HTTP requests with sequential/parallel modes and configurable error handling |
| 📤 [Upload Request Service](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/UPLOAD_REQUEST_README.md) | Multi-file upload with progress tracking, validation, and form-data configuration |
| 🔐 [Encryption Utils](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/ENCRYPTION_README.md) | AES symmetric and RSA asymmetric encryption utilities |
| 📝 [Logger Service](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/LOGGER_README.md) | Context-aware logging with automatic dev/prod mode detection |
| 📚 [Models Reference](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/MODELS_README.md) | Complete reference for all data models and configuration interfaces |

### Detailed Docs for Angular 19+

| Documentation | Description |
|---------------|-------------|
| 📖 [Signal Services Overview](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/SIGNAL_SERVICES_README.md) | Overview of the signal-based service set and migration guidance |
| 📖 [HTTP Manager Signals Service](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/HTTP_SIGNALS_MANAGER_README.md) | Signal-based HTTP client for modern reactive UI with Angular Signals |
| 📖 [Local Storage Signals Manager Service](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/LOCAL_STORAGE_SIGNALS_README.md) | Signal-based persisted storage patterns |
| 📖 [Store State Signals Manager Service](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/STORE_STATE_SIGNALS_README.md) | Signal-based state persistence and computed state |
| 📖 [WebSocket Signals Manager Service](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/WEBSOCKET_SIGNALS_README.md) | Signal-driven WebSocket connection and subscription management |
| 📖 [Message Tracker Signals Service](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/MESSAGE_TRACKER_SIGNALS_README.md) | Signal-based message counting, presence, and channel metadata |
| 🚀 [Batch Request Service](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/BATCH_REQUEST_README.md) | Execute multiple HTTP requests with sequential/parallel modes and configurable error handling |

### Shared Services

| Documentation | Description |
|---------------|-------------|
| 📖 [Utils Service](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/UTILS_SERVICES_README.md) | Utility functions for JSON handling, encryption, headers, and validation |

### Core Components

| Documentation | Description |
|---------------|-------------|
| 🏗️ [Architecture](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/ARCHITECTURE.md) | System architecture, data flows, and design patterns |
| 🔧 [Interceptors](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/INTERCEPTOR_README.md) | HTTP interceptors for error handling, headers, authentication, and debugging |

### Additional Resources

- **Request Manager Services** - Detailed API documentation for the request manager services ([`src/lib/services/request-manager-services/README.md`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/lib/services/request-manager-services/README.md))
- **Encryption Utils** - Encryption utility documentation ([`src/lib/services/utils/encryption/README.md`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/lib/services/utils/encryption/README.md))

## 🎮 Demo Examples

Comprehensive demo components showcase all library features in action:

### Available Demos

Located in [`src/lib/http-request-services-demo/`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/lib/http-request-services-demo/):

| Demo Component | Features Demonstrated |
|----------------|----------------------|
| **HttpRequestServicesDemoComponent** | Main demo hub with service selection |
| **RequestManagerDemoComponent** | HTTP CRUD, file downloads, streaming, polling, retry |
| **RequestManagerStateDemoComponent** | State management, pagination, WebSocket sync, IndexedDB caching |
| **RequestManagerWsDemoComponent** | Real-time chat, AI messaging, notifications, presence tracking |
| **LocalStorageDemoComponent** | Encrypted storage, expiration, reactive signals |
| **LocalStorageSignalsDemoComponent** | Signal-based localStorage API |
| **DatabaseDataDemoComponent** | IndexedDB CRUD, querying, bulk operations |
| **RequestSignalsManagerDemoComponent** | Signal-based HTTP with file downloads |
| **StoreStateManagerDemoComponent** | Persistent state with localStorage sync |

### Demo Features

**HTTP Service Demos:**

- ✅ Basic CRUD operations
- ✅ File download with progress tracking
- ✅ Streaming responses (NDJSON, SSE)
- ✅ Polling with countdown timers
- ✅ Retry logic with custom delays
- ✅ Error handling with toast notifications

**State Management Demos:**

- ✅ ComponentStore integration
- ✅ Automatic state updates
- ✅ Pagination controls
- ✅ WebSocket real-time sync
- ✅ IndexedDB caching
- ✅ Database clear/refresh

**WebSocket Demos:**

- ✅ Channel-based messaging (PUB- channels)
- ✅ Private state sync (SYS- channels)
- ✅ Persistent notifications (MES- channels)
- ✅ User presence tracking
- ✅ Message history & replay
- ✅ AI chat integration
- ✅ Multi-room support

**Storage Demos:**

- ✅ Encrypted localStorage
- ✅ SessionStorage usage
- ✅ Expiration management
- ✅ Signal-based API
- ✅ Reactive updates

### Usage

```html
<app-http-request-services-demo
  [server]="'http://localhost:8080'"
  [wsServer]="'ws://localhost:8080'"
  [jwtToken]="'your-jwt-token'"
  [adapter]="myAdapterFunction"
  [mapper]="myMapperFunction">
</app-http-request-services-demo>
```

### Sample Models

Demo includes production-ready sample models:

- `User` - User data structures
- `ClientInfo` - Client details
- `SessionData` - Session management
- `AIMessage` - AI chat messages
- `Notification` - Notification structures

## 📖 Migration Guide

### From HttpClient to HTTPManagerService

**Before:**

```typescript
http.get('api/users').subscribe(users => {
  this.users = users;
  this.loading = false;
});
```

**After:**

```typescript
httpManager.getRequest(
  ApiRequest.adapt({ path: ['users'] })
).subscribe();

data$ = this.httpManager.data$;
isLoading$ = this.httpManager.isPending$;
```

### From Manual State to HTTPManagerStateService

**Before:**

```typescript
users: User[] = [];
loading = false;

loadUsers() {
  this.loading = true;
  this.http.get('api/users').subscribe(users => {
    this.users = users;
    this.loading = false;
  });
}

addUser(user: User) {
  this.http.post('api/users', user).subscribe(newUser => {
    this.users = [...this.users, newUser];
  });
}
```

**After:**

```typescript
@Injectable()
export class UsersStore extends HTTPManagerStateService<User> {
  constructor() {
    super(ApiRequest.adapt({ path: ['users'] }), DataType.ARRAY);
  }
  
  loadUsers() { this.fetchRecords(); }
  addUser(user: User) { this.createRecord(user); }
}

// Component
data$ = this.usersStore.data$;
isLoading$ = this.usersStore.isPending$;
```

## 📋 API Reference

### Core Models

All models follow the `<Name>Interface` + `<Name>Model` pattern with static `adapt()` methods.

| Model | Description | Documentation |
|-------|-------------|---------------|
| **ApiRequest** | HTTP request configuration | [`Models Guide`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/MODELS_README.md#apirequest) |
| **RetryOptions** | Retry behavior settings | [`Models Guide`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/MODELS_README.md#retryoptions) |
| **DataType** | Data structure type (ARRAY, OBJECT) | [`Models Guide`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/MODELS_README.md#datatype) |
| **DatabaseStorage** | IndexedDB configuration | [`Models Guide`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/MODELS_README.md#databasestorage) |
| **SettingOptions** | Storage settings | [`Models Guide`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/MODELS_README.md#settingoptions) |
| **WSOptions** | WebSocket configuration | [`Models Guide`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/MODELS_README.md#wsoptions) |
| **ConfigOptions** | Global library configuration | [`Models Guide`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/MODELS_README.md#configoptions) |
| **StateStorageOptions** | Persistent state configuration | [`Models Guide`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/MODELS_README.md#statestorageoptions) |
| **TableSchemaDef** | Database table schema | [`Models Guide`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/MODELS_README.md#tableschemadef) |
| **ChannelMessage** | WebSocket message structure | [`Models Guide`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/MODELS_README.md#channelmessage) |
| **WSUser** | WebSocket user info | [`Models Guide`](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/MODELS_README.md#wsuser) |

### Enums

| Enum | Values | Description |
|------|--------|-------------|
| **DataType** | `ARRAY`, `OBJECT` | Response data structure |
| **StreamType** | `NDJSON`, `SSE` | Streaming response types |
| **StorageType** | `GLOBAL`, `SESSION` | Storage scope |
| **CommunicationType** | `subscribe`, `unsubscribe`, `message`, `notification`, etc. | WebSocket message types |
| **ChannelType** | `SYS`, `PUB`, `MES` | Channel prefixes |
| **ToastColors** | `SUCCESS`, `WARN`, `ERROR`, `INFO` | Toast notification colors |

### Configuration Tokens

| Token | Type | Purpose |
|-------|------|---------|
| **CONFIG_SETTINGS_TOKEN** | `ConfigOptions` | Global library configuration |
| **APP_ID** | `string` | Application ID for encryption |

### Complete API Documentation

For comprehensive API reference with all methods, parameters, and examples:
📋 **[Complete API Reference](https://github.com/micheleboni/npm-angular/tree/main/projects/http-request-manager/src/docs/COMPLETE_API_REFERENCE.md)**

## 🧩 Angular 22 Support Matrix

This library is published with Angular 22 as the supported baseline. Older Angular tracks remain documented for reference, but the peer dependency range and toolchain target Angular 22.

| Angular Version | Track | Recommended Service |
|-----------------|-------|---------------------|
| 14-18 | Observable + NgRx | `HTTPManagerService`, `HTTPManagerStateService`, `WebSocketManagerService` |
| 19-21 | Signals | `HTTPManagerSignalsService`, `StoreStateManagerSignalsService`, `WebSocketSignalsManagerService` |
| **22 (supported)** | **Signals (default) + Observable** | **All of the above — module-based bootstrap** |

### Required Toolchain

| Tool | Version |
|------|---------|
| Angular | `^22.0.1` |
| Angular CLI / `@angular-devkit/build-angular` | `^22.0.1` |
| Angular CDK | `^22.0.1` |
| Angular Material | `^22.0.1` |
| `@ngrx/component-store` | `^21.1.1` |
| `@ngx-translate/core` | `^17.0.0` |
| TypeScript | `~6.0.0` |
| Node.js | `>=20.19.0` (Angular 22 CLI requires `>=22.22.3` / `>=24.15.0` / `>=26.0.0`) |
| `ng-packagr` | `^22.0.0` |
| RxJS | `~7.8.0` |
| zone.js | `~0.16.2` |

> The library's `package.json` declares an `engines.node` of `>=20.19.0` to match the Angular 22 toolchain requirements.

## 🤝 Contributing

This library is designed to be enterprise-ready and production-safe. All features include comprehensive error handling, TypeScript support, and extensive configuration options.

## 📄 License

This project is part of the Angular application library suite.

---

**Need help?** Check out the detailed documentation for each service, explore the demo examples, or review the architecture documentation for implementation guidance.
