npm package: @saqib_0089/web-framework
Description: A lightweight Express.js alternative built with TypeScript
Author: Your Name
Latest version: 1.0.0

# 📚 My Web Framework Documentation

A minimal, expressive, and modular web framework built with **TypeScript**, inspired by **Express.js**.

---

## 🧭 Table of Contents

1. [Getting Started](#getting-started)
2. [Project Structure](#project-structure)
3. [Core Concepts](#core-concepts)
4. [API Reference](#api-reference)

   * [Application](#application)
   * [Router](#router)
   * [Request](#request)
   * [Response](#response)
   * [Middleware](#middleware)
   * [Error Handling](#error-handling)
5. [Usage Example](#usage-example)
6. [Key Features](#key-features)
7. [Extending the Framework](#extending-the-framework)

---

## 🚀 Getting Started

### Installation

Clone the repository:

```bash
git clone https://github.com/yourusername/my-web-framework.git
cd my-web-framework
npm install
```

### Development

```bash
npm run dev
```

### Build

```bash
npm run build
```

---

## 🏗️ Project Structure

```text
my-web-framework/
├── src/
│   ├── core/         # Core logic (App, Router, Req/Res)
│   ├── types/        # Type definitions
│   ├── utils/        # Utilities (e.g. path matcher)
│   └── index.ts      # Main export
├── package.json
└── tsconfig.json
```

---

## 💡 Core Concepts

### ✅ Routing

Define routes with HTTP methods:

```ts
app.get('/users', handler);
app.post('/users', handler);
```

### ✅ Middleware

Add reusable logic like logging, authentication:

```ts
app.use((req, res, next) => {
  console.log('Request received');
  next();
});
```

### ✅ Request/Response

Extended wrappers over Node.js native objects with helpers:

```ts
req.params, req.body, res.json(), res.status()
```

---

## 📖 API Reference

### 🔹 Application

```ts
const app = createApp();
```

Inherits from `Router`.

#### Methods

| Method         | Description                              |
| -------------- | ---------------------------------------- |
| `listen(port)` | Starts the HTTP server on the given port |
| `close()`      | Stops the server                         |
| `useError(fn)` | Adds an error-handling middleware        |

---

### 🔹 Router

Handles routes and middleware.

#### Methods

| Method                | Description                             |
| --------------------- | --------------------------------------- |
| `use(fn)`             | Registers global middleware             |
| `use(path, fn)`       | Registers middleware for specific paths |
| `get(path, ...fn)`    | Registers a GET route                   |
| `post(path, ...fn)`   | Registers a POST route                  |
| `put(path, ...fn)`    | Registers a PUT route                   |
| `delete(path, ...fn)` | Registers a DELETE route                |
| `patch(path, ...fn)`  | Registers a PATCH route                 |

---

### 🔹 Request

```ts
(req: Request)
```

Custom wrapper for Node’s `IncomingMessage`.

| Property      | Description                |
| ------------- | -------------------------- |
| `method`      | HTTP method                |
| `url`         | Full URL                   |
| `pathname`    | URL path without query     |
| `query`       | Query parameters as object |
| `params`      | Route parameters           |
| `body`        | Parsed request body        |
| `get(name)`   | Get a header value         |
| `parseBody()` | Parses request body        |

---

### 🔹 Response

```ts
(res: Response)
```

Custom wrapper for Node’s `ServerResponse`.

| Method              | Description                          |
| ------------------- | ------------------------------------ |
| `status(code)`      | Sets response status                 |
| `header(name, val)` | Sets header                          |
| `json(data)`        | Sends JSON                           |
| `send(data)`        | Sends raw text or buffer             |
| `redirect(url)`     | Redirects the client                 |
| `cookie(name, val)` | Sets cookie with optional attributes |

---

### 🔹 Middleware

A function of the form:

```ts
(req: Request, res: Response, next: NextFunction) => void
```

Call `next()` to continue to the next middleware or route handler.

---

### 🔹 Error Handling

Register a custom error handler:

```ts
app.useError((err, req, res, next) => {
  res.status(500).json({ error: err.message });
});
```

---

## 🧪 Usage Example

```ts
import createApp, { Request, Response, NextFunction } from './src/index';

const app = createApp();

// Logger Middleware
app.use((req, res, next) => {
  console.log(`${req.method} ${req.pathname}`);
  next();
});

// Route with params
app.get('/user/:id', (req, res) => {
  res.json({ userId: req.params.id });
});

// Body parsing
app.post('/user', async (req, res) => {
  res.status(201).json({ user: req.body });
});

// Error handler
app.useError((err, req, res) => {
  res.status(500).json({ error: err.message });
});

// Start server
app.listen(3000, () => {
  console.log('🚀 Server running on http://localhost:3000');
});
```

---

## 🌟 Key Features

* ✅ Full **routing system**: `GET`, `POST`, `PUT`, `DELETE`, `PATCH`
* ✅ Clean **middleware chaining**
* ✅ Typed and **extensible Request/Response**
* ✅ Built-in **error handling**
* ✅ **Path parameters** and **query parsing**
* ✅ Custom **body parsing** for JSON and `x-www-form-urlencoded`
* ✅ Modular and **type-safe architecture**

---

## 🧩 Extending the Framework

### Static File Serving

Create a middleware:

```ts
import fs from 'fs';
import path from 'path';

function staticFiles(root: string): MiddlewareFunction {
  return (req, res, next) => {
    const filePath = path.join(root, req.pathname);
    if (fs.existsSync(filePath)) {
      const content = fs.readFileSync(filePath);
      res.send(content);
    } else {
      next();
    }
  };
}
```

### Session, CORS, Authentication

Just add as middleware:

```ts
app.use(cors());
app.use(authMiddleware);
```

---

## 📦 Build & Publish

Compile:

```bash
npm run build
```

Publish to NPM:

```bash
npm publish
```

---

## 📘 Contributing

1. Fork this repo
2. Make changes and test
3. Submit a pull request 🎉

---

## 📝 License

This project is licensed under the MIT License.