jkunz 4a0a7c69b5
Default (tags) / security (push) Failing after 1s
Default (tags) / test (push) Failing after 0s
Default (tags) / metadata (push) Skipped
v11.0.0
2026-08-15 17:36:15 +00:00
2026-08-15 17:36:15 +00:00
2026-08-15 17:36:15 +00:00
2026-08-15 17:36:15 +00:00

@api.global/typedserver

A powerful TypeScript-first web server framework for building modern full-stack applications. Features static file serving, live reload, type-safe API integration, decorator-based routing, 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/. 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/ account to submit Pull Requests directly.

Features

  • 🔒 Type-Safe API — Full TypeScript support with @api.global/typedrequest and @api.global/typedsocket
  • 🎯 Decorator Routing — Clean, expressive routing with @Route, @Get, @Post decorators via smartserve
  • 🛡️ Security Headers — Built-in CSP, HSTS, X-Frame-Options, and comprehensive security configuration
  • 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
  • 🗜️ Compression — Automatic Brotli + Gzip response compression
  • 📦 Bundled Content — Serve pre-bundled content from memory for zero-filesystem deployments

📦 Installation

# Using pnpm (recommended)
pnpm add @api.global/typedserver

# Using npm
npm install @api.global/typedserver

🚀 Quick Start

Basic Server

import { TypedServer } from '@api.global/typedserver';

const server = new TypedServer({
  serveDir: './public',
  cors: true,
  watch: true,           // Enable file watching
  injectReload: true,    // Inject live reload script
});

await server.start();
console.log('Server running on port 3000!');

Full Configuration

import { TypedServer } from '@api.global/typedserver';

const server = new TypedServer({
  port: 8080,
  serveDir: './dist',
  cors: true,

  // Development
  watch: true,
  injectReload: true,
  noCache: true,            // Disable browser caching

  // 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',
  },

  // Compression
  compression: {
    enabled: true,
    algorithms: ['br', 'gzip'],
    threshold: 1024,
  },
});

await server.start();

🛣️ Routing

TypedServer uses a unified routing system powered by @push.rocks/smartserve. You can add routes using decorators or the programmatic API.

Decorator-Based Routing

Create clean, expressive controllers using decorators:

import * as smartserve from '@push.rocks/smartserve';

@smartserve.Route('/api/users')
class UserController {
  @smartserve.Get('/')
  async listUsers(ctx: smartserve.IRequestContext): Promise<Response> {
    const users = await getUsersFromDb();
    return new Response(JSON.stringify(users), {
      headers: { 'Content-Type': 'application/json' },
    });
  }

  @smartserve.Get('/:id')
  async getUser(ctx: smartserve.IRequestContext): Promise<Response> {
    const userId = ctx.params.id;
    const user = await getUserById(userId);
    return new Response(JSON.stringify(user), {
      headers: { 'Content-Type': 'application/json' },
    });
  }

  @smartserve.Post('/')
  async createUser(ctx: smartserve.IRequestContext): Promise<Response> {
    const userData = await ctx.json();
    const newUser = await createUserInDb(userData);
    return new Response(JSON.stringify(newUser), {
      status: 201,
      headers: { 'Content-Type': 'application/json' },
    });
  }
}

// Register the controller
smartserve.ControllerRegistry.registerInstance(new UserController());

Programmatic Routes with addRoute()

Add routes dynamically using the addRoute() API:

import { TypedServer } from '@api.global/typedserver';

const server = new TypedServer({ serveDir: './public', cors: true });

// Simple route
server.addRoute('/api/health', 'GET', async (ctx) => {
  return new Response(JSON.stringify({ status: 'ok' }), {
    headers: { 'Content-Type': 'application/json' },
  });
});

// Route with parameters (Express-style :param syntax)
server.addRoute('/api/items/:id', 'GET', async (ctx) => {
  const itemId = ctx.params.id;
  return new Response(JSON.stringify({ id: itemId }), {
    headers: { 'Content-Type': 'application/json' },
  });
});

// Wildcard routes
server.addRoute('/files/*path', 'GET', async (ctx) => {
  const filePath = ctx.params.path;
  return new Response(`Requested: ${filePath}`);
});

