balda 0.0.21 → 0.0.22

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.
package/lib/index.d.ts DELETED
@@ -1,4049 +0,0 @@
1
- import { IRouter, RequestHandler, Router as Router$1 } from 'express';
2
- export { ErrorRequestHandler as ExpressErrorMiddleware, RequestHandler as ExpressMiddleware, NextFunction as ExpressNextFunction, Request as ExpressRequest, Response as ExpressResponse } from 'express';
3
- import { ApolloServerOptions, BaseContext } from '@apollo/server';
4
- import { DocumentNode, GraphQLResolveInfo } from 'graphql';
5
- import { ServerResponse, IncomingMessage, Server as Server$2 } from 'node:http';
6
- import { Http2Server } from 'node:http2';
7
- import { Server as Server$1, ServerOptions as ServerOptions$1 } from 'node:https';
8
- export { ServerOptions as HttpsServerOptions } from 'node:https';
9
- import { Ajv } from 'ajv';
10
- import { ZodType, z, ZodAny } from 'zod';
11
- import { TSchema, Static } from '@sinclair/typebox';
12
- import * as pino from 'pino';
13
- import pino__default, { pino as pino$1 } from 'pino';
14
- import { schedule, TaskContext } from 'node-cron';
15
- import { IClientSubscribeOptions, IClientOptions, IClientPublishOptions, MqttClient } from 'mqtt';
16
- import { SQSClientConfig, SendMessageCommandInput } from '@aws-sdk/client-sqs';
17
- import { Queue, JobsOptions, Job } from 'bullmq';
18
- import { SendOptions } from 'pg-boss';
19
- import { AsyncLocalStorage } from 'node:async_hooks';
20
- import { S3Client } from '@aws-sdk/client-s3';
21
- import { Transporter } from 'nodemailer';
22
-
23
- type GraphQLTypeDef = string | DocumentNode | string[] | DocumentNode[] | (() => string | DocumentNode | string[] | DocumentNode[]);
24
- type GraphQLResolvers = Record<string, unknown> | Record<string, unknown>[] | unknown;
25
- interface GraphQLContext extends BaseContext {
26
- }
27
- type GraphQLResolverFunction<TContext = GraphQLContext> = (parent: unknown, args: Record<string, unknown>, context: TContext, info: GraphQLResolveInfo) => unknown | Promise<unknown>;
28
- type GraphQLResolverMap<TContext = GraphQLContext> = Record<string, GraphQLResolverFunction<TContext> | Record<string, unknown>>;
29
- type GraphQLSchemaInput = {
30
- typeDefs: GraphQLTypeDef;
31
- resolvers?: GraphQLResolvers;
32
- };
33
- type GraphQLOptions = {
34
- schema?: GraphQLSchemaInput;
35
- apolloOptions?: Omit<ApolloServerOptions<GraphQLContext>, "typeDefs" | "resolvers"> & {
36
- context?: ((arg: any) => GraphQLContext | Promise<GraphQLContext>) | GraphQLContext;
37
- };
38
- };
39
- type GraphQLResolverType = "Query" | "Mutation" | "Subscription";
40
-
41
- declare class GraphQL {
42
- private schemaOptions;
43
- private apolloOptions;
44
- isEnabled: boolean;
45
- constructor(options?: GraphQLOptions);
46
- getSchemaOptions(): GraphQLSchemaInput;
47
- getApolloOptions(): Omit<ApolloServerOptions<GraphQLContext>, "typeDefs" | "resolvers">;
48
- /**
49
- * Add a type definition to the schema
50
- */
51
- addTypeDef(typeDef: GraphQLTypeDef): void;
52
- /**
53
- * Add a resolver to the schema
54
- * @param type - The resolver type (Query, Mutation, Subscription, or a custom type name)
55
- * @param resolvers - An object mapping field names to resolver functions, or a full resolver object
56
- */
57
- addResolver(type: GraphQLResolverType, resolvers: GraphQLResolverMap): void;
58
- addResolver(resolver: GraphQLResolvers): void;
59
- addResolver(type: string, resolvers: GraphQLResolverMap): void;
60
- private initializeConfiguration;
61
- private createDisabledConfiguration;
62
- private createEnabledConfiguration;
63
- private resolveSchemaOptions;
64
- private resolveApolloOptions;
65
- private addResolverByType;
66
- private ensureResolversInitialized;
67
- private mergeResolverIntoObject;
68
- private addFullResolver;
69
- private addResolverArray;
70
- private addResolverObject;
71
- private addTypeDefArray;
72
- private ensureTypeDefsArray;
73
- }
74
-
75
- type SyncOrAsync<T = void> = T | Promise<T>;
76
-
77
- type AjvInstance = InstanceType<typeof Ajv>;
78
- type AjvCompileParams = Parameters<AjvInstance["compile"]>;
79
-
80
- type RequestSchema = ZodType | TSchema | AjvCompileParams[0];
81
- type ValidatedData<T extends RequestSchema> = T extends ZodType ? z.infer<T> : T extends TSchema ? Static<T> : T extends AjvCompileParams[0] ? any : any;
82
- interface CustomValidationError {
83
- status?: number;
84
- message?: string;
85
- }
86
- interface ValidationOptions {
87
- /**
88
- * The schema to validate the request body against (Zod, TypeBox, or plain JSON schema)
89
- */
90
- body?: RequestSchema;
91
- /**
92
- * The schema to validate the query parameters against (Zod, TypeBox, or plain JSON schema)
93
- */
94
- query?: RequestSchema;
95
- /**
96
- * The schema to validate both body and query against (Zod, TypeBox, or plain JSON schema)
97
- */
98
- all?: RequestSchema;
99
- /**
100
- * Whether to use safe validation (returns original data if validation fails instead of throwing)
101
- * @default false
102
- */
103
- safe?: boolean;
104
- }
105
-
106
- type StaticPluginOptions = {
107
- /**
108
- * The file system directory path where the assets are located
109
- * @example "./tmp/assets" or "public"
110
- */
111
- source: string;
112
- /**
113
- * The URL path where the assets will be served
114
- * @example "/assets" or "/public"
115
- */
116
- path: string;
117
- };
118
- type FileAllowedMimeType = "text/html" | "text/css" | "application/javascript" | "application/typescript" | "text/jsx" | "text/tsx" | "application/json" | "application/xml" | "application/yaml" | "text/csv" | "text/plain" | "text/markdown" | "image/png" | "image/jpeg" | "image/gif" | "image/svg+xml" | "image/x-icon" | "image/webp" | "image/avif" | "image/bmp" | "image/tiff" | "image/heic" | "image/heif" | "video/mp4" | "video/webm" | "video/x-msvideo" | "video/quicktime" | "video/x-matroska" | "video/x-ms-wmv" | "video/x-flv" | "video/x-m4v" | "video/mpeg" | "video/3gpp" | "audio/mpeg" | "audio/wav" | "audio/ogg" | "audio/flac" | "audio/aac" | "audio/mp4" | "audio/x-ms-wma" | "audio/opus" | "audio/midi" | "font/woff" | "font/woff2" | "font/ttf" | "font/otf" | "application/vnd.ms-fontobject" | "application/pdf" | "application/msword" | "application/vnd.openxmlformats-officedocument.wordprocessingml.document" | "application/vnd.ms-excel" | "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" | "application/vnd.ms-powerpoint" | "application/vnd.openxmlformats-officedocument.presentationml.presentation" | "application/vnd.oasis.opendocument.text" | "application/vnd.oasis.opendocument.spreadsheet" | "application/vnd.oasis.opendocument.presentation" | "application/rtf" | "application/epub+zip" | "application/zip" | "application/x-tar" | "application/gzip" | "application/x-bzip2" | "application/x-xz" | "application/vnd.rar" | "application/x-7z-compressed" | "application/wasm" | "application/manifest+json" | "text/calendar" | "text/vcard" | "application/sql" | "application/x-sh" | "application/x-msdos-program" | "application/x-msdownload" | "application/octet-stream" | "application/x-iso9660-image" | "application/x-apple-diskimage" | "application/vnd.android.package-archive" | "application/java-archive" | "application/x-shockwave-flash";
119
-
120
- type FormFile = {
121
- /**
122
- * The name of the form field.
123
- */
124
- formName: string;
125
- /**
126
- * The mime type of the file. (e.g. "image/png")
127
- */
128
- mimeType: string;
129
- /**
130
- * The size of the file in bytes.
131
- */
132
- size: number;
133
- /**
134
- * The temporary path of the file. Will be deleted after the request is processed automatically even in error cases.
135
- */
136
- tmpPath: string;
137
- /**
138
- * The original filename (including extension) as sent by the client
139
- * (e.g. "avatar.png", "document.txt").
140
- */
141
- originalName: string;
142
- };
143
- type FilePluginOptions = {
144
- /**
145
- * The maximum size of each file.
146
- * Supports formats like "5mb", "100kb".
147
- * Example: "10mb", "500kb"
148
- * Default: 1mb
149
- */
150
- maxFileSize?: `${number}mb` | `${number}kb`;
151
- /**
152
- * The maximum number of files allowed in a single request.
153
- */
154
- maxFiles?: number;
155
- /**
156
- * Allowed MIME types for uploaded files.
157
- * If specified, only files with these MIME types will be accepted.
158
- * Example: ['image/jpeg', 'image/png', 'application/pdf']
159
- */
160
- allowedMimeTypes?: (FileAllowedMimeType | (string & {}))[];
161
- };
162
-
163
- /**
164
- * The request object with type-safe path parameters.
165
- * This is the main object that is passed to the handler function.
166
- * It contains the request body, query parameters, files, cookies, etc.
167
- * It also contains the validation methods.
168
- *
169
- * @template Params - The path parameters type (automatically extracted from route)
170
- */
171
- declare class Request<Params extends Record<string, string> = any> {
172
- #private;
173
- /**
174
- * Creates a new request object from a Web API Request object.
175
- * Optimized to inline body check and avoid unnecessary property spreading.
176
- * @param request - The Web API Request object to create a new request object from.
177
- * @returns The new request object.
178
- */
179
- static fromRequest(request: globalThis.Request): Request;
180
- /**
181
- * Convert this request back to a Web API Request object.
182
- * Useful for passing to external libraries that expect standard Request objects.
183
- * @returns A Web API Request object
184
- */
185
- toWebApi(): globalThis.Request;
186
- /**
187
- * Compiles and validates the request data against the input schema.
188
- * @param inputSchema - The schema to validate the request data against (Zod, TypeBox, or plain JSON schema).
189
- * @param data - The request data to validate.
190
- * @param safe - If true, the function will return the original data if the validation fails instead of throwing an error.
191
- * @returns The validated data.
192
- */
193
- private static compileAndValidate;
194
- /**
195
- * The URL of the request
196
- */
197
- url: string;
198
- /**
199
- * The HTTP method of the request
200
- */
201
- method: string;
202
- /**
203
- * The headers of the request
204
- */
205
- headers: globalThis.Headers;
206
- /**
207
- * The signal for aborting the request
208
- */
209
- signal?: AbortSignal;
210
- /**
211
- * The referrer of the request
212
- */
213
- referrer?: string;
214
- /**
215
- * The referrer policy of the request
216
- */
217
- referrerPolicy?: ReferrerPolicy;
218
- /**
219
- * The mode of the request
220
- */
221
- mode?: RequestMode;
222
- /**
223
- * The credentials mode of the request
224
- */
225
- credentials?: RequestCredentials;
226
- /**
227
- * The cache mode of the request
228
- */
229
- cache?: RequestCache;
230
- /**
231
- * The redirect mode of the request
232
- */
233
- redirect?: RequestRedirect;
234
- /**
235
- * The integrity of the request
236
- */
237
- integrity?: string;
238
- /**
239
- * The keepalive flag of the request
240
- */
241
- keepalive?: boolean;
242
- /**
243
- * The parsed body of the request from the body parser middleware.
244
- * If body parser middleware is not used, this will be undefined.
245
- *
246
- * Note: This is untyped - use validation decorators to get typed body as a handler argument.
247
- */
248
- body: any;
249
- /**
250
- * Flag indicating if the body has been read/parsed
251
- */
252
- bodyUsed: boolean;
253
- /**
254
- * The context of the request. Can be augmented extending AsyncLocalStorageContext interface
255
- * @asyncLocalStorage middleware is required
256
- * @example
257
- * ```ts
258
- * declare module "balda" {
259
- * interface AsyncLocalStorageContext {
260
- * userId: string;
261
- * }
262
- * }
263
- * ```
264
- */
265
- ctx: AsyncLocalStorageContext;
266
- /**
267
- * The file of the request.
268
- * @fileParser middleware is required
269
- */
270
- file: (fieldName: string) => FormFile | null;
271
- /**
272
- * The cookies of the request.
273
- * @cookie middleware is required
274
- */
275
- cookies: Record<string, string>;
276
- /**
277
- * The cookie of the request.
278
- * @cookie middleware is required
279
- */
280
- cookie: (name: string) => string | undefined;
281
- /**
282
- * tells if the request has timed out.
283
- * @timeout middleware is required
284
- */
285
- timeout?: boolean;
286
- /**
287
- * The session of the request. Uses cookies to send the session id
288
- * @cookie middleware is required
289
- * @session middleware is required
290
- */
291
- session?: Record<string, any>;
292
- /**
293
- * The session of the request. Uses cookies to send the session id
294
- * @cookie middleware is required
295
- * @session middleware is required
296
- */
297
- saveSession: () => Promise<void>;
298
- /**
299
- * The session of the request.
300
- * @cookie middleware is required
301
- * @session middleware is required
302
- */
303
- destroySession: () => Promise<void>;
304
- /**
305
- * The ip address of the request.
306
- * Tries to get the ip address from the `x-forwarded-for` header. If not available, it will use the remote address from the request.
307
- */
308
- ip?: string;
309
- /**
310
- * The files of the request. Only available for multipart/form-data requests and if the file parser middleware is used.
311
- */
312
- files: FormFile[];
313
- /**
314
- * The parameters of the request. Can be typed with a generic in the Request object
315
- * @example
316
- * ```ts
317
- * Request<{ id: string }>
318
- */
319
- params: Params;
320
- /**
321
- * The query parameters of the request.
322
- * Lazy parsed - only parses URLSearchParams when accessed
323
- *
324
- * Note: This is untyped - use validation decorators to get typed query as a handler argument.
325
- */
326
- get query(): Record<string, string>;
327
- set query(value: Record<string, string>);
328
- /**
329
- * Set the raw query string (called by server implementations)
330
- * @internal
331
- */
332
- setQueryString(queryString: string): void;
333
- /**
334
- * The id of the request.
335
- */
336
- get id(): string;
337
- set id(value: string);
338
- /**
339
- * The validated body of the request.
340
- * @param inputSchema - The schema to validate the body against (Zod schema or JSON Schema).
341
- * @param safe - If true, the function will return the original body if the validation fails instead of throwing an error.
342
- */
343
- validate<T extends RequestSchema>(inputSchema: T, safe?: boolean): ValidatedData<T>;
344
- /**
345
- * Validates the query string of the request.
346
- * @param inputSchema - The schema to validate the query against (Zod schema or JSON Schema).
347
- * @param safe - If true, the function will return undefined if the validation fails instead of throwing an error.
348
- */
349
- validateQuery<T extends RequestSchema>(inputSchema: T, safe?: boolean): ValidatedData<T>;
350
- /**
351
- * Validates the body and query string of the request.
352
- * @param inputSchema - The schema to validate against (Zod schema or JSON Schema).
353
- * @param safe - If true, the function will return undefined if the validation fails instead of throwing an error.
354
- */
355
- validateAll<T extends RequestSchema>(inputSchema: T, safe?: boolean): ValidatedData<T>;
356
- }
357
-
358
- interface AsyncLocalStorageContext {
359
- }
360
- type AsyncLocalStorageContextSetters<K extends keyof AsyncLocalStorageContext = keyof AsyncLocalStorageContext> = Record<K, (req: Request) => SyncOrAsync<AsyncLocalStorageContext[K]>>;
361
-
362
- interface JsonOptions {
363
- /**
364
- * The maximum size of the JSON body in bytes.
365
- * If the body is larger than this limit, the request will be rejected.
366
- * Default: 100kb
367
- */
368
- sizeLimit?: `${number}mb` | `${number}kb`;
369
- /**
370
- * If true, the JSON body will be parsed as an empty object if it is empty.
371
- * Default: false (body will be undefined)
372
- */
373
- parseEmptyBodyAsObject?: boolean;
374
- /**
375
- * The custom error message to return when the JSON body is too large.
376
- * Default: response with status 413 and body { message: "ERR_REQUEST_BODY_TOO_LARGE" }
377
- */
378
- customErrorMessage?: {
379
- status?: number;
380
- message?: string;
381
- };
382
- }
383
-
384
- /**
385
- * Options for URL-encoded middleware
386
- */
387
- type UrlEncodedOptions = {
388
- /**
389
- * The maximum size of the URL-encoded body.
390
- * Supports formats like "5mb", "100kb".
391
- * Defaults to "1mb".
392
- */
393
- limit?: `${number}mb` | `${number}kb`;
394
- /**
395
- * Whether to parse extended syntax (objects and arrays). Defaults to false.
396
- */
397
- extended?: boolean;
398
- /**
399
- * The character encoding to use when parsing. Defaults to 'utf8'.
400
- */
401
- charset?: string;
402
- /**
403
- * Whether to allow empty values. Defaults to true.
404
- */
405
- allowEmpty?: boolean;
406
- /**
407
- * Maximum number of parameters to parse. Defaults to 1000.
408
- */
409
- parameterLimit?: number;
410
- };
411
-
412
- type BodyParserOptions = {
413
- json?: JsonOptions;
414
- urlencoded?: UrlEncodedOptions;
415
- fileParser?: FilePluginOptions;
416
- };
417
-
418
- type CompressionOptions = {
419
- /**
420
- * Minimum response size in bytes to trigger compression
421
- * Default: 1024 (1KB)
422
- */
423
- threshold?: number;
424
- /**
425
- * Compression level (0-9)
426
- * 0 = no compression, 9 = maximum compression
427
- * Default: 6
428
- */
429
- level?: number;
430
- /**
431
- * Content types to compress (regex patterns)
432
- * Default: common compressible types (text, json, xml, javascript, etc.)
433
- */
434
- filter?: RegExp[];
435
- };
436
-
437
- /**
438
- * Cookie options for setting cookies
439
- */
440
- type CookieOptions = {
441
- /**
442
- * Domain for the cookie
443
- */
444
- domain?: string;
445
- /**
446
- * Path for the cookie
447
- */
448
- path?: string;
449
- /**
450
- * Expiration date for the cookie
451
- */
452
- expires?: Date;
453
- /**
454
- * Max age in seconds for the cookie
455
- */
456
- maxAge?: number;
457
- /**
458
- * Whether the cookie is secure (HTTPS only)
459
- * @default true
460
- *
461
- * ⚠️ Should be `true` in production to prevent transmission over HTTP
462
- */
463
- secure?: boolean;
464
- /**
465
- * Whether the cookie is HTTP only (prevents JavaScript access)
466
- * @default true
467
- *
468
- * ✅ Recommended: `true` to prevent XSS attacks
469
- */
470
- httpOnly?: boolean;
471
- /**
472
- * SameSite attribute for the cookie
473
- *
474
- * - "Strict": Most secure, cookie not sent on cross-site requests
475
- * - "Lax": Balanced, cookie sent on top-level navigation
476
- * - "None": Least secure, requires secure=true
477
- *
478
- * ✅ Recommended: "Strict" for auth cookies
479
- */
480
- sameSite?: "Strict" | "Lax" | "None";
481
- /**
482
- * Whether the cookie should be signed
483
- */
484
- signed?: boolean;
485
- /**
486
- * Priority for the cookie
487
- */
488
- priority?: "Low" | "Medium" | "High";
489
- };
490
- /**
491
- * Options for the cookie middleware
492
- */
493
- type CookieMiddlewareOptions = {
494
- /**
495
- * Secret key for signing cookies (required if using signed cookies)
496
- */
497
- secret?: string;
498
- /**
499
- * Default options for all cookies set by this middleware
500
- */
501
- defaults?: CookieOptions;
502
- /**
503
- * Whether to enable cookie parsing (defaults to true)
504
- */
505
- parse?: boolean;
506
- /**
507
- * Whether to enable cookie signing (defaults to false)
508
- */
509
- sign?: boolean;
510
- };
511
-
512
- type CorsMethods = "GET" | "POST" | "PUT" | "DELETE" | "OPTIONS" | "PATCH" | "HEAD";
513
- /**
514
- * Options for CORS middleware, similar to Express.js
515
- */
516
- type CorsOptions = {
517
- /**
518
- * Configures the Access-Control-Allow-Origin CORS header.
519
- *
520
- * ⚠️ WARNING: The default value '*' allows ALL origins, which is insecure for production.
521
- *
522
- * For production, explicitly set allowed origins:
523
- * - Single origin: 'https://example.com'
524
- * - Multiple origins: ['https://example.com', 'https://app.example.com']
525
- * - Pattern matching: /^https:\/\/.*\.example\.com$/
526
- *
527
- * Defaults to '*' (allows all origins) - only suitable for development/public APIs.
528
- */
529
- origin?: string | RegExp | (string | RegExp)[];
530
- /**
531
- * Configures the Access-Control-Allow-Methods CORS header. Defaults to 'GET,HEAD,PUT,PATCH,POST,DELETE'.
532
- */
533
- methods?: CorsMethods[] | string;
534
- /**
535
- * Configures the Access-Control-Allow-Headers CORS header. Defaults to allowing all requested headers.
536
- */
537
- allowedHeaders?: string[] | string;
538
- /**
539
- * Configures the Access-Control-Expose-Headers CORS header. Defaults to none.
540
- */
541
- exposedHeaders?: string[] | string;
542
- /**
543
- * Configures the Access-Control-Allow-Credentials CORS header. Defaults to false.
544
- */
545
- credentials?: boolean;
546
- /**
547
- * Configures the Access-Control-Max-Age CORS header. Defaults to undefined (not sent).
548
- */
549
- maxAge?: number;
550
- /**
551
- * Pass the CORS preflight response to the next handler. Defaults to false (ends response).
552
- */
553
- preflightContinue?: boolean;
554
- /**
555
- * Provides a status code to use for successful OPTIONS requests, if preflightContinue is false. Defaults to 204.
556
- */
557
- optionsSuccessStatus?: number;
558
- };
559
-
560
- type ExpressHandler = RequestHandler;
561
- type ExpressRouter = IRouter;
562
- interface ExpressAdapterOptions {
563
- basePath?: string;
564
- }
565
-
566
- /**
567
- * Options for helmet middleware
568
- */
569
- interface HelmetOptions {
570
- dnsPrefetchControl?: boolean;
571
- frameguard?: boolean | {
572
- action: "DENY" | "SAMEORIGIN" | string;
573
- };
574
- hsts?: boolean | {
575
- maxAge?: number;
576
- includeSubDomains?: boolean;
577
- preload?: boolean;
578
- };
579
- contentTypeOptions?: boolean;
580
- ieNoOpen?: boolean;
581
- xssFilter?: boolean;
582
- referrerPolicy?: false | string;
583
- crossOriginResourcePolicy?: false | string;
584
- crossOriginOpenerPolicy?: false | string;
585
- crossOriginEmbedderPolicy?: false | string;
586
- contentSecurityPolicy?: false | string;
587
- }
588
-
589
- type LoggerOptions = Parameters<typeof pino$1>[0];
590
-
591
- interface LogOptions {
592
- /**
593
- * Whether to log the request.
594
- * @default true
595
- */
596
- logRequest?: boolean;
597
- /**
598
- * What to log for the request.
599
- * @default true for all properties
600
- */
601
- requestPayload?: {
602
- method?: boolean;
603
- url?: boolean;
604
- ip?: boolean;
605
- headers?: boolean;
606
- /** Only json objects and strings are logged */
607
- body?: boolean;
608
- };
609
- /**
610
- * Whether to log the response.
611
- * @default true
612
- */
613
- logResponse?: boolean;
614
- /**
615
- * Whether to log the response body.
616
- * @default false
617
- */
618
- responsePayload?: {
619
- status?: boolean;
620
- headers?: boolean;
621
- body?: boolean;
622
- };
623
- /**
624
- * What to log for the response.
625
- * @default true for all properties
626
- */
627
- pinoOptions?: LoggerOptions;
628
- }
629
-
630
- type MethodOverrideOptions = {
631
- /**
632
- * HTTP methods that can be overridden
633
- * Default: ['POST']
634
- */
635
- methods?: string[];
636
- /**
637
- * Header name to read the override method from
638
- * Default: 'X-HTTP-Method-Override'
639
- */
640
- header?: string;
641
- };
642
-
643
- type StorageStrategy = "memory" | "custom";
644
- type BaseRateLimiterOptions = {
645
- /**
646
- * The number of requests per window
647
- * @default 100
648
- */
649
- limit?: number;
650
- /**
651
- * The message to return when the rate limit is exceeded
652
- * @default "ERR_RATE_LIMIT_EXCEEDED"
653
- */
654
- message?: string;
655
- /**
656
- * The status code to return when the rate limit is exceeded
657
- * @default 429
658
- */
659
- statusCode?: number;
660
- /**
661
- * The storage strategy to use
662
- * @default "memory"
663
- */
664
- storageStrategy?: StorageStrategy;
665
- };
666
- /**
667
- * Key Strategy
668
- */
669
- type IpRateLimiterOptions = {
670
- /**
671
- * The type of rate limiter
672
- */
673
- type: "ip";
674
- } & BaseRateLimiterOptions;
675
- type CustomRateLimiterOptions = {
676
- /**
677
- * The type of rate limiter
678
- */
679
- type: "custom";
680
- /**
681
- * Generate a key for the rate limiter from the request (e.g. user id, email, etc.)
682
- */
683
- key: (req: Request) => string;
684
- /**
685
- * The storage strategy to use
686
- * @default "memory"
687
- */
688
- storageStrategy?: StorageStrategy;
689
- } & BaseRateLimiterOptions;
690
- /**
691
- * Memory Storage Strategy
692
- */
693
- type MemoryStorageStrategy = {
694
- /**
695
- * The type of storage strategy
696
- */
697
- type: "memory";
698
- /**
699
- * The window in milliseconds
700
- * @default 60000
701
- */
702
- windowMs?: number;
703
- };
704
- /**
705
- * Custom Storage Strategy
706
- */
707
- type CustomStorageStrategy = {
708
- /**
709
- * The type of storage strategy
710
- */
711
- type: "custom";
712
- /**
713
- * Set a value in the storage
714
- */
715
- set: (key: string, value: any) => Promise<void>;
716
- /**
717
- * Get a value from the storage
718
- */
719
- get: (key: string) => Promise<any>;
720
- };
721
- type StorageOptions$1 = MemoryStorageStrategy | CustomStorageStrategy;
722
- /**
723
- * Rate limiter options
724
- */
725
- type RateLimiterKeyOptions = IpRateLimiterOptions | CustomRateLimiterOptions;
726
-
727
- type SessionStore = {
728
- get: (sid: string) => Promise<Record<string, any> | undefined>;
729
- set: (sid: string, value: Record<string, any>, ttlSeconds?: number) => Promise<void>;
730
- destroy: (sid: string) => Promise<void>;
731
- };
732
- type SessionOptions = {
733
- /** Cookie name used for session id */
734
- name?: string;
735
- /** Secret used to sign session id (optional, for future) */
736
- secret?: string;
737
- /** TTL seconds for session */
738
- ttl?: number;
739
- /** Custom store, default is in-memory */
740
- store?: SessionStore;
741
- /** Whether to set HttpOnly secure flags */
742
- cookie?: {
743
- path?: string;
744
- httpOnly?: boolean;
745
- secure?: boolean;
746
- sameSite?: "Strict" | "Lax" | "None";
747
- domain?: string;
748
- };
749
- };
750
-
751
- /**
752
- * Type of Swagger UI to use
753
- */
754
- type SwaggerUIType = "standard" | "rapidoc" | "scalar" | "elements" | "custom";
755
- type HTMLString = string;
756
- /**
757
- * Custom UI generator function that takes the spec URL and global options and returns HTML
758
- */
759
- type CustomUIGenerator = (specUrl: string, globalOptions: SwaggerGlobalOptions) => HTMLString;
760
- /**
761
- * Type of request body for a route
762
- */
763
- type SwaggerBodyType = "json" | "form-data" | "urlencoded";
764
- /**
765
- * JSONSchema type for OpenAPI/AJV-compatible schemas
766
- */
767
- type JSONSchema = {
768
- $id?: string;
769
- $schema?: string;
770
- type?: string | string[];
771
- properties?: Record<string, JSONSchema>;
772
- items?: JSONSchema | JSONSchema[];
773
- required?: string[];
774
- enum?: any[];
775
- allOf?: JSONSchema[];
776
- oneOf?: JSONSchema[];
777
- anyOf?: JSONSchema[];
778
- not?: JSONSchema;
779
- additionalProperties?: boolean | JSONSchema;
780
- description?: string;
781
- format?: string;
782
- default?: any;
783
- title?: string;
784
- definitions?: Record<string, JSONSchema>;
785
- [key: string]: any;
786
- };
787
- /**
788
- * Base options shared across all Swagger UI types
789
- */
790
- type SwaggerGlobalOptionsBase = {
791
- /** The path to the swagger documentation, defaults to /docs for the UI and /docs/json for the raw json */
792
- path?: string;
793
- /** API title */
794
- title?: string;
795
- /** API description */
796
- description?: string;
797
- /** API version */
798
- version?: string;
799
- /** Server URLs */
800
- servers?: string[];
801
- /** Components (schemas, responses, parameters, etc.) */
802
- components?: Record<string, any>;
803
- /** Security schemes (OpenAPI 3.0 style) */
804
- securitySchemes?: Record<string, Security>;
805
- /** OpenID Connect configuration (discovery document) */
806
- openIdConnect?: OpenIDConnectConfig;
807
- /** API tags */
808
- tags?: Record<string, any>;
809
- /** Global security requirements */
810
- security?: Security[];
811
- /** External documentation */
812
- externalDocs?: {
813
- description?: string;
814
- url: string;
815
- };
816
- /** Info object (detailed metadata) */
817
- info?: {
818
- title: string;
819
- description?: string;
820
- version: string;
821
- termsOfService?: string;
822
- contact?: {
823
- name?: string;
824
- url?: string;
825
- email?: string;
826
- };
827
- license?: {
828
- name: string;
829
- url?: string;
830
- };
831
- };
832
- /**
833
- * OpenAPI models to be shown in the documentation. Must be valid OpenAPI/AJV JSONSchema objects.
834
- */
835
- models?: Record<string, JSONSchema> | JSONSchema[];
836
- };
837
- /**
838
- * Global documentation options for the API (OpenAPI/Swagger style)
839
- */
840
- type SwaggerGlobalOptions = (SwaggerGlobalOptionsBase & {
841
- /** Type of Swagger UI to use, one of 'standard', 'redoc', 'rapidoc', 'scalar', or 'elements'. Defaults to 'standard'. */
842
- type?: Exclude<SwaggerUIType, "custom">;
843
- }) | (SwaggerGlobalOptionsBase & {
844
- /** Type of Swagger UI to use. When set to 'custom', customUIGenerator is required. */
845
- type: "custom";
846
- /** Custom UI generator function. Required when type is 'custom'. Must return a string of HTML that uses the given specUrl. */
847
- customUIGenerator: CustomUIGenerator;
848
- });
849
- /**
850
- * Route-specific documentation options (for individual endpoints)
851
- */
852
- type SwaggerRouteOptions = {
853
- /** Service category where the route belongs to */
854
- service?: string;
855
- /** Name of the route */
856
- name?: string;
857
- /** Query parameters schema */
858
- query?: ZodType;
859
- /** Request body schema */
860
- requestBody?: ZodType;
861
- /** Responses for this route */
862
- responses?: Record<number, ZodType>;
863
- /** Errors for this route */
864
- errors?: Record<number, ZodType>;
865
- /** Security requirements for this route */
866
- security?: Security[] | Security;
867
- /** Description of the route */
868
- description?: string;
869
- /** Deprecated flag */
870
- deprecated?: boolean;
871
- /** Exclude from swagger */
872
- excludeFromSwagger?: boolean;
873
- /**
874
- * The request body type for this route. Allowed values: 'json', 'form-data', 'urlencoded'. Defaults to 'json'.
875
- */
876
- bodyType?: SwaggerBodyType;
877
- };
878
- type OAuth2Flows = {
879
- implicit?: OAuth2Flow;
880
- authorizationCode?: OAuth2Flow;
881
- clientCredentials?: OAuth2Flow;
882
- password?: OAuth2Flow;
883
- };
884
- type OAuth2Flow = {
885
- authorizationUrl?: string;
886
- tokenUrl?: string;
887
- refreshUrl?: string;
888
- scopes: Record<string, string>;
889
- };
890
- type OpenIDConnectConfig = {
891
- issuer: string;
892
- authorizationEndpoint: string;
893
- tokenEndpoint: string;
894
- userinfoEndpoint?: string;
895
- jwksUri: string;
896
- endSessionEndpoint?: string;
897
- introspectionEndpoint?: string;
898
- revocationEndpoint?: string;
899
- scopesSupported?: string[];
900
- responseTypesSupported?: string[];
901
- grantTypesSupported?: string[];
902
- tokenEndpointAuthMethodsSupported?: string[];
903
- subjectTypesSupported?: string[];
904
- idTokenSigningAlgValuesSupported?: string[];
905
- claimsSupported?: string[];
906
- codeChallengeMethodsSupported?: string[];
907
- };
908
- type Security = BearerOptions | ApiKeyOptions | OAuth2Options | OpenIdConnectOptions;
909
- type BearerOptions = {
910
- type: "bearer";
911
- bearerFormat?: string;
912
- description?: string;
913
- };
914
- type ApiKeyOptions = {
915
- type: "apiKey";
916
- name: string;
917
- in: "header" | "query" | "cookie";
918
- description?: string;
919
- };
920
- type OAuth2Options = {
921
- type: "oauth2";
922
- flows: OAuth2Flows;
923
- description?: string;
924
- name?: string;
925
- };
926
- type OpenIdConnectOptions = {
927
- type: "openIdConnect";
928
- openIdConnectUrl: string;
929
- description?: string;
930
- name?: string;
931
- };
932
-
933
- /**
934
- * Swagger plugin that serves the swagger UI and JSON specification, by default the UI will be available at /docs and the JSON specification at /docs/json
935
- * @warning The json specification is always available at /${globalOptions.path}/json
936
- * @internal
937
- */
938
- declare const swagger: (globalOptions?: SwaggerGlobalOptions | boolean) => void;
939
-
940
- type TimeoutOptions = {
941
- /** Timeout in milliseconds */
942
- ms: number;
943
- };
944
-
945
- type TrustProxyOptions = {
946
- /** Enable using X-Forwarded-* headers to determine client IP */
947
- trust?: boolean;
948
- /** Header name to read the client IP chain from */
949
- header?: string;
950
- /** Select which IP from the chain to use: 'first' (client) or 'last' (closest proxy) */
951
- hop?: "first" | "last";
952
- };
953
-
954
- /**
955
- * The next function.
956
- * This is the function that is passed to the handler function.
957
- * It has a pointer to the next middleware or handler function of the middleware chain.
958
- */
959
- type NextFunction = () => SyncOrAsync;
960
-
961
- /**
962
- * The response object with optional type-safe response body.
963
- * This is the main object that is passed to the handler function.
964
- * It contains the response body, status, headers, etc.
965
- * It also contains the methods to send the response.
966
- * @template TBody - The expected response body type (for type safety)
967
- */
968
- declare class Response$1<TBody = any> {
969
- static toWebResponse(response: Response$1): globalThis.Response;
970
- /**
971
- * The node http response object available only on the node runtime, useful for direct response manipulation
972
- * @warning undefined on other runtimes since they already use Web API Response object
973
- */
974
- nodeResponse: ServerResponse;
975
- /**
976
- * The status of the response
977
- */
978
- responseStatus: number;
979
- /**
980
- * The headers of the response
981
- */
982
- headers: Record<string, string>;
983
- /**
984
- * The body of the response
985
- */
986
- private body;
987
- constructor(status?: number);
988
- /**
989
- * Set a header for the response
990
- */
991
- setHeader(key: string, value: string): this;
992
- /**
993
- * Set the status of the response, status defaults to 200
994
- */
995
- status(status: number): this;
996
- /**
997
- * Send a response with the given body, tries to determine the content type based on the body type, status defaults to 200
998
- * @warning If cannot determine the content type, it will be sent as is
999
- */
1000
- send(body: TBody): void;
1001
- /**
1002
- * Send a response with the given body without any content type or encoding (as is), status defaults to 200
1003
- */
1004
- raw(body: any): void;
1005
- /**
1006
- * Send a response with the given text, status defaults to 200
1007
- */
1008
- text(body: string): void;
1009
- /**
1010
- * Send a response with the given JSON, status defaults to 200
1011
- */
1012
- json(body: TBody extends Record<string, unknown> | Array<unknown> ? TBody : Record<string, unknown> | Array<unknown>): void;
1013
- /**
1014
- * Send a response with the given HTML, status defaults to 200
1015
- */
1016
- html(htmlString: string): void;
1017
- /**
1018
- * Send a response with the given XML, status defaults to 200
1019
- */
1020
- xml(body: string): void;
1021
- /**
1022
- * Send a response with the given binary with Content-Type of application/octet-stream header, status defaults to 200
1023
- */
1024
- download(body: Uint8Array | Buffer): void;
1025
- /**
1026
- * Send a response with the given file content, status defaults to 200
1027
- * @param options only affects node and bun environment
1028
- */
1029
- file(pathToFile: string, options?: {
1030
- encoding?: string;
1031
- flag?: string;
1032
- }): void;
1033
- /**
1034
- * 2XX Success
1035
- */
1036
- /**
1037
- * 200 OK
1038
- */
1039
- ok(body?: TBody): void;
1040
- /**
1041
- * 201 Created
1042
- */
1043
- created(body?: TBody): void;
1044
- /**
1045
- * 202 Accepted
1046
- */
1047
- accepted(body?: TBody): void;
1048
- /**
1049
- * 204 No Content
1050
- */
1051
- noContent(): void;
1052
- /**
1053
- * 206 Partial Content
1054
- */
1055
- partialContent(body?: TBody): void;
1056
- /**
1057
- * 3XX Redirection
1058
- */
1059
- /**
1060
- * 300 Multiple Choices
1061
- */
1062
- multipleChoices(url: string): void;
1063
- redirect(url: string): void;
1064
- /**
1065
- * 301 Moved Permanently
1066
- */
1067
- movedPermanently(url: string): void;
1068
- /**
1069
- * 302 Found (Temporary Redirect)
1070
- */
1071
- found(url: string): void;
1072
- /**
1073
- * 303 See Other
1074
- */
1075
- seeOther(url: string): void;
1076
- /**
1077
- * 304 Not Modified
1078
- */
1079
- notModified(): void;
1080
- /**
1081
- * 307 Temporary Redirect
1082
- */
1083
- temporaryRedirect(url: string): void;
1084
- /**
1085
- * 308 Permanent Redirect
1086
- */
1087
- permanentRedirect(url: string): void;
1088
- /**
1089
- * 4XX Client Errors
1090
- */
1091
- /**
1092
- * 400 Bad Request
1093
- */
1094
- badRequest(body?: TBody): void;
1095
- /**
1096
- * 401 Unauthorized
1097
- */
1098
- unauthorized(body?: TBody): void;
1099
- /**
1100
- * 403 Forbidden
1101
- */
1102
- forbidden(body?: TBody): void;
1103
- /**
1104
- * 404 Not Found
1105
- */
1106
- notFound(body?: TBody): void;
1107
- /**
1108
- * 405 Method Not Allowed
1109
- */
1110
- methodNotAllowed(body?: TBody): void;
1111
- /**
1112
- * 406 Not Acceptable
1113
- */
1114
- notAcceptable(body?: TBody): void;
1115
- /**
1116
- * 409 Conflict
1117
- */
1118
- conflict(body?: TBody): void;
1119
- /**
1120
- * 410 Gone
1121
- */
1122
- gone(body?: TBody): void;
1123
- /**
1124
- * 413 Payload Too Large
1125
- */
1126
- payloadTooLarge(body?: TBody): void;
1127
- /**
1128
- * 415 Unsupported Media Type
1129
- */
1130
- unsupportedMediaType(body?: TBody): void;
1131
- /**
1132
- * 422 Unprocessable Entity
1133
- */
1134
- unprocessableEntity(body?: TBody): void;
1135
- /**
1136
- * 429 Too Many Requests
1137
- */
1138
- tooManyRequests(body?: TBody): void;
1139
- /**
1140
- * 5XX Server Errors
1141
- */
1142
- internalServerError(body?: TBody): void;
1143
- /**
1144
- * 501 Not Implemented
1145
- */
1146
- notImplemented(body?: TBody): void;
1147
- /**
1148
- * 502 Bad Gateway
1149
- */
1150
- badGateway(body?: TBody): void;
1151
- /**
1152
- * 503 Service Unavailable
1153
- */
1154
- serviceUnavailable(body?: TBody): void;
1155
- /**
1156
- * 504 Gateway Timeout
1157
- */
1158
- gatewayTimeout(body?: TBody): void;
1159
- /**
1160
- * 505 HTTP Version Not Supported
1161
- */
1162
- httpVersionNotSupported(body?: TBody): void;
1163
- /**
1164
- * Set a cookie for the response, cookie middleware must be registered in order to use this function
1165
- */
1166
- cookie?(_name: string, _value: string, _options?: CookieOptions): void;
1167
- /**
1168
- * Clear a cookie for the response, cookie middleware must be registered in order to use this function
1169
- */
1170
- clearCookie?(_name: string, _options?: CookieOptions): void;
1171
- /**
1172
- * Stream a response using an async generator or ReadableStream
1173
- * Sets appropriate headers for Server-Sent Events by default
1174
- */
1175
- stream(source: AsyncGenerator<any> | Generator<any> | ReadableStream, options?: {
1176
- customHeaders?: Record<string, string>;
1177
- }): void;
1178
- /**
1179
- * Get the body of the response
1180
- */
1181
- getBody(): any;
1182
- }
1183
-
1184
- /**
1185
- * Extracts parameter names from a path string and creates a typed object
1186
- * @example ExtractParams<"/users/:id/posts/:postId"> → { id: string; postId: string }
1187
- */
1188
- type ExtractParams<T extends string> = T extends `${infer _Start}:${infer Param}/${infer Rest}` ? {
1189
- [K in Param | keyof ExtractParams<Rest>]: string;
1190
- } : T extends `${infer _Start}:${infer Param}` ? {
1191
- [K in Param]: string;
1192
- } : Record<string, never>;
1193
- /**
1194
- * Helper type to infer the output type from a Zod schema, TypeBox schema, or any schema with _output
1195
- */
1196
- type InferSchemaType<T> = T extends ZodAny ? z.infer<T> : T extends TSchema ? Static<T> : T;
1197
-
1198
- /**
1199
- * Singleton that handles the routing of requests to the appropriate handler(s).
1200
- */
1201
- declare class Router {
1202
- private trees;
1203
- private routes;
1204
- private middlewares;
1205
- private basePath;
1206
- private staticRouteCache;
1207
- /**
1208
- * Create a new router with an optional base path and default middlewares.
1209
- * Base path is normalized so it never produces duplicate slashes and never ends with a trailing slash (except root).
1210
- */
1211
- constructor(basePath?: string, middlewares?: ServerRouteMiddleware[]);
1212
- /** Returns a shallow copy of all registered routes. */
1213
- getRoutes(): Route[];
1214
- /**
1215
- * Add or update a route
1216
- * @internal
1217
- */
1218
- addOrUpdate(method: HttpMethod, path: string, middleware: ServerRouteMiddleware[], handler: ServerRouteHandler, swaggerOptions?: SwaggerRouteOptions): void;
1219
- /**
1220
- * Find the matching route for the given HTTP method and path.
1221
- * Returns the resolved middleware chain, handler, and extracted params; or null if not found.
1222
- * Uses O(1) cache lookup for static routes, falls back to O(k) tree traversal for dynamic routes.
1223
- */
1224
- find(method: string, rawPath: string): {
1225
- middleware: ServerRouteMiddleware[];
1226
- handler: ServerRouteHandler;
1227
- params: Params;
1228
- } | null;
1229
- /**
1230
- * Register a GET route under this router's base path with type-safe path parameters.
1231
- */
1232
- get<TPath extends string = string>(path: TPath, handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>, swaggerOptions?: SwaggerRouteOptions): void;
1233
- get<TPath extends string = string>(path: TPath, middleware: ServerRouteMiddleware | ServerRouteMiddleware[], handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>, swaggerOptions?: SwaggerRouteOptions): void;
1234
- /**
1235
- * Register a POST route under this router's base path with type-safe path parameters.
1236
- */
1237
- post<TPath extends string = string>(path: TPath, handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>, swaggerOptions?: SwaggerRouteOptions): void;
1238
- post<TPath extends string = string>(path: TPath, middleware: ServerRouteMiddleware | ServerRouteMiddleware[], handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>, swaggerOptions?: SwaggerRouteOptions): void;
1239
- /**
1240
- * Register a PATCH route under this router's base path with type-safe path parameters.
1241
- */
1242
- patch<TPath extends string = string>(path: TPath, handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>, swaggerOptions?: SwaggerRouteOptions): void;
1243
- patch<TPath extends string = string>(path: TPath, middleware: ServerRouteMiddleware | ServerRouteMiddleware[], handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>, swaggerOptions?: SwaggerRouteOptions): void;
1244
- /**
1245
- * Register a PUT route under this router's base path with type-safe path parameters.
1246
- */
1247
- put<TPath extends string = string>(path: TPath, handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>, swaggerOptions?: SwaggerRouteOptions): void;
1248
- put<TPath extends string = string>(path: TPath, middleware: ServerRouteMiddleware | ServerRouteMiddleware[], handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>, swaggerOptions?: SwaggerRouteOptions): void;
1249
- /**
1250
- * Register a DELETE route under this router's base path with type-safe path parameters.
1251
- */
1252
- delete<TPath extends string = string>(path: TPath, handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>, swaggerOptions?: SwaggerRouteOptions): void;
1253
- delete<TPath extends string = string>(path: TPath, middleware: ServerRouteMiddleware | ServerRouteMiddleware[], handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>, swaggerOptions?: SwaggerRouteOptions): void;
1254
- /**
1255
- * Register an OPTIONS route under this router's base path with type-safe path parameters.
1256
- */
1257
- options<TPath extends string = string>(path: TPath, handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>, swaggerOptions?: SwaggerRouteOptions): void;
1258
- options<TPath extends string = string>(path: TPath, middleware: ServerRouteMiddleware | ServerRouteMiddleware[], handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>, swaggerOptions?: SwaggerRouteOptions): void;
1259
- /**
1260
- * Register an HEAD route under this router's base path with type-safe path parameters.
1261
- */
1262
- head<TPath extends string = string>(path: TPath, handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>, swaggerOptions?: SwaggerRouteOptions): void;
1263
- head<TPath extends string = string>(path: TPath, middleware: ServerRouteMiddleware | ServerRouteMiddleware[], handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>, swaggerOptions?: SwaggerRouteOptions): void;
1264
- /**
1265
- * Create a grouped router that shares a base path and middlewares.
1266
- * The callback receives a child router where routes are defined; routes
1267
- * are then merged back into the parent with the composed base path and middlewares.
1268
- */
1269
- group(path: string, middleware: ServerRouteMiddleware[] | ServerRouteMiddleware, cb: (router: Router) => void): void;
1270
- group(path: string, cb: (router: Router) => void): void;
1271
- /**
1272
- * Apply global middlewares to all routes
1273
- * @param middlewares - The middlewares to apply
1274
- * @internal
1275
- */
1276
- applyGlobalMiddlewaresToAllRoutes(middlewares: ServerRouteMiddleware[]): void;
1277
- private normalizeBasePath;
1278
- private joinPath;
1279
- }
1280
-
1281
- type Params = Record<string, string>;
1282
- interface Route {
1283
- method: string;
1284
- path: string;
1285
- middleware: ServerRouteMiddleware[];
1286
- handler: ServerRouteHandler;
1287
- swaggerOptions?: SwaggerRouteOptions;
1288
- }
1289
- /**
1290
- * The client router is a subset of the router that is used to define routes on library level by the end user.
1291
- */
1292
- type ClientRouter = Omit<Router, "applyGlobalMiddlewaresToAllRoutes" | "addOrUpdate">;
1293
-
1294
- type ServerPlugin = {
1295
- bodyParser?: BodyParserOptions;
1296
- cors?: CorsOptions;
1297
- static?: StaticPluginOptions;
1298
- helmet?: HelmetOptions;
1299
- cookie?: CookieMiddlewareOptions;
1300
- log?: LogOptions;
1301
- rateLimiter?: {
1302
- keyOptions?: RateLimiterKeyOptions;
1303
- storageOptions?: StorageOptions$1;
1304
- };
1305
- trustProxy?: TrustProxyOptions;
1306
- timeout?: TimeoutOptions;
1307
- session?: SessionOptions;
1308
- methodOverride?: MethodOverrideOptions;
1309
- compression?: CompressionOptions;
1310
- asyncLocalStorage?: AsyncLocalStorageContextSetters;
1311
- };
1312
- type NodeHttpClient = "http" | "http2" | "https" | "http2-secure";
1313
- type ServerOptions<H extends NodeHttpClient = NodeHttpClient> = {
1314
- /** Specific node client to use for nodejs, default to `http` */
1315
- nodeHttpClient?: H;
1316
- /** The port to listen on, uses the PORT env if present, defaults to 80 */
1317
- port?: number;
1318
- /** The hostname to listen on, uses the HOST env if present, defaults to 0.0.0.0 */
1319
- host?: string;
1320
- /** Controller patterns to match, defaults to an empty array */
1321
- controllerPatterns?: string[];
1322
- /** Basic plugins to apply to all requests, plugins are applied in order based on where they are defined in the `plugins` object, by default no plugins are applied */
1323
- plugins?: ServerPlugin;
1324
- /** The tap options to interact with the underlying server connector before it is used to listen for incoming requests */
1325
- tapOptions?: ServerTapOptions;
1326
- /**
1327
- * The swagger options to apply to the server, by default swagger plugin is applied with standard options, you can pass a boolean to enable or disable the plugin or you can pass an object to apply custom options to the plugin
1328
- * @example
1329
- * ```ts
1330
- * const server = new Server({
1331
- * swagger: true,
1332
- * });
1333
- * ```
1334
- */
1335
- swagger?: Parameters<typeof swagger>[0] | boolean;
1336
- /**
1337
- * The graphql options to apply to the server, by default graphql plugin is not enabled, you can pass a boolean to enable or disable the plugin or you can pass an object to apply custom options to the plugin (when options are provided the plugin is always enabled)
1338
- * @example
1339
- * ```ts
1340
- * const server = new Server({
1341
- * graphql: true,
1342
- * });
1343
- * ```
1344
- * @example
1345
- * ```ts
1346
- * const server = new Server({
1347
- * graphql: {
1348
- * schema: createSchema({ typeDefs: `type Query { hello: String }`, resolvers: { Query: { hello: () => 'Hello World' } } }),
1349
- * },
1350
- * });
1351
- * ```
1352
- */
1353
- graphql?: GraphQLOptions;
1354
- /**
1355
- * Custom AJV instance to use for the server for validation, by default a global instance is used, you can pass a custom instance to use for the server validation
1356
- * @example
1357
- * ```ts
1358
- * const server = new Server({
1359
- * ajvInstance: new Ajv(),
1360
- * });
1361
- * ```
1362
- */
1363
- ajvInstance?: Ajv;
1364
- /**
1365
- * An AbortSignal to gracefully shutdown the server when aborted
1366
- * @example
1367
- * ```ts
1368
- * const controller = new AbortController();
1369
- * const server = new Server({
1370
- * abortSignal: controller.signal,
1371
- * });
1372
- *
1373
- * await server.waitUntilListening();
1374
- *
1375
- * // Later: abort the server
1376
- * controller.abort();
1377
- * ```
1378
- */
1379
- abortSignal?: AbortSignal;
1380
- } & (H extends "https" | "http2-secure" ? HttpsOptions<H> : {});
1381
- /** Internal resolved server options with all required properties */
1382
- type ResolvedServerOptions = {
1383
- nodeHttpClient: NodeHttpClient;
1384
- port: number;
1385
- host: string;
1386
- controllerPatterns: string[];
1387
- plugins: ServerPlugin;
1388
- tapOptions: ServerTapOptions;
1389
- swagger: Parameters<typeof swagger>[0] | boolean;
1390
- graphql?: GraphQLOptions;
1391
- abortSignal?: AbortSignal;
1392
- };
1393
- type ServerErrorHandler = (req: Request, res: Response$1, next: NextFunction, error: Error) => SyncOrAsync;
1394
- interface ServerInterface {
1395
- /**
1396
- * Identifier for the balda server instance
1397
- */
1398
- _brand: "BaldaServer";
1399
- /**
1400
- * Whether the server is in production mode NODE_ENV is set to "production"
1401
- */
1402
- isProduction: boolean;
1403
- /**
1404
- * Whether the server is listening for requests
1405
- */
1406
- isListening: boolean;
1407
- /**
1408
- * The url of the server
1409
- */
1410
- url: string;
1411
- /**
1412
- * The port of the server
1413
- */
1414
- port: number;
1415
- /**
1416
- * The host of the server
1417
- */
1418
- host: string;
1419
- /**
1420
- * Settings applied before server is listening, this is used to tap into the server connector for the current runtime and modify it before it is used to listen for incoming requests
1421
- * @warning Must be used before `listen` method
1422
- */
1423
- tapOptions?: ServerTapOptions;
1424
- /**
1425
- * Server options passed to the constructor
1426
- */
1427
- serverOptions: ResolvedServerOptions;
1428
- /**
1429
- * Main singleton router instance of the server
1430
- */
1431
- router: ClientRouter;
1432
- /**
1433
- * Hash the given data using the native hash function of the current runtime
1434
- * @param data - The data to hash
1435
- * @returns The hashed data
1436
- */
1437
- hash: (data: string) => Promise<string>;
1438
- /**
1439
- * Compare the given data with the given hash using the native hash function of the current runtime
1440
- * @param hash - The hash to compare the data with
1441
- * @param data - The data to compare with the hash
1442
- * @returns Whether the data matches the hash
1443
- */
1444
- compareHash: (hash: string, data: string) => Promise<boolean>;
1445
- /**
1446
- * Get the environment variables of the server using the native environment variables of the current runtime
1447
- */
1448
- getEnvironment: () => Record<string, string>;
1449
- /**
1450
- * The path to the temporary directory, you can append a path to the temporary directory to get a new path.
1451
- * It uses the current working directory of the runtime to get the base path.
1452
- * @example
1453
- * ```ts
1454
- * server.tmpPath("my-app"); // -> ${cwd}/tmp/my-app
1455
- * ```
1456
- */
1457
- tmpDir: (...append: string[]) => string;
1458
- /**
1459
- * Create a new directory
1460
- * @param path - The path to the directory
1461
- * @param options - The options to create the directory
1462
- * @param options.recursive - Whether to create the directory recursively
1463
- * @param options.mode - The mode of the directory
1464
- */
1465
- mkdir: (path: string, options?: {
1466
- recursive?: boolean;
1467
- mode?: number | string;
1468
- }) => Promise<void>;
1469
- /**
1470
- * Mount an Express middleware or router at a specific path for compatibility with Express-based libraries like AdminJS
1471
- * @param pathOrMiddleware - The path to mount at, or the Express middleware/router if mounting at root
1472
- * @param maybeMiddleware - The Express middleware or router when path is provided
1473
- */
1474
- useExpress: (pathOrMiddleware: string | RequestHandler | ExpressRouter, maybeMiddleware?: RequestHandler | ExpressRouter) => void;
1475
- /**
1476
- * Convert an Express middleware to a Balda-compatible middleware
1477
- * @param middleware - The Express middleware to convert
1478
- * @returns A Balda-compatible middleware
1479
- */
1480
- expressMiddleware: (middleware: RequestHandler) => ServerRouteMiddleware;
1481
- /**
1482
- * Mount an Express router at a specific base path
1483
- * @param basePath - The base path to mount the router at
1484
- * @param expressRouter - The Express router to mount
1485
- */
1486
- mountExpressRouter: (basePath: string, expressRouter: ExpressRouter) => void;
1487
- /**
1488
- * Shorthand for the server.router.get method
1489
- */
1490
- get: (...args: any[]) => void;
1491
- /**
1492
- * Shorthand for the server.router.post method
1493
- */
1494
- post: (...args: any[]) => void;
1495
- /**
1496
- * Shorthand for the server.router.put method
1497
- */
1498
- put: (...args: any[]) => void;
1499
- /**
1500
- * Shorthand for the server.router.patch method
1501
- */
1502
- patch: (...args: any[]) => void;
1503
- /**
1504
- * Shorthand for the server.router.delete method
1505
- */
1506
- delete: (...args: any[]) => void;
1507
- /**
1508
- * Shorthand for the server.router.options method
1509
- */
1510
- options: (...args: any[]) => void;
1511
- /**
1512
- * Shorthand for the server.router.head method
1513
- */
1514
- head: (...args: any[]) => void;
1515
- /**
1516
- * Shorthand for the server.router.group method
1517
- */
1518
- group: (...args: any[]) => void;
1519
- /**
1520
- * Get the node server instance, you must be using node runtime to use this method based on the nodeHttpClient option passed to the server constructor (defaults to http)
1521
- * @throws if the runtime is not node
1522
- */
1523
- getNodeServer: () => RuntimeServerMap<"node", NodeHttpClient>;
1524
- /**
1525
- * Get the bun server instance, you must be using bun runtime to use this method
1526
- * @throws if the runtime is not bun
1527
- */
1528
- getBunServer: () => RuntimeServerMap<"bun">;
1529
- /**
1530
- * Get the deno server instance, you must be using deno runtime to use this method
1531
- * @throws if the runtime is not deno
1532
- */
1533
- getDenoServer: () => RuntimeServerMap<"deno">;
1534
- /**
1535
- * Embed the given key into the server instance, this is useful for embedding the server with custom context inside the server instance, you can extend the server with your own properties to type it
1536
- * @param key - The key to embed
1537
- * @param value - The value to embed
1538
- * @warning There are some keys that are protected and cannot be embedded, you can find the list of protected keys in the PROTECTED_KEYS constant
1539
- * @throws An error if the key is already defined in the server instance or if the key is protected
1540
- * @example
1541
- * ```typescript
1542
- * // For better type safety, you can declare a module for the server interface
1543
- * declare module "balda" {
1544
- * interface Server {
1545
- * myCustomProperty: string;
1546
- * }
1547
- * }
1548
- *
1549
- * server.embed("myCustomProperty", "myCustomValue");
1550
- * console.log(server.myCustomProperty); // Type safe if ServerInterface is extended
1551
- * ```
1552
- */
1553
- embed: (key: string, value: any) => void;
1554
- /**
1555
- * Register a signal event listener to the server, this is useful for handling signals like SIGINT, SIGTERM, etc.
1556
- * @param event - The signal event to listen for
1557
- * @param cb - The callback to be called when the signal event is received
1558
- */
1559
- on: (event: SignalEvent, cb: () => SyncOrAsync) => void;
1560
- /**
1561
- * Register a signal event listener to the server, this is useful for handling signals like SIGINT, SIGTERM, etc.
1562
- * @param event - The signal event to listen for
1563
- * @param cb - The callback to be called when the signal event is received
1564
- */
1565
- once: (event: SignalEvent, cb: () => SyncOrAsync) => void;
1566
- /**
1567
- * Register a global middleware to be applied to all routes after the listener is bound, the middleware is applied in the order it is registered
1568
- */
1569
- use: (middleware: ServerRouteMiddleware) => void;
1570
- /**
1571
- * Set the error handler for the server
1572
- * @param errorHandler - The error handler to be applied to all routes
1573
- */
1574
- setErrorHandler: (errorHandler?: ServerErrorHandler) => void;
1575
- /**
1576
- * Sets a custom handler for 404 Not Found responses.
1577
- * If not set, the default RouteNotFoundError will be used.
1578
- *
1579
- * @param notFoundHandler - Optional handler to customize 404 responses
1580
- * @example
1581
- * server.setNotFoundHandler((req, res) => {
1582
- * res.status(404).json({ error: "Custom not found message" });
1583
- * });
1584
- */
1585
- setNotFoundHandler: (notFoundHandler?: ServerRouteHandler) => void;
1586
- /**
1587
- * Binds the server to the port and hostname defined in the serverOptions, meant to be called only once
1588
- * It initializes the server without blocking the event loop, you can pass a callback to be called when the server is listening
1589
- * Use `waitUntilListening` instead if you want to wait for the server to be listening for requests before returning
1590
- * @warning All routes defined with decorators are defined on this method just before the server starts listening for requests
1591
- */
1592
- listen: (cb?: ServerListenCallback) => void;
1593
- /**
1594
- * Binds the server to the port and hostname defined in the serverOptions, meant to be called only once
1595
- * It initializes the server blocking the event loop, it will wait for the server to be listening for requests before returning
1596
- * Use `listen` instead if you want to initialize the server without blocking the event loop
1597
- * @warning All routes defined with decorators are defined on this method just before the server starts listening for requests
1598
- */
1599
- waitUntilListening: () => Promise<void>;
1600
- /**
1601
- * Closes the server and frees the port
1602
- * This method is idempotent and can be called multiple times safely
1603
- * @alias disconnect
1604
- */
1605
- close: () => Promise<void>;
1606
- /**
1607
- * Disconnects the server and frees the port
1608
- * This method is idempotent and can be called multiple times safely
1609
- * Subsequent calls after the first will have no effect
1610
- */
1611
- disconnect: () => Promise<void>;
1612
- /**
1613
- * Configure hash settings for password hashing
1614
- * @param options - Hash configuration options
1615
- * @param options.iterations - Number of PBKDF2 iterations (default: 600,000)
1616
- * @param options.saltLength - Salt length in bytes (default: 16)
1617
- * @param options.keyLength - Key length in bits (default: 256)
1618
- */
1619
- configureHash: (options: {
1620
- iterations?: number;
1621
- saltLength?: number;
1622
- keyLength?: number;
1623
- }) => void;
1624
- /**
1625
- * Returns a mock server instance that can be used to test the server without starting it
1626
- * It will import the controllers and apply the plugins to the mock server
1627
- * @param options - The options for the mock server
1628
- * @param options.controllerPatterns - Custom controller patterns to import if the mock server must not be initialized with the same controller patterns as the server
1629
- */
1630
- getMockServer: () => Promise<MockServer>;
1631
- /**
1632
- * Exit current runtime process with the given code based on the current runtime
1633
- * @param code - The code to exit with, defaults to 0
1634
- * @example
1635
- * ```typescript
1636
- * server.exit(1); // If node process.exit(1) is called
1637
- * server.exit(); // If deno Deno.exit(0) is called
1638
- * ```
1639
- */
1640
- exit: (code?: number) => void;
1641
- }
1642
- type StandardMethodOptions = {
1643
- middlewares?: ServerRouteMiddleware[] | ServerRouteMiddleware;
1644
- swagger?: SwaggerRouteOptions;
1645
- };
1646
- type SignalEvent = Deno.Signal | NodeJS.Signals;
1647
-
1648
- type RunTimeType = "bun" | "node" | "deno";
1649
-
1650
- type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "OPTIONS" | "HEAD";
1651
- type NodeServer = Server$2 | Server$1 | Http2Server;
1652
- type RuntimeServer = NodeServer | ReturnType<typeof Bun.serve> | ReturnType<typeof Deno.serve>;
1653
- type RuntimeServerMap<T extends RunTimeType, H extends NodeHttpClient = "http"> = T extends "node" ? H extends "https" ? Server$1 : H extends "http2" | "http2-secure" ? Http2Server : Server$2 : T extends "bun" ? ReturnType<typeof Bun.serve> : T extends "deno" ? ReturnType<typeof Deno.serve> : never;
1654
- type HttpsOptions<T extends NodeHttpClient> = T extends "https" | "http2-secure" ? {
1655
- /** HTTPS/TLS options, required when nodeHttpClient is 'https' or 'http2-secure' */
1656
- httpsOptions: ServerOptions$1;
1657
- } : never;
1658
- type ServerConnectInput<H extends NodeHttpClient = NodeHttpClient> = {
1659
- /** The port to listen on, defaults to 80 */
1660
- port: number;
1661
- /** The hostname to listen on, defaults to 0.0.0.0 */
1662
- host: string;
1663
- /** The server routes with their corresponding handler */
1664
- routes: ServerRoute[];
1665
- /** The options for the server tap function */
1666
- tapOptions?: ServerTapOptions;
1667
- /** The runtime to use for the server */
1668
- runtime: RunTimeType;
1669
- /** Specific node client to use */
1670
- nodeHttpClient: H;
1671
- /** The graphql options to apply to the server */
1672
- graphql?: GraphQL;
1673
- } & (H extends "https" ? HttpsOptions<H> : {});
1674
- type ServerRouteMiddleware = (req: Request, res: Response$1, next: NextFunction) => SyncOrAsync;
1675
- type ServerRouteHandler = (req: Request, res: Response$1) => SyncOrAsync;
1676
- interface ServerRoute {
1677
- /** The path for the route */
1678
- path: string;
1679
- /** The HTTP method for the route */
1680
- method: HttpMethod;
1681
- /** The handler to call when the route is requested */
1682
- handler: ServerRouteHandler;
1683
- /** The middleware chain to call before the handler */
1684
- middlewares?: ServerRouteMiddleware[];
1685
- }
1686
- type ServerListenCallback = ({ port, host, url, }: {
1687
- port: number;
1688
- host: string;
1689
- url: string;
1690
- }) => SyncOrAsync;
1691
- /**
1692
- * Custom bun fetch call to be used as an hook inside Bun.serve method
1693
- */
1694
- type CustomBunFetch = (req: Request, server: Bun.Server<any>) => SyncOrAsync;
1695
- /**
1696
- * Custom deno fetch call to be used as an hook inside Deno.serve method
1697
- */
1698
- type CustomDenoFetch = (...options: Parameters<Parameters<typeof Deno.serve>[0]["handler"]>) => SyncOrAsync<Response | void>;
1699
- /**
1700
- * The options for the server tap function, allows you to interact with the server behavior before it is used to listen for incoming requests
1701
- */
1702
- type ServerTapOptionsBuilder<T extends RunTimeType> = T extends "node" ? (req: Omit<IncomingMessage, "url">) => Promise<void> : T extends "bun" ? Partial<Parameters<typeof Bun.serve>[0]> & {
1703
- fetch?: CustomBunFetch;
1704
- } : T extends "deno" ? Partial<Omit<Parameters<typeof Deno.serve>[0], "handler">> & {
1705
- handler?: CustomDenoFetch;
1706
- websocket?: {
1707
- open?: (ws: WebSocket) => void;
1708
- message?: (ws: WebSocket, message: string) => void;
1709
- close?: (ws: WebSocket) => void;
1710
- };
1711
- } : never;
1712
- type BunTapOptions = ServerTapOptionsBuilder<"bun">;
1713
- type NodeTapOptions = ServerTapOptionsBuilder<"node">;
1714
- type DenoTapOptions = ServerTapOptionsBuilder<"deno">;
1715
- type ServerTapOptions = {
1716
- bun?: BunTapOptions;
1717
- node?: NodeTapOptions;
1718
- deno?: DenoTapOptions;
1719
- };
1720
-
1721
- declare class MockResponse<T = any> {
1722
- private readonly response;
1723
- constructor(response: Response$1);
1724
- body(): T;
1725
- statusCode(): number;
1726
- headers(): Record<string, string>;
1727
- assertStatus(status: number): this;
1728
- assertHeader(header: string, value: string): this;
1729
- assertHeaderExists(header: string): this;
1730
- assertHeaderNotExists(header: string): this;
1731
- assertBodySubset(subset: Partial<T>): this;
1732
- assertBodyDeepEqual(expected: T): this;
1733
- assertBodyNotSubset(subset: Partial<T>): this;
1734
- assertBodyNotDeepEqual(expected: T): this;
1735
- assertCustom(assertion: (response: Response$1) => void): this;
1736
- private assertSubset;
1737
- private assertDeepEqual;
1738
- private assertNotSubset;
1739
- private assertNotDeepEqual;
1740
- private assertArraySubset;
1741
- private assertArrayDeepEqual;
1742
- private isObject;
1743
- }
1744
-
1745
- /**
1746
- * Type-safe options for the mock server
1747
- * @template TBody - The request body type
1748
- * @template TQuery - The query parameters type
1749
- */
1750
- interface MockServerOptions<TBody = any, TQuery extends Record<string, string> = any> {
1751
- /**
1752
- * The body of the request (typed)
1753
- */
1754
- body?: TBody;
1755
- /**
1756
- * The form data of the request
1757
- */
1758
- formData?: FormData;
1759
- /**
1760
- * The urlencoded body of the request
1761
- */
1762
- urlencoded?: Record<string, string>;
1763
- /**
1764
- * The headers of the request
1765
- */
1766
- headers?: Record<string, string>;
1767
- /**
1768
- * The query parameters of the request (typed)
1769
- */
1770
- query?: TQuery;
1771
- /**
1772
- * The cookies of the request
1773
- */
1774
- cookies?: Record<string, string>;
1775
- /**
1776
- * The ip of the request
1777
- */
1778
- ip?: string;
1779
- }
1780
-
1781
- /**
1782
- * Allows to mock server requests without needing to start the server, useful for testing purposes
1783
- */
1784
- declare class MockServer {
1785
- readonly server: Server<NodeHttpClient>;
1786
- private ensureGraphQLHandler;
1787
- constructor(server: Server<NodeHttpClient>);
1788
- /**
1789
- * Simulates an HTTP request without making an actual network call, useful for testing purposes
1790
- * Executes the middleware chain and handler of the route
1791
- * @param method - The HTTP method (GET, POST, PUT, DELETE, PATCH)
1792
- * @param path - The request path
1793
- * @param options - Request options including body, headers, query params, etc.
1794
- * @throws {Error} - If more than one of body, formData, urlencoded is provided
1795
- */
1796
- request<TResponse = any, TBody = any, TQuery extends Record<string, string> = any>(method: HttpMethod, path: string, options?: MockServerOptions<TBody, TQuery>): Promise<MockResponse<TResponse>>;
1797
- /**
1798
- * Type-safe GET request
1799
- * @template TResponse - The response body type
1800
- * @template TQuery - The query parameters type
1801
- * @example
1802
- * const res = await mock.get<UserResponse, { id: string }>("/users/123");
1803
- */
1804
- get<TResponse = any, TQuery extends Record<string, string> = any>(path: string, options?: Omit<MockServerOptions<never, TQuery>, "body" | "formData" | "urlencoded">): Promise<MockResponse<TResponse>>;
1805
- /**
1806
- * Type-safe POST request
1807
- * @template TResponse - The response body type
1808
- * @template TBody - The request body type
1809
- * @template TQuery - The query parameters type
1810
- * @example
1811
- * const res = await mock.post<UserResponse, CreateUserInput>("/users", { body: { name: "John" } });
1812
- */
1813
- post<TResponse = any, TBody = any, TQuery extends Record<string, string> = any>(path: string, options?: MockServerOptions<TBody, TQuery>): Promise<MockResponse<TResponse>>;
1814
- /**
1815
- * Type-safe PUT request
1816
- * @template TResponse - The response body type
1817
- * @template TBody - The request body type
1818
- * @template TQuery - The query parameters type
1819
- * @example
1820
- * const res = await mock.put<UserResponse, UpdateUserInput>("/users/123", { body: { name: "Jane" } });
1821
- */
1822
- put<TResponse = any, TBody = any, TQuery extends Record<string, string> = any>(path: string, options?: MockServerOptions<TBody, TQuery>): Promise<MockResponse<TResponse>>;
1823
- /**
1824
- * Type-safe PATCH request
1825
- * @template TResponse - The response body type
1826
- * @template TBody - The request body type
1827
- * @template TQuery - The query parameters type
1828
- * @example
1829
- * const res = await mock.patch<UserResponse, Partial<UpdateUserInput>>("/users/123", { body: { name: "Jane" } });
1830
- */
1831
- patch<TResponse = any, TBody = any, TQuery extends Record<string, string> = any>(path: string, options?: MockServerOptions<TBody, TQuery>): Promise<MockResponse<TResponse>>;
1832
- /**
1833
- * Type-safe DELETE request (no body allowed per HTTP spec)
1834
- * @template TResponse - The response body type
1835
- * @template TQuery - The query parameters type
1836
- * @example
1837
- * const res = await mock.delete<DeleteResponse>("/users/123");
1838
- */
1839
- delete<TResponse = any, TQuery extends Record<string, string> = any>(path: string, options?: Omit<MockServerOptions<never, TQuery>, "body" | "formData">): Promise<MockResponse<TResponse>>;
1840
- /**
1841
- * Converts FormData to a proper multipart/form-data body with boundaries
1842
- */
1843
- private formDataToMultipart;
1844
- private handleGraphQLRequest;
1845
- private validateOptions;
1846
- }
1847
-
1848
- /**
1849
- * The server class that is used to create and manage the server
1850
- */
1851
- declare class Server<H extends NodeHttpClient = NodeHttpClient> implements ServerInterface {
1852
- #private;
1853
- readonly _brand: "BaldaServer";
1854
- readonly serverOptions: ResolvedServerOptions;
1855
- readonly router: ClientRouter;
1856
- isListening: boolean;
1857
- isProduction: boolean;
1858
- graphql: GraphQL;
1859
- /**
1860
- * The constructor for the server
1861
- * @warning Routes will only be defined after calling the `listen` method so you're free to define middlewares before calling it
1862
- * @param options - The options for the server
1863
- * @param options.port - The port to listen on, if not provided, it will use the PORT environment variable, if not provided, it will default to 80
1864
- * @param options.host - The hostname to listen on, if not provided, it will use the HOST environment variable, if not provided, it will default to 0.0.0.0
1865
- * @param options.controllerPatterns - The patterns to match for controllers, defaults to an empty array
1866
- * @param options.plugins - The plugins to apply to the server, by default no plugins are applied, plugins are applied in the order they are defined in the options
1867
- * @param options.logger - The logger to use for the server, by default a default logger is used
1868
- * @param options.tapOptions - Options fetch to the runtime server before the server is up and running
1869
- * @param options.abortSignal - An optional AbortSignal to gracefully shutdown the server when aborted
1870
- */
1871
- constructor(options?: ServerOptions<H>);
1872
- get url(): string;
1873
- get port(): number;
1874
- get host(): string;
1875
- get routes(): Route[];
1876
- hash(data: string): Promise<string>;
1877
- compareHash(hash: string, data: string): Promise<boolean>;
1878
- getEnvironment(): Record<string, string>;
1879
- tmpDir(...append: string[]): string;
1880
- mkdir(path: string, options?: {
1881
- recursive?: boolean;
1882
- mode?: number | string;
1883
- }): Promise<void>;
1884
- get<TPath extends string = string>(path: TPath, handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>): void;
1885
- get<TPath extends string = string>(path: TPath, options: StandardMethodOptions, handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>): void;
1886
- post<TPath extends string = string>(path: TPath, handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>): void;
1887
- post<TPath extends string = string>(path: TPath, options: StandardMethodOptions, handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>): void;
1888
- patch<TPath extends string = string>(path: TPath, handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>): void;
1889
- patch<TPath extends string = string>(path: TPath, options: StandardMethodOptions, handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>): void;
1890
- put<TPath extends string = string>(path: TPath, handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>): void;
1891
- put<TPath extends string = string>(path: TPath, options: StandardMethodOptions, handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>): void;
1892
- delete<TPath extends string = string>(path: TPath, handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>): void;
1893
- delete<TPath extends string = string>(path: TPath, options: StandardMethodOptions, handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>): void;
1894
- options<TPath extends string = string>(path: TPath, handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>): void;
1895
- options<TPath extends string = string>(path: TPath, options: StandardMethodOptions, handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>): void;
1896
- head<TPath extends string = string>(path: TPath, handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>): void;
1897
- head<TPath extends string = string>(path: TPath, options: StandardMethodOptions, handler: (req: Request<ExtractParams<TPath>>, res: Response$1) => void | Promise<void>): void;
1898
- group(path: string, middleware: ServerRouteMiddleware[] | ServerRouteMiddleware, cb: (router: ClientRouter) => void): void;
1899
- group(path: string, cb: (router: ClientRouter) => void): void;
1900
- getNodeServer(): RuntimeServerMap<"node", H>;
1901
- getBunServer(): RuntimeServerMap<"bun">;
1902
- getDenoServer(): RuntimeServerMap<"deno">;
1903
- embed(key: string, value: any): void;
1904
- exit(code?: number): void;
1905
- on(event: SignalEvent, cb: () => SyncOrAsync): void;
1906
- on(event: string, cb: () => SyncOrAsync): void;
1907
- once(event: SignalEvent, cb: () => SyncOrAsync): void;
1908
- once(event: string, cb: () => SyncOrAsync): void;
1909
- use(...middlewares: ServerRouteMiddleware[]): void;
1910
- useExpress(pathOrMiddleware: string | RequestHandler | Router$1, maybeMiddleware?: RequestHandler | Router$1): void;
1911
- expressMiddleware(middleware: RequestHandler): ServerRouteMiddleware;
1912
- mountExpressRouter(basePath: string, expressRouter: Router$1): void;
1913
- setErrorHandler(errorHandler?: ServerErrorHandler): void;
1914
- setNotFoundHandler(notFoundHandler?: ServerRouteHandler): void;
1915
- listen(cb?: ServerListenCallback): void;
1916
- waitUntilListening(): Promise<void>;
1917
- /**
1918
- * Closes the server and frees the port
1919
- * This method is idempotent and can be called multiple times safely
1920
- * @returns A promise that resolves when the server is closed
1921
- */
1922
- close(): Promise<void>;
1923
- /**
1924
- * Disconnects the server and frees the port
1925
- * This method is idempotent and can be called multiple times safely
1926
- * Subsequent calls after the first will have no effect
1927
- * @returns A promise that resolves when the server is disconnected
1928
- */
1929
- disconnect(): Promise<void>;
1930
- configureHash(options: {
1931
- iterations?: number;
1932
- saltLength?: number;
1933
- keyLength?: number;
1934
- }): void;
1935
- getMockServer(options?: Pick<ServerOptions, "controllerPatterns">): Promise<MockServer>;
1936
- private importControllers;
1937
- private extractOptionsAndHandlerFromRouteRegistration;
1938
- private applyPlugins;
1939
- /**
1940
- * Initializes the server by importing the controllers and applying the plugins, it's idempotent, it will not re-import the controllers or apply the plugins if the server was already initialized (e.g. mockServer init)
1941
- * @internal
1942
- */
1943
- private bootstrap;
1944
- /**
1945
- * Handles not found routes by delegating to custom handler or default error response
1946
- * Checks if the path exists for other methods and returns 405 if so
1947
- * @internal
1948
- */
1949
- private handleNotFound;
1950
- /**
1951
- * Registers a not found route for all routes that are not defined
1952
- * @internal
1953
- */
1954
- private registerNotFoundRoutes;
1955
- /**
1956
- * Sets up the abort signal handler to gracefully shutdown the server when aborted
1957
- * @internal
1958
- */
1959
- private setupAbortSignalHandler;
1960
- }
1961
-
1962
- type CronSchedule = {
1963
- name: string;
1964
- args: Parameters<typeof schedule>;
1965
- };
1966
- type CronScheduleParams = Parameters<typeof schedule>;
1967
-
1968
- /**
1969
- * Decorator to schedule a cron job. Must be applied to a class method. By default, the cron job will not overlap with other cron jobs of the same type.
1970
- * ```ts
1971
- * @cron('* * * * *', { timezone: 'Europe/Istanbul' })
1972
- * async test() {
1973
- * console.log('test');
1974
- * }
1975
- * ```
1976
- */
1977
- declare const cron: (schedule: CronScheduleParams[0], options?: CronScheduleParams[2]) => (target: any, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
1978
-
1979
- type FlagType = "boolean" | "string" | "number" | "list";
1980
- type InferFlagType<T extends FlagType> = T extends "boolean" ? boolean : T extends "string" ? string : T extends "number" ? number : T extends "list" ? string[] : never;
1981
- type ArgOptions = {
1982
- /**
1983
- * The description of the argument.
1984
- */
1985
- description?: string;
1986
- /**
1987
- * Whether the argument is required.
1988
- * @default false
1989
- */
1990
- required?: boolean;
1991
- /**
1992
- * The default value of the argument.
1993
- */
1994
- defaultValue?: string;
1995
- /**
1996
- * A function to parse the argument value.
1997
- * @default The value is returned as is.
1998
- */
1999
- parse?: (value: string) => string;
2000
- };
2001
- type FlagOptions<T extends FlagType> = {
2002
- /**
2003
- * The description of the flag.
2004
- */
2005
- description?: string;
2006
- /**
2007
- * The type of the flag.
2008
- */
2009
- type: T;
2010
- /**
2011
- * The name of the flag.
2012
- * @default The name of the field.
2013
- */
2014
- name?: string;
2015
- /**
2016
- * The aliases of the flag.
2017
- */
2018
- aliases?: string[] | string;
2019
- /**
2020
- * The default value of the flag.
2021
- */
2022
- defaultValue?: InferFlagType<T>;
2023
- /**
2024
- * Whether the flag is required.
2025
- * @default false
2026
- */
2027
- required?: boolean;
2028
- /**
2029
- * A function to parse the flag value.
2030
- * @default The value is returned as is.
2031
- */
2032
- parse?: (value: any) => InferFlagType<T>;
2033
- };
2034
-
2035
- declare const VALIDATION_ERROR_SYMBOL = "VALIDATION_ERROR";
2036
- declare const ARG_SYMBOL = "ARG";
2037
- /**
2038
- * Decorator to mark a field of a command class as an argument.
2039
- * @param options - The options for the argument.
2040
- * @warning Arguments are evaluated in the order they are defined in the Command class.
2041
- */
2042
- declare const arg: (options: ArgOptions) => (target: any, propertyKey: string) => void;
2043
-
2044
- declare const flag: {
2045
- <T extends FlagType>(options: FlagOptions<T>): (target: any, propertyKey: string) => void;
2046
- boolean(options: Omit<FlagOptions<"boolean">, "type">): (target: any, propertyKey: string) => void;
2047
- string(options: Omit<FlagOptions<"string">, "type">): (target: any, propertyKey: string) => void;
2048
- number(options: Omit<FlagOptions<"number">, "type">): (target: any, propertyKey: string) => void;
2049
- list(options: Omit<FlagOptions<"list">, "type">): (target: any, propertyKey: string) => void;
2050
- array(options: Omit<FlagOptions<"list">, "type">): (target: any, propertyKey: string) => void;
2051
- };
2052
-
2053
- /**
2054
- * Decorator to mark a class as a controller, routes defined in the controller will be registered at import time when calling the `listen` method.
2055
- * You can customize the path pattern for controller imports in the server options `controllerPatterns`
2056
- * @param path - The path pattern for the controller.
2057
- * @param swaggerOptions - The swagger options for the controller that will be applied to all routes defined in the controller. Controller options will override route options.
2058
- * @swagger If swagger is enabled, the default service name for all routes defined in the controller will be the controller name.
2059
- * @swagger For naming commodity, the default service name will remove the "Controller" suffix if it exists. e.g. "UserController" -> "User"
2060
- */
2061
- declare const controller: (path?: string, swaggerOptions?: SwaggerRouteOptions) => (target: any) => void;
2062
-
2063
- /**
2064
- * Decorator to mark a handler for a DELETE request with type-safe path parameters and response body
2065
- * DELETE requests cannot have a request body (by HTTP spec)
2066
- * Query params must be validated with @validate decorators to be typed
2067
- * @param path - The path of the route (path parameters will be automatically inferred)
2068
- * @param options - The options for the route
2069
- * @warning Must receive the request and response as the first two arguments or it might not work as expected.
2070
- * @example
2071
- * ```ts
2072
- * import { del, controller, Request, Response } from "balda";
2073
- *
2074
- * type DeletedResponse = { id: string; deleted: boolean };
2075
- *
2076
- * @controller("/api")
2077
- * class MyController {
2078
- * @del("/:id")
2079
- * async handler(
2080
- * req: Request<{ id: string }>,
2081
- * res: Response<DeletedResponse>
2082
- * ) {
2083
- * const { id } = req.params; // ✅ id is typed as string!
2084
- * res.json({ id, deleted: true });
2085
- * }
2086
- * }
2087
- * ```
2088
- */
2089
- declare const del: <TPath extends string = string>(path: TPath, options?: SwaggerRouteOptions) => <T extends (req: Request<ExtractParams<TPath>>, res: Response$1, ...args: any[]) => any>(target: any, propertyKey: string, descriptor: PropertyDescriptor) => TypedPropertyDescriptor<T>;
2090
-
2091
- /**
2092
- * Decorator to mark a handler for a GET request with type-safe path parameters and response body
2093
- * GET requests cannot have a request body (by HTTP spec)
2094
- * Body and query must be validated with @validate decorators to be typed
2095
- * @param path - The path of the route (path parameters will be automatically inferred)
2096
- * @param options - The options for the route
2097
- * @warning Must receive the request and response as the first two arguments or it might not work as expected.
2098
- * @example
2099
- * ```ts
2100
- * import { get, controller, validate, Request, Response } from "balda";
2101
- * import { z } from "zod";
2102
- *
2103
- * const UserQuerySchema = z.object({ include: z.string().optional() });
2104
- * type UserQuery = z.infer<typeof UserQuerySchema>;
2105
- * type UserResponse = { id: string; name: string };
2106
- *
2107
- * @controller("/api")
2108
- * class MyController {
2109
- * @get("/:id")
2110
- * @validate.query(UserQuerySchema)
2111
- * async handler(
2112
- * req: Request<{ id: string }>,
2113
- * res: Response<UserResponse>,
2114
- * query: UserQuery // ✅ Validated and typed!
2115
- * ) {
2116
- * const { id } = req.params; // ✅ id is typed as string!
2117
- * const { include } = query; // ✅ query is validated and typed!
2118
- * res.json({ id, name: "John" });
2119
- * }
2120
- * }
2121
- * ```
2122
- */
2123
- declare const get: <TPath extends string = string>(path: TPath, options?: SwaggerRouteOptions) => <T extends (req: Request<ExtractParams<TPath>>, res: Response$1, ...args: any[]) => any>(target: any, propertyKey: string, descriptor: PropertyDescriptor) => TypedPropertyDescriptor<T>;
2124
-
2125
- /**
2126
- * Decorator to mark a handler for a PATCH request with type-safe path parameters and response body
2127
- * Body and query must be validated with @validate decorators to be typed
2128
- * @param path - The path of the route (path parameters will be automatically inferred)
2129
- * @param options - The options for the route
2130
- * @warning Must receive the request and response as the first two arguments or it might not work as expected.
2131
- * @example
2132
- * ```ts
2133
- * import { patch, controller, validate, Request, Response } from "balda";
2134
- * import { z } from "zod";
2135
- *
2136
- * const UpdateUserSchema = z.object({ name: z.string().optional() });
2137
- * type UpdateUserInput = z.infer<typeof UpdateUserSchema>;
2138
- * type UpdatedResponse = { id: string; updated: boolean };
2139
- *
2140
- * @controller("/api")
2141
- * class MyController {
2142
- * @patch("/:id")
2143
- * @validate.body(UpdateUserSchema)
2144
- * async handler(
2145
- * req: Request<{ id: string }>,
2146
- * res: Response<UpdatedResponse>,
2147
- * body: UpdateUserInput // ✅ Validated and typed!
2148
- * ) {
2149
- * const { id } = req.params; // ✅ id is typed as string!
2150
- * res.json({ id, updated: true });
2151
- * }
2152
- * }
2153
- * ```
2154
- */
2155
- declare const patch: <TPath extends string = string>(path: TPath, options?: SwaggerRouteOptions) => <T extends (req: Request<ExtractParams<TPath>>, res: Response$1, ...args: any[]) => any>(target: any, propertyKey: string, descriptor: PropertyDescriptor) => TypedPropertyDescriptor<T>;
2156
-
2157
- /**
2158
- * Decorator to mark a handler for a POST request with type-safe path parameters and response body
2159
- * Body and query must be validated with @validate decorators to be typed
2160
- * @param path - The path of the route (path parameters will be automatically inferred)
2161
- * @param options - The options for the route
2162
- * @warning Must receive the request and response as the first two arguments or it might not work as expected.
2163
- * @example
2164
- * ```ts
2165
- * import { post, controller, validate, Request, Response } from "balda";
2166
- * import { z } from "zod";
2167
- *
2168
- * const CreateUserSchema = z.object({ name: z.string(), email: z.string().email() });
2169
- * type CreateUserInput = z.infer<typeof CreateUserSchema>;
2170
- * type CreatedResponse = { id: string; created: boolean };
2171
- *
2172
- * @controller("/api")
2173
- * class MyController {
2174
- * @post("/")
2175
- * @validate.body(CreateUserSchema)
2176
- * async handler(
2177
- * req: Request<{}>,
2178
- * res: Response<CreatedResponse>,
2179
- * body: CreateUserInput // ✅ Validated and typed!
2180
- * ) {
2181
- * const { name, email } = body; // ✅ body is validated and typed!
2182
- * res.json({ id: "123", created: true });
2183
- * }
2184
- * }
2185
- * ```
2186
- */
2187
- declare const post: <TPath extends string = string>(path: TPath, options?: SwaggerRouteOptions) => <T extends (req: Request<ExtractParams<TPath>>, res: Response$1, ...args: any[]) => any>(target: any, propertyKey: string, descriptor: PropertyDescriptor) => TypedPropertyDescriptor<T>;
2188
-
2189
- /**
2190
- * Decorator to mark a handler for a PUT request with type-safe path parameters and response body
2191
- * Body and query must be validated with @validate decorators to be typed
2192
- * @param path - The path of the route (path parameters will be automatically inferred)
2193
- * @param options - The options for the route
2194
- * @warning Must receive the request and response as the first two arguments or it might not work as expected.
2195
- * @example
2196
- * ```ts
2197
- * import { put, controller, validate, Request, Response } from "balda";
2198
- * import { z } from "zod";
2199
- *
2200
- * const UpdateUserSchema = z.object({ name: z.string(), email: z.string().email() });
2201
- * type UpdateUserInput = z.infer<typeof UpdateUserSchema>;
2202
- * type UserResponse = { id: string; name: string };
2203
- *
2204
- * @controller("/api")
2205
- * class MyController {
2206
- * @put("/:id")
2207
- * @validate.body(UpdateUserSchema)
2208
- * async handler(
2209
- * req: Request<{ id: string }>,
2210
- * res: Response<UserResponse>,
2211
- * body: UpdateUserInput // ✅ Validated and typed!
2212
- * ) {
2213
- * const { id } = req.params; // ✅ id is typed as string!
2214
- * res.json({ id, name: body.name });
2215
- * }
2216
- * }
2217
- * ```
2218
- */
2219
- declare const put: <TPath extends string = string>(path: TPath, options?: SwaggerRouteOptions) => <T extends (req: Request<ExtractParams<TPath>>, res: Response$1, ...args: any[]) => any>(target: any, propertyKey: string, descriptor: PropertyDescriptor) => TypedPropertyDescriptor<T>;
2220
-
2221
- /**
2222
- * Type-safe handler for routes with typed path parameters and response
2223
- * Body and query are validated first and passed as separate typed arguments
2224
- * @example
2225
- * TypedHandler<"/users/:id", CreateUserSchema, SearchQuerySchema, UserResponse>
2226
- * → (req: Request<{ id: string }>, res: Response<UserResponse>, body: CreateUserInput, query: SearchQuery) => void | Promise<void>
2227
- */
2228
- type TypedHandler<TPath extends string, TBody extends RequestSchema | undefined = undefined, TQuery extends RequestSchema | undefined = undefined, TResponseBody = any> = (req: Request<ExtractParams<TPath>>, res: Response$1<TResponseBody>, ...args: [
2229
- ...(TBody extends RequestSchema ? [body: InferSchemaType<TBody>] : []),
2230
- ...(TQuery extends RequestSchema ? [query: InferSchemaType<TQuery>] : [])
2231
- ]) => void | Promise<void>;
2232
- /**
2233
- * Metadata for typed routes
2234
- * Stores path and extracted parameter types
2235
- */
2236
- interface TypedRouteMetadata<TPath extends string = string> {
2237
- path: TPath;
2238
- params: ExtractParams<TPath>;
2239
- }
2240
-
2241
- /**
2242
- * Decorator to mark a middleware for a route or a controller class
2243
- */
2244
- declare const middleware: (middleware: ServerRouteMiddleware | ServerRouteMiddleware[]) => (target: any, propertyKey?: string, descriptor?: PropertyDescriptor) => any;
2245
-
2246
- interface SerializeOptions {
2247
- /**
2248
- * The status code to serialize the response body against (useful only for the documentation does not affect the actual response status)
2249
- * @default 200
2250
- */
2251
- status?: number;
2252
- /**
2253
- * Whether to use safe serialization (returns original data if serialization fails instead of throwing)
2254
- * Advised to only set unsafe if development environment
2255
- * @default true
2256
- */
2257
- safe?: boolean;
2258
- }
2259
-
2260
- declare const serialize: <T extends RequestSchema>(schema: T, options?: SerializeOptions) => (target: any, propertyKey: string, descriptor: PropertyDescriptor) => void;
2261
-
2262
- declare const validate: {
2263
- (options: ValidationOptions & {
2264
- customError?: CustomValidationError;
2265
- }): (target: any, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
2266
- query(schema: RequestSchema, customError?: CustomValidationError): (target: any, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
2267
- body(schema: RequestSchema, customError?: CustomValidationError): (target: any, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
2268
- all(schema: RequestSchema, customError?: CustomValidationError): (target: any, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
2269
- };
2270
-
2271
- /**
2272
- * Base class for cron jobs with logger instance
2273
- * @example
2274
- * export default class MyCron extends BaseCron {
2275
- * @cron("* * * * *")
2276
- * handle() {
2277
- * this.logger.info("Running cron job");
2278
- * }
2279
- * }
2280
- */
2281
- declare class BaseCron {
2282
- protected readonly logger: pino.Logger<string, boolean>;
2283
- }
2284
-
2285
- declare class CronService {
2286
- static scheduledJobs: CronSchedule[];
2287
- /**
2288
- * @description Schedule a cron job.
2289
- * @internal
2290
- * @example
2291
- * CronService.register('test', '0 0 * * *', () => {
2292
- * console.log('test');
2293
- * }, {
2294
- * timezone: 'Europe/Istanbul',
2295
- * });
2296
- */
2297
- static register(name: string, ...args: CronScheduleParams): void;
2298
- /**
2299
- * @description Start the cron scheduler.
2300
- */
2301
- static run(): Promise<void>;
2302
- /**
2303
- * @description Main error handler for cron jobs. You can write your own error handler by overriding this static method for example with sentry.
2304
- */
2305
- static globalErrorHandler(context: TaskContext): void;
2306
- /**
2307
- * @description Import all cron jobs from the app/cron/schedules directory
2308
- */
2309
- static massiveImportCronJobs(cronJobPatterns: string[]): Promise<void>;
2310
- }
2311
- declare const setCronGlobalErrorHandler: (globalErrorHandler: (...args: Parameters<(typeof CronService)["globalErrorHandler"]>) => void) => void;
2312
-
2313
- /**
2314
- * Base class for MQTT handlers with logger instance
2315
- * @example
2316
- * declare module "balda" {
2317
- * export interface BaseMqtt {
2318
- * logger: Logger;
2319
- * }
2320
- * }
2321
- *
2322
- * export default class TemperatureHandler extends BaseMqtt {
2323
- * @mqtt("home/temperature")
2324
- * handle(topic: string, message: Buffer) {
2325
- * this.logger.info("Received temperature:", message.toString());
2326
- * }
2327
- * }
2328
- */
2329
- declare class BaseMqtt {
2330
- protected readonly logger: pino.Logger<string, boolean>;
2331
- }
2332
-
2333
- interface MqttTopics {
2334
- }
2335
- /**
2336
- * Expands MQTT wildcard patterns to allow publishing to concrete topics
2337
- * - "test/wildcard/+/data" allows "test/wildcard/anything/data"
2338
- * - "test/multilevel/#" allows "test/multilevel/anything/else"
2339
- */
2340
- type ExpandWildcardTopic<T extends string> = T extends `${infer Before}/+/${infer After}` ? `${Before}/${string}/${ExpandWildcardTopic<After>}` : T extends `${infer Before}/+` ? `${Before}/${string}` : T extends `${infer Before}/#` ? `${Before}/${string}` : T;
2341
- /**
2342
- * Expands all wildcard topics in MqttTopics interface
2343
- */
2344
- type ExpandedMqttTopics<T extends MqttTopics> = {
2345
- [K in keyof T as K extends string ? ExpandWildcardTopic<K> : K]: T[K];
2346
- };
2347
- /**
2348
- * Union of exact topic keys and expanded wildcard topics
2349
- */
2350
- type PublishTopic<T extends MqttTopics> = keyof T | keyof ExpandedMqttTopics<T>;
2351
- type MqttHandler<T extends MqttTopics> = (topic: keyof T, message: T[keyof T]) => void | Promise<void>;
2352
- type MqttSubscription<T extends MqttTopics> = {
2353
- name: string;
2354
- topic: keyof T;
2355
- handler: MqttHandler<T>;
2356
- options?: IClientSubscribeOptions;
2357
- };
2358
- type MqttSubscribeOptions = IClientSubscribeOptions;
2359
- type MqttPublishOptions = IClientPublishOptions;
2360
- type MqttConnectionOptions = IClientOptions;
2361
-
2362
- declare class MqttService {
2363
- static subscriptions: MqttSubscription<MqttTopics>[];
2364
- static client: MqttClient | null;
2365
- static connectionOptions: MqttConnectionOptions;
2366
- /**
2367
- * @description Register an MQTT subscription handler.
2368
- * @internal
2369
- * @example
2370
- * MqttService.register('test', 'home/temperature', (topic, message) => {
2371
- * console.log('Received message:', message.toString());
2372
- * }, { qos: 1 });
2373
- */
2374
- static register<T extends MqttTopics>(name: string, topic: keyof T, handler: MqttHandler<T>, options?: IClientSubscribeOptions): void;
2375
- /**
2376
- * @description Connect to the MQTT broker and subscribe to all registered topics.
2377
- */
2378
- static connect(connectionOptions?: MqttConnectionOptions): Promise<void>;
2379
- /**
2380
- * @description Subscribe to all registered topics.
2381
- * @internal
2382
- */
2383
- private static subscribeToTopics;
2384
- /**
2385
- * @description Handle incoming MQTT messages.
2386
- * @internal
2387
- */
2388
- private static handleMessage;
2389
- /**
2390
- * @description Main error handler for MQTT operations. You can write your own error handler by overriding this static method for example with sentry.
2391
- */
2392
- static globalErrorHandler(error: Error): SyncOrAsync<void>;
2393
- static setOnDisconnectHandler(handler: () => void): void;
2394
- static setOnReconnectHandler(handler: () => void): void;
2395
- /**
2396
- * @description Import all MQTT handlers from specified patterns
2397
- */
2398
- static massiveImportMqttHandlers(mqttHandlerPatterns: string[]): Promise<void>;
2399
- /**
2400
- * Create a decorator to subscribe to an MQTT topic
2401
- * Messages are automatically parsed: Buffer -> JSON object (if valid) -> string
2402
- * Supports MQTT wildcards: + (single level) and # (multi level)
2403
- *
2404
- * Handler signature can be either:
2405
- * - `handler(message: T)` - just the message (topic omitted)
2406
- * - `handler(topic: string, message: T)` - include topic for wildcards or logging
2407
- *
2408
- * @example
2409
- * @mqtt.handler('home/temperature', { qos: 1 })
2410
- * handleTemperature(message: { value: number; unit: string }) {
2411
- * console.log('Temperature:', message.value, message.unit);
2412
- * }
2413
- *
2414
- * @example With topic parameter (useful for wildcards)
2415
- * @mqtt.handler('home/+/temperature', { qos: 1 })
2416
- * handleRoomTemperature(topic: string, message: string) {
2417
- * const room = topic.split('/')[1];
2418
- * console.log(`${room} temperature:`, message);
2419
- * }
2420
- */
2421
- subscribe<T extends MqttTopics = MqttTopics>(topic: keyof T, options?: IClientSubscribeOptions): (target: any, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
2422
- /**
2423
- * @description Unsubscribe from an MQTT topic
2424
- * @param topic - The topic to unsubscribe from
2425
- * @throws BaldaError if the MQTT client is not connected
2426
- * @example
2427
- * await mqtt.unsubscribe('home/temperature');
2428
- */
2429
- unsubscribe<T extends MqttTopics>(topic: keyof T): Promise<void>;
2430
- /**
2431
- * @description Publish a message to an MQTT topic
2432
- * @param topic - The topic to publish to (supports wildcard expansions)
2433
- * @param message - The message payload (string, Buffer, or object that will be JSON stringified)
2434
- * @param options - Publish options (qos, retain, etc.)
2435
- * @throws BaldaError if the MQTT client is not connected or is not installed as a dependency
2436
- */
2437
- publish<T extends MqttTopics>(topic: PublishTopic<T>, message: T[keyof T], options?: MqttPublishOptions): Promise<void>;
2438
- /**
2439
- * @description Disconnect the MQTT client gracefully
2440
- */
2441
- static disconnect(): Promise<void>;
2442
- }
2443
- declare const setMqttGlobalErrorHandler: (globalErrorHandler: (...args: Parameters<(typeof MqttService)["globalErrorHandler"]>) => void) => void;
2444
- /**
2445
- * Singleton instance for publishing MQTT messages
2446
- * @example
2447
- * import { mqtt } from 'balda';
2448
- *
2449
- * await mqtt.publish('home/temperature', { value: 23.5, unit: 'C' }, { qos: 1 });
2450
- */
2451
- declare const mqtt: MqttService;
2452
-
2453
- /**
2454
- * Base class for queue handlers with logger instance
2455
- * @example
2456
- * const myQueue = bullmqQueue<MyPayload>("my-topic");
2457
- *
2458
- * export default class MyQueue extends BaseQueue {
2459
- * @myQueue.subscribe()
2460
- * async handle(payload: MyPayload) {
2461
- * this.logger.info({ payload }, "Processing queue message");
2462
- * }
2463
- * }
2464
- */
2465
- declare class BaseQueue {
2466
- protected readonly logger: pino.Logger<string, boolean>;
2467
- }
2468
-
2469
- declare class BullMQPubSub implements GenericPubSub {
2470
- private queues;
2471
- private workers;
2472
- private bullmqClient;
2473
- publish<TPayload>(topic: string, payload: TPayload, options?: PublishOptions<"bullmq">): Promise<{
2474
- id: string;
2475
- }>;
2476
- subscribe<TPayload>(topic: string, handler: (payload: TPayload) => Promise<void>): Promise<void>;
2477
- unsubscribe(topic: string): Promise<void>;
2478
- private getQueue;
2479
- private getBullMQClient;
2480
- publishWithConfig<TPayload>(topic: string, payload: TPayload, options?: PublishOptions<"bullmq">, queueConfig?: BullMQQueueOptions): Promise<{
2481
- id: string;
2482
- }>;
2483
- subscribeWithConfig<TPayload>(topic: string, handler: (payload: TPayload) => Promise<void>, queueConfig?: BullMQQueueOptions): Promise<void>;
2484
- private getQueueWithConfig;
2485
- private getQueueKey;
2486
- private getWorkerKey;
2487
- }
2488
-
2489
- declare class MemoryPubSub implements GenericPubSub {
2490
- private subscribers;
2491
- private messageQueue;
2492
- private readonly maxQueueSize;
2493
- private processingPromise;
2494
- constructor(maxQueueSize?: number);
2495
- /**
2496
- * Clear all subscribers and pending messages
2497
- * @internal Used for test cleanup
2498
- */
2499
- clear(): void;
2500
- publish<TPayload>(topic: string, payload: TPayload, _options?: Record<string, unknown>): Promise<{
2501
- id: string;
2502
- }>;
2503
- subscribe<TPayload>(topic: string, handler: (payload: TPayload) => Promise<void>): Promise<void>;
2504
- unsubscribe(topic: string): Promise<void>;
2505
- private processQueue;
2506
- }
2507
-
2508
- declare class PGBossPubSub implements GenericPubSub {
2509
- private boss;
2510
- private createdQueues;
2511
- private workers;
2512
- publish<TPayload>(topic: string, payload: TPayload, options?: PublishOptions<"pgboss">): Promise<{
2513
- id: string;
2514
- }>;
2515
- subscribe<TPayload>(topic: string, handler: (payload: TPayload) => Promise<void>): Promise<void>;
2516
- unsubscribe(topic: string): Promise<void>;
2517
- private getBoss;
2518
- private ensureQueue;
2519
- publishWithConfig<TPayload>(topic: string, payload: TPayload, options?: PublishOptions<"pgboss">, queueConfig?: PGBossQueueOptions): Promise<{
2520
- id: string;
2521
- }>;
2522
- subscribeWithConfig<TPayload>(topic: string, handler: (payload: TPayload) => Promise<void>, queueConfig?: PGBossQueueOptions): Promise<void>;
2523
- private bossInstances;
2524
- private getBossWithConfig;
2525
- private ensureQueueWithBoss;
2526
- }
2527
-
2528
- declare class SQSPubSub implements GenericPubSub {
2529
- private consumers;
2530
- private client?;
2531
- private sqsLib;
2532
- private sqsConsumerLib;
2533
- publish<TPayload>(topic: string, payload: TPayload, options?: PublishOptions<"sqs">): Promise<{
2534
- id: string;
2535
- }>;
2536
- subscribe<TPayload>(topic: string, handler: (payload: TPayload) => Promise<void>): Promise<void>;
2537
- unsubscribe(topic: string): Promise<void>;
2538
- private getClient;
2539
- private getSqsLib;
2540
- private getSqsConsumerLib;
2541
- private resolveQueueUrl;
2542
- publishWithConfig<TPayload>(topic: string, payload: TPayload, options?: PublishOptions<"sqs">, queueConfig?: SQSQueueOptions): Promise<{
2543
- id: string;
2544
- }>;
2545
- subscribeWithConfig<TPayload>(topic: string, handler: (payload: TPayload) => Promise<void>, queueConfig?: SQSQueueOptions): Promise<void>;
2546
- private getClientWithConfig;
2547
- }
2548
-
2549
- type BullMQAddTaskOptions = JobsOptions;
2550
- type PGBossSendOptions = SendOptions;
2551
- type SQSPublishOptions = Omit<SendMessageCommandInput, "MessageBody">;
2552
- /**
2553
- * Built-in provider keys
2554
- */
2555
- type BuiltInProviderKey = "bullmq" | "sqs" | "pgboss" | "memory";
2556
- type PublishOptions<T extends BuiltInProviderKey> = T extends "bullmq" ? BullMQAddTaskOptions : T extends "sqs" ? SQSPublishOptions : T extends "pgboss" ? PGBossSendOptions : T extends "memory" ? Record<string, unknown> : never;
2557
- type SQSQueueOptions = {
2558
- queueUrl: string;
2559
- client?: SQSClientConfig;
2560
- };
2561
- type BullMQQueueOptions = ConstructorParameters<typeof Queue>[1];
2562
- type PGBossQueueOptions = {
2563
- connectionString?: string;
2564
- };
2565
- /**
2566
- * Generic PubSub interface for typed queues
2567
- * @template TPayload - The type of the payload
2568
- * @returns A Promise that resolves to an object with an id property
2569
- * @example
2570
- * ```typescript
2571
- * const pubsub: GenericPubSub<{ name: string }> = {
2572
- * async publish(topic, payload, options) {
2573
- * return { id: '123' };
2574
- * },
2575
- * async subscribe(topic, handler) {
2576
- * console.log('subscribed');
2577
- * },
2578
- * async unsubscribe(topic) {
2579
- * console.log('unsubscribed');
2580
- * },
2581
- * };
2582
- * ```
2583
- */
2584
- interface GenericPubSub<TPayload = unknown> {
2585
- publish(topic: string, payload: TPayload, options?: Record<string, unknown>): Promise<{
2586
- id: string;
2587
- }>;
2588
- subscribe(topic: string, handler: (payload: TPayload) => Promise<void>): Promise<void>;
2589
- unsubscribe(topic: string): Promise<void>;
2590
- }
2591
- interface QueueProvider {
2592
- bullmq: BullMQPubSub;
2593
- sqs: SQSPubSub;
2594
- pgboss: PGBossPubSub;
2595
- memory: MemoryPubSub;
2596
- }
2597
- type QueueProviderKey = keyof QueueProvider;
2598
-
2599
- type QueueOptionsForProvider<P extends BuiltInProviderKey> = P extends "sqs" ? SQSQueueOptions : P extends "bullmq" ? BullMQQueueOptions : P extends "pgboss" ? PGBossQueueOptions : P extends "memory" ? Record<string, unknown> : never;
2600
- /**
2601
- * TypedQueue for built-in providers (sqs, bullmq, pgboss)
2602
- */
2603
- declare class TypedQueue<TPayload, TProvider extends BuiltInProviderKey = BuiltInProviderKey> {
2604
- readonly topic: string;
2605
- readonly provider: TProvider;
2606
- private readonly queueOptions?;
2607
- constructor(topic: string, provider: TProvider, queueOptions?: QueueOptionsForProvider<TProvider> | undefined);
2608
- publish(payload: TPayload, options?: PublishOptions<TProvider>): Promise<{
2609
- id: string;
2610
- }>;
2611
- /**
2612
- * Subscribe to the queue, to be used as a decorator on a class method
2613
- * @example
2614
- * ```ts
2615
- * @queue.subscribe()
2616
- * async handle(payload: TPayload) {
2617
- * console.log(payload);
2618
- * }
2619
- * ```
2620
- */
2621
- subscribe(): MethodDecorator;
2622
- /**
2623
- * Subscribe to the queue with the given handler
2624
- * @param handler - The handler function to subscribe to the queue
2625
- * @returns A promise that resolves when subscription is complete
2626
- * @example
2627
- * ```ts
2628
- * await queue.subscribe(async (payload: TPayload) => {
2629
- * console.log(payload);
2630
- * });
2631
- * // Later: await queue.unsubscribe()
2632
- * ```
2633
- */
2634
- subscribe(handler: (payload: TPayload) => Promise<void>): Promise<void>;
2635
- /**
2636
- * Unsubscribe from the queue
2637
- * @returns A promise that resolves when unsubscription is complete
2638
- * @example
2639
- * ```ts
2640
- * await queue.unsubscribe();
2641
- * ```
2642
- */
2643
- unsubscribe(): Promise<void>;
2644
- private createSubscribeDecorator;
2645
- private subscribeWithCallback;
2646
- }
2647
- /**
2648
- * CustomTypedQueue for user-defined custom providers
2649
- */
2650
- declare class CustomTypedQueue<TPayload, TOptions = Record<string, unknown>> {
2651
- readonly topic: string;
2652
- private readonly pubsub;
2653
- constructor(topic: string, pubsub: GenericPubSub<TPayload>);
2654
- publish(payload: TPayload, options?: TOptions): Promise<{
2655
- id: string;
2656
- }>;
2657
- subscribe(): MethodDecorator;
2658
- subscribe(handler: (payload: TPayload) => Promise<void>): Promise<void>;
2659
- /**
2660
- * Unsubscribe from the queue
2661
- * @returns A promise that resolves when unsubscription is complete
2662
- * @example
2663
- * ```ts
2664
- * await queue.unsubscribe();
2665
- * ```
2666
- */
2667
- unsubscribe(): Promise<void>;
2668
- private createSubscribeDecorator;
2669
- }
2670
-
2671
- /**
2672
- * Create a typed SQS queue
2673
- * @param topic - The queue topic name
2674
- * @param options - SQS-specific options including queueUrl
2675
- * @returns A TypedQueue instance for SQS
2676
- *
2677
- * @example
2678
- * ```typescript
2679
- * const userQueue = sqsQueue<{ userId: string }>('user-events', {
2680
- * queueUrl: 'https://sqs.us-east-1.amazonaws.com/123456789/my-queue'
2681
- * });
2682
- *
2683
- * // Publishing
2684
- * await userQueue.publish({ userId: '123' });
2685
- *
2686
- * // Subscribing with decorator
2687
- * class UserHandler {
2688
- * @userQueue.subscribe()
2689
- * async handle(payload: { userId: string }) {}
2690
- * }
2691
- *
2692
- * // Subscribing with callback
2693
- * await userQueue.subscribe(async (payload) => {
2694
- * console.log(payload.userId);
2695
- * });
2696
- * ```
2697
- */
2698
- declare function sqsQueue<TPayload>(topic: string, options?: SQSQueueOptions): TypedQueue<TPayload, "sqs">;
2699
- /**
2700
- * Create a typed BullMQ queue
2701
- * @param topic - The queue topic name
2702
- * @param options - BullMQ-specific options (connection, job options, etc.)
2703
- * @returns A TypedQueue instance for BullMQ
2704
- *
2705
- * @example
2706
- * ```typescript
2707
- * const orderQueue = bullmqQueue<{ orderId: number }>('orders', {
2708
- * connection: { host: 'localhost', port: 6379 }
2709
- * });
2710
- *
2711
- * // Publishing
2712
- * await orderQueue.publish({ orderId: 123 });
2713
- *
2714
- * // Subscribing with decorator
2715
- * class OrderHandler {
2716
- * @orderQueue.subscribe()
2717
- * async handle(payload: { orderId: number }) {}
2718
- * }
2719
- * ```
2720
- */
2721
- declare function bullmqQueue<TPayload>(topic: string, options?: BullMQQueueOptions): TypedQueue<TPayload, "bullmq">;
2722
- /**
2723
- * Create a typed PGBoss queue
2724
- * @param topic - The queue topic name
2725
- * @param options - PGBoss-specific options
2726
- * @returns A TypedQueue instance for PGBoss
2727
- *
2728
- * @example
2729
- * ```typescript
2730
- * const notificationQueue = pgbossQueue<{ message: string }>('notifications');
2731
- *
2732
- * // Publishing
2733
- * await notificationQueue.publish({ message: 'Hello!' });
2734
- *
2735
- * // Subscribing with decorator
2736
- * class NotificationHandler {
2737
- * @notificationQueue.subscribe()
2738
- * async handle(payload: { message: string }) {}
2739
- * }
2740
- * ```
2741
- */
2742
- declare function pgbossQueue<TPayload>(topic: string, options?: PGBossQueueOptions): TypedQueue<TPayload, "pgboss">;
2743
- /**
2744
- * Create a typed in-memory queue
2745
- * @param topic - The queue topic name
2746
- * @returns A TypedQueue instance for in-memory processing
2747
- *
2748
- * @example
2749
- * ```typescript
2750
- * const emailQueue = memoryQueue<{ to: string; subject: string }>('emails');
2751
- *
2752
- * // Publishing
2753
- * await emailQueue.publish({ to: 'user@example.com', subject: 'Hello' });
2754
- *
2755
- * // Subscribing with decorator
2756
- * class EmailHandler {
2757
- * @emailQueue.subscribe()
2758
- * async handle(payload: { to: string; subject: string }) {}
2759
- * }
2760
- * ```
2761
- */
2762
- declare function memoryQueue<TPayload>(topic: string): TypedQueue<TPayload, "memory">;
2763
- /**
2764
- * Create a typed queue with a custom PubSub provider
2765
- * @param topic - The queue topic name
2766
- * @param pubsub - A custom PubSub implementation
2767
- * @returns A CustomTypedQueue instance for the custom provider
2768
- *
2769
- * @example
2770
- * ```typescript
2771
- * const customProvider: GenericPubSub<MyPayload> = {
2772
- * async publish(topic, payload, options) {
2773
- * // Custom publish logic
2774
- * return { id: 'custom-id' };
2775
- * },
2776
- * async subscribe(topic, handler) {
2777
- * // Custom subscribe logic
2778
- * }
2779
- * };
2780
- *
2781
- * const customQueue = createQueue<{ data: string }>('custom-topic', customProvider);
2782
- *
2783
- * await customQueue.publish({ data: 'test' });
2784
- * ```
2785
- */
2786
- declare function createQueue<TPayload, TOptions = Record<string, unknown>>(topic: string, pubsub: GenericPubSub<TPayload>): CustomTypedQueue<TPayload, TOptions>;
2787
-
2788
- /**
2789
- * Options for BullMQ configuration
2790
- * @param options - The options for BullMQ
2791
- * @param errorHandler - Custom error handler that will be triggered when a job fails, for logging or debug purposes
2792
- */
2793
- type BullMQConfigurationOptions = ConstructorParameters<typeof Queue>[1] & {
2794
- errorHandler?: (job: Job, error: Error) => SyncOrAsync;
2795
- };
2796
- declare class BullMQConfiguration {
2797
- static options: BullMQConfigurationOptions;
2798
- }
2799
- /**
2800
- * Define globally custom BullMQ configuration
2801
- * @param options - The BullMQ configuration options
2802
- */
2803
- declare const defineBullMQConfiguration: (options: BullMQConfigurationOptions) => void;
2804
-
2805
- type CustomQueueConfiguration = GenericPubSub;
2806
-
2807
- type PGBossConfigurationOptions = {
2808
- connectionString?: string;
2809
- boss?: unknown;
2810
- errorHandler?: (error: Error) => SyncOrAsync;
2811
- };
2812
- declare class PGBossConfiguration {
2813
- static options: PGBossConfigurationOptions;
2814
- }
2815
- declare const definePGBossConfiguration: (options: PGBossConfigurationOptions) => void;
2816
-
2817
- type SQSConfigurationOptions = {
2818
- client?: SQSClientConfig;
2819
- consumer?: {
2820
- batchSize?: number;
2821
- visibilityTimeout?: number;
2822
- waitTimeSeconds?: number;
2823
- queueUrlMap: Record<string, string>;
2824
- };
2825
- errorHandler?: (error: Error) => SyncOrAsync;
2826
- };
2827
- declare class SQSConfiguration {
2828
- static options: SQSConfigurationOptions;
2829
- }
2830
- declare const defineSQSConfiguration: (options: SQSConfigurationOptions) => void;
2831
-
2832
- declare class QueueManager {
2833
- static map: Map<QueueProviderKey, GenericPubSub>;
2834
- static getProvider<P extends QueueProviderKey>(provider: P): GenericPubSub<P>;
2835
- static setProvider(provider: QueueProviderKey, pubsub: GenericPubSub<QueueProviderKey>): void;
2836
- /**
2837
- * Clear the memory provider state
2838
- * @internal Used for test cleanup
2839
- */
2840
- static clearMemoryProvider(): void;
2841
- }
2842
-
2843
- /**
2844
- * Main entry point to define the queue configuration, meant to be called only once in the application bootstrap
2845
- * @bullmq - The BullMQ configuration options
2846
- * @pgboss - The PGBoss configuration options
2847
- * @sqs - The SQS configuration options
2848
- * @string - The custom queue provider name with it's PubSub implementation
2849
- * @example
2850
- * defineQueueConfiguration({
2851
- * bullmq: {
2852
- * connection: {
2853
- * host: "127.0.0.1",
2854
- * password: "root",
2855
- * username: "default",
2856
- * db: 0,
2857
- * },
2858
- * },
2859
- * pgboss: {
2860
- * connectionString: "postgres://root:root@localhost:5432/database",
2861
- * },
2862
- * sqs: {
2863
- * client: { region: "us-east-1" },
2864
- * },
2865
- * custom: new CustomPubSub(),
2866
- * });
2867
- * @example
2868
- * defineQueueConfiguration({
2869
- * custom: new CustomPubSub(),
2870
- * });
2871
- */
2872
- declare const defineQueueConfiguration: (options: {
2873
- bullmq?: Parameters<typeof defineBullMQConfiguration>[0];
2874
- pgboss?: Parameters<typeof definePGBossConfiguration>[0];
2875
- sqs?: Parameters<typeof defineSQSConfiguration>[0];
2876
- } & { [key in Exclude<QueueProviderKey, "bullmq" | "pgboss" | "sqs">]?: CustomQueueConfiguration; }) => void;
2877
-
2878
- type QueueHandler = (payload: unknown) => Promise<void>;
2879
- type TypedQueueRegistration = {
2880
- name: string;
2881
- topic: string;
2882
- handler: QueueHandler;
2883
- provider: BuiltInProviderKey;
2884
- queueOptions?: unknown;
2885
- };
2886
- type CustomQueueRegistration = {
2887
- name: string;
2888
- topic: string;
2889
- handler: QueueHandler;
2890
- pubsub: GenericPubSub;
2891
- };
2892
- declare class QueueService {
2893
- static typedQueueSubscribers: Map<string, TypedQueueRegistration>;
2894
- static customQueueSubscribers: Map<string, CustomQueueRegistration>;
2895
- /**
2896
- * Factory function for creating handler instances.
2897
- * Can be overridden to provide custom dependency injection.
2898
- * @default Creates new instance using constructor
2899
- */
2900
- static instanceFactory: (ctor: Function) => object;
2901
- static registerTypedQueue(name: string, topic: string, handler: QueueHandler, provider: BuiltInProviderKey, queueOptions?: unknown): void;
2902
- static registerCustomQueue(name: string, topic: string, handler: QueueHandler, pubsub: GenericPubSub): void;
2903
- static run(): Promise<void>;
2904
- static massiveImportQueues(queueHandlerPatterns: string[], options?: {
2905
- throwOnError?: boolean;
2906
- }): Promise<void>;
2907
- }
2908
-
2909
- /**
2910
- * The logger instance, can be overridden by the `defineLoggerConfig` function
2911
- */
2912
- declare let logger: pino__default.Logger<string, boolean>;
2913
- /**
2914
- * Define the logger config, this will override the logger instance with the given options
2915
- * @param options - The logger options
2916
- */
2917
- declare const defineLoggerConfig: (options?: LoggerOptions) => void;
2918
-
2919
- type Argument = string;
2920
- type FlagSchema = Record<string, string | number | boolean | Array<string | number | boolean>>;
2921
-
2922
- type CommandOptions = {
2923
- /**
2924
- * If true, the command won't be killed after it's finished. Defaults to false.
2925
- */
2926
- keepAlive?: boolean;
2927
- /**
2928
- * Category for grouping commands in help output
2929
- * @example 'generator', 'development', 'production', 'database'
2930
- */
2931
- category?: string;
2932
- /**
2933
- * Mark command as deprecated with optional replacement
2934
- * @example { message: 'Use generate-controller instead', replacement: 'generate-controller' }
2935
- */
2936
- deprecated?: {
2937
- message?: string;
2938
- replacement?: string;
2939
- };
2940
- /**
2941
- * Custom validation function that runs before handle()
2942
- */
2943
- validate?: (command: typeof Command) => boolean | Promise<boolean>;
2944
- };
2945
-
2946
- /**
2947
- * Base class for all cli commands.
2948
- * @abstract
2949
- */
2950
- declare abstract class Command {
2951
- /**
2952
- * The name of the command.
2953
- */
2954
- static commandName: string;
2955
- /**
2956
- * package manager that called the command (e.g. npx, yarn, bun etc.)
2957
- */
2958
- static calledBy: string;
2959
- /**
2960
- * The description of the command.
2961
- */
2962
- static description: string;
2963
- /**
2964
- * The help text of the command.
2965
- */
2966
- static help: string[] | string;
2967
- /**
2968
- * The options of the command.
2969
- */
2970
- static options: CommandOptions;
2971
- /**
2972
- * Static arguments in order to be validated by decorators. Will be fetched in the command instance.
2973
- */
2974
- static args: Argument[];
2975
- /**
2976
- * Static flags in order to be validated by decorators. Will be fetched in the command instance.
2977
- */
2978
- static flags: FlagSchema;
2979
- static readonly logger: pino.Logger<string, boolean>;
2980
- /**
2981
- * Main entry point for the command.
2982
- */
2983
- static handle(): Promise<void>;
2984
- /**
2985
- * Enhanced help flag handler with rich formatting and command information
2986
- */
2987
- static handleHelpFlag(flags: FlagSchema): void;
2988
- private static readonly generateHelpOutput;
2989
- static readonly validateContext: (target: any) => void;
2990
- }
2991
-
2992
- declare class BuildCommand extends Command {
2993
- static commandName: string;
2994
- static description: string;
2995
- static help: string[];
2996
- static clearDist: boolean;
2997
- static entry: string;
2998
- static output: string;
2999
- static tsconfig: string;
3000
- static assets: string;
3001
- static format: "esm" | "cjs";
3002
- static packages: "external" | "bundle";
3003
- static sourcemap: boolean;
3004
- static handle(): Promise<void>;
3005
- }
3006
-
3007
- declare class CronStartCommand extends Command {
3008
- static commandName: string;
3009
- static description: string;
3010
- static help: string[];
3011
- static options: CommandOptions;
3012
- static pattern: string;
3013
- static additionalPatterns?: string[];
3014
- static handle(): Promise<void>;
3015
- }
3016
-
3017
- declare class GenerateCommand extends Command {
3018
- static commandName: string;
3019
- static description: string;
3020
- static help: string[];
3021
- /**
3022
- * The path where the command will be generated
3023
- */
3024
- static path: string;
3025
- static name: string;
3026
- static handle(): Promise<void>;
3027
- static getCommandTemplate(): string;
3028
- }
3029
-
3030
- declare class GenerateControllerCommand extends Command {
3031
- static commandName: string;
3032
- static description: string;
3033
- static help: string[];
3034
- static controllerName: string;
3035
- static path: string;
3036
- static handle(): Promise<void>;
3037
- static getControllerTemplate(): string;
3038
- }
3039
-
3040
- declare class GenerateCron extends Command {
3041
- static commandName: string;
3042
- static description: string;
3043
- static help: string[];
3044
- static fileName: string;
3045
- static path: string;
3046
- static handle(): Promise<void>;
3047
- static getCronTemplate(): string;
3048
- }
3049
-
3050
- declare class GenerateMiddlewareCommand extends Command {
3051
- static commandName: string;
3052
- static description: string;
3053
- static help: string[];
3054
- static middlewareName: string;
3055
- static path: string;
3056
- static handle(): Promise<void>;
3057
- static getMiddlewareTemplate(): string;
3058
- }
3059
-
3060
- declare class GenerateMqttCommand extends Command {
3061
- static commandName: string;
3062
- static description: string;
3063
- static help: string[];
3064
- static path: string;
3065
- static topic: string;
3066
- static handle(): Promise<void>;
3067
- static getMqttTemplate(isValidLiteral: boolean): string;
3068
- }
3069
-
3070
- declare class GeneratePluginCommand extends Command {
3071
- static commandName: string;
3072
- static description: string;
3073
- static help: string[];
3074
- static pluginName: string;
3075
- static pluginPath: string;
3076
- static handle(): Promise<void>;
3077
- static getPluginTemplate(): string;
3078
- }
3079
-
3080
- declare class GenerateQueueCommand extends Command {
3081
- static commandName: string;
3082
- static description: string;
3083
- static help: string[];
3084
- static queueName: string;
3085
- static path: string;
3086
- static provider: string;
3087
- static handle(): Promise<void>;
3088
- static getQueueTemplate(isValidLiteral: boolean): string;
3089
- }
3090
-
3091
- declare class GenerateSdkCommand extends Command {
3092
- static commandName: string;
3093
- static description: string;
3094
- static help: string[];
3095
- static serverPath: string;
3096
- static outputPath: string;
3097
- static swaggerPath?: string;
3098
- static httpClient: string;
3099
- static unwrapResponseData: boolean;
3100
- static singleHttpClient: boolean;
3101
- static typePrefix?: string;
3102
- static typeSuffix?: string;
3103
- static enumNamesAsValues: boolean;
3104
- static sortTypes: boolean;
3105
- static handle(): Promise<void>;
3106
- }
3107
-
3108
- declare class InitCommand extends Command {
3109
- static commandName: string;
3110
- static description: string;
3111
- static help: string[];
3112
- static srcPath: string;
3113
- static typescript: boolean;
3114
- static mqtt: boolean;
3115
- static cron: boolean;
3116
- static graphql: boolean;
3117
- static devDependencies: string[];
3118
- static handle(): Promise<void>;
3119
- static getServerTemplate(): string;
3120
- static getIndexTemplate(): string;
3121
- static getMqttConfigTemplate(): string;
3122
- static getCronConfigTemplate(): string;
3123
- static getGraphqlConfigTemplate(): string;
3124
- }
3125
-
3126
- declare class InitMailerCommand extends Command {
3127
- static commandName: string;
3128
- static description: string;
3129
- static help: string[];
3130
- static templateEngine: "handlebars" | "ejs" | "edge" | "mustache" | "custom" | "none";
3131
- static outputPath: string;
3132
- static mailerDependencies: Record<string, string[]>;
3133
- static handle(): Promise<void>;
3134
- static getConfigTemplate(): string;
3135
- static getAdapterImport(): string;
3136
- static getTemplateAdapterSetup(): string;
3137
- static getTemplateExample(): string;
3138
- }
3139
-
3140
- declare class InitQueueCommand extends Command {
3141
- static commandName: string;
3142
- static description: string;
3143
- static help: string[];
3144
- static queueType: "bullmq" | "sqs" | "pgboss";
3145
- static outputPath: string;
3146
- static queueDependencies: Record<string, string[]>;
3147
- static handle(): Promise<void>;
3148
- static getConfigTemplate(): string;
3149
- static getBullMQTemplate(): string;
3150
- static getSQSTemplate(): string;
3151
- static getPGBossTemplate(): string;
3152
- }
3153
-
3154
- declare class KeyGenerateCommand extends Command {
3155
- static commandName: string;
3156
- static description: string;
3157
- static help: string[];
3158
- static type?: string;
3159
- static handle(): Promise<void>;
3160
- private static saveKeyToEnvFile;
3161
- }
3162
-
3163
- declare class ListCommand extends Command {
3164
- static commandName: string;
3165
- static description: string;
3166
- static help: string[];
3167
- static handle(): Promise<void>;
3168
- private static groupByCategory;
3169
- private static displayCategorizedCommands;
3170
- }
3171
-
3172
- declare class ServeCommand extends Command {
3173
- static commandName: string;
3174
- static description: string;
3175
- static help: string[];
3176
- static runtime: RunTimeType;
3177
- static options: CommandOptions;
3178
- static entry: string;
3179
- static denoImportMap?: string;
3180
- static handle(): Promise<void>;
3181
- private static handleNodeHotReload;
3182
- }
3183
-
3184
- declare class SetupStorageCommand extends Command {
3185
- static commandName: string;
3186
- static description: string;
3187
- static help: string[];
3188
- static storageType: string;
3189
- static outputPath: string;
3190
- static handle(): Promise<void>;
3191
- private static getDependencies;
3192
- private static checkMissingDependencies;
3193
- private static createStorageSetup;
3194
- private static getConfigTemplate;
3195
- }
3196
-
3197
- declare const baseCommands: (typeof BuildCommand | typeof CronStartCommand | typeof GenerateCommand | typeof GenerateControllerCommand | typeof GenerateCron | typeof GenerateMiddlewareCommand | typeof GenerateMqttCommand | typeof GeneratePluginCommand | typeof GenerateQueueCommand | typeof GenerateSdkCommand | typeof InitCommand | typeof InitMailerCommand | typeof InitQueueCommand | typeof KeyGenerateCommand | typeof ListCommand | typeof ServeCommand | typeof SetupStorageCommand)[];
3198
- /**
3199
- * Singleton that registers all commands and provides a way to execute them.
3200
- * Commands are loaded from the commands directory, and are expected to have a default export with the command class that extends the base command class.
3201
- * Commands can be run both as `.js` or `.ts` files. If the file is a ts file `typescript` npm package must be installed.
3202
- * You can use the `CommandRegistry.setCommandsPattern` method to change the pattern of the commands to load.
3203
- * @example
3204
- * // commands/test.ts
3205
- * export default class TestCommand extends Command {
3206
- * static name = "test";
3207
- * async handle() {
3208
- * console.log("Test command");
3209
- * }
3210
- * }
3211
- */
3212
- declare class CommandRegistry {
3213
- private commands;
3214
- private builtInCommands;
3215
- static commandsPattern: string;
3216
- static logger: pino.Logger<string, boolean>;
3217
- /**
3218
- * Private constructor to prevent direct instantiation
3219
- * @internal Not meant to be used outside by the user
3220
- */
3221
- private constructor();
3222
- static getInstance(): CommandRegistry;
3223
- static setCommandsPattern(pattern: string): void;
3224
- getCommand(name: string): typeof Command | null;
3225
- getCommands(): (typeof Command)[];
3226
- getBuiltInCommands(): (typeof Command)[];
3227
- getUserDefinedCommands(): (typeof Command)[];
3228
- isBuiltInCommand(commandName: string): boolean;
3229
- loadCommands(commandsPattern: string): Promise<void>;
3230
- }
3231
- declare const commandRegistry: CommandRegistry;
3232
-
3233
- declare class NativeHash {
3234
- private ITERATIONS;
3235
- private SALT_LENGTH;
3236
- private KEY_LENGTH;
3237
- configure(options: {
3238
- iterations?: number;
3239
- saltLength?: number;
3240
- keyLength?: number;
3241
- }): void;
3242
- hash(data: string): Promise<string>;
3243
- compare(hash: string, data: string): Promise<boolean>;
3244
- private encodeBase64;
3245
- private decodeBase64;
3246
- }
3247
- declare const hash: NativeHash;
3248
-
3249
- declare const asyncStorage: AsyncLocalStorage<Record<string, any>>;
3250
- /**
3251
- * Async local storage plugin middleware, used to store data in the request context
3252
- */
3253
- declare const asyncLocalStorage: (ctxSetters: AsyncLocalStorageContextSetters) => ServerRouteMiddleware;
3254
-
3255
- type LocalStorageProviderOptions = {
3256
- /**
3257
- * The directory to store the files
3258
- */
3259
- directory: string;
3260
- };
3261
- /**
3262
- * Local storage provider, stores files in the local filesystem
3263
- * Note: This provider does not support signed URLs (getDownloadUrl/getUploadUrl)
3264
- */
3265
- declare class LocalStorageProvider implements StorageInterface {
3266
- private readonly options;
3267
- private wasDirectoryEnsured;
3268
- constructor(options: LocalStorageProviderOptions);
3269
- getDownloadUrl(_key: string, _expiresInSeconds?: number): Promise<string>;
3270
- getUploadUrl(_key: string, _expiresInSeconds?: number): Promise<string>;
3271
- getPublicUrl(_key: string): Promise<string>;
3272
- listObjects(prefix?: string): Promise<string[]>;
3273
- getObject<R extends ReturnType$1 = "raw">(key: string, returnType?: R): Promise<ReturnTypeMap<R>>;
3274
- putObject<T = Uint8Array>(key: string, value: T, _contentType?: string): Promise<void>;
3275
- deleteObject(key: string): Promise<void>;
3276
- private listFilesRecursively;
3277
- private readDirectory;
3278
- private ensureDirectoryExists;
3279
- }
3280
-
3281
- type S3ClientConfig = ConstructorParameters<typeof S3Client>[0];
3282
- type S3StorageProviderOptions = {
3283
- s3ClientConfig: S3ClientConfig & {
3284
- bucketName: string;
3285
- };
3286
- /**
3287
- * The cloudfront options (optional), allows to get the cloudfront signed url for an object, enables the `getDownloadUrl` method that throws an error if not configured
3288
- */
3289
- cloudfrontOptions?: {
3290
- /**
3291
- * The CloudFront distribution domain name (e.g., 'd1234567890.cloudfront.net')
3292
- */
3293
- domainName: string;
3294
- /**
3295
- * The CloudFront key pair ID
3296
- */
3297
- keyPairId: string;
3298
- /**
3299
- * The private key in PEM format for signing URLs
3300
- */
3301
- privateKey: string;
3302
- };
3303
- };
3304
- declare class S3StorageProvider implements StorageInterface {
3305
- private s3Lib;
3306
- private s3PresignerLib;
3307
- private cloudfrontSignerLib;
3308
- private s3Client;
3309
- readonly options: S3StorageProviderOptions;
3310
- constructor(options: S3StorageProviderOptions);
3311
- getDownloadUrl(key: string, expiresInSeconds?: number): Promise<string>;
3312
- getUploadUrl(key: string, expiresInSeconds?: number): Promise<string>;
3313
- getPublicUrl(key: string): Promise<string>;
3314
- listObjects(prefix?: string): Promise<string[]>;
3315
- getObject<R extends ReturnType$1 = "raw">(key: string, returnType?: R): Promise<ReturnTypeMap<R>>;
3316
- putObject<T = Uint8Array>(key: string, value: T, contentType?: string): Promise<void>;
3317
- deleteObject(key: string): Promise<void>;
3318
- private ensureClient;
3319
- }
3320
-
3321
- type ReturnType$1 = "raw" | "text" | "stream";
3322
- type ReturnTypeMap<T extends ReturnType$1> = T extends "raw" ? Uint8Array : T extends "text" ? string : T extends "stream" ? ReadableStream : never;
3323
- /**
3324
- * High level storage interface, provides a unified way to interact with different storage providers
3325
- */
3326
- interface StorageInterface {
3327
- /**
3328
- * Get the download signed url of the object
3329
- * @param key - The key of the object
3330
- * @returns The download signed url of the object
3331
- * @warning not available in local storage provider
3332
- * @throws if using local storage provider
3333
- */
3334
- getDownloadUrl: (key: string, expiresInSeconds?: number) => Promise<string>;
3335
- /**
3336
- * Get the upload signed url of the object
3337
- * @param key - The key of the object
3338
- * @returns The upload signed url of the object
3339
- * @warning not available in local storage provider
3340
- * @throws if using local storage provider
3341
- */
3342
- getUploadUrl: (key: string, expiresInSeconds?: number) => Promise<string>;
3343
- /**
3344
- * Get the public url of the object
3345
- * @param key - The key of the object
3346
- * @returns The public url of the object
3347
- * @warning not available in local storage provider
3348
- * @throws if using local storage provider
3349
- */
3350
- getPublicUrl: (key: string) => Promise<string>;
3351
- /**
3352
- * List the objects from the storage
3353
- * @param prefix - The prefix of the objects
3354
- * @returns The objects from the storage
3355
- */
3356
- listObjects: (prefix?: string) => Promise<string[]>;
3357
- /**
3358
- * Get the object from the storage
3359
- * @param key - The key of the object
3360
- * @throws If no file is found for the given key
3361
- * @returns The object from the storage
3362
- */
3363
- getObject: <R extends ReturnType$1 = "raw">(key: string, returnType: R) => Promise<ReturnTypeMap<R>>;
3364
- /**
3365
- * Put the object into the storage
3366
- * @param key - The key of the object
3367
- * @param value - The value of the object
3368
- * @param contentType - The content type of the object
3369
- * @returns The object from the storage
3370
- */
3371
- putObject: <T = Uint8Array>(key: string, value: T, contentType?: string) => Promise<void>;
3372
- /**
3373
- * Delete the object from the storage
3374
- * @param key - The key of the object
3375
- * @returns The object from the storage
3376
- */
3377
- deleteObject: (key: string) => Promise<void>;
3378
- }
3379
- type StorageOptions<T extends BaseStorageProviderOptions> = {
3380
- /**
3381
- * The default provider to use
3382
- */
3383
- defaultProvider: keyof T;
3384
- };
3385
- /**
3386
- * Mapping of the storage provider options
3387
- */
3388
- interface BaseStorageProviderOptions {
3389
- local?: LocalStorageProvider;
3390
- s3?: S3StorageProvider;
3391
- azureBlobStorage?: AzureBlobStorageProvider;
3392
- }
3393
- /**
3394
- * Custom storage providers
3395
- */
3396
- interface CustomStorageProviderOptions {
3397
- [key: string]: StorageInterface;
3398
- }
3399
- type StorageProviderOptions = CustomStorageProviderOptions & BaseStorageProviderOptions;
3400
-
3401
- type BlobStorageProviderOptions = {
3402
- /**
3403
- * The container name
3404
- */
3405
- containerName: string;
3406
- /**
3407
- * The connection string to the storage account
3408
- */
3409
- connectionString: string;
3410
- /**
3411
- * The storage account name
3412
- */
3413
- storageAccountName: string;
3414
- /**
3415
- * The storage account key
3416
- */
3417
- storageAccountKey: string;
3418
- };
3419
- declare class AzureBlobStorageProvider implements StorageInterface {
3420
- private readonly options;
3421
- private azureBlobLib;
3422
- private blobServiceClient;
3423
- private containerClient;
3424
- private sharedKeyCredential;
3425
- constructor(options: BlobStorageProviderOptions);
3426
- getDownloadUrl(key: string, expiresInSeconds?: number): Promise<string>;
3427
- getUploadUrl(key: string, expiresInSeconds?: number): Promise<string>;
3428
- getPublicUrl(key: string): Promise<string>;
3429
- listObjects(prefix?: string): Promise<string[]>;
3430
- getObject<R extends ReturnType$1 = "raw">(key: string, returnType?: R): Promise<ReturnTypeMap<R>>;
3431
- putObject<T = Uint8Array>(key: string, value: T, contentType?: string): Promise<void>;
3432
- deleteObject(key: string): Promise<void>;
3433
- private ensureClient;
3434
- }
3435
-
3436
- declare class Storage<T extends StorageProviderOptions> implements StorageInterface {
3437
- private readonly providerOptions;
3438
- private readonly defaultProvider;
3439
- private readonly providerMap;
3440
- constructor(providerOptions: T, storageOptions: StorageOptions<T>);
3441
- /**
3442
- * Use a specific provider
3443
- * @param provider - The provider to use
3444
- * @returns The storage instance
3445
- */
3446
- use(provider: keyof T): StorageInterface;
3447
- getDownloadUrl(key: string, expiresInSeconds?: number): Promise<string>;
3448
- getUploadUrl(key: string, expiresInSeconds?: number): Promise<string>;
3449
- getPublicUrl(key: string): Promise<string>;
3450
- listObjects(prefix?: string): Promise<string[]>;
3451
- getObject<R extends ReturnType$1 = "raw">(key: string, returnType?: R): Promise<ReturnTypeMap<R>>;
3452
- putObject<T = Buffer<ArrayBufferLike>>(key: string, value: T, contentType?: string): Promise<void>;
3453
- deleteObject(key: string): Promise<void>;
3454
- }
3455
-
3456
- /**
3457
- * Email address type that enforces the basic email format
3458
- */
3459
- type Email = `${string}@${string}`;
3460
- /**
3461
- * Builder for constructing email options
3462
- */
3463
- declare class MailOptionsBuilder {
3464
- private options;
3465
- private templateOptions?;
3466
- /**
3467
- * Set the sender email address
3468
- * @param email - The sender email address
3469
- */
3470
- from(email: Email): this;
3471
- /**
3472
- * Set recipient email address(es)
3473
- * @param email - Single email address or array of email addresses
3474
- */
3475
- to(email: Email | Email[]): this;
3476
- /**
3477
- * Set carbon copy recipient email address(es)
3478
- * @param email - Single email address or array of email addresses
3479
- */
3480
- cc(email: Email | Email[]): this;
3481
- /**
3482
- * Set blind carbon copy recipient email address(es)
3483
- * @param email - Single email address or array of email addresses
3484
- */
3485
- bcc(email: Email | Email[]): this;
3486
- /**
3487
- * Set email subject
3488
- * @param text - The email subject line
3489
- */
3490
- subject(text: string): this;
3491
- /**
3492
- * Set plain text email body
3493
- * @param content - The plain text content of the email
3494
- */
3495
- text(content: string): this;
3496
- /**
3497
- * Set HTML email body
3498
- * @param content - The HTML content of the email
3499
- */
3500
- html(content: string): this;
3501
- /**
3502
- * Set template string and data for rendering
3503
- * @param template - The template string to render
3504
- * @param data - The data to pass to the template for rendering
3505
- */
3506
- template(template: string, data: Record<string, unknown>): this;
3507
- /**
3508
- * Set template file path and data for rendering
3509
- * @param templatePath - The path to the template file
3510
- * @param data - The data to pass to the template for rendering
3511
- */
3512
- templateFile(templatePath: string, data: Record<string, unknown>): this;
3513
- /**
3514
- * Add an attachment
3515
- * @param attachment - The attachment to add to the email
3516
- */
3517
- attachment(attachment: Attachment): this;
3518
- /**
3519
- * Add multiple attachments
3520
- * @param attachments - Array of attachments to add to the email
3521
- */
3522
- attachments(attachments: Attachment[]): this;
3523
- /**
3524
- * Check if this builder has template options
3525
- */
3526
- hasTemplate(): boolean;
3527
- /**
3528
- * Check if the template is a file path
3529
- */
3530
- isTemplateFile(): boolean;
3531
- /**
3532
- * Build the final MailOptions or TemplateMailOptions object
3533
- */
3534
- build(): MailOptions | TemplateMailOptions;
3535
- }
3536
- /**
3537
- * Helper function to create a new MailOptionsBuilder
3538
- */
3539
- declare const mailOptions: () => MailOptionsBuilder;
3540
-
3541
- /**
3542
- * Options for sending an email
3543
- */
3544
- type MailOptions = {
3545
- /**
3546
- * The sender email address (optional if set in provider config)
3547
- */
3548
- from?: Email;
3549
- /**
3550
- * Recipient email address(es)
3551
- */
3552
- to: Email | Email[];
3553
- /**
3554
- * Carbon copy recipient email address(es)
3555
- */
3556
- cc?: Email | Email[];
3557
- /**
3558
- * Blind carbon copy recipient email address(es)
3559
- */
3560
- bcc?: Email | Email[];
3561
- /**
3562
- * Email subject line
3563
- */
3564
- subject: string;
3565
- /**
3566
- * Plain text version of the email body
3567
- */
3568
- text?: string;
3569
- /**
3570
- * HTML version of the email body
3571
- */
3572
- html?: string;
3573
- /**
3574
- * Email attachments
3575
- */
3576
- attachments?: Attachment[];
3577
- };
3578
- /**
3579
- * Email attachment configuration
3580
- */
3581
- type Attachment = {
3582
- /**
3583
- * Name of the attached file
3584
- */
3585
- filename: string;
3586
- /**
3587
- * Attachment content as string or Buffer
3588
- */
3589
- content?: string | Buffer;
3590
- /**
3591
- * Path to file to attach
3592
- */
3593
- path?: string;
3594
- /**
3595
- * Content type (MIME type) of the attachment
3596
- */
3597
- contentType?: string;
3598
- };
3599
- /**
3600
- * Options for sending an email with a template
3601
- * Omits html and text as they will be generated from the template
3602
- */
3603
- type TemplateMailOptions = Omit<MailOptions, "html" | "text"> & {
3604
- /**
3605
- * Template string to render or path to template file
3606
- */
3607
- template: string;
3608
- /**
3609
- * Data to pass to the template for rendering
3610
- */
3611
- data: Record<string, unknown>;
3612
- /**
3613
- * Whether the template is a file path
3614
- */
3615
- isFilePath?: boolean;
3616
- };
3617
- /**
3618
- * Interface for template adapters
3619
- * Implement this to create custom template engines
3620
- */
3621
- interface TemplateAdapter {
3622
- /**
3623
- * Render a template string with data
3624
- * @param template - The template string to render
3625
- * @param data - Data to interpolate into the template
3626
- * @returns Rendered HTML string (can be sync or async)
3627
- */
3628
- render(template: string, data: Record<string, unknown>): Promise<string> | string;
3629
- /**
3630
- * Render a template from a file
3631
- * @param templatePath - Path to the template file
3632
- * @param data - Data to interpolate into the template
3633
- * @returns Promise resolving to rendered HTML string
3634
- */
3635
- renderFromFile(templatePath: string, data: Record<string, unknown>): Promise<string>;
3636
- }
3637
- /**
3638
- * Interface for mail provider instances
3639
- */
3640
- interface MailProviderInterface {
3641
- /**
3642
- * Send an email using builder callback
3643
- * @param builderFn - Callback function that receives and configures the mail options builder
3644
- */
3645
- send(builderFn: (builder: MailOptionsBuilder) => MailOptionsBuilder | void): Promise<void>;
3646
- /**
3647
- * Verify the mail provider connection
3648
- * @returns Promise resolving to true if connection is valid
3649
- */
3650
- verify(): Promise<boolean>;
3651
- }
3652
- /**
3653
- * Configuration options for a mail provider
3654
- */
3655
- type MailProviderOptions = {
3656
- /**
3657
- * Nodemailer transporter instance
3658
- */
3659
- transporter: Transporter;
3660
- /**
3661
- * Optional template adapter for rendering email templates
3662
- */
3663
- templateAdapter?: TemplateAdapter;
3664
- /**
3665
- * Default sender email address for this provider
3666
- */
3667
- from?: Email;
3668
- };
3669
- /**
3670
- * Map of provider names to their configuration options
3671
- */
3672
- type MailerProviderOptions = Record<string, MailProviderOptions>;
3673
- /**
3674
- * Configuration options for the Mailer instance
3675
- */
3676
- type MailerOptions<T extends MailerProviderOptions> = {
3677
- /**
3678
- * Name of the default provider to use
3679
- */
3680
- defaultProvider: keyof T;
3681
- };
3682
- /**
3683
- * Interface for the main Mailer class
3684
- */
3685
- interface MailerInterface {
3686
- /**
3687
- * Switch to a specific mail provider
3688
- * @param provider - Name of the provider to use
3689
- * @returns The mail provider instance
3690
- */
3691
- use(provider: string): MailProviderInterface;
3692
- /**
3693
- * Send an email using the default provider with builder pattern
3694
- * Automatically infers whether to use template or regular send based on builder configuration
3695
- * @param builderFn - Callback function that receives and configures the mail options builder
3696
- */
3697
- send(builderFn: (builder: MailOptionsBuilder) => MailOptionsBuilder | void): Promise<void>;
3698
- /**
3699
- * Defer sending an email with an internal in memory queue
3700
- * The email will be sent in a second moment, when the queue is processed
3701
- * @param builderFn - Callback function that receives and configures the mail options builder
3702
- */
3703
- later(builderFn: (builder: MailOptionsBuilder) => MailOptionsBuilder | void): Promise<void>;
3704
- /**
3705
- * Verify the default provider connection
3706
- * @returns Promise resolving to true if connection is valid
3707
- */
3708
- verify(): Promise<boolean>;
3709
- }
3710
-
3711
- /**
3712
- * Handlebars template adapter
3713
- * Requires: npm install handlebars @types/handlebars
3714
- */
3715
- declare class HandlebarsAdapter implements TemplateAdapter {
3716
- private handlebars;
3717
- render(template: string, data: Record<string, unknown>): Promise<string>;
3718
- renderFromFile(templatePath: string, data: Record<string, unknown>): Promise<string>;
3719
- /**
3720
- * Register a helper function
3721
- */
3722
- registerHelper(name: string, fn: (...args: unknown[]) => unknown): Promise<void>;
3723
- /**
3724
- * Register a partial template
3725
- */
3726
- registerPartial(name: string, template: string): Promise<void>;
3727
- private ensureHandlebars;
3728
- }
3729
-
3730
- /**
3731
- * Edge.js template adapter
3732
- * Requires: npm install edge.js
3733
- */
3734
- declare class EdgeAdapter implements TemplateAdapter {
3735
- private edge;
3736
- render(template: string, data: Record<string, unknown>): Promise<string>;
3737
- renderFromFile(templatePath: string, data: Record<string, unknown>): Promise<string>;
3738
- /**
3739
- * Register a global helper
3740
- */
3741
- global(name: string, value: unknown): Promise<void>;
3742
- /**
3743
- * Register a custom tag
3744
- */
3745
- registerTag(tag: unknown): Promise<void>;
3746
- private ensureEdge;
3747
- }
3748
-
3749
- /**
3750
- * Mustache template adapter
3751
- * Requires: npm install mustache @types/mustache
3752
- */
3753
- declare class MustacheAdapter implements TemplateAdapter {
3754
- private mustache;
3755
- private partials;
3756
- render(template: string, data: Record<string, unknown>): Promise<string>;
3757
- renderFromFile(templatePath: string, data: Record<string, unknown>): Promise<string>;
3758
- /**
3759
- * Register a partial template
3760
- */
3761
- registerPartial(name: string, template: string): void;
3762
- private ensureMustache;
3763
- }
3764
-
3765
- /**
3766
- * EJS template adapter
3767
- * Requires: npm install ejs @types/ejs
3768
- */
3769
- declare class EjsAdapter implements TemplateAdapter {
3770
- private ejs;
3771
- private options;
3772
- constructor(options?: Record<string, unknown>);
3773
- render(template: string, data: Record<string, unknown>): Promise<string>;
3774
- renderFromFile(templatePath: string, data: Record<string, unknown>): Promise<string>;
3775
- private ensureEjs;
3776
- }
3777
-
3778
- /**
3779
- * Custom template adapter example
3780
- * Simple string interpolation with {{variable}} syntax
3781
- *
3782
- * Use this as a base to create your own custom adapter
3783
- */
3784
- declare class CustomAdapter implements TemplateAdapter {
3785
- private helpers;
3786
- render(template: string, data: Record<string, unknown>): string;
3787
- renderFromFile(templatePath: string, data: Record<string, unknown>): Promise<string>;
3788
- /**
3789
- * Register a custom helper function
3790
- * Usage in template: {{name:uppercase}}
3791
- */
3792
- registerHelper(name: string, fn: (value: unknown) => string): void;
3793
- }
3794
-
3795
- declare class MailProvider implements MailProviderInterface {
3796
- private readonly transporter;
3797
- private readonly templateAdapter?;
3798
- private readonly defaultFrom?;
3799
- constructor(options: MailProviderOptions);
3800
- send(builderFn: (builder: MailOptionsBuilder) => MailOptionsBuilder | void): Promise<void>;
3801
- private sendDirect;
3802
- private sendWithTemplate;
3803
- verify(): Promise<boolean>;
3804
- }
3805
-
3806
- declare class Mailer<T extends MailerProviderOptions> implements MailerInterface {
3807
- private readonly defaultProvider;
3808
- private readonly providerMap;
3809
- private emailQueue;
3810
- private queueInitialized;
3811
- constructor(providerOptions: T, mailerOptions: MailerOptions<T>);
3812
- /**
3813
- * Use a specific mail provider
3814
- * @param provider - The provider to use
3815
- * @returns The mail provider instance
3816
- */
3817
- use(provider: keyof T): MailProviderInterface;
3818
- send(builderFn: (builder: MailOptionsBuilder) => MailOptionsBuilder | void): Promise<void>;
3819
- later(builderFn: (builder: MailOptionsBuilder) => MailOptionsBuilder | void): Promise<void>;
3820
- private initializeQueue;
3821
- private processEmail;
3822
- verify(): Promise<boolean>;
3823
- private getDefaultProvider;
3824
- }
3825
-
3826
- declare class BaldaError extends Error {
3827
- constructor(message: string);
3828
- }
3829
-
3830
- declare class MailerError extends BaldaError {
3831
- constructor(message: string);
3832
- }
3833
- declare class ProviderNotFoundError extends MailerError {
3834
- constructor(providerName: string);
3835
- }
3836
- declare class TemplateAdapterNotConfiguredError extends MailerError {
3837
- constructor();
3838
- }
3839
- declare class InvalidDefaultProviderError extends MailerError {
3840
- constructor(providerName: string);
3841
- }
3842
-
3843
- /**
3844
- * Base class for all plugins.
3845
- *
3846
- * Plugins are used to extend the functionality of the server.
3847
- *
3848
- * @example
3849
- * ```ts
3850
- * import { Server, BasePlugin } from "balda";
3851
- *
3852
- * export class MyPlugin extends BasePlugin {
3853
- * async handle(): Promise<ServerRouteMiddleware> {
3854
- * return async (req, res, next) => {
3855
- * console.log("My plugin is running");
3856
- * await next();
3857
- * };
3858
- * }
3859
- * }
3860
- *
3861
- * const server = new Server();
3862
- * server.use(new MyPlugin().handle());
3863
- * ```
3864
- *
3865
- * @abstract
3866
- */
3867
- declare abstract class BasePlugin {
3868
- abstract handle(...args: any[]): Promise<ServerRouteMiddleware>;
3869
- }
3870
-
3871
- /**
3872
- * Compression middleware for gzip compression of response bodies
3873
- *
3874
- * @param options Compression middleware options
3875
- */
3876
- declare const compression: (options?: CompressionOptions) => ServerRouteMiddleware;
3877
-
3878
- /**
3879
- * Cookie middleware for parsing and setting cookies, must be used in order to use the cookie methods on the request and response objects
3880
- *
3881
- * @param options Cookie middleware options
3882
- */
3883
- declare const cookie: (options?: CookieMiddlewareOptions) => ServerRouteMiddleware;
3884
-
3885
- /**
3886
- * CORS plugin
3887
- *
3888
- * ⚠️ SECURITY WARNING: By default, this plugin allows ALL origins ('*').
3889
- * For production environments, explicitly configure allowed origins.
3890
- *
3891
- * @param options CORS options (all optional)
3892
- *
3893
- * @example
3894
- * // Development (permissive)
3895
- * cors()
3896
- *
3897
- * @example
3898
- * // Production (secure)
3899
- * cors({
3900
- * origin: ['https://example.com', 'https://app.example.com'],
3901
- * credentials: true
3902
- * })
3903
- */
3904
- declare const cors: (options?: CorsOptions) => ServerRouteMiddleware;
3905
-
3906
- /**
3907
- * Converts an Express middleware to a Balda middleware
3908
- */
3909
- declare function expressMiddleware(expressHandler: RequestHandler, basePath?: string): ServerRouteMiddleware;
3910
- /**
3911
- * Converts an Express handler to a Balda handler
3912
- */
3913
- declare function expressHandler(handler: RequestHandler, basePath?: string): ServerRouteHandler;
3914
- /**
3915
- * Mounts an Express router at a specific base path
3916
- * This extracts all routes from the Express router and registers them with Balda
3917
- */
3918
- declare function mountExpressRouter(basePath: string, expressRouter: Router$1): void;
3919
- /**
3920
- * Creates an Express adapter that provides a use method for mounting Express middleware/routers
3921
- *
3922
- * @example
3923
- * ```ts
3924
- * import AdminJS from 'adminjs'
3925
- * import AdminJSExpress from '@adminjs/express'
3926
- * import { createExpressAdapter } from 'balda'
3927
- *
3928
- * const admin = new AdminJS({...})
3929
- * const adminRouter = AdminJSExpress.buildRouter(admin)
3930
- *
3931
- * const server = new Server()
3932
- * const express = createExpressAdapter(server)
3933
- * express.use('/admin', adminRouter)
3934
- * ```
3935
- */
3936
- declare function createExpressAdapter(server: {
3937
- use: (...middlewares: ServerRouteMiddleware[]) => void;
3938
- }): {
3939
- use(pathOrMiddleware: string | RequestHandler | Router$1, maybeMiddleware?: RequestHandler | Router$1): void;
3940
- };
3941
-
3942
- /**
3943
- * Sets common HTTP security headers
3944
- * @param options Helmet options (all optional)
3945
- */
3946
- declare const helmet: (options?: HelmetOptions) => ServerRouteMiddleware;
3947
-
3948
- /**
3949
- * Logs the request and response of the handler, can be set both on a specific route or on a global middleware.
3950
- * @warning Only json objects and strings are logged from the request and response.
3951
- */
3952
- declare const log: (options?: LogOptions) => ServerRouteMiddleware;
3953
-
3954
- /**
3955
- * Method override middleware for supporting HTTP verbs like PUT/DELETE in clients that don't support them
3956
- *
3957
- * @param options Method override middleware options
3958
- */
3959
- declare const methodOverride: (options?: MethodOverrideOptions) => ServerRouteMiddleware;
3960
-
3961
- /**
3962
- * Rate limiter plugin
3963
- * Rate limiter is a plugin that limits the number of requests to a resource.
3964
- * It can be used to protect a resource from abuse.
3965
- * @param keyOptions Rate limiter key options, tells the middleware how to retrieve the key from the request in to discriminate what to rate limit (all optional, defaults to ip)
3966
- * @param storageOptions Rate limiter storage options, tells the middleware how to store the rate limit data (all optional, defaults to memory)
3967
- */
3968
- declare const rateLimiter: (keyOptions?: RateLimiterKeyOptions, storageOptions?: StorageOptions$1) => ServerRouteMiddleware;
3969
-
3970
- /**
3971
- * Session plugin middleware, used to store the session in the request and response objects
3972
- * Uses cookies to send the session id
3973
- * @warning Must be used after the cookie middleware
3974
- * @param options Session options
3975
- * @param options.name The name of the session cookie
3976
- * @param options.ttl The TTL of the session in seconds
3977
- * @param options.store The store to use for the session
3978
- * @param options.cookie The cookie options
3979
- */
3980
- declare const session: (options?: SessionOptions) => ServerRouteMiddleware;
3981
-
3982
- /**
3983
- * Creates a static file serving middleware and registers all routes for the given path
3984
- * @param options - The options for serving static files
3985
- * @param options.source - The file system directory path where the assets are located
3986
- * @param options.path - The URL path where the assets will be served
3987
- * @param swaggerOptions - Optional swagger documentation options
3988
- * @example
3989
- * serveStatic({ source: 'tmp/assets', path: '/assets' }) // Serves from ./tmp/assets at /assets/*
3990
- *
3991
- * @example
3992
- * serveStatic({ source: 'public', path: '/public' }) // Serves from ./public at /public/*
3993
- */
3994
- declare const serveStatic: (options: StaticPluginOptions, swaggerOptions?: SwaggerRouteOptions) => ServerRouteMiddleware;
3995
- declare function getContentType(ext: string): string;
3996
-
3997
- /**
3998
- * Timeout plugin middleware, used to timeout the request if it takes too long
3999
- * It fills the req.timeout property with true if the request times out
4000
- * @param options Timeout options
4001
- * @param options.ms The timeout in milliseconds
4002
- * @param options.status The status code to return if the request times out
4003
- * @param options.message The message to return if the request times out
4004
- */
4005
- declare const timeout: (options: TimeoutOptions) => ServerRouteMiddleware;
4006
-
4007
- /**
4008
- * Trust proxy plugin middleware, used to trust the proxy headers to get the client ip
4009
- * @param options Trust proxy options (all optional)
4010
- * @param options.trust Whether to trust the proxy headers
4011
- * @param options.header The header name to read the client IP chain from
4012
- * @param options.hop The hop to use to get the client IP
4013
- */
4014
- declare const trustProxy: (options?: TrustProxyOptions) => ServerRouteMiddleware;
4015
-
4016
- type PolicyProvider = {
4017
- [K: string]: (...args: any[]) => Promise<boolean> | boolean;
4018
- };
4019
- type PolicyMetadata = {
4020
- scope: string;
4021
- handler: string;
4022
- manager: PolicyManager<any>;
4023
- };
4024
- type PolicyDecorator<T extends Record<string, PolicyProvider>> = <S extends keyof T & string, H extends keyof T[S] & string>(scope: S, handler: H) => (target: any, propertyKey?: string, descriptor?: PropertyDescriptor) => any;
4025
-
4026
- declare class PolicyManager<T extends Record<string, PolicyProvider>> {
4027
- private readonly providers;
4028
- constructor(providers: T);
4029
- /**
4030
- * Creates a decorator for the policy manager with typed parameters
4031
- */
4032
- createDecorator(): PolicyDecorator<T>;
4033
- /**
4034
- * Checks if the user has access to the given scope and handler
4035
- * @param scope - The scope to check access for
4036
- * @param handler - The handler to check access for
4037
- * @param args - The arguments to pass to the handler
4038
- */
4039
- canAccess<K extends keyof T, L extends T[K]>(scope: K, handler: keyof L, ...args: Parameters<T[K][keyof T[K]]>): ReturnType<T[K][keyof T[K]]>;
4040
- }
4041
-
4042
- declare const createPolicyDecorator: <T extends Record<string, PolicyProvider>>(manager: PolicyManager<T>) => PolicyDecorator<T>;
4043
-
4044
- /**
4045
- * Singleton main router instance that handles all route registrations inside the balda server
4046
- */
4047
- declare const router: ClientRouter;
4048
-
4049
- export { ARG_SYMBOL, type Attachment, AzureBlobStorageProvider, BaseCron, BaseMqtt, BasePlugin, BaseQueue, type BaseStorageProviderOptions, type BlobStorageProviderOptions, BullMQConfiguration, type BullMQConfigurationOptions, BullMQPubSub, type BunTapOptions, Command, type CommandOptions, CommandRegistry, type CronSchedule, type CronScheduleParams, CronService, CustomAdapter, type CustomQueueConfiguration, type CustomStorageProviderOptions, CustomTypedQueue, type CustomValidationError, type DenoTapOptions, EdgeAdapter, EjsAdapter, type Email, type ExpandedMqttTopics, type ExpressAdapterOptions, type ExpressHandler, type ExpressRouter, type ExtractParams, type FileAllowedMimeType, GraphQL, type GraphQLContext, type GraphQLOptions, type GraphQLResolverFunction, type GraphQLResolverMap, type GraphQLResolverType, type GraphQLResolvers, type GraphQLSchemaInput, type GraphQLTypeDef, HandlebarsAdapter, type HttpMethod, type HttpsOptions, type InferSchemaType, InvalidDefaultProviderError, LocalStorageProvider, type LocalStorageProviderOptions, type LoggerOptions, type MailOptions, MailOptionsBuilder, MailProvider, type MailProviderInterface, type MailProviderOptions, Mailer, MailerError, type MailerInterface, type MailerOptions, type MailerProviderOptions, MemoryPubSub, MockResponse, MockServer, type MockServerOptions, type MqttConnectionOptions, type MqttHandler, type MqttPublishOptions, MqttService, type MqttSubscribeOptions, type MqttSubscription, type MqttTopics, MustacheAdapter, type NextFunction, type NodeHttpClient, type NodeServer, type NodeTapOptions, PGBossConfiguration, type PGBossConfigurationOptions, PGBossPubSub, type PolicyDecorator, PolicyManager, type PolicyMetadata, type PolicyProvider, ProviderNotFoundError, type PublishTopic, QueueManager, QueueService, Request, type RequestSchema, type ResolvedServerOptions, Response$1 as Response, type ReturnType$1 as ReturnType, type ReturnTypeMap, type RuntimeServer, type RuntimeServerMap, S3StorageProvider, type S3StorageProviderOptions, SQSConfiguration, type SQSConfigurationOptions, SQSPubSub, type SerializeOptions, Server, type ServerConnectInput, type ServerErrorHandler, type ServerInterface, type ServerListenCallback, type ServerOptions, type ServerPlugin, type ServerRoute, type ServerRouteHandler, type ServerRouteMiddleware, type ServerTapOptions, type ServerTapOptionsBuilder, type SignalEvent, type StandardMethodOptions, type StaticPluginOptions, Storage, type StorageInterface, type StorageOptions, type StorageProviderOptions, type TemplateAdapter, TemplateAdapterNotConfiguredError, type TemplateMailOptions, type TypedHandler, TypedQueue, type TypedRouteMetadata, VALIDATION_ERROR_SYMBOL, type ValidatedData, type ValidationOptions, arg, asyncLocalStorage, asyncStorage, baseCommands, bullmqQueue, commandRegistry, compression, controller, cookie, cors, createExpressAdapter, createPolicyDecorator, createQueue, cron, Server as default, defineLoggerConfig, defineQueueConfiguration, del, expressHandler, expressMiddleware, flag, get, getContentType, hash, helmet, log, logger, mailOptions, memoryQueue, methodOverride, middleware, mountExpressRouter, mqtt, patch, pgbossQueue, post, put, rateLimiter, router, serialize, serveStatic, session, setCronGlobalErrorHandler, setMqttGlobalErrorHandler, sqsQueue, timeout, trustProxy, validate };