jkunz 0ffaf108dc
Default (tags) / security (push) Failing after 0s
Default (tags) / test (push) Failing after 0s
Default (tags) / release (push) Skipped
Default (tags) / metadata (push) Skipped
v6.0.0
2026-08-15 10:54:24 +00:00
2026-08-15 10:54:24 +00:00
2026-08-15 10:54:24 +00:00
2026-08-15 10:54:24 +00:00

@push.rocks/smartserve

A blazing-fast, cross-platform HTTP server for Node.js, Deno, and Bun with decorator-based routing, OpenAPI/Swagger integration, automatic compression, WebSocket support, static file serving, and WebDAV protocol. 🚀

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.

Install

npm install @push.rocks/smartserve
# or
pnpm add @push.rocks/smartserve

Features

Feature Description
Cross-Platform Works seamlessly on Node.js, Deno, and Bun with zero config
🎯 Decorator-Based Routing Clean, expressive @Route, @Get, @Post decorators
📖 OpenAPI/Swagger Auto-generate OpenAPI 3.1 specs with built-in Swagger UI & ReDoc
Request Validation Validate requests against JSON Schema with automatic coercion
🗜️ Auto Compression Brotli/gzip compression with smart content detection
🛡️ Guards & Interceptors Built-in @Guard, @Transform, @Intercept for auth & transformation
📁 Static File Server Streaming, ETags, Range requests, directory listing, pre-compressed files
🌐 WebDAV Support Mount as network drive with full RFC 4918 compliance
🔌 WebSocket Ready Native WebSocket support with TypedRouter for type-safe RPC
Zero Overhead Native Web Standards API (Request/Response) on Deno/Bun
🔒 HTTPS/TLS Built-in TLS support with certificate configuration

Quick Start

import { SmartServe, Route, Get, Post, type IRequestContext } from '@push.rocks/smartserve';

@Route('/api')
class UserController {
  @Get('/hello')
  hello() {
    return { message: 'Hello World! 👋' };
  }

  @Get('/users/:id')
  getUser(ctx: IRequestContext) {
    return { id: ctx.params.id, name: 'John Doe' };
  }

  @Post('/users')
  async createUser(ctx: IRequestContext<{ name: string; email: string }>) {
    const body = await ctx.json();
    return { id: 'new-id', ...body };
  }
}

const server = new SmartServe({ port: 3000 });
server.register(UserController);
await server.start();

console.log('🚀 Server running at http://localhost:3000');

Lifecycle and controller ownership

server.register() keeps a durable controller declaration for that SmartServe instance. stop() releases its active process-wide controller lease, OpenAPI routes, WebSocket state, and runtime adapter resources. A later start() reacquires the same declaration, so start()stop()start() preserves the registered routes.

Controller registrations are identity-safe when several SmartServe instances use the same controller constructor: stopping one instance removes only its own lease and reveals the newest remaining owner. Releasing the final explicit lease does not implicitly construct a replacement controller.

Cleanup attempts every owned phase. Concurrent stop() calls share the same work; a failed cleanup retains only unresolved resources for a later stop() retry. Registering during start, stop, or an unresolved cleanup failure is rejected. Application WebSocket close callbacks keep their documented isolated logging behavior.

Table of Contents


Decorators

Route Decorators

import { Route, Get, Post, Put, Delete, Patch, All } from '@push.rocks/smartserve';

@Route('/api/v1')  // Base path for all routes in this controller
class ApiController {
  @Get('/items')           // GET /api/v1/items
  listItems() {
    return [{ id: 1, name: 'Item 1' }];
  }

  @Get('/items/:id')       // GET /api/v1/items/:id
  getItem(ctx: IRequestContext) {
    return { id: ctx.params.id };
  }

  @Post('/items')          // POST /api/v1/items
  async createItem(ctx: IRequestContext<{ name: string }>) {
    const body = await ctx.json();
    return { created: body.name };
  }

  @Put('/items/:id')       // PUT /api/v1/items/:id
  async updateItem(ctx: IRequestContext) {
    const body = await ctx.json();
    return { updated: ctx.params.id, ...body };
  }

  @Delete('/items/:id')    // DELETE /api/v1/items/:id
  deleteItem(ctx: IRequestContext) {
    return { deleted: ctx.params.id };
  }