await server.start();

🔌 Type-Safe API Integration

Adding TypedRequest Handlers

import { TypedServer } from '@api.global/typedserver';
import * as typedrequest from '@api.global/typedrequest';
import type {
  ITypedRequest,
  implementsTR,
} from '@api.global/typedrequest-interfaces';

// Define your typed request interface
interface IGetUser extends implementsTR<ITypedRequest, IGetUser> {
  method: 'getUser';
  request: { userId: string };
  response: { name: string; email: string };
}

const server = new TypedServer({ serveDir: './public', cors: true });

// 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 8 for real-time communication. It binds each application router through TypedSocket's generated transport routing surface and requires the exact package-major handshake before application RPC:

import { TypedServer } from '@api.global/typedserver';
import * as typedrequest from '@api.global/typedrequest';
import type {
  ITypedRequest,
  implementsTR,
} from '@api.global/typedrequest-interfaces';

interface IChatMessage extends implementsTR<ITypedRequest, 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() };
  })
);

await server.start();

// Push messages to connected clients
const connections = await server.typedsocket.findAllTargetConnectionsByTag('chat-member');
for (const conn of connections) {
  // Push to specific clients via TypedSocket
}

Client-owned connection tags are denied unless clientTagPolicy contains an exact rule for the name. Authentication and authorization tags must be assigned by a server handler to the exact request peer:

interface IRegisterConnection extends implementsTR<ITypedRequest, IRegisterConnection> {
  method: 'registerConnection';
  request: { identity: { accessToken: string } };
  response: { registered: true };
}

declare const identityVerifier: {
  verifyAccessToken(accessToken: string): Promise<{ userId: string }>;
};

server.typedrouter.addTypedHandler(
  new typedrequest.TypedHandler<IRegisterConnection>(
    'registerConnection',
    async ({ identity }, typedTools) => {
      const verifiedIdentity = await identityVerifier.verifyAccessToken(identity.accessToken);
      const connection = server.getServerConnectionForRequest(typedTools);
      server.setServerTag(connection, 'authenticated', { userId: verifiedIdentity.userId });
      return { registered: true };
    },
  ),
);

getServerConnectionForRequest() fails closed for HTTP requests and detached or forged request metadata. A name assigned through setServerTag() remains server-owned; clients cannot overwrite or remove it. Use removeServerTag() when the server revokes that connection state.

Configure virtualStreamAuthorizationAdapter when server handlers create VirtualStreams through server.typedsocket.createVirtualStream(). The adapter must synchronously bind application authority and revalidate it for the exact request peer as defined by TypedSocket 8.

TypedSocket and native HTTP requests expose transport-owned cancellation through TypedTools.abortSignal. TypedSocket 8 propagates exact remote request cancellation; the native /typedrequest route forwards the request connection signal. Handlers must stop their owned work when that signal aborts.

TypedServer's own frontend and service-worker bundles register their connection role through the built-in registerTypedServerConnection RPC during every initial connection and reconnect. Those infrastructure tags are server-owned; application broadcasts should use a separate application-specific tag such as chat-member.

☁️ Edge Worker (Cloudflare Workers)

Deploy your application to the edge with Cloudflare Workers:

import { EdgeWorker, DomainRouter } from '@api.global/typedserver/edgeworker';

const worker = new EdgeWorker();

// Configure domain routing with caching
worker.domainRouter.addDomainInstruction({
  domainPattern: '*.example.com',
  originUrl: 'https://origin.example.com',
  type: 'cache',
  cacheConfig: { maxAge: 3600 },
});

// Pass-through to origin for API routes
worker.domainRouter.addDomainInstruction({
  domainPattern: 'api.example.com',
  originUrl: 'https://api-origin.example.com',
  type: 'origin',
});

// Cloudflare Worker entry point
export default {
  fetch: worker.fetchFunction.bind(worker),
};

🔧 Service Worker Client

Manage service workers in your frontend application:

import { getServiceworkerClient } from '@api.global/typedserver/web_serviceworker_client';

// 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
// - Version updates

TypedRequest Diagnostics

