@faasjs/core 8.0.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,814 @@
1
+ import * as z from "zod";
2
+ import { ZodTypeAny, output } from "zod";
3
+ import { Logger } from "@faasjs/node-utils";
4
+ import { IncomingMessage, Server as Server$1, ServerResponse } from "node:http";
5
+ import knex, { Knex as Knex$1, Knex as OriginKnex } from "knex";
6
+
7
+ //#region src/utils.d.ts
8
+ /**
9
+ * Assigns a name to a given function handler, which will be displayed in logs and error messages.
10
+ *
11
+ * @template T - The type of the function handler.
12
+ * @param {string} name - The name to assign to the function handler.
13
+ * @param {T} handler - The function handler to which the name will be assigned.
14
+ * @returns {T} - The original function handler with the assigned name.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * import { nameFunc } from '@faasjs/core'
19
+ *
20
+ * const handler = nameFunc('myHandler', () => {
21
+ * return 'Hello World'
22
+ * })
23
+ *
24
+ * console.log(handler.name) // => 'myHandler'
25
+ * ```
26
+ */
27
+ declare function nameFunc<T extends (...args: any[]) => any>(name: string, handler: T): T;
28
+ //#endregion
29
+ //#region src/func.d.ts
30
+ type Handler<TEvent = any, TContext = any, TResult = any> = (data: InvokeData<TEvent, TContext>) => Promise<TResult>;
31
+ type Next = () => Promise<void>;
32
+ type ExportedHandler<TEvent = any, TContext = any, TResult = any> = (event?: TEvent, context?: TContext, callback?: (...args: any) => any) => Promise<TResult>;
33
+ type Plugin = {
34
+ [key: string]: any;
35
+ readonly type: string;
36
+ readonly name: string;
37
+ onMount?: (data: MountData, next: Next) => Promise<void>;
38
+ onInvoke?: (data: InvokeData, next: Next) => Promise<void>;
39
+ };
40
+ type Config = {
41
+ [key: string]: any;
42
+ plugins?: {
43
+ [key: string]: {
44
+ [key: string]: any;
45
+ type?: string;
46
+ config?: {
47
+ [key: string]: any;
48
+ };
49
+ };
50
+ };
51
+ };
52
+ type MountData = {
53
+ [key: string]: any;
54
+ config: Config;
55
+ event: any;
56
+ context: any;
57
+ };
58
+ type InvokeData<TEvent = any, TContext = any, TResult = any> = {
59
+ [key: string]: any;
60
+ event: TEvent;
61
+ context: TContext;
62
+ callback: any;
63
+ response: any;
64
+ logger: Logger;
65
+ handler?: Handler<TEvent, TContext, TResult>;
66
+ config: Config;
67
+ };
68
+ type LifeCycleKey = 'onMount' | 'onInvoke';
69
+ type FuncConfig<TEvent = any, TContext = any, TResult = any> = {
70
+ plugins?: Plugin[];
71
+ handler?: Handler<TEvent, TContext, TResult>;
72
+ };
73
+ /**
74
+ * Get the event type of a func.
75
+ *
76
+ * @example
77
+ * ```ts
78
+ * import { defineApi } from '@faasjs/core'
79
+ * import type { FuncEventType } from '@faasjs/core'
80
+ *
81
+ * const func = defineApi<undefined, { counter: number }>({
82
+ * async handler() {
83
+ * return null
84
+ * },
85
+ * })
86
+ *
87
+ * FuncEventType<typeof func> // => { counter: number }
88
+ * ```
89
+ */
90
+ type FuncEventType<T extends Func<any, any, any>> = T extends Func<infer P, any, any> ? P : any;
91
+ /**
92
+ * Get the return type of a func.
93
+ *
94
+ * @example
95
+ * ```ts
96
+ * import { defineApi } from '@faasjs/core'
97
+ * import type { FuncReturnType } from '@faasjs/core'
98
+ *
99
+ * const func = defineApi<undefined, any, any, number>({
100
+ * async handler() {
101
+ * return 1
102
+ * },
103
+ * })
104
+ *
105
+ * FuncReturnType<typeof func> // => number
106
+ * ```
107
+ */
108
+ type FuncReturnType<T extends Func<any, any, any>> = T extends Func<any, any, infer R> ? R : any;
109
+ type NormalizePluginType<TType extends string> = TType extends `npm:${infer Name}` ? Name : TType extends `@faasjs/${infer Name}` ? Name : TType;
110
+ type UnionToIntersection<T> = (T extends unknown ? (arg: T) => void : never) extends ((arg: infer TResult) => void) ? TResult : never;
111
+ type Simplify<T> = { [K in keyof T]: T[K] } & {};
112
+ /**
113
+ * Plugin event augmentation map.
114
+ *
115
+ * Extend this interface in plugin packages to describe which event fields are
116
+ * injected when the plugin is enabled through `faas.yaml`.
117
+ */
118
+ interface FaasPluginEventMap {}
119
+ type ResolvePluginEvent<TType extends string> = NormalizePluginType<TType> extends keyof FaasPluginEventMap ? FaasPluginEventMap[NormalizePluginType<TType>] : Record<never, never>;
120
+ /**
121
+ * Infer event type from plugin type names.
122
+ *
123
+ * @example
124
+ * ```ts
125
+ * type Event = InferPluginEvent<['http']>
126
+ * ```
127
+ */
128
+ type InferPluginEvent<TPlugins extends readonly string[]> = Simplify<Record<string, any> & UnionToIntersection<ResolvePluginEvent<TPlugins[number]>>>;
129
+ declare function parseFuncFilenameFromStack(stack?: string): string | undefined;
130
+ declare class Func<TEvent = any, TContext = any, TResult = any> {
131
+ [key: string]: any;
132
+ plugins: Plugin[];
133
+ handler?: Handler<TEvent, TContext, TResult>;
134
+ config: Config;
135
+ mounted: boolean;
136
+ filename?: string;
137
+ private cachedFunctions;
138
+ /**
139
+ * Create a cloud function.
140
+ */
141
+ constructor(config: FuncConfig<TEvent, TContext>);
142
+ private getCachedFunctions;
143
+ private compose;
144
+ /**
145
+ * First time mount the function.
146
+ */
147
+ mount(data?: {
148
+ event: TEvent;
149
+ context: TContext;
150
+ config?: Config;
151
+ logger?: Logger;
152
+ }): Promise<void>;
153
+ /**
154
+ * Invoke the function.
155
+ */
156
+ invoke(data: InvokeData<TEvent, TContext, TResult>): Promise<void>;
157
+ /**
158
+ * Export the function.
159
+ */
160
+ export(): {
161
+ handler: ExportedHandler<TEvent, TContext, TResult>;
162
+ };
163
+ }
164
+ type UseifyPlugin<T> = T & {
165
+ mount: (data?: MountData) => Promise<T>;
166
+ };
167
+ declare function usePlugin<T extends Plugin>(plugin: T & {
168
+ mount?: (data?: MountData) => Promise<T>;
169
+ }): UseifyPlugin<T>;
170
+ /**
171
+ * Create a cloud function.
172
+ */
173
+ declare function useFunc<TEvent = any, TContext = any, TResult = any>(handler: () => Handler<TEvent, TContext, TResult>): Func<TEvent, TContext, TResult>;
174
+ //#endregion
175
+ //#region src/knex/plugin.d.ts
176
+ /**
177
+ * Origin [knex](https://knexjs.org/) instance.
178
+ */
179
+ declare const originKnex: typeof knex;
180
+ type KnexConfig = {
181
+ name?: string;
182
+ config?: OriginKnex.Config;
183
+ };
184
+ declare function initPostgresTypeParsers(): Promise<void>;
185
+ declare class Knex implements Plugin {
186
+ readonly type = "knex";
187
+ readonly name: string;
188
+ config: OriginKnex.Config;
189
+ adapter: OriginKnex;
190
+ query: OriginKnex;
191
+ logger: Logger;
192
+ constructor(config?: KnexConfig);
193
+ onMount(data: MountData, next: Next): Promise<void>;
194
+ onInvoke(data: InvokeData<any, any, any>, next: Next): Promise<void>;
195
+ raw<TResult = any>(sql: string, bindings?: OriginKnex.RawBinding[] | OriginKnex.ValueDict): Promise<OriginKnex.Raw<TResult>>;
196
+ /**
197
+ * Wraps a transaction, returning a promise that resolves to the return value of the callback.
198
+ *
199
+ * - Support 'commit' and 'rollback' event.
200
+ */
201
+ transaction<TResult = any>(scope: (trx: OriginKnex.Transaction<any, any>) => Promise<TResult>, config?: OriginKnex.TransactionConfig, options?: {
202
+ trx?: OriginKnex.Transaction;
203
+ }): Promise<TResult>;
204
+ schema(): OriginKnex.SchemaBuilder;
205
+ quit(): Promise<void>;
206
+ }
207
+ declare function useKnex(config?: KnexConfig): UseifyPlugin<Knex>;
208
+ declare function query<TName extends OriginKnex.TableNames>(table: TName): OriginKnex.QueryBuilder<OriginKnex.TableType<TName>, {
209
+ _base: OriginKnex.ResolveTableType<OriginKnex.TableType<TName>, 'base'>;
210
+ _hasSelection: false;
211
+ _keys: never;
212
+ _aliases: {};
213
+ _single: false;
214
+ _intersectProps: {};
215
+ _unionProps: never;
216
+ }[]>;
217
+ declare function query<TName extends {} = any, TResult = any[]>(table: string): OriginKnex.QueryBuilder<TName, TResult>;
218
+ declare function transaction<TResult = any>(scope: (trx: OriginKnex.Transaction<any, any>) => Promise<TResult>, config?: OriginKnex.TransactionConfig, options?: {
219
+ trx?: OriginKnex.Transaction;
220
+ }): Promise<TResult>;
221
+ declare function raw<TResult = any>(sql: string, bindings?: OriginKnex.RawBinding[] | OriginKnex.ValueDict): Promise<OriginKnex.Raw<TResult>>;
222
+ //#endregion
223
+ //#region src/http/session.d.ts
224
+ type SessionOptions = {
225
+ key: string;
226
+ secret: string;
227
+ salt?: string;
228
+ signedSalt?: string;
229
+ keylen?: number;
230
+ iterations?: number;
231
+ digest?: string;
232
+ cipherName?: string;
233
+ };
234
+ type SessionContent = string | number | {
235
+ [key: string]: any;
236
+ } | null | undefined;
237
+ declare class Session<S extends Record<string, string> = any, C extends Record<string, string> = any> {
238
+ content: Record<string, string | number>;
239
+ readonly config: {
240
+ key: string;
241
+ secret: string;
242
+ salt: string;
243
+ signedSalt: string;
244
+ keylen: number;
245
+ iterations: number;
246
+ digest: string;
247
+ cipherName: string;
248
+ };
249
+ private readonly secret;
250
+ private readonly signedSecret;
251
+ private readonly cookie;
252
+ private changed?;
253
+ constructor(cookie: Cookie<C, S>, config: SessionOptions);
254
+ invoke(cookie?: string, logger?: Logger): void;
255
+ encode(text: SessionContent): string;
256
+ decode<TData = any>(text: string): TData | SessionContent;
257
+ read(key: string): string | number;
258
+ write(key: string, value?: string | number | null): Session<S, C>;
259
+ update(): Session<S, C>;
260
+ }
261
+ //#endregion
262
+ //#region src/http/cookie.d.ts
263
+ type CookieOptions = {
264
+ domain?: string;
265
+ path?: string;
266
+ expires?: number;
267
+ secure?: boolean;
268
+ httpOnly?: boolean;
269
+ sameSite?: 'Strict' | 'Lax' | 'None';
270
+ session?: SessionOptions;
271
+ [key: string]: any;
272
+ };
273
+ declare class Cookie<C extends Record<string, string> = any, S extends Record<string, string> = any> {
274
+ session: Session<S, C>;
275
+ content: Record<string, string>;
276
+ readonly config: {
277
+ domain?: string;
278
+ path: string;
279
+ expires: number;
280
+ secure: boolean;
281
+ httpOnly: boolean;
282
+ sameSite?: 'Strict' | 'Lax' | 'None';
283
+ session: SessionOptions;
284
+ };
285
+ logger: Logger | undefined;
286
+ private setCookie;
287
+ constructor(config: CookieOptions, logger?: Logger);
288
+ invoke(cookie: string | undefined, logger: Logger): Cookie<C, S>;
289
+ read(key: string): any;
290
+ write(key: string, value: string | null | undefined, opts?: {
291
+ domain?: string;
292
+ path?: string;
293
+ expires?: number | string;
294
+ secure?: boolean;
295
+ httpOnly?: boolean;
296
+ sameSite?: 'Strict' | 'Lax' | 'None';
297
+ }): Cookie<C, S>;
298
+ headers(): {
299
+ 'Set-Cookie'?: string[];
300
+ };
301
+ }
302
+ //#endregion
303
+ //#region src/http/index.d.ts
304
+ declare const ContentType: {
305
+ [key: string]: string;
306
+ };
307
+ type HttpConfig = {
308
+ [key: string]: any;
309
+ name?: string;
310
+ config?: {
311
+ [key: string]: any; /** POST as default */
312
+ method?: 'BEGIN' | 'GET' | 'POST' | 'DELETE' | 'HEAD' | 'PUT' | 'OPTIONS' | 'TRACE' | 'PATCH' | 'ANY';
313
+ timeout?: number; /** file relative path as default */
314
+ path?: string;
315
+ ignorePathPrefix?: string;
316
+ functionName?: string;
317
+ cookie?: CookieOptions;
318
+ };
319
+ };
320
+ type Response = {
321
+ statusCode?: number;
322
+ headers?: {
323
+ [key: string]: string;
324
+ };
325
+ body?: string | ReadableStream;
326
+ message?: string;
327
+ };
328
+ declare class HttpError extends Error {
329
+ readonly statusCode: number;
330
+ readonly message: string;
331
+ constructor({
332
+ statusCode,
333
+ message
334
+ }: {
335
+ statusCode?: number;
336
+ message: string;
337
+ });
338
+ }
339
+ declare class Http<TParams extends Record<string, any> = any, TCookie extends Record<string, string> = any, TSession extends Record<string, string> = any> implements Plugin {
340
+ readonly type = "http";
341
+ readonly name: string;
342
+ headers: {
343
+ [key: string]: string;
344
+ };
345
+ body: any;
346
+ params: TParams;
347
+ cookie: Cookie<TCookie, TSession>;
348
+ session: Session<TSession, TCookie>;
349
+ config: HttpConfig;
350
+ private response;
351
+ constructor(config?: HttpConfig);
352
+ onMount(data: MountData, next: Next): Promise<void>;
353
+ onInvoke(data: InvokeData, next: Next): Promise<void>;
354
+ private parseEventParams;
355
+ private buildResponse;
356
+ private finalizeBody;
357
+ /**
358
+ * set header
359
+ * @param key {string} key
360
+ * @param value {string} value
361
+ */
362
+ setHeader(key: string, value: string): Http<TParams, TCookie, TSession>;
363
+ /**
364
+ * set Content-Type
365
+ * @param type {string} 类型
366
+ * @param charset {string} 编码
367
+ */
368
+ setContentType(type: string, charset?: string): Http<TParams, TCookie, TSession>;
369
+ /**
370
+ * set status code
371
+ * @param code {number} 状态码
372
+ */
373
+ setStatusCode(code: number): Http<TParams, TCookie, TSession>;
374
+ /**
375
+ * set body
376
+ * @param body {*} 内容
377
+ */
378
+ setBody(body: string): Http<TParams, TCookie, TSession>;
379
+ }
380
+ declare function useHttp<TParams extends Record<string, any> = any, TCookie extends Record<string, string> = any, TSession extends Record<string, string> = any>(config?: HttpConfig): UseifyPlugin<Http<TParams, TCookie, TSession>>;
381
+ declare module '@faasjs/core' {
382
+ interface FaasPluginEventMap {
383
+ http: {
384
+ headers?: Record<string, any>;
385
+ body?: any;
386
+ params?: Record<string, any>;
387
+ queryString?: Record<string, any>;
388
+ httpMethod?: string;
389
+ path?: string;
390
+ raw?: {
391
+ request?: unknown;
392
+ response?: unknown;
393
+ };
394
+ };
395
+ }
396
+ }
397
+ //#endregion
398
+ //#region src/middleware/middleware.d.ts
399
+ type MiddlewareEvent = {
400
+ body: any;
401
+ raw: {
402
+ request: IncomingMessage;
403
+ response: ServerResponse;
404
+ };
405
+ };
406
+ type MiddlewareContext = {
407
+ logger: Logger;
408
+ };
409
+ type Middleware = (request: IncomingMessage & {
410
+ body?: any;
411
+ }, response: ServerResponse, context: MiddlewareContext) => void | Promise<void>;
412
+ /**
413
+ * Apply a middleware function to handle incoming requests.
414
+ *
415
+ * @param handler - The middleware function to handle the request and response.
416
+ * @returns A function that processes the event and applies the middleware.
417
+ *
418
+ * @example
419
+ * ```typescript
420
+ * import { useMiddleware } from '@faasjs/core'
421
+ *
422
+ * export const func = useMiddleware((request, response, logger) => {
423
+ * response.setHeader('X-Hello', 'World')
424
+ * response.end('Hello, World!')
425
+ * logger.info('Hello, World!')
426
+ * })
427
+ * ```
428
+ */
429
+ declare function useMiddleware(handler: Middleware): Promise<Func<MiddlewareEvent, any, any>>;
430
+ /**
431
+ * Apply an array of middleware functions to an event.
432
+ *
433
+ * @param {Middleware[]} handlers - An array of middleware functions to be applied.
434
+ * @returns {Promise<void>} A promise that resolves when all middleware functions have been applied.
435
+ *
436
+ * @example
437
+ * ```typescript
438
+ * import { useMiddlewares } from '@faasjs/core'
439
+ *
440
+ * export const func = useMiddlewares([
441
+ * (request, response) => {
442
+ * if (request.url === '/hi') return
443
+ * response.end('Hello, World!')
444
+ * },
445
+ * (request, response) => {
446
+ * if (request.url === '/hello') return
447
+ * response.end('Hi, World!')
448
+ * }
449
+ * ])
450
+ * ```
451
+ */
452
+ declare function useMiddlewares(handlers: Middleware[]): Promise<Func<MiddlewareEvent, any, any>>;
453
+ //#endregion
454
+ //#region src/middleware/static.d.ts
455
+ type StaticHandlerOptions = {
456
+ root: string;
457
+ /**
458
+ * Not found handler.
459
+ *
460
+ * If set to `true`, the middleware will respond with a default 404 status code.
461
+ * If set to a string as a fallback path, the middleware will respond with the file at that path.
462
+ * If set to a function, the middleware will call the function with the request, response, and logger.
463
+ * If set to `false`, the middleware will do nothing.
464
+ *
465
+ * @default false
466
+ */
467
+ notFound?: Middleware | boolean | string;
468
+ /**
469
+ * Cache static files.
470
+ * If set to `true`, the middleware will cache static files.
471
+ * If set to a string, the middleware will cache static files with the specified key.
472
+ * If set to `false`, the middleware will not cache static files.
473
+ *
474
+ * @default true
475
+ */
476
+ cache?: boolean | string;
477
+ /**
478
+ * Strip prefix from the URL.
479
+ *
480
+ * @example
481
+ * ```typescript
482
+ * import { useMiddleware, staticHandler } from '@faasjs/core'
483
+ *
484
+ * export const func = useMiddleware(staticHandler({ root: __dirname + '/public', stripPrefix: '/public' })) // /public/index.html -> /index.html
485
+ * ```
486
+ */
487
+ stripPrefix?: string | RegExp;
488
+ };
489
+ /**
490
+ * Middleware to handle static file requests.
491
+ *
492
+ * @param {StaticHandlerOptions} options - Options for the static handler.
493
+ * @returns {Middleware} The middleware function.
494
+ *
495
+ * The middleware resolves the requested URL to a file path within the specified root directory.
496
+ * If the file exists, it reads the file content and sends it in the response.
497
+ * If the file does not exist, it does nothing.
498
+ *
499
+ * @example
500
+ * ```typescript
501
+ * import { useMiddleware, staticHandler } from '@faasjs/core'
502
+ *
503
+ * export const func = useMiddleware(staticHandler({ root: __dirname + '/public' }))
504
+ * ```
505
+ */
506
+ declare function staticHandler(options: StaticHandlerOptions): Middleware;
507
+ //#endregion
508
+ //#region src/cron/index.d.ts
509
+ type CronJobContext = {
510
+ now: Date;
511
+ logger: Logger;
512
+ job: CronJob;
513
+ };
514
+ type CronJobHandler = (context: CronJobContext) => void | Promise<void>;
515
+ type CronJobErrorHandler = (error: Error, context: CronJobContext) => void | Promise<void>;
516
+ type CronJobOptions = {
517
+ /**
518
+ * Name of the cron job, used in logs.
519
+ *
520
+ * @default random name
521
+ */
522
+ name?: string;
523
+ /**
524
+ * Cron expression in 5-field format:
525
+ * minute hour dayOfMonth month dayOfWeek
526
+ *
527
+ * Supported syntax per field: wildcard (`*`), step (every n units), and fixed number.
528
+ */
529
+ expression: string;
530
+ /**
531
+ * Job handler.
532
+ */
533
+ handler: CronJobHandler;
534
+ /**
535
+ * Called when handler throws.
536
+ */
537
+ onError?: CronJobErrorHandler;
538
+ /**
539
+ * Custom logger for this cron job.
540
+ */
541
+ logger?: Logger;
542
+ };
543
+ /**
544
+ * Simple cron job scheduler with 5-field cron expression support.
545
+ */
546
+ declare class CronJob {
547
+ readonly name: string;
548
+ readonly expression: string;
549
+ readonly handler: CronJobHandler;
550
+ private readonly onError;
551
+ private readonly logger;
552
+ private readonly matchers;
553
+ private timer;
554
+ private started;
555
+ private lastTickMinute;
556
+ constructor(options: CronJobOptions);
557
+ start(): void;
558
+ stop(): void;
559
+ get isStarted(): boolean;
560
+ private scheduleNext;
561
+ private tick;
562
+ private execute;
563
+ private handleError;
564
+ }
565
+ /**
566
+ * Create and register a cron job.
567
+ *
568
+ * Registered jobs are managed by `Server` lifecycle automatically.
569
+ */
570
+ declare function createCronJob(options: CronJobOptions): CronJob;
571
+ declare function removeCronJob(cronJob: CronJob): boolean;
572
+ declare function listCronJobs(): CronJob[];
573
+ //#endregion
574
+ //#region src/server/index.d.ts
575
+ type ServerHandlerOptions = {
576
+ requestedAt?: number;
577
+ filepath?: string;
578
+ };
579
+ declare function getAll(): Server[];
580
+ declare function closeAll(): Promise<void>;
581
+ /**
582
+ * Options for configuring the server.
583
+ */
584
+ /**
585
+ * Configuration options for the server.
586
+ */
587
+ type ServerOptions = {
588
+ /**
589
+ * The port on which the server will listen. Defaults to `3000` if not provided.
590
+ *
591
+ * @default 3000
592
+ */
593
+ port?: number;
594
+ /**
595
+ * Callback function that is invoked when the server starts.
596
+ *
597
+ * This function is executed asynchronously and will not interrupt the server
598
+ * if an error occurs during its execution.
599
+ *
600
+ * @param context - An object containing the logger instance.
601
+ *
602
+ * @example
603
+ * ```typescript
604
+ * const server = new Server(process.cwd(), {
605
+ * onStart: async ({ logger }) => {
606
+ * logger.info('Server started');
607
+ * }
608
+ * });
609
+ * ```
610
+ */
611
+ onStart?: (context: {
612
+ logger: Logger;
613
+ }) => Promise<void>;
614
+ /**
615
+ * Callback function that is invoked when an error occurs.
616
+ *
617
+ * This function is executed asynchronously and allows handling of errors
618
+ * that occur during server operation.
619
+ *
620
+ * @param error - The error that occurred.
621
+ * @param context - An object containing the logger instance.
622
+ *
623
+ * @example
624
+ * ```typescript
625
+ * const server = new Server(process.cwd(), {
626
+ * onError: async (error, { logger }) => {
627
+ * logger.error(error);
628
+ * }
629
+ * });
630
+ * ```
631
+ */
632
+ onError?: (error: Error, context: {
633
+ logger: Logger;
634
+ }) => Promise<void>;
635
+ /**
636
+ * Callback function that is invoked when the server is closed.
637
+ *
638
+ * This function is executed asynchronously and can be used to perform
639
+ * cleanup tasks or log server shutdown events.
640
+ *
641
+ * @param context - An object containing the logger instance.
642
+ *
643
+ * @example
644
+ * ```typescript
645
+ * const server = new Server(process.cwd(), {
646
+ * onClose: async ({ logger }) => {
647
+ * logger.info('Server closed');
648
+ * }
649
+ * });
650
+ * ```
651
+ */
652
+ onClose?: (context: {
653
+ logger: Logger;
654
+ }) => Promise<void>;
655
+ /**
656
+ * Callback function that is invoked before handling each request.
657
+ *
658
+ * This function is executed asynchronously before the main request handling logic.
659
+ * It can be used for request preprocessing, authentication, logging, etc.
660
+ *
661
+ * @param req - The incoming HTTP request object.
662
+ * @param res - The server response object.
663
+ *
664
+ * @example
665
+ * ```typescript
666
+ * const server = new Server(process.cwd(), {
667
+ * beforeHandle: async (req, res) => {
668
+ * console.log(`Processing ${req.method} request to ${req.url}`)
669
+ *
670
+ * if (req.method !== 'POST')
671
+ * res.writeHead(405, { 'Allow': 'POST' }) // If you write response, it will finish the request
672
+ * }
673
+ * });
674
+ * ```
675
+ */
676
+ beforeHandle?: Middleware;
677
+ /**
678
+ * Whether to mount cron job lifecycle with this server instance.
679
+ *
680
+ * When enabled, `server.listen()` mounts registered cron jobs and
681
+ * `server.close()` unmounts them.
682
+ *
683
+ * @default true
684
+ */
685
+ cronJob?: boolean;
686
+ };
687
+ /**
688
+ * FaasJS Server.
689
+ *
690
+ * @param {string} root The root path of the server.
691
+ * @param {ServerOptions} opts The options of the server.
692
+ * @returns {Server}
693
+ * @example
694
+ * ```ts
695
+ * import { Server } from '@faasjs/core'
696
+ *
697
+ * const server = new Server(process.cwd(), {
698
+ * port: 8080,
699
+ * })
700
+ *
701
+ * server.listen()
702
+ * ```
703
+ */
704
+ declare class Server {
705
+ readonly root: string;
706
+ readonly logger: Logger;
707
+ readonly options: ServerOptions;
708
+ protected closed: boolean;
709
+ private activeRequests;
710
+ private cachedFuncs;
711
+ private onError;
712
+ private server;
713
+ private sockets;
714
+ constructor(root: string, opts?: ServerOptions);
715
+ handle(req: IncomingMessage, res: ServerResponse<IncomingMessage>, options?: ServerHandlerOptions): Promise<void>;
716
+ private readRequestBody;
717
+ private runBeforeHandle;
718
+ private getOrLoadHandler;
719
+ private invokeHandler;
720
+ private buildResponseHeaders;
721
+ private pipeToResponse;
722
+ /**
723
+ * Start server.
724
+ * @returns {Server}
725
+ */
726
+ listen(): Server$1;
727
+ /**
728
+ * Close server.
729
+ */
730
+ close(): Promise<void>;
731
+ /**
732
+ * Middleware function to handle incoming HTTP requests.
733
+ *
734
+ * @param req - The incoming HTTP request object.
735
+ * @param res - The server response object.
736
+ * @param next - A callback function to pass control to the next middleware.
737
+ * @returns A promise that resolves when the middleware processing is complete.
738
+ */
739
+ middleware(req: IncomingMessage, res: ServerResponse<IncomingMessage>, next: () => void): Promise<void>;
740
+ private getFilePath;
741
+ private handleOptionRequest;
742
+ }
743
+ //#endregion
744
+ //#region src/knex/pglite.d.ts
745
+ type MountedKnexAdapter = {
746
+ adapter: Knex$1;
747
+ query: Knex$1;
748
+ config: Record<string, unknown>;
749
+ };
750
+ type MountFaasKnexOptions = {
751
+ /** key of `globalThis.FaasJS_Knex`, default is `knex` */name?: string; /** optional config metadata passed through to `@faasjs/core` */
752
+ config?: Record<string, unknown>;
753
+ };
754
+ /**
755
+ * Create a knex instance backed by `knex-pglite`.
756
+ * If connection is missing, it defaults to an in-memory database.
757
+ */
758
+ declare function createPgliteKnex(config?: Partial<Knex$1.Config>, connection?: string): Promise<Knex$1>;
759
+ /**
760
+ * Mount a knex adapter to `globalThis.FaasJS_Knex` for `@faasjs/core`.
761
+ */
762
+ declare function mountFaasKnex(db: Knex$1, options?: MountFaasKnexOptions): void;
763
+ /**
764
+ * Remove mounted knex adapter from `globalThis.FaasJS_Knex`.
765
+ */
766
+ declare function unmountFaasKnex(name?: string): void;
767
+ //#endregion
768
+ //#region src/knex/schema.d.ts
769
+ /**
770
+ * Migration helper for FaasJS knex plugin.
771
+ */
772
+ declare class KnexSchema {
773
+ readonly knex: {
774
+ name: string;
775
+ adapter?: Knex$1;
776
+ config: Knex$1.Config;
777
+ };
778
+ constructor(knex: {
779
+ name: string;
780
+ adapter?: Knex$1;
781
+ config: Knex$1.Config;
782
+ });
783
+ private getAdapter;
784
+ private getMigratorConfig;
785
+ migrateLatest(): Promise<any>;
786
+ migrateRollback(): Promise<any>;
787
+ migrateStatus(): Promise<number>;
788
+ migrateCurrentVersion(): Promise<string>;
789
+ migrateMake(name: string): Promise<string>;
790
+ }
791
+ //#endregion
792
+ //#region src/index.d.ts
793
+ type ZodSchema = ZodTypeAny;
794
+ type KnexQuery = Knex['query'];
795
+ type DefineApiData<TSchema extends ZodSchema | undefined = undefined, TEvent = any, TContext = any, TResult = any> = InvokeData<TEvent, TContext, TResult> & {
796
+ params: TSchema extends ZodSchema ? output<NonNullable<TSchema>> : Record<string, never>;
797
+ knex: KnexQuery | undefined;
798
+ };
799
+ type DefineApiOptions<TSchema extends ZodSchema | undefined = undefined, TEvent = any, TContext = any, TResult = any> = {
800
+ schema?: TSchema;
801
+ handler: (data: DefineApiData<TSchema, TEvent, TContext, TResult>) => Promise<TResult>;
802
+ };
803
+ /**
804
+ * Create an HTTP API function with optional Zod validation.
805
+ *
806
+ * Plugins are always auto-loaded from `func.config.plugins`.
807
+ * Plugin module exports must be either a named class (normalized from
808
+ * plugin type) or a default class export.
809
+ *
810
+ * The `http` plugin is required.
811
+ */
812
+ declare function defineApi<TSchema extends ZodSchema | undefined = undefined, TEvent = any, TContext = any, TResult = any>(options: DefineApiOptions<TSchema, TEvent, TContext, TResult>): Func<TEvent, TContext, TResult>;
813
+ //#endregion
814
+ export { Config, ContentType, Cookie, type CookieOptions, CronJob, type CronJobContext, type CronJobErrorHandler, type CronJobHandler, type CronJobOptions, DefineApiData, DefineApiOptions, ExportedHandler, FaasPluginEventMap, Func, FuncConfig, FuncEventType, FuncReturnType, Handler, Http, type HttpConfig, HttpError, InferPluginEvent, InvokeData, Knex, KnexConfig, KnexSchema, LifeCycleKey, type Middleware, type MiddlewareContext, type MiddlewareEvent, MountData, MountFaasKnexOptions, MountedKnexAdapter, Next, NormalizePluginType, type OriginKnex, Plugin, ResolvePluginEvent, type Response, Server, type ServerHandlerOptions, type ServerOptions, Session, type SessionContent, type SessionOptions, Simplify, type StaticHandlerOptions, UnionToIntersection, UseifyPlugin, closeAll, createCronJob, createPgliteKnex, defineApi, getAll, initPostgresTypeParsers, listCronJobs, mountFaasKnex, nameFunc, originKnex, parseFuncFilenameFromStack, query, raw, removeCronJob, staticHandler, transaction, unmountFaasKnex, useFunc, useHttp, useKnex, useMiddleware, useMiddlewares, usePlugin, z };