  @All('/webhook')         // Matches ALL HTTP methods
  handleWebhook(ctx: IRequestContext) {
    return { method: ctx.method };
  }
}

Guards (Authentication/Authorization)

Guards protect routes by returning true (allow) or false (reject with 403):

import { Route, Get, Guard, hasBearerToken, type IRequestContext } from '@push.rocks/smartserve';

// Custom guard function
const isAuthenticated = (ctx: IRequestContext) => {
  return ctx.headers.has('Authorization');
};

const isAdmin = (ctx: IRequestContext) => {
  return ctx.headers.get('X-Role') === 'admin';
};

@Route('/admin')
@Guard(isAuthenticated)
@Guard(isAdmin)  // Multiple guards - all must pass
class AdminController {
  @Get('/dashboard')
  dashboard() {
    return { admin: true };
  }

  // Method-level guard (runs after class guards)
  @Get('/super-secret')
  @Guard((ctx) => ctx.headers.get('X-Super') === 'yes')
  superSecret() {
    return { level: 'super-secret' };
  }
}

// Built-in utility guards
@Route('/protected')
@Guard(hasBearerToken())  // Requires Authorization: Bearer <token>
class ProtectedController {
  @Get('/data')
  getData() {
    return { protected: true };
  }
}

Transforms (Response Modification)

Transforms modify the response before sending:

import { Route, Get, Transform, wrapSuccess, addTimestamp } from '@push.rocks/smartserve';

// Custom transform
const addVersion = <T extends object>(data: T) => ({
  ...data,
  apiVersion: '2.0',
});

@Route('/api')
@Transform(wrapSuccess)  // Built-in: wraps in { success: true, data: ... }
class ApiController {
  @Get('/info')
  @Transform(addTimestamp)  // Built-in: adds timestamp field
  @Transform(addVersion)    // Transforms stack
  getInfo() {
    return { name: 'MyAPI' };
  }
  // Response: { success: true, data: { name: 'MyAPI', timestamp: '...', apiVersion: '2.0' } }
}

Intercept (Full Control)

For complete control over request/response flow:

import { Route, Get, Intercept, type IRequestContext } from '@push.rocks/smartserve';

@Route('/api')
@Intercept({
  // Runs BEFORE handler
  request: async (ctx) => {
    console.log(`📥 ${ctx.method} ${ctx.path}`);

    // Return Response to short-circuit
    if (ctx.headers.get('X-Block') === 'true') {
      return new Response('Blocked', { status: 403 });
    }

    // Add data to state for handler access
    ctx.state.requestTime = Date.now();

    // Return void to continue with original context
  },

  // Runs AFTER handler
  response: async (data, ctx) => {
    const duration = Date.now() - (ctx.state.requestTime as number);
    console.log(`📤 Response in ${duration}ms`);
    return { ...data, processedIn: `${duration}ms` };
  },
})
class LoggedController {
  @Get('/data')
  getData() {
    return { items: [1, 2, 3] };
  }
}

OpenAPI & Swagger

SmartServe includes first-class OpenAPI 3.1 support with automatic spec generation, Swagger UI, ReDoc, and request validation.

Documenting APIs

import {
  SmartServe,
  Route,
  Get,
  Post,
  ApiOperation,
  ApiParam,
  ApiQuery,
  ApiRequestBody,
  ApiResponseBody,
  ApiTag,
  ApiSecurity,
  type IRequestContext,
} from '@push.rocks/smartserve';

// Define JSON Schemas for validation
const UserSchema = {
  type: 'object',
  properties: {
    id: { type: 'string', format: 'uuid' },
    name: { type: 'string', minLength: 1 },
    email: { type: 'string', format: 'email' },
  },
  required: ['id', 'name', 'email'],
} as const;

const CreateUserSchema = {
  type: 'object',
  properties: {
    name: { type: 'string', minLength: 1 },
    email: { type: 'string', format: 'email' },
  },
  required: ['name', 'email'],
} as const;