The service worker dashboard records TypedRequest metadata only: method, correlationId, direction, phase, timestamp, optional durationMs, hasError, and payloadRedacted: true. Request and response payloads and error text are discarded before BroadcastChannel transport and are never stored, searched, displayed, or copied by the dashboard.

Dashboard contract version 2 also normalizes entries received from cached 8.10 clients or workers into the metadata-only shape. Existing 8.10 page and service-worker code can still expose raw traffic until the controlling worker is replaced and open pages are reloaded, so deployments should complete normal service-worker activation and client refresh before treating the old capture path as retired.

📦 Bundled Content

Serve pre-bundled content directly from memory — useful for single-binary deployments or embedding assets in server-side code:

import { TypedServer } from '@api.global/typedserver';

const server = new TypedServer({
  cors: true,
  bundledContent: [
    {
      path: '/index.html',
      contentBase64: Buffer.from('<html><body>Hello!</body></html>').toString('base64'),
    },
    {
      path: '/app.js',
      contentBase64: Buffer.from('console.log("loaded")').toString('base64'),
    },
  ],
  spaFallback: true,
});

await server.start();

Bundled content takes priority over filesystem serving and supports ETag-based conditional requests with immutable caching.

🛡️ Security Headers

Configure comprehensive security headers including CSP, HSTS, and more:

import { TypedServer } from '@api.global/typedserver';

const server = new TypedServer({
  serveDir: './dist',
  cors: true,

  securityHeaders: {
    // Content Security Policy
    csp: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", "'unsafe-inline'", 'https://cdn.example.com'],
      styleSrc: ["'self'", "'unsafe-inline'"],
      imgSrc: ["'self'", 'data:', 'https:'],
      connectSrc: ["'self'", 'wss:', 'https://api.example.com'],
      fontSrc: ["'self'", 'https://fonts.gstatic.com'],
      frameAncestors: ["'none'"],
      upgradeInsecureRequests: true,
    },

    // HSTS (HTTP Strict Transport Security)
    hstsMaxAge: 31536000,         // 1 year
    hstsIncludeSubDomains: true,
    hstsPreload: true,

    // Other security headers
    xFrameOptions: 'DENY',
    xContentTypeOptions: true,
    xXssProtection: true,
    referrerPolicy: 'strict-origin-when-cross-origin',

    // Cross-Origin policies
    crossOriginOpenerPolicy: 'same-origin',
    crossOriginEmbedderPolicy: 'require-corp',
    crossOriginResourcePolicy: 'same-origin',

    // Permissions Policy
    permissionsPolicy: {
      camera: [],
      microphone: [],
      geolocation: ['self'],
    },
  },
});

await server.start();

Security Headers Reference

Header Option Description
Content-Security-Policy csp Controls resources the browser can load
Strict-Transport-Security hstsMaxAge, hstsIncludeSubDomains, hstsPreload Forces HTTPS connections
X-Frame-Options xFrameOptions Prevents clickjacking attacks
X-Content-Type-Options xContentTypeOptions Prevents MIME-sniffing
X-XSS-Protection xXssProtection Legacy XSS filter
Referrer-Policy referrerPolicy Controls referrer information
Permissions-Policy permissionsPolicy Controls browser features
Cross-Origin-Opener-Policy crossOriginOpenerPolicy Isolates browsing context
Cross-Origin-Embedder-Policy crossOriginEmbedderPolicy Controls cross-origin embedding
Cross-Origin-Resource-Policy crossOriginResourcePolicy Controls cross-origin resource sharing

🗜️ Compression

TypedServer supports automatic response compression using Brotli and Gzip. Compression is powered by smartserve and enabled by default.

Configuration

import { TypedServer } from '@api.global/typedserver';

const server = new TypedServer({
  serveDir: './dist',
  cors: true,

  // Enable with defaults (brotli + gzip, threshold: 1024 bytes)
  compression: true,

  // Or disable completely
  // compression: false,

  // Or configure in detail
  // compression: {
  //   enabled: true,
  //   algorithms: ['br', 'gzip'],    // Preferred order
  //   threshold: 1024,               // Min size to compress (bytes)
  //   level: 4,                      // Compression level (1-11 for brotli, 1-9 for gzip)
  //   exclude: ['/api/stream/*'],    // Skip these paths
  // },
});

