import { bodyParser } from "@koa/bodyparser"; import cors from "@koa/cors"; import multer, { File as MulterFile } from "@koa/multer"; import Router, { RouterContext } from "@koa/router"; import App, { Context, Context as Context$1, Middleware, Middleware as Middleware$1, Next, default as App$1 } from "koa"; import serve from "koa-static"; import { OutgoingHttpHeaders } from "node:http"; import { Catalog, I18n } from "@ttoss/i18n-core"; export * from "@koa/router"; //#region src/addHealthCheck.d.ts export interface AddHealthCheckOptions { /** * The Koa application instance to attach the health check to. */ app: App$1; /** * The path for the health endpoint. * @default '/health' */ path?: string; } /** * Adds a health check endpoint to the Koa application. * * @example * ```typescript * import { App, addHealthCheck } from '@ttoss/http-server'; * * const app = new App(); * addHealthCheck({ app }); * * app.listen(3000); * // GET /health returns { status: 'ok' } * ``` * * @example * ```typescript * // Custom path * addHealthCheck({ app, path: '/health' }); * ``` */ export declare const addHealthCheck: ({ app, path }: AddHealthCheckOptions) => void; //#endregion //#region src/dispatchInProcess.d.ts type InProcessRequest = { /** The HTTP method, in any case. */ method: string; /** The path plus any query string, e.g. `/api/v1/items?limit=10`. */ path: string; /** Request headers. An `undefined` value is left out. */ headers?: Record; /** The request body, sent as JSON. `undefined` sends none. */ body?: unknown; }; type InProcessResponse = { status: number; headers: OutgoingHttpHeaders; /** * The body as a client would read it: a JSON body is round-tripped through * `JSON.stringify`, so a `Date` arrives as its ISO string, and a `Buffer` as * UTF-8 text. `undefined` when the response has none. */ body: unknown; }; /** * Serves one request against a Koa app in this process, with no socket and no * port: the app's whole middleware chain runs, exactly as it would for a * request that arrived over the network. * * Useful when one surface of an application calls another — an MCP tool * dispatching to the REST route it was generated from — without a second * implementation of validation, authorization or error handling, and without * a loopback request to the process's own port. * * An error that escapes the middleware answers as Koa would answer it (its * `status`, or 500) and is emitted on the app's `error` event when it has a * listener. */ export declare const dispatchInProcess: ({ app, ...request }: InProcessRequest & { app: App$1; }) => Promise; //#endregion //#region src/httpError.d.ts /** * A deliberate, client-facing HTTP error normalized out of an unknown thrown * value — what `ctx.throw(401, 'Unauthorized', { headers })` produces. */ interface NormalizedHttpError { /** The 4xx status the thrower asked for. */ status: number; /** The message the thrower attached, safe to expose to the client. */ message: string; /** * Headers the thrower attached to the error (a `401`'s `WWW-Authenticate`, * for instance). Empty when the error carried none. */ headers: Record; } /** * Normalizes an error thrown by a library middleware — `authMiddleware`, * `createMcpRouter`'s `auth`, or any `ctx.throw` — into the status, message, * and headers a catch-all error middleware must preserve. * * An app with its own error envelope typically recognizes only its own error * class and turns everything else into a `500`. That swallows a deliberate * `401` **and its `WWW-Authenticate` header**, which is the whole RFC 9728 * discovery chain for MCP clients: the client gets an opaque server error where * it expected the pointer to the authorization server, so OAuth discovery never * starts. Run thrown values through this helper before falling back to `500`. * * Returns `undefined` for anything that is not a deliberate, exposable 4xx — * a genuine bug still becomes a `500` with nothing leaked. Only errors that opt * in via `expose === true` (which `http-errors` sets for 4xx) pass through. * * @example * ```typescript * import { applyHttpErrorHeaders, toHttpError } from '@ttoss/http-server'; * * app.use(async (ctx, next) => { * try { * await next(); * } catch (error) { * if (error instanceof ApiError) { * writeError(ctx, error); * return; * } * * const httpError = toHttpError(error); * * if (httpError) { * applyHttpErrorHeaders({ ctx, error }); * writeError(ctx, new ApiError(httpError.status, httpError.message)); * return; * } * * console.error('Unhandled request error:', error); * writeError(ctx, new ApiError(500, 'internal_error')); * } * }); * ``` */ export declare const toHttpError: (error: unknown) => NormalizedHttpError | undefined; /** * Copies the headers a thrower attached to an error onto the response — the * `WWW-Authenticate` header of a `401`, above all. * * Call it from a catch-all error middleware alongside {@link toHttpError}: * without this half the status is right but MCP discovery is still broken, * because the header that names the authorization server never reaches the * client. Non-string header values are ignored; a value that is not an error * object, or an error without headers, is a no-op. */ export declare const applyHttpErrorHeaders: ({ ctx, error }: { /** The Koa context whose response headers are being written. */ ctx: Context$1; /** The caught value, of unknown shape. */ error: unknown; }) => void; //#endregion //#region src/i18n.d.ts type Requested = string | string[] | null | undefined; /** What {@link i18nMiddleware} puts on `ctx.state`. */ type I18nState = { /** The negotiated locale. */ locale: string; /** Renders message references in {@link I18nState.locale}. */ i18n: I18n; }; /** * Negotiates the request locale and renders `LocalizedError`s at the HTTP * boundary. * * - Sets `ctx.state.locale` and `ctx.state.i18n` for handlers that render * message references themselves. The locale comes from `getUserLocale` (a * stored preference) first, then `Accept-Language`, then the catalog's * fallback. * - A thrown `LocalizedError` that is client-facing (a 4xx `status`, or the * `expected` marker) becomes `{ error: { code, message } }` with that status * (400 by default). * - Any other `LocalizedError` has its `message` rendered in place and is * rethrown, so the app's own error handling (and reporting) still sees it. * Every non-localized error is rethrown untouched. * * Mount it before the routes and after any catch-all error middleware. */ export declare const i18nMiddleware: ({ catalog, getUserLocale }: { catalog: Pick; getUserLocale?: (ctx: Context$1) => Requested | Promise; }) => Middleware$1; //#endregion //#region src/rateLimit.d.ts /** What one {@link RateLimiter.consume} call answers. */ interface RateLimitResult { /** Whether this request is inside the limit. It was counted only if so. */ allowed: boolean; /** Requests left in the current window after this one. */ remaining: number; /** When the current window ends, in epoch milliseconds. */ resetAt: number; } interface RateLimiter { /** Counts one request against `key`, unless the window is already full. */ consume: (args: { key: string; limit: number; }) => RateLimitResult; } /** * A fixed-window counter per key, held in this process's memory. * * In this process and no further: with N instances the effective limit is N * times the configured one. That is the right trade for stopping a runaway * client; a shared counter would put a store in the path of every request. * A fixed window allows a burst of twice the limit at a boundary, for the * same reason. * * Expired keys are swept at most once a window, inside `consume`, so a key * per IP does not grow memory without bound and no timer holds the process * open. */ export declare const createRateLimiter: ({ windowMs, now }: { windowMs: number; /** Clock, for tests. */ now?: () => number; }) => RateLimiter; /** * Koa middleware over {@link createRateLimiter}: a request over the limit is * answered `429` through `ctx.throw`, carrying `Retry-After`, so an error * middleware using `toHttpError` and `applyHttpErrorHeaders` keeps both. * * Every response carries `RateLimit-Limit`, `RateLimit-Remaining` and * `RateLimit-Reset` (seconds until the window ends). A `key` returning * `undefined` skips the limit for that request. * * When the key or the limit is only known inside the handler, use * `createRateLimiter` directly. */ export declare const rateLimit: ({ windowMs, limit, key, message, now }: { windowMs: number; limit: number | ((ctx: Context$1) => number); key: (ctx: Context$1) => string | undefined; message?: string; /** Clock, for tests. */ now?: () => number; }) => Middleware$1; //#endregion export { App, type Context, type I18nState, type InProcessRequest, type InProcessResponse, type Middleware, type MulterFile, type Next, type NormalizedHttpError, type RateLimitResult, type RateLimiter, Router, type RouterContext, bodyParser, cors, multer, serve };