@Route('/api/users')
@ApiTag('Users')
class UserController {
  @Get('/')
  @ApiOperation({
    summary: 'List all users',
    description: 'Returns a paginated list of users',
  })
  @ApiQuery('page', {
    description: 'Page number',
    schema: { type: 'integer', minimum: 1, default: 1 },
  })
  @ApiQuery('limit', {
    description: 'Items per page',
    schema: { type: 'integer', minimum: 1, maximum: 100, default: 20 },
  })
  @ApiResponseBody(200, {
    description: 'List of users',
    schema: { type: 'array', items: UserSchema },
  })
  listUsers(ctx: IRequestContext) {
    const page = ctx.query.page ?? '1';
    const limit = ctx.query.limit ?? '20';
    return { users: [], page: parseInt(page), limit: parseInt(limit) };
  }

  @Get('/:id')
  @ApiOperation({ summary: 'Get user by ID' })
  @ApiParam('id', {
    description: 'User UUID',
    schema: { type: 'string', format: 'uuid' },
  })
  @ApiResponseBody(200, { description: 'User found', schema: UserSchema })
  @ApiResponseBody(404, { description: 'User not found' })
  getUser(ctx: IRequestContext) {
    return { id: ctx.params.id, name: 'John Doe', email: 'john@example.com' };
  }

  @Post('/')
  @ApiOperation({ summary: 'Create a new user' })
  @ApiRequestBody({
    description: 'User data',
    schema: CreateUserSchema,
  })
  @ApiResponseBody(201, { description: 'User created', schema: UserSchema })
  @ApiResponseBody(400, { description: 'Validation error' })
  @ApiSecurity('bearerAuth')
  async createUser(ctx: IRequestContext<{ name: string; email: string }>) {
    const body = await ctx.json();
    return { id: 'new-uuid', name: body.name, email: body.email };
  }
}

Request Validation

When you define @ApiRequestBody, @ApiParam, or @ApiQuery with schemas, SmartServe automatically validates incoming requests:

const server = new SmartServe({
  port: 3000,
  openapi: {
    enabled: true,
    info: {
      title: 'My API',
      version: '1.0.0',
      description: 'A well-documented API',
    },
    validate: true,  // 🔥 Enable automatic request validation
  },
});

server.register(UserController);
await server.start();

// Invalid request → 400 Bad Request with details
// POST /api/users with { "name": "" }
// Response: { "error": "Validation failed", "source": "body", "details": [...] }

Automatic Type Coercion: Query and path parameters are automatically coerced to their schema types:

@Get('/items')
@ApiQuery('page', { schema: { type: 'integer', default: 1 } })
@ApiQuery('active', { schema: { type: 'boolean' } })
listItems(ctx: IRequestContext) {
  // ctx.query.page is coerced to number (1)
  // ctx.query.active is coerced to boolean
  return { page: ctx.query.page, active: ctx.query.active };
}

Swagger UI & ReDoc

const server = new SmartServe({
  port: 3000,
  openapi: {
    enabled: true,
    info: {
      title: 'My Awesome API',
      version: '2.0.0',
      description: 'API documentation with interactive testing',
      contact: {
        name: 'API Support',
        email: 'support@example.com',
      },
    },
    servers: [
      { url: 'http://localhost:3000', description: 'Development' },
      { url: 'https://api.example.com', description: 'Production' },
    ],
    securitySchemes: {
      bearerAuth: {
        type: 'http',
        scheme: 'bearer',
        bearerFormat: 'JWT',
      },
    },
    // Customize paths
    specPath: '/openapi.json',    // Default: /openapi.json
    swaggerPath: '/docs',         // Default: /docs
    redocPath: '/redoc',          // Default: /redoc
  },
});

await server.start();

// 📖 Swagger UI:  http://localhost:3000/docs
// 📕 ReDoc:       http://localhost:3000/redoc
// 📄 OpenAPI:     http://localhost:3000/openapi.json

Compression

SmartServe automatically compresses responses using Brotli or gzip based on client support:

const server = new SmartServe({
  port: 3000,
  compression: {
    enabled: true,          // Default: true
    threshold: 1024,        // Min bytes to compress (default: 1KB)
    level: 6,               // Compression level 1-11 for br, 1-9 for gzip
    preferBrotli: true,     // Prefer Brotli over gzip
  },
});

Per-Route Compression Control

import { Route, Get, Compress, NoCompress } from '@push.rocks/smartserve';