Compression Options Reference

Option Type Default Description
enabled boolean true Enable/disable compression
algorithms string[] ['br', 'gzip'] Preferred algorithms in order
threshold number 1024 Minimum response size (bytes) to compress
level number 4 Compression level (1-11 for brotli, 1-9 for gzip)
compressibleTypes string[] auto MIME types to compress
exclude string[] [] Path patterns to skip

📋 Configuration Reference

IServerOptions

Option Type Default Description
surfaces ITypedServerSurface[] Enable isolated named host/path surfaces on one listener
authorityValidation 'legacy' | 'strict' 'legacy' Validate one canonical Host authority; surface mode is always strict
serveDir string Directory to serve static files from
bundledContent IBundledContentItem[] Base64-encoded files to serve from memory
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
noCache boolean false Disable browser caching via response headers
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 PEM encoded TLS certificate chain; requires privateKey
privateKey string PEM encoded TLS private key; requires publicKey
clientTagPolicy ITypedSocketClientTagPolicy deny all Exact policy for client-owned TypedSocket tags
virtualStreamAuthorizationAdapter IVirtualStreamAuthorizationAdapter Bind and revalidate application authority for server-created VirtualStreams
listenHostname string '0.0.0.0' Interface address the listener binds to; pass '127.0.0.1' for a loopback-only server
defaultAnswer function Custom default response handler
feedMetadata object RSS feed metadata options
blockWaybackMachine boolean false Block Wayback Machine archiving
securityHeaders ISecurityHeaders Security headers configuration
compression ICompressionConfig | boolean true Response compression configuration
connectionTimeout number Node.js socket inactivity timeout in milliseconds; must be an integer in 1..2147483647
headersTimeout number Node.js deadline for receiving complete HTTP headers in milliseconds; must be an integer in 1..2147483647
requestTimeout number Node.js deadline for receiving a complete HTTP request in milliseconds; must be an integer in 1..2147483647
cleanupTimeoutMs number 5000 Maximum time allowed for each owned cleanup attempt during stop() in milliseconds; must be an integer in 1..2147483647
typedRequestMaxBodyBytes number Reject native HTTP TypedRequest POST bodies larger than this byte count before admission or decoding; must be an integer in 1..2147483647
requestAdmission (context) => boolean | Response | void Admit or reject an HTTP request before CORS, routing, health checks, and static content
websocketAdmission (context) => boolean | Response | void Admit or reject a WebSocket request before the protocol upgrade
websocketMaxPayloadBytes number Reject oversized WebSocket messages before TypedRouter parsing or handler dispatch; valid values are 1..2147483647
typedRequestAdmission (request, context) => boolean | Response | void Admit or reject a decoded HTTP TypedRequest before routing

HTTP timeout options are supported by the Node.js adapter. SmartServe rejects configured HTTP timeouts at startup under Bun and Deno instead of silently running without the requested deadlines.

When publicKey and privateKey are configured, TypedServer terminates HTTPS and WSS directly on its single listener. Both values are required and parsed during construction, before controllers, transports, watchers, or a listener are created.

Request Admission

Admission callbacks guard a legacy single-router server by host, path, origin, or TypedRequest method:

const server = new TypedServer({
  websocketMaxPayloadBytes: 64 * 1024,
  typedRequestMaxBodyBytes: 256 * 1024,
  requestAdmission: (context) => {
    const host = new URL(context.request.url).hostname;
    return host === 'api.example.com';
  },
  websocketAdmission: (context) => {
    return context.request.headers.get('origin') === 'https://app.example.com';
  },
  typedRequestAdmission: (request, context) => {
    const host = new URL(context.request.url).hostname;
    return host !== 'login.example.com' || request.method === 'login';
  },
});

Return false for a 403 rejection, a Response for a custom rejection, or true/void to continue. Rejected requests retain configured security headers without receiving CORS headers. HTTP TypedRequest handlers receive the server-owned request context as tools.localData.requestContext; caller localData cannot replace it.

