API Reference
Core
initSegment
Creates Next.js App Route handlers used by the main Optional Catch-all Segment . The function accepts the following options:
segmentName?: string- the name of the segment that will be used in the route. Default is an empty string (root segment).controllers: Record<string, Function>- the list of controllers.exposeValidation?: boolean- set tofalseif you want to hide validation logic from the client-side code.emitSchema?: boolean- set totrueif you want to emit the schema for the segment. The schema will be emitted to the .vovk-schema folder.onError?: (err: Error, req: VovkRequest) => void | Promise<void>- called on controller exceptions; can be used to log errors by a third-party service. The second argument can be utilized to retrieve the request URL, authorization info, and other useful information about the failed request.
JSONLinesResponse
JSONLinesResponse is a utility class for creating responses in the JSON Lines format. It extends the standard Response class and adds support for streaming JSON objects as individual lines. See the JSON Lines documentation for more info.
Decorators
@get, @post, @put, @patch, @del, @head, @options
HTTP method decorators define an HTTP method for a handler. They accept two optional arguments:
path? = ''- the path for the route.opts?: { cors?: boolean, headers?: Record<string, string>, staticParams?: Record<string, string>[] }- options for the route.- If
corsis set totrue, it will add CORS headers to the response and make theOPTIONSHTTP method properly handled. headersis an object with headers to be added to the response.staticParams(@getdecorator only) is an array of objects with static parameters that can be used in the route path, e.g.,[{ id: '123' }].
- If
import { get } from 'vovk';
export default class HelloController {
@get('world', { cors: true, headers: { 'x-hello': 'world' }, staticParams: [{ id: '123' }] })
static getHelloWorld(req, { id }: { id: string }) {
return { hello: 'world', id };
}
}Each decorator has an .auto() method that can be used to generate the path automatically based on the controller and method names. It accepts the same options as the decorator itself.
import { get } from 'vovk';
export default class HelloController {
@get.auto({ cors: true, headers: { 'x-hello': 'world' }, staticParams: [{ id: '123' }] })
static getHelloWorld(req, { id }: { id: string }) {
return { hello: 'world', id };
}
}@prefix
The @prefix(p: string) decorator is used to prepend a sub-path to the endpoint. Its use is optional.
import { prefix, get } from 'vovk';
@prefix('hello')
export default class HelloController {
@get('world')
static getHelloWorld() {
return { hello: 'world' };
}
}@operation
The @operation(openAPIOperationObject) decorator can be used to add OpenAPI documentation to the controller method. It accepts an object with summary, description, and other OpenAPI Operation Object properties.
It also accepts custom AI-related properties, such as x-tool-description, which can be used to generate LLM tools. Read more about it in the function calling documentation.
import { operation } from 'vovk';
export default class HelloController {
@operation({
summary: 'Get Hello World',
description: 'Returns a hello world message',
})
@get('world')
static getHelloWorld() {
return { hello: 'world' };
}
}Utils
createDecorator
createDecorator is a higher-order function that produces a decorator factory (a function that returns a decorator) for controller class methods. It accepts a middleware function with the following parameters:
import { createDecorator, get } from 'vovk';
const myDecorator = createDecorator(
(req, next, a: string, b: number) => {
// do something with the request
},
(a: string, b: number) => {
// modify schema here
}
);
export default class MyController {
@get.auto()
@myDecorator('foo', 1) // Passes 'foo' as 'a', and 1 as 'b'
static doSomething() {
// ...
}
}See the decorators docs for more info.
fetcher
Function that creates a data-fetching layer for the RPC client. It handles HTTP requests, client-side validation, and response parsing. It’s imported by the generated TypeScript, ESM, and CJS files and can be customized in the config. A new fetcher can be created using the createFetcher function.
createFetcher
Function that creates a custom fetcher for the RPC client. It accepts a generic type parameter that defines the options for the resulting RPC methods. The function returns a fetcher function that will be used in the createRPC function.
import { createFetcher } from 'vovk';
export const fetcher = createFetcher<{
successMessage?: string; // "Successfully created a new user"
useAuth?: boolean; // if true, Authorization header will be set
someOtherCustomFlag?: boolean; // any custom flag that you want to pass to the RPC method
}>({
prepareRequestInit: async (init, { useAuth, someOtherCustomFlag }) => {
// ...
return {
...init,
headers: {
...init.headers,
...(useAuth ? { Authorization: 'Bearer token' } : {}),
},
};
},
transformResponse: async (data, { someOtherCustomFlag }) => {
// ...
return {
...data,
};
},
onSuccess: async (data, { successMessage }) => {
if (successMessage) {
alert(successMessage);
}
},
onError: async (error) => {
alert(error.message);
},
});generateStaticAPI
Function that generates an API that is created at build time instead of on-demand at request time. It accepts a record of controllers and an optional slug that is used to generate the static API path. The function returns an array of static parameters that can be used in the generateStaticParams function.
// ...
export type Controllers = typeof controllers;
export function generateStaticParams() {
return generateStaticAPI(controllers);
}
export const { GET } = initSegment({ controllers });See the static segment documentation for more info.
withValidationLibrary (advanced)
A lower-order function that allows to create a custom validation function for controller methods. See the source code of the Zod 3 validation library for an example.
createStandardValidation
Creates a custom validation library that uses Standard Schema. The only option for this function is the toJSONSchema function, which defines how to convert the models to JSON Schema format.
import type { type } from 'arktype';
import { createStandardValidation } from 'vovk';
export const withArk = createStandardValidation({
toJSONSchema: (model: type) => model.toJsonSchema(),
});import { prefix, post, operation } from 'vovk';
import { type } from 'arktype';
import { withArk } from '@/lib/withArk';
@prefix('users')
export default class UserController {
@operation({
summary: 'Update user',
description: 'Update user by ID with',
})
@post('{id}')
static updateUser = withArk({
body: type({
name: type('string').describe('User full name'),
age: type('0 < number < 120').describe('User age'),
email: type('string.email').describe('User email'),
}),
// ...
async handle(req, { id }) {
// ...
},
});
}Read more about it on Standard Schema page.
multitenant
A Next.js middleware utility that routes subdomains to specific segments.
// ... middleware ...
const { action, destination, message, subdomains } = multitenant({
requestUrl: request.url,
requestHost: request.headers.get('host') ?? '',
targetHost: process.env.VERCEL ? 'multitenant.vovk.dev' : 'localhost:3000',
overrides: {
// ...
},
});
// ...For more info, check the multitenant guide.
createLLMTools
A utility function that turns RPC modules or controllers into LLM tools based on the input schemas of their methods.
import { createLLMTools } from 'vovk';
import { UserRPC } from 'vovk-client';
import TaskController from '@/modules/task/TaskController';
const { tools, toolsByName } = createLLMTools({
meta: { hello: 'world' },
modules: {
UserRPC,
TaskController,
},
resultFormatter: (result) => `Result: ${JSON.stringify(result, null, 2)}`,
onExecute: (result, { moduleName, handlerName, body, query, params }) =>
console.log(`${moduleName}.${handlerName} executed with`, {
body,
query,
params,
result,
}),
onError: (e) => console.error("Error", e),
});For more info, check the function calling guide.
modules
Key-value object where keys are module names and values are objects with methods. Each method should have a schema: VovkHandlerSchema property and either isRPC: true (for RPC modules) or the fn function (for controllers).
onExecute
Called after each tool execution. Accepts 2 arguments: result - the result of the tool execution, and an object with extra info.
onError
Called when an error is thrown during tool execution. Accepts 1 argument: the error object.
resultFormatter: 'mcp' | Function
A function that formats the result of the tool execution. It accepts 2 arguments: the result of the tool execution and the handler schema: VovkHandlerSchema. The function should return data in a format that’s sent back to the LLM when the function is executed. If set to 'mcp', it will format the result in a way that is compatible with the MCP format ({ content: [{ type: 'text', text: 'Serialized result text' }] }).
meta
Data that will be passed as the meta property of each function (controller handler or RPC method). See meta for more info.
caller (advanced)
The low-level function that calls the handler function or RPC method. Check the source code of the defaultCaller function for more info.
createValidateOnClient
Creates the validateOnClient function, which is used to define how client-side validation should be performed for RPC methods for all segments or for some segments. createValidateOnClient accepts a validate property that receives input data, validation schema, and some additional options, and returns the validated data or throws an error if validation fails.
import { validateData } from 'validation-library';
import { createValidateOnClient, HttpException, HttpStatus } from 'vovk';
export const validateOnClient = createValidateOnClient({
validate: async (input, schema, meta) => {
const isValid = validateData(input, schema);
if (!isValid) {
throw new HttpException(HttpStatus.NULL, 'Validation failed');
}
return input;
},
});For more details on client-side validation, see the Client Validation section.
progressive
An experimental utility function that allows you to make one request and get multiple responses, each resolved as a promise separately.
const { users: usersPromise, tasks: tasksPromise } = progressive(ProgressiveRPC.streamProgressiveResponse);Read more about it in the progressive responses documentation.
HttpException
A custom error class that extends the built-in Error class. It represents an HTTP error with a status code and a message. It can be used to throw errors in controller methods and is caught by the framework to return proper HTTP responses.
import { HttpException, HttpStatus } from 'vovk';
throw new HttpException(HttpStatus.BAD_REQUEST, 'Invalid request', { some: 'cause' });The third argument is optional and can be used to pass additional data that can be useful for logging or debugging and can be accessed via the error.cause property on the client side.
Read more about it in the error handling documentation.
Inference Types
VovkOutput
Allows you to infer the output type of the controller method or RPC method when output validation is used: VovkOutput<typeof MyController.method> or VovkOutput<typeof MyRPC.method>.
VovkIteration
Allows you to infer the iteration type of the controller method or RPC method when iteration validation is used: VovkIteration<typeof MyController.method> or VovkIteration<typeof MyRPC.method>.
VovkBody
Allows you to infer the type of the request input body of the controller method or RPC method when body validation is used: VovkBody<typeof MyController.method> or VovkBody<typeof MyRPC.method>.
VovkQuery
Allows you to infer the type of the request query of the controller method or RPC method when query validation is used: VovkQuery<typeof MyController.method> or VovkQuery<typeof MyRPC.method>.
VovkParams
Allows you to infer the type of the request params of the controller method or RPC method when params validation is used: VovkParams<typeof MyController.method> or VovkParams<typeof MyRPC.method>.
VovkReturnType
As output validation isn’t required, the VovkReturnType type allows you to infer the returned type of the controller method or RPC method: VovkReturnType<typeof MyController.method> or VovkReturnType<typeof MyRPC.method>.
VovkYieldType
As iteration validation isn’t required, the VovkYieldType type allows you to infer the yielded type of the controller method or RPC method: VovkYieldType<typeof MyController.method> or VovkYieldType<typeof MyRPC.method>.
Other Types and Enums
VovkRequest
Extends the Next.js built-in NextRequest object to make it return proper types for .json(), .nextUrl.searchParams, and also adds a vovk property that provides more advanced input retrieval methods.
See the request documentation for more info.
HttpStatus enum
Used to throw and catch errors thrown by the server. Notice the NULL member. It can be used to simulate HTTP errors on client validation errors (this approach is used in vovk-zod ).
export enum HttpStatus {
NULL = 0,
CONTINUE = 100,
SWITCHING_PROTOCOLS = 101,
PROCESSING = 102,
EARLYHINTS = 103,
OK = 200,
CREATED = 201,
ACCEPTED = 202,
NON_AUTHORITATIVE_INFORMATION = 203,
NO_CONTENT = 204,
RESET_CONTENT = 205,
PARTIAL_CONTENT = 206,
AMBIGUOUS = 300,
MOVED_PERMANENTLY = 301,
FOUND = 302,
SEE_OTHER = 303,
NOT_MODIFIED = 304,
TEMPORARY_REDIRECT = 307,
PERMANENT_REDIRECT = 308,
BAD_REQUEST = 400,
UNAUTHORIZED = 401,
PAYMENT_REQUIRED = 402,
FORBIDDEN = 403,
NOT_FOUND = 404,
METHOD_NOT_ALLOWED = 405,
NOT_ACCEPTABLE = 406,
PROXY_AUTHENTICATION_REQUIRED = 407,
REQUEST_TIMEOUT = 408,
CONFLICT = 409,
GONE = 410,
LENGTH_REQUIRED = 411,
PRECONDITION_FAILED = 412,
PAYLOAD_TOO_LARGE = 413,
URI_TOO_LONG = 414,
UNSUPPORTED_MEDIA_TYPE = 415,
REQUESTED_RANGE_NOT_SATISFIABLE = 416,
EXPECTATION_FAILED = 417,
I_AM_A_TEAPOT = 418,
MISDIRECTED = 421,
UNPROCESSABLE_ENTITY = 422,
FAILED_DEPENDENCY = 424,
PRECONDITION_REQUIRED = 428,
TOO_MANY_REQUESTS = 429,
INTERNAL_SERVER_ERROR = 500,
NOT_IMPLEMENTED = 501,
BAD_GATEWAY = 502,
SERVICE_UNAVAILABLE = 503,
GATEWAY_TIMEOUT = 504,
HTTP_VERSION_NOT_SUPPORTED = 505,
}VovkSchema
The full schema of the composed client or for a segment in the segmented client. Can be represented as
{
segments: { [key: string]: VovkSegmentSchema };
meta?: VovkMetaSchema
}VovkSegmentSchema
The schema of a segment. Contains segment information and a record of controllers. Can be represented as
{
controllers: { [key: string]: VovkControllerSchema };
segmentName: string;
segmentType: 'segment' | 'mixin'
}VovkControllerSchema
The schema of a controller. Can be represented as
{
rpcModuleName: string;
originalControllerName?: string;
prefix?: string;
forceApiRoot?: string;
handlers: { [key: string]: VovkHandlerSchema }
}VovkHandlerSchema
The schema of a handler. Contains paths, HTTP methods, validation schemas, etc.
VovkMetaSchema
The schema of the meta information.
VovkConfig
The shape of the config file.
VovkLLMTool
The shape of the LLM tool created by the createLLMTools function.
System Functions for Additional Hacking (Advanced)
createVovkApp
An internal function that creates the Vovk.ts app with the decorators and init function.
export const { get, post, put, patch, del, head, options, prefix, initSegment } = createVovkApp();createRPC
Function that creates RPC modules out of the schema and types inferred from controllers. It’s imported by the generated TypeScript, ESM, and CJS files and can be customized in the config.
createCodeSamples
Creates code samples that are used by Scalar and README.md generators.
openAPIToVovkSchema
Converts OpenAPI schema to Vovk.ts schema.
vovkSchemaToOpenAPI
Converts Vovk.ts schema to OpenAPI schema.
resolveGeneratorConfigValues
Resolves the generator config values for a specific case (if it’s a bundle, segmented or composed client, etc.) based on the provided schema and options.
System Types
KnownAny
The only type that isn’t named with the Vovk prefix; represents any.
VovkRPCModule
An object that represents an RPC module created by the createRPC function.
VovkFetcher
An object that represents a fetcher function used to make API requests.
VovkFetcherOptions
An object that represents the options for the fetcher function.
VovkStreamAsyncIterable
The iterable object returned by an RPC method for JSON Lines responses. Besides Symbol.asyncIterator, Symbol.dispose, and Symbol.asyncDispose methods, it also contains a status property with the HTTP status code, an asPromise method that resolves all data as a single promise, an onIterate method that accepts a callback function and calls it on each iteration, and a abortController: AbortController that aborts the request with the abortController.abort() method.
const response = await StreamRPC.streamLines();
for await (const item of response) {
console.log(item);
if(something) {
response.abortController.abort();
}
}
const allItems = await response.asPromise();VovkValidateOnClient
A function that represents the client-side validation function created by the createValidateOnClient function.
VovkErrorResponse
The shape of error responses.
VovkTypedMethod
An internal type used by the withValidationLibrary function that adds required types to the controller method for further inference.
VovkBasicJSONSchema
A basic JSON Schema object used internally with type, properties, and all other JSON Schema keywords.
VovkSchemaIdEnum
An enum that contains IDs of the JSON Schema files that are generated by Vovk.ts.
export enum VovkSchemaIdEnum {
META = 'https://vovk.dev/api/schema/v3/meta.json',
CONFIG = 'https://vovk.dev/api/schema/v3/config.json',
SEGMENT = 'https://vovk.dev/api/schema/v3/segment.json',
SCHEMA = 'https://vovk.dev/api/schema/v3/schema.json',
}VovkOperationObject
Extends OperationObject imported from the openapi3-ts/oas31 package by adding LLM-tool-specific properties that start with x-tool-.
VovkValidationType
A union type of possible validation types.
export type VovkValidationType = 'body' | 'query' | 'params' | 'output' | 'iteration';VovkStrictConfig
An internal type that represents the config file with all default values applied.
VovkOutputConfig
The configuration options for the generator that can be defined as root-level outputConfig, outputConfig.segments[segmentName], bundle.outputConfig, or templateDef.outputConfig in the config file. The actual values are resolved by the resolveGeneratorConfigValues function.
VovkReadmeConfig
The configuration options for README generation at VovkOutputConfig.readme, such as banner, installCommand, or description.
VovkSamplesConfig
The configuration options for code samples generation at VovkOutputConfig.samples, such as apiRoot or headers.
VovkPackageJson
The configuration options for the package.json generation. Has extra keys rs_name and py_name that are used to override the name field for Rust and Python packages.
VovkOpenAPIMixin
The configuration options for OpenAPI generation at VovkOutputConfig.openAPIMixin. See OpenAPI Mixins for more info.