@Route('/api')
class ApiController {
  @Get('/large-data')
  @Compress({ level: 9 })  // Force high compression
  getLargeData() {
    return { data: '...massive payload...' };
  }

  @Get('/already-compressed')
  @NoCompress()  // Skip compression (e.g., for pre-compressed content)
  getCompressed() {
    return someCompressedBuffer;
  }
}

Pre-Compressed Static Files

Serve .br or .gz files automatically when available:

const server = new SmartServe({
  port: 3000,
  static: {
    root: './dist',
    precompressed: true,  // Serve main.js.br instead of main.js
  },
});

Static File Server

Serve static files with streaming, ETags, Range requests, and directory listing:

const server = new SmartServe({
  port: 3000,
  static: {
    root: './public',
    index: ['index.html', 'index.htm'],
    dotFiles: 'deny',               // 'allow' | 'deny' | 'ignore'
    etag: true,                     // Generate ETags for caching
    lastModified: true,             // Add Last-Modified header
    cacheControl: 'max-age=3600',   // Or function: (path) => 'max-age=...'
    extensions: ['.html'],          // Try these extensions for extensionless URLs
    precompressed: true,            // Serve .br/.gz files when available
    directoryListing: {
      showHidden: false,
      sortBy: 'name',               // 'name' | 'size' | 'modified'
      sortOrder: 'asc',
    },
  },
});

Or use the shorthand:

const server = new SmartServe({
  port: 3000,
  static: './public',  // Uses sensible defaults
});

WebDAV Support

Mount the server as a network drive on macOS, Windows, or Linux:

const server = new SmartServe({
  port: 8080,
  webdav: {
    root: '/path/to/files',
    auth: (ctx) => {
      // Optional: Basic authentication
      const auth = ctx.headers.get('Authorization');
      if (!auth) return false;
      const [, credentials] = auth.split(' ');
      const [user, pass] = atob(credentials).split(':');
      return user === 'admin' && pass === 'secret';
    },
    locking: true,  // Enable RFC 4918 exclusive write locks
  },
});

await server.start();
// 💾 Connect: Finder → Go → Connect to Server → http://localhost:8080

Supported WebDAV Methods:

Method Description
OPTIONS Capability discovery
PROPFIND Directory listing and file metadata
MKCOL Create directory
COPY Copy files/directories
MOVE Move/rename files/directories
LOCK Acquire exclusive write lock
UNLOCK Release lock
GET / PUT / DELETE File operations

HTTP Timeouts

The Node.js adapter can enforce independent socket inactivity, header, and complete-request deadlines:

const server = new SmartServe({
  port: 3000,
  connectionTimeout: 15_000,
  headersTimeout: 10_000,
  requestTimeout: 120_000,
});

Each configured value must be an integer from 1 through 2147483647 milliseconds. Bun and Deno currently reject these options at startup instead of silently ignoring a deadline they cannot enforce.

On Node.js, the Web Request.signal passed to handlers aborts when the client disconnects, the request or response transport fails, or the server stops. Request-body and streamed-response work receives the same cancellation. A normally completed response leaves the signal un-aborted; requestTimeout continues to mean Node's complete-request deadline rather than a handler timer.


WebSocket Support

WebSocket connections are handled natively across all runtimes:

const server = new SmartServe({
  port: 3000,
  websocket: {
    maxPayloadBytes: 64 * 1024,
    admit: (context) => {
      const origin = context.request.headers.get('origin');
      return origin === 'https://app.example.com';
    },
    onOpen: (peer) => {
      console.log(`🔗 Connected: ${peer.id}`);
      peer.send('Welcome!');
      peer.tags.add('authenticated');  // Tag for filtering
    },
    onMessage: (peer, message) => {
      console.log(`📨 ${message.text}`);
      peer.send(`Echo: ${message.text}`);
    },
    onClose: (peer, code, reason) => {
      console.log(`👋 Disconnected: ${peer.id}`);
    },
    onError: (peer, error) => {
      console.error(`❌ Error: ${error.message}`);
    },
  },
});

admit runs before the WebSocket protocol upgrade on Node.js, Bun, and Deno. Return false for a 403 rejection, return a Response for a custom rejection, or return true/void to allow the connection. The request context exposes the requested host, origin, path, headers, and URL, so applications can enforce their transport boundary before a peer exists.