When typedRequestMaxBodyBytes is configured, TypedServer counts the actual streamed bytes for the native POST /typedrequest endpoint before request or TypedRequest admission runs. Oversized bodies are drained and answered with a JSON 413 without invoking admission callbacks, custom handlers, or the TypedRouter. Unreadable bodies receive the same JSON 400 class as invalid request decoding. Configure requestTimeout separately when uploads also need a duration deadline; the byte ceiling is not a time limit.

Named Host and Path Surfaces

Use surfaces when different hostnames or path trees must expose different backend routers. Surface selection uses exact canonical hostnames and boundary-aware path prefixes. The longest matching prefix wins. HTTP and WebSocket routers remain separate, the selected surface is bound once per request or connection, and unknown hosts and paths return 404 before CORS.

import { TypedServer } from '@api.global/typedserver';
import { TypedRouter } from '@api.global/typedrequest';

const publicHttp = new TypedRouter();
const publicSocket = new TypedRouter();
const adminHttp = new TypedRouter();
const adminSocket = new TypedRouter();
const publicBundle = [];

const server = new TypedServer({
  cors: false,
  surfaces: [
    {
      name: 'public',
      match: {
        hostnames: ['freelance.club', 'localhost'],
        websocketPathPrefixes: ['/socket'],
      },
      httpTypedRouter: publicHttp,
      websocketTypedRouter: publicSocket,
      cors: true,
      bundledContent: publicBundle,
      spaFallback: true,
    },
    {
      name: 'superadmin',
      match: {
        hostnames: ['superadmin.freelance.club', 'superadmin.localhost'],
        websocketPathPrefixes: ['/socket'],
      },
      httpTypedRouter: adminHttp,
      websocketTypedRouter: adminSocket,
      typedRequestMaxBodyBytes: 128 * 1024,
      cors: false,
      securityHeaders: { xFrameOptions: 'DENY' },
      requestAdmission: async (context) => {
        return await admitAdminOriginAndSession(context);
      },
    },
  ],
});

await server.start();

Each surface may configure its own typedRequestPath, typedRequestMaxBodyBytes, httpHandler, admission callbacks, response policy, static/bundled content, SPA fallback, and health endpoint. IRequestContext.state is shared across global admission, surface admission, TypedRequest admission, and the selected handler. An omitted surface typedRequestMaxBodyBytes inherits the top-level value; a surface value overrides it. Exact host/path surface selection happens first; an unknown match returns 404 before admission callbacks and CORS. For HTTP, top-level requestAdmission runs before surface requestAdmission. For decoded HTTP RPC, top-level typedRequestAdmission runs before surface typedRequestAdmission. For WebSockets, top-level websocketAdmission runs before surface websocketAdmission, then the selected router is bound for the peer's lifetime. Built-in development RPC methods are excluded by default; set includeBuiltinTypedHandlers: true only on a surface that needs them.

After a surface WebSocket completes TypedSocket's exact-major handshake, the connection receives the protected server-owned tag typedserver_surface:<surface-name>. The tag is not discoverable before TypedSocket publishes connection readiness, and clients cannot assign, replace, or remove it.

Surface mode does not use the process-global decorated-controller registry or addRoute(). Supply an instance-local httpHandler instead. Top-level legacy content options are rejected in surface mode so content cannot be exposed on the wrong hostname accidentally. Omitting surfaces preserves the legacy single-router, decorated-controller, and addRoute() behavior.

TypedServer instances are single-use. start() rejects concurrent starts and any restart after stop or failed startup. Successful stop and repeated stops after completed cleanup are idempotent. stop() can cancel an in-progress start while cleaning partially initialized transports, watchers, and owned router composition. Owned cleanup attempts are initiated independently, so one stalled component does not prevent transport cleanup from starting. If a cleanup rejects or exceeds cleanupTimeoutMs, stop() rejects with an AggregateError. Timed-out owner promises remain retained, so later stop() calls await the same unresolved operations without starting duplicates; rejected cleanups are retried.

🏗️ Package Exports

@api.global/typedserver
├── .                           — Main server (TypedServer)
├── /backend                    — Alias for main server
├── /infohtml                   — Info HTML page generator
├── /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 with best practices built-in.

UtilityWebsiteServer

Optimized for modern web applications with SPA support, live reload, and caching disabled by default during development:

