@argos-js/core
v0.1.3
Published
Core routing, middleware engine, and application context for Argos-JS
Maintainers
Readme
@argos-js/core
The high-performance, enterprise-grade core engine and request lifecycle pipeline for the Argos-JS framework.
Argos-JS is a modular, high-throughput TypeScript backend framework engineered for high-concurrency enterprise workloads. It delivers an asynchronous runtime with zero global leaks, an $O(k)$ prefix Radix Tree router, built-in near-cache acceleration, compile-time request validation, and native ArgosDB database integration.
Quick Start
You can scaffold a full-featured Argos-JS project using our interactive CLI:
npx @argos-js/cli init meu-appOr install @argos-js/core directly into an existing TypeScript project:
# npm
npm install @argos-js/core
# pnpm
pnpm add @argos-js/coreMinimal Server Example
import { ArgosApp, v } from '@argos-js/core';
const app = new ArgosApp();
// Route with chainable schema validation
app.post('/api/users', async (ctx) => {
const user = await ctx.validate({
name: v.string().min(2, 'Name must have at least 2 characters'),
email: v.string().email('Invalid email address'),
});
return ctx.json({ success: true, user }, 201);
});
await app.listen(3000);
console.log('🚀 Argos server running at http://localhost:3000');Argos-JS Modular Ecosystem
Argos-JS follows a canonical modular architecture. Install only what your application requires:
| Package | Description |
|---------|-------------|
| @argos-js/core | HTTP routing ($O(k)$ Radix tree), middleware engine, validation, and lifecycle hooks |
| @argos-js/auth | JWT management (HS256, RS256, Ed25519), strict refresh rotation, HTTP Basic & OAuth2/PKCE |
| @argos-js/cache | Multi-tier caching with L1 near-cache memory, Redis, and Pulse CDC invalidation |
| @argos-js/argosdb | Direct edge client and type-safe query builder for ArgosDB |
| @argos-js/events | Event bus, CDC event streaming, and reactive message distribution |
| @argos-js/queue | High-throughput asynchronous background job queue and workers |
| @argos-js/routine | Distributed cron task scheduler with cluster overlap prevention |
| @argos-js/data | Enterprise data mapping, schema migrations, and tenancy tools |
| @argos-js/cli | Developer CLI for code generation, migrations, and interactive scaffolding |
| @argos-js/mail | Asynchronous transactional email delivery service (SMTP, Resend, SendGrid) |
| @argos-js/i18n | Fast zero-dependency internationalization and localization |
| @argos-js/bff | Backend-for-Frontend aggregation utilities and client gateway |
| @argos-js/net | Low-level TCP, HTTP adapters, and binary stream channel bindings |
Core Features
- ⚡ High-performance Radix router with route groups and wildcard parameters
- 🔄 High-Performance Lifecycle Hooks (
addHook):onRequest,preValidation,preHandler, andonResponsewith zero runtime overhead - 🚀 High-Throughput Schema-Based JSON Serializer (
ctx.json(data, schema)) inspired by Fastify with JIT string assembly and automated memoization - 🛡️ Built-in middleware pipeline (CORS, timing, logging, static files, error handling)
- 🔒 Native webhook HMAC signature verification
- 🧪 Context-driven architecture (
ArgosContext) with zero global leaks - 💎 Fluent Request Validation Engine (
v&ctx.validate) with compile-time type inference and automated 422 HTTP responses - 📖 Interactive API Docs & OpenAPI 3.1 Generator (
app.registerDocs): Zero-configuration Scalar UI documentation at/docsand dynamic OpenAPI 3.1.0 specification at/openapi.json
Fluent Request Validation
@argos-js/core provides a lightweight, chainable validation engine through the v utility, coupled directly with ctx.validate() on the request context.
The v Schema Builder
The v helper allows building expressive validation rules with strict TypeScript type inference:
| Validator | Methods | Description |
|-----------|---------|-------------|
| v.string() | .min(n, msg?), .max(n, msg?), .email(msg?), .optional() | String validations and email regex check |
| v.number() | .min(n, msg?), .max(n, msg?), .positive(msg?), .int(msg?), .optional() | Numeric checks, auto-coerces string numbers |
| v.boolean() | .optional() | Accepts booleans and common string flags ('true', 'false', '1', '0') |
| v.array(itemSchema) | .min(n, msg?), .max(n, msg?), .optional() | Validates array items against child schema |
| v.enum(values) | .optional() | Restricts values to an allowed set of literals |
| v.object(shape) | .optional() | Validates nested objects and maps errors per field |
Using ctx.validate()
The ctx.validate(schema, source?) method provides end-to-end type safety:
- Smart Default Source: Automatically selects
bodyforPOST,PUT, andPATCHrequests, andqueryforGETandDELETErequests. You can also specify'body','query', or'params'explicitly. - Strict Return Type: Returns the strongly typed, validated object without needing manual casts.
- Automated 422 Handling: If validation fails, execution halts immediately and returns an HTTP
422 Unprocessable Entityresponse with structured field error messages.
Example: POST Endpoint (Body Validation)
import { ArgosApp, v } from '@argos-js/core';
const app = new ArgosApp();
app.post('/api/users', async (ctx) => {
// Automatically reads and validates the JSON request body
const user = await ctx.validate({
name: v.string().min(2, 'Name must contain at least 2 characters').max(50),
email: v.string().email('Please provide a valid email'),
age: v.number().int().positive().min(18, 'Must be at least 18 years old').optional(),
role: v.enum(['admin', 'member', 'guest'] as const),
newsletter: v.boolean().optional(),
tags: v.array(v.string()).optional(),
});
// `user` is fully typed at compile-time:
// { name: string; email: string; age?: number; role: 'admin' | 'member' | 'guest'; ... }
return ctx.json({ success: true, user }, 201);
});Example: GET Endpoint (Query Parameters Validation)
app.get('/api/search', async (ctx) => {
// Automatically reads and validates query string parameters (?q=argos&page=2)
const query = await ctx.validate({
q: v.string().min(1, 'Search query cannot be empty'),
page: v.number().int().positive().optional(),
limit: v.number().int().min(1).max(100).optional(),
});
return ctx.json({ query });
});Error Response Format (HTTP 422)
When validation fails, Argos-JS automatically sends a structured response:
{
"success": false,
"error": "Validation failed",
"fields": {
"name": "Name must contain at least 2 characters",
"email": "Please provide a valid email",
"role": "The field must be one of: admin, member, guest"
}
}Interactive API Docs (Scalar & OpenAPI 3.1)
@argos-js/core provides automated OpenAPI 3.1.0 specification generation and an embedded Scalar UI interactive documentation engine.
Quick Setup
Enable interactive documentation with a single call on your ArgosApp instance:
import { ArgosApp, v, routeDoc } from '@argos-js/core';
const app = new ArgosApp();
// Enable Scalar UI on /docs and OpenAPI 3.1 spec on /openapi.json
app.registerDocs({
title: 'My Store API',
version: '1.0.0',
theme: 'purple',
});
// Documented route with validation and responses
app.post(
'/api/users',
routeDoc(
{
summary: 'Register a new customer',
tags: ['Users'],
body: v.object({
name: v.string().min(2),
email: v.string().email(),
nickname: v.string().nullable().optional(),
}),
response: {
201: {
description: 'User registered successfully',
schema: v.object({
id: v.string(),
name: v.string(),
}),
},
},
},
async (ctx) => {
const data = await ctx.validate({
name: v.string().min(2),
email: v.string().email(),
nickname: v.string().nullable().optional(),
});
return ctx.json({ id: 'usr_1', name: data.name }, 201);
}
)
);
app.listen(3000);Key Capabilities
- Automatic Radix Tree Inspection: Inspecion dynamic routes registered in the Radix Tree and converts
:paramtokens to OpenAPI{param}path templates (e.g./users/:id➔/users/{id}). - OpenAPI 3.1.0 JSON Schema Converter (
toJsonSchema): Converts Argosvvalidators (v.string(),v.number(),v.boolean(),v.enum(),v.array(),v.object()). - OpenAPI 3.1 Nullable Types: Generates
{ type: [type, 'null'] }when.nullable()modifier is present. - Automated 422 Response: Automatically adds standard HTTP 422 Unprocessable Entity error schema whenever input validation (
body,params, orquery) is detected. - Scalar UI Embed: Serves modern Scalar API reference CDN (
@scalar/api-reference) at/docs.
High-Throughput Schema-Based JSON Serialization
Inspired by Fastify's fast-json-stringify, @argos-js/core includes a compiled schema-based serialization engine. When serving high-traffic APIs, standard JSON.stringify introduces measurable overhead because V8 must dynamically inspect object prototypes and traverse every key with generic reflection.
By compiling a schema ahead-of-time with compileSerializer(schema) or simply passing schema into ctx.json(data, schema), Argos-JS unrolls the object's properties into a specialized, JIT-optimized string builder routine.
Performance Advantages
- 🚀 Zero Reflection at Runtime: Pre-computes key literals (e.g.
"\"name\":") and inlines primitive escapes directly. - ⚡ JIT Unrolled Property Access: Reads properties via fixed-offset access, maximizing V8 inline cache (IC) hits.
- 🔒 Automated Security Projection: Only fields explicitly declared in the schema are serialized. Unlisted database attributes (e.g., password hashes, internal tokens) are automatically omitted.
- 🧠 Internal Map Cache: Compiled functions are automatically cached per schema definition. Repeated requests incur zero recompilation cost.
- 🛡️ Safe Fallback: If no schema is passed to
ctx.json(data), standardJSON.stringify(data)is seamlessly preserved.
Usage in Route Handlers (ctx.json)
Pass any fluent schema definition (v.object, v.array, or plain shape records) directly as the second argument:
import { ArgosApp, v } from '@argos-js/core';
const app = new ArgosApp();
// Define response schema
const userResponseSchema = v.object({
id: v.number(),
username: v.string(),
email: v.string(),
role: v.enum(['admin', 'user', 'guest']),
tags: v.array(v.string()),
active: v.boolean(),
});
app.get('/api/users/:id', async (ctx) => {
const user = await fetchUser(ctx.params.id);
// ctx.json automatically compiles and caches the serializer for userResponseSchema
return ctx.json(user, userResponseSchema);
});
// Explicit HTTP Status Codes (e.g. 201 Created)
app.post('/api/users', async (ctx) => {
const newUser = await createUser(ctx.body);
return ctx.json(newUser, userResponseSchema, 201);
});Direct Compilation with compileSerializer
You can also pre-compile schemas directly for microservices, queues, or WebSocket payloads:
import { compileSerializer, v } from '@argos-js/core';
const metricSchema = v.object({
cpu: v.number(),
memory: v.number(),
timestamp: v.string(),
});
// Compile once (cached internally)
const stringifyMetric = compileSerializer(metricSchema);
const json = stringifyMetric({
cpu: 45.2,
memory: 1024,
timestamp: new Date().toISOString(),
internalKernelInfo: 'omitted-from-output',
});
// Output: {"cpu":45.2,"memory":1024,"timestamp":"2026-10-02T10:00:00.000Z"}Zero-Socket Request Injection (app.inject)
@argos-js/core provides a built-in in-memory request simulation engine via app.inject(). It dispatches HTTP requests directly through the application's registered middleware chain and route handlers without binding TCP ports or using OS network sockets.
Why Zero-Socket Testing?
- ⚡ Ultra Fast: Eliminates socket creation, network latency, and TCP handshake overhead.
- 🛡️ Zero Port Conflicts: Multiple test suites can run in parallel without competing for ports.
- 🧪 Complete Pipeline Coverage: Executes actual middlewares (CORS, timing, validation, auth) and route handlers.
InjectOptions
| Option | Type | Description |
|--------|------|-------------|
| method | 'GET' \| 'POST' \| 'PUT' \| 'PATCH' \| 'DELETE' \| string | HTTP method (default: 'GET') |
| url | string | Target URL path supporting query strings (e.g. '/search?q=argos') |
| headers | Record<string, string> | Optional custom HTTP headers |
| payload / body | any | Request body. Plain objects/arrays are automatically serialized to JSON with content-type: application/json |
| query | Record<string, string \| number \| boolean> | Optional structured query params |
InjectResponse
| Property / Method | Return Type | Description |
|-------------------|-------------|-------------|
| statusCode | number | HTTP status code (e.g. 200, 201, 422, 404) |
| headers | Record<string, string \| string[]> | Response headers |
| body | string | Raw response body string |
| json<T>() | T | Helper that parses body directly as JSON |
Unit & Integration Testing Examples
Testing GET with Query Parameters
import { describe, it, expect } from 'vitest';
import { ArgosApp } from '@argos-js/core';
describe('Search Controller', () => {
it('should return matching items from query string', async () => {
const app = new ArgosApp();
app.get('/search', (ctx) => {
return ctx.json({ term: ctx.query.q, page: Number(ctx.query.page || 1) });
});
const res = await app.inject({
method: 'GET',
url: '/search?q=argos&page=2',
});
expect(res.statusCode).toBe(200);
expect(res.json()).toEqual({ term: 'argos', page: 2 });
});
it('supports URL shorthand for simple GET requests', async () => {
const app = new ArgosApp();
app.get('/health', (ctx) => ctx.json({ ok: true }));
const res = await app.inject('/health');
expect(res.statusCode).toBe(200);
expect(res.json()).toEqual({ ok: true });
});
});Testing POST with Fluent Validation
import { describe, it, expect } from 'vitest';
import { ArgosApp, v } from '@argos-js/core';
describe('User Registration', () => {
const app = new ArgosApp();
app.post('/api/users', async (ctx) => {
const user = await ctx.validate({
name: v.string().min(2),
email: v.string().email(),
});
return ctx.created(user);
});
it('returns 201 Created on valid input', async () => {
const res = await app.inject({
method: 'POST',
url: '/api/users',
payload: { name: 'Alice', email: '[email protected]' },
});
expect(res.statusCode).toBe(201);
expect(res.json().data).toEqual({ name: 'Alice', email: '[email protected]' });
});
it('returns 422 Unprocessable Entity on validation failure', async () => {
const res = await app.inject({
method: 'POST',
url: '/api/users',
payload: { name: 'A', email: 'invalid-email' },
});
expect(res.statusCode).toBe(422);
const body = res.json();
expect(body.success).toBe(false);
expect(body.fields).toHaveProperty('name');
expect(body.fields).toHaveProperty('email');
});
});High-Performance Lifecycle Hooks (addHook)
@argos-js/core provides fine-grained lifecycle hooks inspired by high-throughput systems like Fastify. Hooks let you tap into specific phases of request execution with zero overhead:
- Pre-allocated arrays: Stored in dedicated arrays to eliminate dynamic hash-table lookups.
- Zero empty Promises: If no hook is registered for a given stage, execution skips immediately without allocating unnecessary microtasks.
- Early interruption: Returning an HTTP response from
onRequest,preValidation, orpreHandlerimmediately halts the execution pipeline.
Hook Stages
| Hook Stage | Signature | Description |
|------------|-----------|-------------|
| onRequest | (ctx) => Promise<res \| void> | Executed before routing resolution and body parsing (rate limiting, CORS, start timestamps). Returning a response aborts routing and controller execution. |
| preValidation | (ctx) => Promise<res \| void> | Executed before ctx.validate() and controller. Ideal for sanitization, trimming, and query/body normalization. |
| preHandler | (ctx) => Promise<res \| void> | Executed immediately before the controller. Returning a response aborts the controller execution. |
| onResponse | (ctx, payload) => Promise<void> | Executed after the response is finalized and ready to send. Ideal for structured APM logging and metrics collection. |
Examples
1. Structured Logging and APM Metrics (onRequest + onResponse)
import { ArgosApp } from '@argos-js/core';
const app = new ArgosApp();
// 1. Mark request arrival timestamp
app.addHook('onRequest', async (ctx) => {
(ctx as any)._startTime = performance.now();
});
// 2. Collect latency and emit APM metrics after response is ready
app.addHook('onResponse', async (ctx, payload) => {
const duration = (performance.now() - (ctx as any)._startTime).toFixed(2);
console.log(JSON.stringify({
timestamp: new Date().toISOString(),
method: ctx.method,
path: ctx.path,
statusCode: payload.statusCode,
latencyMs: Number(duration),
requestId: ctx.id,
}));
});2. Rate Limiting Guard (onRequest)
app.addHook('onRequest', async (ctx) => {
const clientIp = ctx.headers['x-forwarded-for'] || '127.0.0.1';
const isRateLimited = await checkRateLimit(clientIp);
if (isRateLimited) {
// Interrupts immediately: routing and controller are NOT executed
return ctx.json({ error: 'Too Many Requests', retryAfter: 60 }, 429);
}
});3. Payload Sanitization Before Validation (preValidation)
import { v } from '@argos-js/core';
// Trim whitespace and lower-case emails before validation runs
app.addHook('preValidation', async (ctx) => {
const body = ctx.bodyJson<Record<string, string>>();
if (body) {
if (typeof body.name === 'string') body.name = body.name.trim();
if (typeof body.email === 'string') body.email = body.email.trim().toLowerCase();
}
});
app.post('/api/users', async (ctx) => {
// ctx.validate automatically receives sanitized values!
const user = await ctx.validate({
name: v.string().min(2),
email: v.string().email(),
});
return ctx.json({ user }, 201);
});4. Authentication Guard (preHandler)
app.addHook('preHandler', async (ctx) => {
const token = ctx.headers['authorization'];
if (!token) {
return ctx.json({ error: 'Unauthorized: missing Bearer token' }, 401);
}
});High-Speed Radix Tree Router ($O(k)$)
@argos-js/core and @argos-js/net feature a zero-dependency, high-throughput Radix Tree (compressed prefix tree) routing engine. Instead of scanning an array of routes linearly ($O(n)$ regex searches), routing resolves in $O(k)$ time proportional only to the path length / segment count $k$.
Key Capabilities
- Strict Precedence Hierarchy: Resolves matching conflicts deterministically: $$\text{Static Nodes } (1) > \text{Parametric Nodes } (2) > \text{Wildcard Nodes } (3)$$
- Automatic Parameter Extraction: Fast extraction into
ctx.paramswith zero redundant heap allocations. - Smart Backtracking: If a static branch matches partially but dead-ends further down the path, the router automatically backtracks to parametric and wildcard alternatives.
- Per-Method Routing Trees: Dedicated trees for each HTTP method (
GET,POST,PUT,PATCH,DELETE,OPTIONS,HEAD). - Direct Router Inspection (
lookup): Programmatic lookup returning matched handler, hooks, middlewares, and extracted params without firing HTTP execution.
Route Matching Types
| Type | Syntax | Example | Matches |
|------|--------|---------|---------|
| Static | Exact path segment | /posts/popular | /posts/popular |
| Parametric | :paramName | /posts/:id | /posts/123, /posts/abc-def |
| Wildcard | * or *paramName | /static/*path | /static/css/theme.css, /static/js/app.min.js |
Precedence Example
Given the following route definitions:
app.get('/posts/popular', (ctx) => ctx.json({ type: 'static' }));
app.get('/posts/:id', (ctx) => ctx.json({ type: 'param', id: ctx.params.id }));
app.get('/posts/*', (ctx) => ctx.json({ type: 'wildcard' }));
// 1. Exact match hits static node
await app.inject('/posts/popular'); // => { type: 'static' }
// 2. Variable matches parametric node
await app.inject('/posts/42'); // => { type: 'param', id: '42' }
// 3. Trailing sub-path falls back to wildcard
await app.inject('/posts/42/details/extra'); // => { type: 'wildcard' }Route Inspection with app.lookup()
You can query the routing tree directly for debugging, metrics, or gateway forwarding:
const match = app.lookup('GET', '/orgs/argos-js/repos/core/issues/101');
if (match) {
console.log(match.handler); // [Function: issueController]
console.log(match.params); // { orgId: 'argos-js', repoId: 'core', issueId: '101' }
console.log(match.middlewares); // Array of route-level middlewares
console.log(match.hooks); // Route-level lifecycle hooks
} else {
console.log('No route matched (404)');
}License
MIT