Set maxPayloadBytes to an integer from 1 through 2147483647 bytes to reject oversized messages before TypedRouter JSON parsing or onMessage dispatch. The limit is enforced by the native runtime where supported and by SmartServe before application dispatch on every runtime. SmartServe sends WebSocket code 1009 when the runtime exposes the oversized message; a native runtime may terminate the message before an application close frame can be sent. Omitting the option preserves the runtime's existing default.

Strict Request Authority

Enable strict authority validation when host identity is a security boundary:

const server = new SmartServe({
  port: 3000,
  authorityValidation: 'strict',
});

Strict mode requires exactly one syntactically valid Host authority before SmartServe constructs the request URL. Duplicate, merged, padded, malformed, userinfo-bearing, path-bearing, and out-of-range-port authorities receive 400 Bad Request. The parsed hostname and effective port must also match the request URL authority. The default legacy mode preserves historical behavior.

parseRequestAuthority(rawHostValues) exposes the same parser for boundary code that has access to raw header values. It returns IParsedRequestAuthority and throws InvalidRequestAuthorityError when the authority is missing, ambiguous, or malformed.

WebSocket Heartbeat

SmartServe sends WebSocket control-frame pings by default on Node.js and Bun to keep idle proxy paths active and to close stale peers that stop responding with pongs.

const server = new SmartServe({
  port: 3000,
  websocket: {
    heartbeat: {
      intervalMs: 30_000,  // default
      timeoutMs: 15_000,   // default, must be lower than intervalMs
    },
    onMessage: (peer, message) => {
      peer.send(`Echo: ${message.text}`);
    },
  },
});

Set heartbeat: false to disable automatic pings. The heartbeat option also accepts an optional payload string or Uint8Array for ping frames. The Deno adapter does not currently support control-frame heartbeat; explicitly enabling heartbeat on Deno throws during startup.

Generic Raw-Frame Transport

Bind a generic owner when an integration needs normalized binary messages while TypedRouter continues to handle text RPC messages:

import {
  SmartServe,
  type IWebSocketTransportOwner,
} from '@push.rocks/smartserve';
import { TypedRouter } from '@api.global/typedrequest';

const typedRouter = new TypedRouter();

const priorityFrames = [{ type: 'text' as const, text: 'ready' }];
const binaryFrames = [
  { type: 'binary' as const, data: new Uint8Array([1, 2, 3]) },
];

const transportOwner: IWebSocketTransportOwner = {
  onOpen: (peer) => {
    peer.rawFrameScheduler?.wake();
  },
  onFrame: (_peer, frame) => {
    if (frame.type === 'binary') {
      console.log(frame.data, frame.size);
    }
  },
  pullPriorityFrame: () => priorityFrames.shift(),
  pullBinaryFrame: () => binaryFrames.shift(),
  onOutboundFrameSettled: (_peer, frame, settlement) => {
    console.log(frame.type, settlement.status, settlement.bufferedAmount);
  },
  onTypedResponseSettled: (_peer, response, settlement) => {
    console.log(response.correlation?.id, settlement.status);
  },
};

const server = new SmartServe({
  port: 3000,
  websocket: {
    typedRouter,
    transportOwner,
  },
});

transportOwner and resolveTransportOwner(context) are mutually exclusive. The resolver runs once before upgrade, and returning undefined rejects the upgrade with 404. The selected owner, peer object, and per-peer scheduler stay exact for that physical connection. Owner open, frame, error, and close callbacks are invoked in native event order; close is delivered once. Raw-frame listeners, owner frame callbacks, queue pulls, and settlement callbacks are synchronous enqueue/accounting boundaries. SmartServe catches synchronous throws and observes an accidentally returned Promise without awaiting it. onTypedResponseSettled receives the exact TypedRouter response envelope after its text frame reaches the runtime's canonical sent, accepted, failed, or rejected settlement. TypedRequest 8 wire requests must carry a fresh, non-empty requestInstanceId. SmartServe rejects malformed envelopes before TypedRouter routing and serializes a response only when its method, correlation ID, and request instance ID exactly match the request. Legacy onConnectionOpen, onOpen, onError, and onClose Promise returns are also observed but never awaited by adapter dispatch, preserving non-blocking WebSocket lifecycle behavior.