import { utilityservers } from '@api.global/typedserver';

const websiteServer = new utilityservers.UtilityWebsiteServer({
  serveDir: './dist',
  domain: 'example.com',
  // Validate one canonical Host authority without restricting valid hostnames.
  authorityValidation: 'strict',
  // Optional strict exact-host allowlist. superadmin.localhost works in dev.
  exactHostnames: ['example.com', 'localhost'],

  // Optional direct HTTPS/WSS listener. The certificate must cover every host.
  publicKey: certificatePem,
  privateKey: privateKeyPem,

  // SPA fallback enabled by default
  spaFallback: true,   // default: true

  // Security headers
  securityHeaders: {
    csp: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", "'unsafe-inline'"],
      styleSrc: ["'self'", "'unsafe-inline'"],
    },
    xFrameOptions: 'SAMEORIGIN',
    xContentTypeOptions: true,
  },

  // Compression (enabled by default)
  compression: true,

  // Other options
  cors: true,          // default: true
  forceSsl: false,     // default: false
  appSemVer: '1.0.0',
  port: 3000,          // default: 3000

  // Optional ads.txt entries (only served if configured)
  adsTxt: [
    'google.com, pub-1234567890, DIRECT, f08c47fec0942fa0',
  ],

  // RSS feed metadata
  feedMetadata: {
    title: 'My Blog',
    description: 'A cool blog',
    link: 'https://example.com',
  },

  // Add custom routes
  addCustomRoutes: async (typedserver) => {
    typedserver.addRoute('/api/custom', 'GET', async () => {
      return new Response('Custom route!');
    });
  },
});

await websiteServer.start();

authorityValidation forwards the underlying TypedServer authority contract. Use 'strict' when application admission needs to inspect any syntactically valid hostname or IP authority while rejecting missing, duplicate, or malformed Host authorities before application routing. exactHostnames accepts canonical hostname-only values without ports. When present, it always enables strict authority validation for both HTTP and WebSocket admission and requests for non-allowlisted hosts return 404. publicKey, privateKey, and clientTagPolicy are forwarded unchanged to the underlying TypedServer, so localhost and superadmin.localhost can share one direct TLS listener without a reverse proxy. The exact-host allowlist remains the first admission gate when addCustomRoutes installs application-specific HTTP or WebSocket admission callbacks; those callbacks run only for an allowed host.

UtilityServiceServer

Optimized for API services with auto-generated info page:

import { utilityservers } from '@api.global/typedserver';

const serviceServer = new utilityservers.UtilityServiceServer({
  serviceName: 'My API',
  serviceVersion: '1.0.0',
  serviceDomain: 'api.example.com',
  port: 8080,

  // Add custom routes
  addCustomRoutes: async (typedserver) => {
    typedserver.addRoute('/api/status', 'GET', async () => {
      return new Response(JSON.stringify({ status: 'healthy' }), {
        headers: { 'Content-Type': 'application/json' },
      });
    });
  },
});

await serviceServer.start();

🧩 Architecture Overview

┌─────────────────────────────────────────────────────────────┐
│                      TypedServer                            │
├─────────────────────────────────────────────────────────────┤
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐ │
│  │ SmartServe  │  │ TypedRouter │  │    TypedSocket      │ │
│  │ (Routing)   │  │ (RPC)       │  │    (WebSocket)      │ │
│  └─────────────┘  └─────────────┘  └─────────────────────┘ │
│         │                │                    │             │
│         ▼                ▼                    ▼             │
│  ┌─────────────────────────────────────────────────────┐   │
│  │              Request Handler Pipeline               │   │
│  │  1. Controller Registry (Decorated Routes)          │   │
│  │  2. Bundled Content (in-memory)                     │   │
│  │  3. HTML Injection (live reload)                    │   │
│  │  4. Static File Serving (filesystem)                │   │
│  │  5. SPA Fallback                                    │   │
│  └─────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────┘

This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the license file.

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.

Company Information

Task Venture Capital GmbH Registered at District Court Bremen HRB 35230 HB, Germany

For any legal inquiries or further information, please contact us via email at hello@task.vc.

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.

S
Description
No description provided
Readme
3.3 MiB
Languages
TypeScript 100%