@zero-server/sdk 0.9.0 → 0.9.2

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.
Files changed (126) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +460 -437
  3. package/index.js +414 -412
  4. package/lib/app.js +1172 -1172
  5. package/lib/auth/authorize.js +399 -399
  6. package/lib/auth/enrollment.js +367 -367
  7. package/lib/auth/index.js +57 -57
  8. package/lib/auth/jwt.js +731 -731
  9. package/lib/auth/oauth.js +362 -362
  10. package/lib/auth/session.js +588 -588
  11. package/lib/auth/trustedDevice.js +409 -409
  12. package/lib/auth/twoFactor.js +1150 -1150
  13. package/lib/auth/webauthn.js +946 -946
  14. package/lib/body/index.js +14 -14
  15. package/lib/body/json.js +109 -109
  16. package/lib/body/multipart.js +440 -440
  17. package/lib/body/raw.js +71 -71
  18. package/lib/body/rawBuffer.js +160 -160
  19. package/lib/body/sendError.js +25 -25
  20. package/lib/body/text.js +75 -75
  21. package/lib/body/typeMatch.js +41 -41
  22. package/lib/body/urlencoded.js +235 -235
  23. package/lib/cli.js +845 -845
  24. package/lib/cluster.js +666 -666
  25. package/lib/debug.js +372 -372
  26. package/lib/env/index.js +460 -460
  27. package/lib/errors.js +683 -683
  28. package/lib/fetch/index.js +256 -256
  29. package/lib/grpc/balancer.js +378 -378
  30. package/lib/grpc/call.js +708 -708
  31. package/lib/grpc/client.js +764 -764
  32. package/lib/grpc/codec.js +1221 -1221
  33. package/lib/grpc/credentials.js +398 -398
  34. package/lib/grpc/frame.js +262 -262
  35. package/lib/grpc/health.js +287 -287
  36. package/lib/grpc/index.js +121 -121
  37. package/lib/grpc/metadata.js +461 -461
  38. package/lib/grpc/proto.js +821 -821
  39. package/lib/grpc/reflection.js +590 -590
  40. package/lib/grpc/server.js +445 -445
  41. package/lib/grpc/status.js +118 -118
  42. package/lib/grpc/watch.js +173 -173
  43. package/lib/http/index.js +10 -10
  44. package/lib/http/request.js +727 -727
  45. package/lib/http/response.js +799 -799
  46. package/lib/lifecycle.js +557 -557
  47. package/lib/middleware/compress.js +230 -230
  48. package/lib/middleware/cookieParser.js +237 -237
  49. package/lib/middleware/cors.js +93 -93
  50. package/lib/middleware/csrf.js +136 -136
  51. package/lib/middleware/errorHandler.js +101 -101
  52. package/lib/middleware/helmet.js +175 -175
  53. package/lib/middleware/index.js +19 -17
  54. package/lib/middleware/logger.js +74 -74
  55. package/lib/middleware/rateLimit.js +88 -88
  56. package/lib/middleware/requestId.js +53 -53
  57. package/lib/middleware/static.js +326 -326
  58. package/lib/middleware/timeout.js +71 -71
  59. package/lib/middleware/validator.js +254 -254
  60. package/lib/observe/health.js +326 -326
  61. package/lib/observe/index.js +50 -50
  62. package/lib/observe/logger.js +359 -359
  63. package/lib/observe/metrics.js +805 -805
  64. package/lib/observe/tracing.js +592 -592
  65. package/lib/orm/adapters/json.js +290 -290
  66. package/lib/orm/adapters/memory.js +764 -764
  67. package/lib/orm/adapters/mongo.js +764 -764
  68. package/lib/orm/adapters/mysql.js +933 -933
  69. package/lib/orm/adapters/postgres.js +1144 -1144
  70. package/lib/orm/adapters/redis.js +1534 -1534
  71. package/lib/orm/adapters/sql-base.js +212 -212
  72. package/lib/orm/adapters/sqlite.js +858 -858
  73. package/lib/orm/audit.js +649 -649
  74. package/lib/orm/cache.js +394 -394
  75. package/lib/orm/geo.js +387 -387
  76. package/lib/orm/index.js +784 -784
  77. package/lib/orm/migrate.js +432 -432
  78. package/lib/orm/model.js +1706 -1706
  79. package/lib/orm/plugin.js +375 -375
  80. package/lib/orm/procedures.js +836 -836
  81. package/lib/orm/profiler.js +233 -233
  82. package/lib/orm/query.js +1772 -1772
  83. package/lib/orm/replicas.js +241 -241
  84. package/lib/orm/schema.js +307 -307
  85. package/lib/orm/search.js +380 -380
  86. package/lib/orm/seed/data/commerce.js +136 -136
  87. package/lib/orm/seed/data/internet.js +111 -111
  88. package/lib/orm/seed/data/locations.js +204 -204
  89. package/lib/orm/seed/data/names.js +338 -338
  90. package/lib/orm/seed/data/person.js +128 -128
  91. package/lib/orm/seed/data/phone.js +211 -211
  92. package/lib/orm/seed/data/words.js +134 -134
  93. package/lib/orm/seed/factory.js +178 -178
  94. package/lib/orm/seed/fake.js +1186 -1186
  95. package/lib/orm/seed/index.js +18 -18
  96. package/lib/orm/seed/rng.js +70 -70
  97. package/lib/orm/seed/seeder.js +124 -124
  98. package/lib/orm/seed/unique.js +68 -68
  99. package/lib/orm/snapshot.js +366 -366
  100. package/lib/orm/tenancy.js +605 -605
  101. package/lib/orm/views.js +350 -350
  102. package/lib/router/index.js +436 -436
  103. package/lib/sse/index.js +8 -8
  104. package/lib/sse/stream.js +349 -349
  105. package/lib/ws/connection.js +451 -451
  106. package/lib/ws/handshake.js +125 -125
  107. package/lib/ws/index.js +14 -14
  108. package/lib/ws/room.js +223 -223
  109. package/package.json +73 -73
  110. package/types/app.d.ts +223 -223
  111. package/types/auth.d.ts +520 -520
  112. package/types/cluster.d.ts +75 -75
  113. package/types/env.d.ts +80 -80
  114. package/types/errors.d.ts +316 -316
  115. package/types/fetch.d.ts +43 -43
  116. package/types/grpc.d.ts +432 -432
  117. package/types/index.d.ts +384 -384
  118. package/types/lifecycle.d.ts +60 -60
  119. package/types/middleware.d.ts +320 -320
  120. package/types/observe.d.ts +304 -304
  121. package/types/orm.d.ts +1887 -1887
  122. package/types/request.d.ts +109 -109
  123. package/types/response.d.ts +157 -157
  124. package/types/router.d.ts +78 -78
  125. package/types/sse.d.ts +78 -78
  126. package/types/websocket.d.ts +126 -126
@@ -1,304 +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;
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;