TypedRouter text requests start in normalized text-frame arrival order and may complete independently by correlation. Raw frames therefore continue to reach the owner during long-running handlers. Closing the peer cancels tracked response wrappers, suppresses late responses, and still observes late handler rejections so they cannot become unhandled rejections.

Incoming Node.js, Bun, and Deno payloads are normalized to discriminated text or binary frames. Binary messages are never passed to TypedRouter JSON parsing. Use websocket.onRawFrame or server.subscribeWebSocketRawFrame(listener) for an additive synchronous listener; the subscription method returns an unsubscribe function. Deno sets binaryType = "arraybuffer"; an unexpected Blob is rejected instead of creating an asynchronous normalization backlog.

Each peer.rawFrameScheduler.wake() requests one turn. A turn pulls at most WEBSOCKET_RAW_PRIORITY_FRAME_MAX_PER_TURN priority text/ping/pong messages, then at most one binary message, and stops. The owner uses settlement and bufferedAmount to decide whether and when to wake again. Explicitly requested follow-up turns start in a later macrotask. Repeated wakes before a turn starts, or repeated wakes while one turn is running, coalesce into at most one pending follow-up turn. Binary messages larger than WEBSOCKET_RAW_BINARY_FRAME_MAX_BYTES (32 KiB) settle as rejected and are not split. The owner retains its queues and accounting and receives sent, accepted, failed, or rejected settlement. Bun resumes after its native drain callback only when an already-requested turn encountered backpressure; Deno reports native acceptance and bufferedAmount but cannot confirm network delivery or send explicit ping/pong control frames.

TypedRouter for Type-Safe RPC

Use @api.global/typedrequest for type-safe WebSocket communication:

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

const typedRouter = new TypedRouter();
typedRouter.addTypedHandler(MyTypedRequest, async (request, tools) => {
  return {
    result: 'processed',
    peerId: tools.localData.peer.id,
  };
});

const server = new SmartServe({
  port: 3000,
  websocket: {
    typedRouter,  // Handles message routing automatically
    onConnectionOpen: (peer) => {
      peer.tags.add('subscriber');
    },
  },
});

// Broadcast to tagged connections
server.broadcastWebSocketByTag('subscriber', { event: 'update' });

When typedRouter is configured, SmartServe supplies the accepted peer as server-owned tools.localData.peer for every handler. Caller-supplied localData is discarded, so a network client cannot forge the peer or its request context. SmartServe does not derive handler cancellation from wire data; cancellation-aware transports such as TypedSocket own trusted incoming request signal registration on the selected router.

Resolve a different router for each accepted connection when one listener serves isolated hosts or protocol surfaces:

const server = new SmartServe({
  port: 3000,
  authorityValidation: 'strict',
  websocket: {
    admit: (context) => allowedOrigins.has(context.headers.get('origin') ?? ''),
    resolveTypedRouter: (context) => {
      if (context.url.hostname === 'public.example.com') return publicRouter;
      if (context.url.hostname === 'admin.example.com') return adminRouter;
      return undefined;
    },
  },
});

The resolver runs once after admission and before upgrade. SmartServe binds the selected router to that peer for its full lifetime; returning undefined rejects the upgrade with 404. resolveTypedRouter is mutually exclusive with typedRouter and onMessage. Connection registry, connection lifecycle, tag-query, and broadcast APIs work whenever websocket is configured, including plain hooks, static or resolved TypedRouter, and generic transport-owner modes. The accepted peer exposes that exact immutable selection as peer.routingSurface; it is undefined when the connection has no TypedRouter. Transport owners can use object identity against this property when authorizing separately routed responses.


HTTPS/TLS

Enable HTTPS with certificate configuration:

import * as fs from 'fs';
import {
  SmartServe,
  validateNodeTlsConfig,
  type ITLSConfig,
} from '@push.rocks/smartserve';

const tls: ITLSConfig = {
  cert: fs.readFileSync('./cert.pem'),
  key: fs.readFileSync('./key.pem'),
  ca: fs.readFileSync('./ca.pem'),     // Optional: CA chain
  minVersion: 'TLSv1.2',               // Optional: minimum TLS version
  passphrase: 'optional-key-passphrase',
};

