Files
typedserver/readme.md

268 lines
8.9 KiB
Markdown
Raw Normal View History

2024-04-14 19:00:39 +02:00
# @api.global/typedserver
A TypeScript-first web server framework for building modern full-stack applications. Features static file serving, live reload, type-safe API integration, service worker support, and edge computing capabilities. Part of the `@api.global` ecosystem.
## Issue Reporting and Security
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
## ✨ Features
- 🔒 **Type-Safe API** - Full TypeScript support with `@api.global/typedrequest` and `@api.global/typedsocket`
-**Live Reload** - Automatic browser refresh on file changes during development
- 🛠️ **Service Worker** - Advanced caching, offline support, and background sync
- ☁️ **Edge Workers** - Cloudflare Workers compatible edge computing with domain routing
- 📡 **WebSocket** - Real-time bidirectional communication via TypedSocket
- 🗺️ **SEO Tools** - Built-in sitemap, RSS feed, and robots.txt generation
- 🎯 **SPA Support** - Single-page application fallback routing
- 📱 **PWA Ready** - Web App Manifest generation for progressive web apps
## 📦 Installation
2024-04-14 19:00:39 +02:00
```bash
# Using pnpm (recommended)
pnpm add @api.global/typedserver
# Using npm
npm install @api.global/typedserver
2024-04-14 19:00:39 +02:00
```
## 🚀 Quick Start
### Basic Server
2023-03-29 14:54:07 +02:00
```typescript
import { TypedServer } from '@api.global/typedserver';
2023-03-29 14:54:07 +02:00
const server = new TypedServer({
serveDir: './public',
cors: true,
watch: true, // Enable file watching
injectReload: true, // Inject live reload script
});
2024-04-14 19:00:39 +02:00
await server.start();
console.log('Server running!');
```
2024-04-14 19:00:39 +02:00
### Full Configuration
2024-04-14 19:00:39 +02:00
```typescript
import { TypedServer } from '@api.global/typedserver';
const server = new TypedServer({
port: 8080,
serveDir: './dist',
cors: true,
// Development
watch: true,
injectReload: true,
// Production
forceSsl: true,
spaFallback: true, // Serve index.html for client-side routes
// SEO
sitemap: true,
feed: true,
robots: true,
domain: 'example.com',
blockWaybackMachine: false,
// PWA
appVersion: 'v1.0.0',
manifest: {
name: 'My App',
short_name: 'myapp',
start_url: '/',
display: 'standalone',
background_color: '#ffffff',
theme_color: '#000000',
},
});
await server.start();
```
2024-04-14 19:00:39 +02:00
## 🔌 Type-Safe API Integration
### Adding TypedRequest Handlers
2024-04-14 19:00:39 +02:00
```typescript
import { TypedServer } from '@api.global/typedserver';
import * as typedrequest from '@api.global/typedrequest';
2024-04-14 19:00:39 +02:00
// Define your typed request interface
interface IGetUser extends typedrequest.implementsTR<IGetUser> {
method: 'getUser';
request: { userId: string };
response: { name: string; email: string };
2024-04-14 19:00:39 +02:00
}
const server = new TypedServer({ serveDir: './public', cors: true });
2024-04-14 19:00:39 +02:00
// Add a typed handler directly to the server's router
server.typedrouter.addTypedHandler<IGetUser>(
new typedrequest.TypedHandler('getUser', async (data) => {
return { name: 'John Doe', email: 'john@example.com' };
})
);
await server.start();
```
### Real-Time WebSocket Communication
TypedServer automatically sets up TypedSocket for real-time communication:
```typescript
import { TypedServer } from '@api.global/typedserver';
import * as typedrequest from '@api.global/typedrequest';
interface IChatMessage extends typedrequest.implementsTR<IChatMessage> {
method: 'sendMessage';
request: { text: string; room: string };
response: { messageId: string; timestamp: number };
}
const server = new TypedServer({ serveDir: './public', cors: true });
// Handle real-time messages
server.typedrouter.addTypedHandler<IChatMessage>(
new typedrequest.TypedHandler('sendMessage', async (data) => {
return { messageId: crypto.randomUUID(), timestamp: Date.now() };
})
);
2024-04-14 19:00:39 +02:00
await server.start();
// Push messages to connected clients
const connections = await server.typedsocket.findAllTargetConnectionsByTag('typedserver_frontend');
for (const conn of connections) {
// Push to specific clients
}
2024-04-14 19:00:39 +02:00
```
## ☁️ Edge Worker (Cloudflare Workers)
2024-04-14 19:00:39 +02:00
```typescript
import { EdgeWorker, DomainRouter } from '@api.global/typedserver/edgeworker';
2024-04-14 19:00:39 +02:00
const worker = new EdgeWorker();
2024-04-14 19:00:39 +02:00
// Configure domain routing
worker.domainRouter.addDomainInstruction({
domainPattern: '*.example.com',
originUrl: 'https://origin.example.com',
type: 'cache',
cacheConfig: { maxAge: 3600 },
});
2024-04-14 19:00:39 +02:00
worker.domainRouter.addDomainInstruction({
domainPattern: 'api.example.com',
originUrl: 'https://api-origin.example.com',
type: 'origin', // Pass through to origin
});
2023-03-29 14:54:07 +02:00
// Cloudflare Worker entry point
export default {
fetch: worker.fetchFunction.bind(worker),
};
2024-04-14 19:00:39 +02:00
```
## 🔧 Service Worker Client
2024-04-14 19:00:39 +02:00
Manage service workers in your frontend application:
2023-03-29 14:54:07 +02:00
```typescript
import { getServiceworkerClient } from '@api.global/typedserver/web_serviceworker_client';
2024-04-14 19:00:39 +02:00
// Initialize and register service worker
const swClient = await getServiceworkerClient({
pollInterval: 30000, // Poll for updates every 30s
});
// The service worker handles:
// - Cache invalidation from server
// - Offline support
// - Background sync
2023-03-29 14:54:07 +02:00
```
## 📋 Configuration Reference
### IServerOptions
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `serveDir` | `string` | - | Directory to serve static files from |
| `port` | `number \| string` | `3000` | Port to listen on |
| `cors` | `boolean` | `true` | Enable CORS headers |
| `watch` | `boolean` | `false` | Watch files for changes |
| `injectReload` | `boolean` | `false` | Inject live reload script into HTML |
| `forceSsl` | `boolean` | `false` | Redirect HTTP to HTTPS |
| `spaFallback` | `boolean` | `false` | Serve index.html for non-file routes |
| `sitemap` | `boolean` | `false` | Generate sitemap at `/sitemap` |
| `feed` | `boolean` | `false` | Generate RSS feed at `/feed` |
| `robots` | `boolean` | `false` | Serve robots.txt |
| `domain` | `string` | - | Domain name for sitemap/feeds |
| `appVersion` | `string` | - | Application version string |
| `manifest` | `object` | - | Web App Manifest configuration |
| `publicKey` | `string` | - | SSL certificate |
| `privateKey` | `string` | - | SSL private key |
| `defaultAnswer` | `function` | - | Custom default response handler |
| `feedMetadata` | `object` | - | RSS feed metadata options |
| `blockWaybackMachine` | `boolean` | `false` | Block Wayback Machine archiving |
## 🏗️ Package Exports
2024-04-14 19:00:39 +02:00
```
@api.global/typedserver
├── . - Main server (TypedServer)
├── /backend - Alias for main server
├── /edgeworker - Cloudflare Workers edge computing
├── /web_inject - Live reload script injection
├── /web_serviceworker - Service Worker implementation
└── /web_serviceworker_client - Service Worker client utilities
```
## 🔄 Utility Servers
Pre-configured server templates for common use cases:
```typescript
import { utilityservers } from '@api.global/typedserver';
// WebsiteServer - optimized for static websites
const websiteServer = new utilityservers.WebsiteServer({
serveDir: './dist',
domain: 'example.com',
});
// ServiceServer - optimized for API services
const serviceServer = new utilityservers.ServiceServer({
cors: true,
});
```
2024-04-14 19:00:39 +02:00
## License and Legal Information
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.
2024-04-14 19:00:39 +02:00
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
2024-04-14 19:00:39 +02:00
### Company Information
2023-03-29 14:54:07 +02:00
Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany
2023-03-29 14:54:07 +02:00
For any legal inquiries or further information, please contact us via email at hello@task.vc.
2023-03-29 14:54:07 +02:00
2024-04-14 19:00:39 +02:00
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.