@zero-server/cli 0.9.1 → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,320 @@
1
+ import { Request } from './request';
2
+ import { Response } from './response';
3
+
4
+ // --- Core Types --------------------------------------------------
5
+
6
+ export type NextFunction = (err?: any) => void;
7
+ export type MiddlewareFunction = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;
8
+ export type ErrorHandlerFunction = (err: any, req: Request, res: Response, next: NextFunction) => void;
9
+
10
+ // --- CORS --------------------------------------------------------
11
+
12
+ export interface CorsOptions {
13
+ origin?: string | string[];
14
+ methods?: string;
15
+ allowedHeaders?: string;
16
+ exposedHeaders?: string;
17
+ credentials?: boolean;
18
+ maxAge?: number;
19
+ }
20
+
21
+ export function cors(options?: CorsOptions): MiddlewareFunction;
22
+
23
+ // --- Body Parsers ------------------------------------------------
24
+
25
+ export interface BodyParserOptions {
26
+ /** Max body size (e.g. '10kb', '1mb'). Default: '1mb'. */
27
+ limit?: string | number;
28
+ /** Content-Type(s) to match. Accepts a string, an array of strings, or a predicate function. */
29
+ type?: string | string[] | ((ct: string) => boolean);
30
+ /** Reject non-HTTPS requests with 403. */
31
+ requireSecure?: boolean;
32
+ /**
33
+ * Verification callback invoked with the raw buffer before parsing.
34
+ * Throw an error to reject the request with 403.
35
+ * Useful for webhook signature verification (e.g. Stripe, GitHub).
36
+ */
37
+ verify?: (req: import('./request').Request, res: import('./response').Response, buf: Buffer, encoding: string) => void;
38
+ /** Decompress gzip/deflate/br request bodies. Default: true. When false, compressed bodies return 415. */
39
+ inflate?: boolean;
40
+ }
41
+
42
+ export interface JsonParserOptions extends BodyParserOptions {
43
+ /** JSON.parse reviver function. */
44
+ reviver?: (key: string, value: any) => any;
45
+ /** Reject non-object/array roots. Default: true. */
46
+ strict?: boolean;
47
+ }
48
+
49
+ export interface UrlencodedParserOptions extends BodyParserOptions {
50
+ /** Enable nested bracket parsing. Default: false. */
51
+ extended?: boolean;
52
+ /** Max number of parameters. Default: 1000. Prevents parameter flooding DoS. */
53
+ parameterLimit?: number;
54
+ /** Max nesting depth for bracket syntax. Default: 32. Prevents deep-nesting DoS. */
55
+ depth?: number;
56
+ }
57
+
58
+ export interface TextParserOptions extends BodyParserOptions {
59
+ /** Fallback character encoding when Content-Type has no charset. Default: 'utf8'. */
60
+ encoding?: BufferEncoding;
61
+ }
62
+
63
+ export interface MultipartOptions {
64
+ /** Upload directory (default: OS temp). */
65
+ dir?: string;
66
+ /** Maximum size per file in bytes. */
67
+ maxFileSize?: number;
68
+ /** Reject non-HTTPS requests with 403. */
69
+ requireSecure?: boolean;
70
+ /** Maximum number of non-file fields. Default: 1000. */
71
+ maxFields?: number;
72
+ /** Maximum number of uploaded files. Default: 10. */
73
+ maxFiles?: number;
74
+ /** Maximum size of a single field value in bytes. Default: 1 MB. */
75
+ maxFieldSize?: number;
76
+ /** Whitelist of allowed MIME types for uploaded files (e.g. ['image/png', 'image/jpeg']). */
77
+ allowedMimeTypes?: string[];
78
+ /** Maximum combined size of all uploaded files in bytes. */
79
+ maxTotalSize?: number;
80
+ }
81
+
82
+ export interface MultipartFile {
83
+ originalFilename: string;
84
+ storedName: string;
85
+ path: string;
86
+ contentType: string;
87
+ size: number;
88
+ }
89
+
90
+ export function json(options?: JsonParserOptions): MiddlewareFunction;
91
+ export function urlencoded(options?: UrlencodedParserOptions): MiddlewareFunction;
92
+ export function text(options?: TextParserOptions): MiddlewareFunction;
93
+ export function raw(options?: BodyParserOptions): MiddlewareFunction;
94
+ export function multipart(options?: MultipartOptions): MiddlewareFunction;
95
+
96
+ // --- Rate Limiting -----------------------------------------------
97
+
98
+ export interface RateLimitOptions {
99
+ /** Time window in ms. Default: 60000. */
100
+ windowMs?: number;
101
+ /** Max requests per window per IP. Default: 100. */
102
+ max?: number;
103
+ /** Custom error message. */
104
+ message?: string;
105
+ /** HTTP status for rate-limited responses. Default: 429. */
106
+ statusCode?: number;
107
+ /** Custom key extraction function. */
108
+ keyGenerator?: (req: Request) => string;
109
+ /** Return true to skip rate limiting for this request. */
110
+ skip?: (req: Request) => boolean;
111
+ /** Custom handler for rate-limited requests (replaces default 429 JSON response). */
112
+ handler?: (req: Request, res: Response) => void;
113
+ }
114
+
115
+ export function rateLimit(opts?: RateLimitOptions): MiddlewareFunction;
116
+
117
+ // --- Logger ------------------------------------------------------
118
+
119
+ export interface LoggerOptions {
120
+ /** Custom log function. Default: console.log. */
121
+ logger?: (...args: any[]) => void;
122
+ /** Colorize output. Default: true when TTY. */
123
+ colors?: boolean;
124
+ /** Format: 'tiny' | 'short' | 'dev'. Default: 'dev'. */
125
+ format?: 'tiny' | 'short' | 'dev';
126
+ }
127
+
128
+ export function logger(opts?: LoggerOptions): MiddlewareFunction;
129
+
130
+ // --- Compression -------------------------------------------------
131
+
132
+ export interface CompressOptions {
133
+ /** Minimum body size to compress. Default: 1024. */
134
+ threshold?: number;
135
+ /** Compression level. */
136
+ level?: number;
137
+ /** Force specific encoding(s). */
138
+ encoding?: string | string[];
139
+ /** Filter function — return false to skip compression. */
140
+ filter?: (req: Request, res: Response) => boolean;
141
+ }
142
+
143
+ export function compress(opts?: CompressOptions): MiddlewareFunction;
144
+
145
+ // --- Helmet (Security Headers) ----------------------------------
146
+
147
+ export interface HelmetOptions {
148
+ /** CSP directive object or `false` to disable. */
149
+ contentSecurityPolicy?: { directives?: Record<string, string[]> } | false;
150
+ /** Set COEP header. Default: false. */
151
+ crossOriginEmbedderPolicy?: boolean;
152
+ /** COOP value. Default: 'same-origin'. */
153
+ crossOriginOpenerPolicy?: string | false;
154
+ /** CORP value. Default: 'same-origin'. */
155
+ crossOriginResourcePolicy?: string | false;
156
+ /** Set X-DNS-Prefetch-Control. Default: true. */
157
+ dnsPrefetchControl?: boolean | false;
158
+ /** X-Frame-Options value. Default: 'deny'. */
159
+ frameguard?: 'deny' | 'sameorigin' | false;
160
+ /** Remove X-Powered-By. Default: true. */
161
+ hidePoweredBy?: boolean;
162
+ /** Set HSTS. Default: true. */
163
+ hsts?: boolean | false;
164
+ /** HSTS max-age in seconds. Default: 15552000. */
165
+ hstsMaxAge?: number;
166
+ /** HSTS includeSubDomains. Default: true. */
167
+ hstsIncludeSubDomains?: boolean;
168
+ /** HSTS preload. Default: false. */
169
+ hstsPreload?: boolean;
170
+ /** Set X-Download-Options. Default: true. */
171
+ ieNoOpen?: boolean;
172
+ /** Set X-Content-Type-Options: nosniff. Default: true. */
173
+ noSniff?: boolean;
174
+ /** X-Permitted-Cross-Domain-Policies. Default: 'none'. */
175
+ permittedCrossDomainPolicies?: string | false;
176
+ /** Referrer-Policy value. Default: 'no-referrer'. */
177
+ referrerPolicy?: string | false;
178
+ /** Set legacy X-XSS-Protection. Default: false. */
179
+ xssFilter?: boolean;
180
+ }
181
+
182
+ export function helmet(opts?: HelmetOptions): MiddlewareFunction;
183
+
184
+ // --- Timeout -----------------------------------------------------
185
+
186
+ export interface TimeoutOptions {
187
+ /** HTTP status code for timeout responses. Default: 408. */
188
+ status?: number;
189
+ /** Error message body. Default: 'Request Timeout'. */
190
+ message?: string;
191
+ }
192
+
193
+ export function timeout(ms?: number, opts?: TimeoutOptions): MiddlewareFunction;
194
+
195
+ // --- Request ID --------------------------------------------------
196
+
197
+ export interface RequestIdOptions {
198
+ /** Response header name. Default: 'X-Request-Id'. */
199
+ header?: string;
200
+ /** Custom ID generator. */
201
+ generator?: () => string;
202
+ /** Trust incoming X-Request-Id. Default: false. */
203
+ trustProxy?: boolean;
204
+ }
205
+
206
+ export function requestId(opts?: RequestIdOptions): MiddlewareFunction;
207
+
208
+ // --- Cookie Parser -----------------------------------------------
209
+
210
+ export interface CookieParserStatic {
211
+ (secret?: string | string[], opts?: { decode?: boolean }): MiddlewareFunction;
212
+ /** Sign a value with a secret. */
213
+ sign(val: string, secret: string): string;
214
+ /** Unsign a signed value against one or more secrets. Returns the original value or false. */
215
+ unsign(val: string, secrets: string | string[]): string | false;
216
+ /** Serialize a value as a JSON cookie string (j: prefix). */
217
+ jsonCookie(val: any): string;
218
+ /** Parse a JSON cookie string (j: prefix). Returns parsed value or original string. */
219
+ parseJSON(str: string): any;
220
+ }
221
+
222
+ export const cookieParser: CookieParserStatic;
223
+
224
+ // --- Static File Serving -----------------------------------------
225
+
226
+ export interface StaticOptions {
227
+ /** Default file for directories. Default: 'index.html'. */
228
+ index?: string | false;
229
+ /** Cache-Control max-age in ms. Default: 0. */
230
+ maxAge?: number;
231
+ /** Dotfile policy: 'allow' | 'deny' | 'ignore'. Default: 'ignore'. */
232
+ dotfiles?: 'allow' | 'deny' | 'ignore';
233
+ /** Fallback extensions. */
234
+ extensions?: string[];
235
+ /** Custom header hook. */
236
+ setHeaders?: (res: Response, filePath: string) => void;
237
+ /** HTTP/2 push: list of asset paths or function returning them. Only triggers for HTML responses on HTTP/2 connections. */
238
+ pushAssets?: string[] | ((filePath: string) => string[]);
239
+ }
240
+
241
+ declare function serveStatic(root: string, options?: StaticOptions): MiddlewareFunction;
242
+ export { serveStatic as static };
243
+
244
+ // --- CSRF Protection ---------------------------------------------
245
+
246
+ export interface CsrfOptions {
247
+ /** Double-submit cookie name. Default: '_csrf'. */
248
+ cookie?: string;
249
+ /** Request header name for the token. Default: 'x-csrf-token'. */
250
+ header?: string;
251
+ /** Bytes of randomness for token generation. Default: 18. */
252
+ saltLength?: number;
253
+ /** HMAC secret. Auto-generated if not provided. */
254
+ secret?: string;
255
+ /** HTTP methods to skip CSRF checks. Default: ['GET', 'HEAD', 'OPTIONS']. */
256
+ ignoreMethods?: string[];
257
+ /** Path prefixes to skip CSRF checks. */
258
+ ignorePaths?: string[];
259
+ /** Custom error handler. Default: sends 403 JSON. */
260
+ onError?: (req: Request, res: Response) => void;
261
+ }
262
+
263
+ export function csrf(options?: CsrfOptions): MiddlewareFunction;
264
+
265
+ // --- Request Validator -------------------------------------------
266
+
267
+ export interface ValidationRule {
268
+ /** Type with coercion. */
269
+ type?: 'string' | 'integer' | 'number' | 'float' | 'boolean' | 'array' | 'json' | 'date' | 'uuid' | 'email' | 'url';
270
+ /** Field is required. */
271
+ required?: boolean;
272
+ /** Default value or factory function. */
273
+ default?: any | (() => any);
274
+ /** Minimum string length. */
275
+ minLength?: number;
276
+ /** Maximum string length. */
277
+ maxLength?: number;
278
+ /** Minimum numeric value. */
279
+ min?: number;
280
+ /** Maximum numeric value. */
281
+ max?: number;
282
+ /** Pattern match constraint. */
283
+ match?: RegExp;
284
+ /** Allowed values. */
285
+ enum?: any[];
286
+ /** Minimum array length. */
287
+ minItems?: number;
288
+ /** Maximum array length. */
289
+ maxItems?: number;
290
+ /** Custom validation function. Return a string to indicate an error. */
291
+ validate?: (value: any) => string | void;
292
+ }
293
+
294
+ export interface ValidatorSchema {
295
+ /** Rules for `req.body` fields. */
296
+ body?: Record<string, ValidationRule>;
297
+ /** Rules for `req.query` fields. */
298
+ query?: Record<string, ValidationRule>;
299
+ /** Rules for `req.params` fields. */
300
+ params?: Record<string, ValidationRule>;
301
+ }
302
+
303
+ export interface ValidatorOptions {
304
+ /** Remove fields not in schema. Default: true. */
305
+ stripUnknown?: boolean;
306
+ /** Custom error handler. Default: sends 422 JSON. */
307
+ onError?: (errors: string[], req: Request, res: Response) => void;
308
+ }
309
+
310
+ export interface ValidateFunction {
311
+ (schema: ValidatorSchema, options?: ValidatorOptions): MiddlewareFunction;
312
+
313
+ /** Validate a single field value against a rule. */
314
+ field(value: any, rule: ValidationRule, field: string): { value: any; error: string | null };
315
+
316
+ /** Validate an object against a schema. */
317
+ object(data: object, schema: Record<string, ValidationRule>, opts?: { stripUnknown?: boolean }): { sanitized: object; errors: string[] };
318
+ }
319
+
320
+ export const validate: ValidateFunction;
@@ -0,0 +1,304 @@
1
+ /// <reference types="node" />
2
+
3
+ import { Request } from './request';
4
+ import { Response } from './response';
5
+ import { MiddlewareFunction } from './middleware';
6
+
7
+ // -- Structured Logger --------------------------------------------
8
+
9
+ export interface LogEntry {
10
+ timestamp: string;
11
+ level: string;
12
+ message: string;
13
+ [key: string]: any;
14
+ }
15
+
16
+ export interface LoggerOptions {
17
+ /** Minimum log level. */
18
+ level?: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal' | 'silent' | number;
19
+ /** Bound context fields merged into every entry. */
20
+ context?: Record<string, any>;
21
+ /** Custom transport function. */
22
+ transport?: (entry: LogEntry) => void;
23
+ /** Force JSON output. */
24
+ json?: boolean;
25
+ /** Enable ANSI colors. Default: TTY detection. */
26
+ colors?: boolean;
27
+ /** Include timestamps. Default: true. */
28
+ timestamps?: boolean;
29
+ /** Output stream override. */
30
+ stream?: NodeJS.WritableStream;
31
+ }
32
+
33
+ export class Logger {
34
+ constructor(opts?: LoggerOptions);
35
+ /** Create a child logger with additional bound context. */
36
+ child(context: Record<string, any>): Logger;
37
+ /** Set the minimum log level. */
38
+ setLevel(level: string | number): Logger;
39
+ trace(message: string, fields?: Record<string, any> | Error): void;
40
+ debug(message: string, fields?: Record<string, any> | Error): void;
41
+ info(message: string, fields?: Record<string, any> | Error): void;
42
+ warn(message: string, fields?: Record<string, any> | Error): void;
43
+ error(message: string, fields?: Record<string, any> | Error): void;
44
+ fatal(message: string, fields?: Record<string, any> | Error): void;
45
+ }
46
+
47
+ export interface StructuredLoggerOptions {
48
+ /** Minimum log level. */
49
+ level?: string | number;
50
+ /** Output format. Default: 'json' in production, 'pretty' otherwise. */
51
+ format?: 'json' | 'pretty';
52
+ /** Custom transport function. */
53
+ transport?: (entry: LogEntry) => void;
54
+ /** Enable ANSI colors. */
55
+ colors?: boolean;
56
+ /** Include timestamps. */
57
+ timestamps?: boolean;
58
+ /** Output stream override. */
59
+ stream?: NodeJS.WritableStream;
60
+ /** Skip logging for certain requests. */
61
+ skip?: (req: Request, res: Response) => boolean;
62
+ /** Extra fields to merge into each request log entry. */
63
+ customFields?: (req: Request, res: Response) => Record<string, any>;
64
+ /** Custom message template. Supports :method, :url, :status, :duration. */
65
+ msg?: string;
66
+ }
67
+
68
+ export function structuredLogger(opts?: StructuredLoggerOptions): MiddlewareFunction;
69
+
70
+ // -- Metrics -------------------------------------------------------
71
+
72
+ export interface CounterOptions {
73
+ name: string;
74
+ help: string;
75
+ labels?: string[];
76
+ }
77
+
78
+ export class Counter {
79
+ readonly name: string;
80
+ readonly help: string;
81
+ readonly type: 'counter';
82
+ constructor(opts: CounterOptions);
83
+ inc(labels?: Record<string, string>, value?: number): void;
84
+ inc(value?: number): void;
85
+ get(labels?: Record<string, string>): number;
86
+ reset(): void;
87
+ collect(): string;
88
+ }
89
+
90
+ export interface GaugeOptions {
91
+ name: string;
92
+ help: string;
93
+ labels?: string[];
94
+ /** Callback invoked before collection to set dynamic values. */
95
+ collect?: (gauge: Gauge) => void;
96
+ }
97
+
98
+ export class Gauge {
99
+ readonly name: string;
100
+ readonly help: string;
101
+ readonly type: 'gauge';
102
+ constructor(opts: GaugeOptions);
103
+ set(labels: Record<string, string>, value: number): void;
104
+ set(value: number): void;
105
+ inc(labels?: Record<string, string>, value?: number): void;
106
+ inc(value?: number): void;
107
+ dec(labels?: Record<string, string>, value?: number): void;
108
+ dec(value?: number): void;
109
+ get(labels?: Record<string, string>): number;
110
+ reset(): void;
111
+ collect(): string;
112
+ }
113
+
114
+ export interface HistogramOptions {
115
+ name: string;
116
+ help: string;
117
+ labels?: string[];
118
+ /** Upper bounds for histogram buckets. */
119
+ buckets?: number[];
120
+ }
121
+
122
+ export class Histogram {
123
+ readonly name: string;
124
+ readonly help: string;
125
+ readonly type: 'histogram';
126
+ constructor(opts: HistogramOptions);
127
+ observe(labels: Record<string, string>, value: number): void;
128
+ observe(value: number): void;
129
+ startTimer(labels?: Record<string, string>): () => void;
130
+ get(labels?: Record<string, string>): { sum: number; count: number } | null;
131
+ reset(): void;
132
+ collect(): string;
133
+ }
134
+
135
+ export interface MetricsRegistryOptions {
136
+ /** Global prefix for all metric names. */
137
+ prefix?: string;
138
+ }
139
+
140
+ export class MetricsRegistry {
141
+ constructor(opts?: MetricsRegistryOptions);
142
+ counter(opts: CounterOptions): Counter;
143
+ gauge(opts: GaugeOptions): Gauge;
144
+ histogram(opts: HistogramOptions): Histogram;
145
+ getMetric(name: string): Counter | Gauge | Histogram | undefined;
146
+ removeMetric(name: string): boolean;
147
+ clear(): void;
148
+ resetAll(): void;
149
+ /** Serialize all metrics to Prometheus text format. */
150
+ metrics(): string;
151
+ /** Return all metrics as a plain object for JSON export or IPC transfer. */
152
+ toJSON(): Record<string, any>;
153
+ /** Merge a metrics snapshot from toJSON() into this registry. */
154
+ merge(snapshot: Record<string, any>): void;
155
+ }
156
+
157
+ export const DEFAULT_BUCKETS: number[];
158
+
159
+ export interface DefaultMetrics {
160
+ httpRequestsTotal: Counter;
161
+ httpRequestDuration: Histogram;
162
+ httpActiveConnections: Gauge;
163
+ wsConnectionsActive: Gauge;
164
+ sseStreamsActive: Gauge;
165
+ grpcCallsActive: Gauge;
166
+ grpcCallsTotal: Counter;
167
+ grpcCallDuration: Histogram;
168
+ dbQueryDuration: Histogram;
169
+ dbPoolActive: Gauge;
170
+ dbPoolIdle: Gauge;
171
+ }
172
+
173
+ export function createDefaultMetrics(registry: MetricsRegistry): DefaultMetrics;
174
+
175
+ export interface MetricsMiddlewareOptions {
176
+ registry?: MetricsRegistry;
177
+ /** Extract route label for metrics. */
178
+ routeLabel?: (req: Request) => string;
179
+ /** Skip metrics for certain requests. */
180
+ skip?: (req: Request) => boolean;
181
+ }
182
+
183
+ export function metricsMiddleware(opts?: MetricsMiddlewareOptions): MiddlewareFunction;
184
+ export function metricsEndpoint(registry: MetricsRegistry): (req: Request, res: Response) => void;
185
+
186
+ // -- Tracing -------------------------------------------------------
187
+
188
+ export class Span {
189
+ readonly name: string;
190
+ readonly traceId: string;
191
+ readonly spanId: string;
192
+ readonly parentSpanId: string | null;
193
+ readonly kind: string;
194
+ readonly attributes: Record<string, any>;
195
+ readonly events: Array<{ name: string; timestamp: number; attributes: Record<string, any> }>;
196
+ readonly status: { code: number; message?: string };
197
+ readonly startTime: number;
198
+ endTime: number | null;
199
+ readonly duration: number | null;
200
+ readonly traceparent: string;
201
+
202
+ constructor(opts: {
203
+ name: string;
204
+ traceId: string;
205
+ parentSpanId?: string;
206
+ kind?: string;
207
+ attributes?: Record<string, any>;
208
+ tracer?: Tracer;
209
+ });
210
+
211
+ setAttribute(key: string, value: string | number | boolean): Span;
212
+ setAttributes(attrs: Record<string, any>): Span;
213
+ addEvent(name: string, attributes?: Record<string, any>): Span;
214
+ setOk(): Span;
215
+ setError(message?: string): Span;
216
+ recordException(err: Error): Span;
217
+ end(): Span;
218
+ toJSON(): Record<string, any>;
219
+ }
220
+
221
+ export interface TracerOptions {
222
+ /** Service name for all spans. */
223
+ serviceName?: string;
224
+ /** Exporter function called with batches of serialised spans. */
225
+ exporter?: (spans: Record<string, any>[]) => void | Promise<void>;
226
+ /** Max spans per export batch. Default: 100. */
227
+ batchSize?: number;
228
+ /** Auto-flush interval in ms. Default: 5000. */
229
+ flushInterval?: number;
230
+ /** Sampling rate (0.0 to 1.0). Default: 1.0. */
231
+ sampleRate?: number;
232
+ /** Extra resource attributes. */
233
+ resource?: Record<string, any>;
234
+ }
235
+
236
+ export class Tracer {
237
+ readonly serviceName: string;
238
+ constructor(opts?: TracerOptions);
239
+ startSpan(name: string, opts?: {
240
+ traceId?: string;
241
+ parentSpanId?: string;
242
+ kind?: string;
243
+ attributes?: Record<string, any>;
244
+ }): Span;
245
+ shouldSample(): boolean;
246
+ onSpanEnd(fn: (span: Span) => void): Tracer;
247
+ flush(): Promise<void>;
248
+ shutdown(): Promise<void>;
249
+ }
250
+
251
+ export function parseTraceparent(header: string): { traceId: string; parentSpanId: string; traceFlags: number } | null;
252
+ export function formatTraceparent(traceId: string, spanId: string, flags?: number): string;
253
+
254
+ export interface TracingMiddlewareOptions {
255
+ tracer?: Tracer;
256
+ /** Extract route label for span name. */
257
+ routeLabel?: (req: Request) => string;
258
+ /** Skip tracing for certain requests. */
259
+ skip?: (req: Request) => boolean;
260
+ /** Propagate W3C trace context via response headers. Default: true. */
261
+ propagate?: boolean;
262
+ }
263
+
264
+ export function tracingMiddleware(opts?: TracingMiddlewareOptions): MiddlewareFunction;
265
+ export function instrumentFetch(fetchFn: Function, tracer: Tracer): Function;
266
+
267
+ // -- Health Checks -------------------------------------------------
268
+
269
+ export interface HealthCheckResult {
270
+ healthy: boolean;
271
+ details?: Record<string, any>;
272
+ }
273
+
274
+ export interface HealthCheckOptions {
275
+ /** Named check functions. */
276
+ checks?: Record<string, () => HealthCheckResult | boolean | Promise<HealthCheckResult | boolean>>;
277
+ /** Max time to wait for all checks in ms. Default: 5000. */
278
+ timeout?: number;
279
+ /** Include check details in response. Default: true. */
280
+ verbose?: boolean;
281
+ /** Called when any check fails. */
282
+ onFailure?: (results: Record<string, any>) => void;
283
+ }
284
+
285
+ export function healthCheck(opts?: HealthCheckOptions): (req: Request, res: Response) => Promise<void>;
286
+
287
+ export interface CreateHealthHandlersOptions {
288
+ checks?: Record<string, () => HealthCheckResult | boolean | Promise<HealthCheckResult | boolean>>;
289
+ includeMemory?: boolean;
290
+ includeEventLoop?: boolean;
291
+ timeout?: number;
292
+ onFailure?: (results: Record<string, any>) => void;
293
+ memoryOpts?: { maxHeapUsedPercent?: number; maxRssBytes?: number };
294
+ eventLoopOpts?: { maxLagMs?: number };
295
+ }
296
+
297
+ export function createHealthHandlers(opts?: CreateHealthHandlersOptions): {
298
+ health: (req: Request, res: Response) => Promise<void>;
299
+ ready: (req: Request, res: Response) => Promise<void>;
300
+ };
301
+
302
+ export function memoryCheck(opts?: { maxHeapUsedPercent?: number; maxRssBytes?: number }): () => HealthCheckResult;
303
+ export function eventLoopCheck(opts?: { maxLagMs?: number }): (() => HealthCheckResult) & { _cleanup(): void };
304
+ export function diskSpaceCheck(opts?: { minFreeBytes?: number }): () => HealthCheckResult;