validateNodeTlsConfig(tls);

const server = new SmartServe({
  port: 443,
  tls,
});

validateNodeTlsConfig() checks Node.js ALPN identifier limits and parses the certificate, private key, optional CA, passphrase, minimum TLS version, and secure-context input without constructing a server or listener. This explicit preflight is useful when a caller must reject TLS input before creating other lifecycle resources. Bun and Deno keep their runtime-specific TLS semantics.


Error Handling

Built-in HTTP error classes with factory methods:

import { HttpError, type IRequestContext } from '@push.rocks/smartserve';

@Route('/api')
class ApiController {
  @Get('/users/:id')
  async getUser(ctx: IRequestContext) {
    const user = await findUser(ctx.params.id);

    if (!user) {
      throw HttpError.notFound('User not found', { id: ctx.params.id });
    }

    return user;
  }
}

// Available factory methods:
HttpError.badRequest(message, details);      // 400
HttpError.unauthorized(message, details);    // 401
HttpError.forbidden(message, details);       // 403
HttpError.notFound(message, details);        // 404
HttpError.conflict(message, details);        // 409
HttpError.internal(message, details);        // 500

Global Error Handler

const server = new SmartServe({
  port: 3000,
  onError: (error, request) => {
    console.error('💥 Server error:', error);

    // Return custom error response
    return new Response(
      JSON.stringify({ error: 'Something went wrong', requestId: crypto.randomUUID() }),
      { status: 500, headers: { 'Content-Type': 'application/json' } }
    );
  },
});

Request Context

Every handler receives a typed request context:

interface IRequestContext<TBody = unknown> {
  request: Request;              // Original Request (body never consumed by framework)
  params: Record<string, string>; // URL path parameters (/users/:id → { id: '123' })
  query: Record<string, string>; // Query string (?page=1 → { page: '1' })
  headers: Headers;              // Request headers
  path: string;                  // Matched route path
  method: THttpMethod;           // GET, POST, PUT, DELETE, etc.
  url: URL;                      // Full URL object
  runtime: 'node' | 'deno' | 'bun';
  state: Record<string, unknown>; // Per-request state (share data between interceptors)

  // 🔥 Lazy body parsing (cached after first call)
  json(): Promise<TBody>;        // Parse as JSON (typed!)
  text(): Promise<string>;       // Parse as text
  arrayBuffer(): Promise<ArrayBuffer>;
  formData(): Promise<FormData>;
}

Lazy Body Parsing: The request body is only consumed when you call json(), text(), etc. This allows raw access to ctx.request for cases like webhook signature verification:

@Post('/webhook')
async handleWebhook(ctx: IRequestContext) {
  // Get raw body for signature verification
  const rawBody = await ctx.request.text();
  const signature = ctx.headers.get('X-Signature');

  if (!verifyHmac(rawBody, signature)) {
    throw HttpError.unauthorized('Invalid signature');
  }

  // Parse the body manually
  const payload = JSON.parse(rawBody);
  return { processed: true };
}

Custom Request Handler

Bypass decorator routing entirely for low-level control:

const server = new SmartServe({ port: 3000 });

server.setHandler(async (request, connectionInfo) => {
  const url = new URL(request.url);

  if (url.pathname === '/health') {
    return new Response('OK', { status: 200 });
  }

  if (url.pathname.startsWith('/api')) {
    // Handle API routes manually
    const body = await request.json();
    return new Response(JSON.stringify({ received: body }), {
      headers: { 'Content-Type': 'application/json' },
    });
  }

  return new Response('Not Found', { status: 404 });
});

await server.start();

Runtime Detection

SmartServe automatically detects and optimizes for the current runtime:

const instance = await server.start();

console.log(instance.runtime);   // 'node' | 'deno' | 'bun'
console.log(instance.port);      // 3000
console.log(instance.hostname);  // '0.0.0.0'
console.log(instance.secure);    // true if TLS enabled

// Server statistics
const stats = instance.stats();
console.log(stats.uptime);           // Seconds since start
console.log(stats.requestsTotal);    // Total requests handled
console.log(stats.requestsActive);   // Currently processing

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
a cross platform server
Readme
1.9 MiB
Languages
TypeScript 100%