UNPKG

nexting

Version:

A comprehensive, type-safe full-stack library for TypeScript/JavaScript applications. Provides server actions, API controllers, React hooks, error handling, and professional logging - all with complete type safety and inference.

218 lines (204 loc) 9.49 kB
import { AsyncState } from 'async-xtate'; export * from 'async-xtate'; import { StatusCodes } from 'http-status-codes'; export * from 'http-status-codes'; import { z, ZodTypeAny } from 'zod'; import * as zod from 'zod'; export { zod }; import { NextRequest } from 'next/server'; interface ServerErrorProps { message: string; uiMessage?: string; code?: string; status?: StatusCodes; } declare class ServerError extends Error { code?: string; status: StatusCodes; uiMessage?: string; constructor(props: ServerErrorProps); toJSON(): { message: string; code: string | undefined; status: StatusCodes; uiMessage: string | undefined; }; } interface ParseServerErrorOptions { defaultMessage?: string; defaultCode?: string; defaultStatus?: StatusCodes; defaultUiMessage?: string; parser?: (error: unknown) => ServerError | null; } declare enum ParseServerErrorCode { ValidationError = "VALIDATION_ERROR", GenericError = "GENERIC_ERROR" } declare const parseServerError: (error: unknown, { defaultMessage, defaultCode, defaultStatus, defaultUiMessage, parser, }?: ParseServerErrorOptions) => ServerError; declare enum LogLevel { ERROR = "ERROR", WARN = "WARN", INFO = "INFO", DEBUG = "DEBUG", TRACE = "TRACE" } interface LogEntry { level: LogLevel; message: string; timestamp: Date; metadata?: Record<string, unknown>; context?: string; requestId?: string; } interface LogFormatter { format(entry: LogEntry): string; } interface LogTransport { log(formattedMessage: string, entry: LogEntry): void | Promise<void>; } interface LoggerConfig { level: LogLevel; context?: string; formatter?: LogFormatter; transports?: LogTransport[]; includeTimestamp?: boolean; includeContext?: boolean; includeMetadata?: boolean; } interface RequestLogData { method: string; url: string; userAgent?: string; ip?: string; headers?: Record<string, string>; body?: unknown; duration?: number; statusCode?: number; } declare class Logger { private config; constructor(config?: Partial<LoggerConfig>); private shouldLog; private writeLog; error(message: string, metadata?: Record<string, unknown>, requestId?: string): Promise<void>; warn(message: string, metadata?: Record<string, unknown>, requestId?: string): Promise<void>; info(message: string, metadata?: Record<string, unknown>, requestId?: string): Promise<void>; debug(message: string, metadata?: Record<string, unknown>, requestId?: string): Promise<void>; trace(message: string, metadata?: Record<string, unknown>, requestId?: string): Promise<void>; child(context: string): Logger; setLevel(level: LogLevel): void; setFormatter(formatter: LogFormatter): void; addTransport(transport: LogTransport): void; } declare class RequestLogger { private logger; constructor(logger: Logger); private extractRequestData; private generateRequestId; logRequest(request: Request): Promise<string>; logResponse(requestId: string, statusCode: number, duration: number, additionalData?: Record<string, unknown>): Promise<void>; logError(requestId: string, error: Error, additionalData?: Record<string, unknown>): Promise<void>; } declare const defaultLogger: Logger; declare const requestLogger: RequestLogger; declare const serverLogger: (request: Request) => Promise<string>; declare const createLogger: (config?: Partial<LoggerConfig>) => Logger; declare const createRequestLogger: (logger?: Logger) => RequestLogger; interface CommonHandlerOptions { error?: ParseServerErrorOptions; logger?: Logger; } interface CommonHandlerOptionsWithSchema<T extends z.ZodTypeAny> extends CommonHandlerOptions { validationSchema: T; } interface ValidationResult<T> { isValid: boolean; data?: T; error?: ReturnType<ServerError['toJSON']>; } declare const validateInput: <T extends z.ZodTypeAny>(input: unknown, schema?: T) => ValidationResult<z.infer<T>>; declare const handleError: (error: unknown, options?: CommonHandlerOptions) => ReturnType<ServerError["toJSON"]>; declare function makeServerAction<R, T extends z.ZodTypeAny>(actionFn: (props: z.infer<T>) => Promise<R>, options: CommonHandlerOptionsWithSchema<T>): (props: z.infer<T>) => Promise<AsyncState<R, ReturnType<ServerError['toJSON']>>>; declare function makeServerAction<R>(actionFn: () => Promise<R>, options?: CommonHandlerOptions): () => Promise<AsyncState<R, ReturnType<ServerError['toJSON']>>>; interface ApiMakerResponse<T> { data: T; status?: StatusCodes; } interface ApiControllerContext { request: NextRequest; } interface ApiControllerProps { params?: Record<string, string>; } declare function makeApiController<BodySchema extends ZodTypeAny, QuerySchema extends ZodTypeAny, ParamsSchema extends ZodTypeAny, R>(controller: (args: { body: z.infer<BodySchema>; query: z.infer<QuerySchema>; params: z.infer<ParamsSchema>; }, ctx: ApiControllerContext) => Promise<R>, options: CommonHandlerOptions & { bodySchema: BodySchema; querySchema: QuerySchema; paramsSchema: ParamsSchema; }): (request: NextRequest, props?: ApiControllerProps) => Promise<Response>; declare function makeApiController<BodySchema extends ZodTypeAny, QuerySchema extends ZodTypeAny, R>(controller: (args: { body: z.infer<BodySchema>; query: z.infer<QuerySchema>; }, ctx: ApiControllerContext) => Promise<ApiMakerResponse<R>>, options: CommonHandlerOptions & { bodySchema: BodySchema; querySchema: QuerySchema; }): (request: NextRequest, props?: ApiControllerProps) => Promise<Response>; declare function makeApiController<BodySchema extends ZodTypeAny, ParamsSchema extends ZodTypeAny, R>(controller: (args: { body: z.infer<BodySchema>; params: z.infer<ParamsSchema>; }, ctx: ApiControllerContext) => Promise<ApiMakerResponse<R>>, options: CommonHandlerOptions & { bodySchema: BodySchema; paramsSchema: ParamsSchema; }): (request: NextRequest, props?: ApiControllerProps) => Promise<Response>; declare function makeApiController<QuerySchema extends ZodTypeAny, ParamsSchema extends ZodTypeAny, R>(controller: (args: { query: z.infer<QuerySchema>; params: z.infer<ParamsSchema>; }, ctx: ApiControllerContext) => Promise<ApiMakerResponse<R>>, options: CommonHandlerOptions & { querySchema: QuerySchema; paramsSchema: ParamsSchema; }): (request: NextRequest, props?: ApiControllerProps) => Promise<Response>; declare function makeApiController<BodySchema extends ZodTypeAny, R>(controller: (args: { body: z.infer<BodySchema>; }, ctx: ApiControllerContext) => Promise<ApiMakerResponse<R>>, options: CommonHandlerOptions & { bodySchema: BodySchema; }): (request: NextRequest, props?: ApiControllerProps) => Promise<Response>; declare function makeApiController<QuerySchema extends ZodTypeAny, R>(controller: (args: { query: z.infer<QuerySchema>; }, ctx: ApiControllerContext) => Promise<ApiMakerResponse<R>>, options: CommonHandlerOptions & { querySchema: QuerySchema; }): (request: NextRequest, props?: ApiControllerProps) => Promise<Response>; declare function makeApiController<ParamsSchema extends ZodTypeAny, R>(controller: (args: { params: z.infer<ParamsSchema>; }, ctx: ApiControllerContext) => Promise<ApiMakerResponse<R>>, options: CommonHandlerOptions & { paramsSchema: ParamsSchema; }): (request: NextRequest, props?: ApiControllerProps) => Promise<Response>; declare function makeApiController<R>(controller: (ctx: ApiControllerContext) => Promise<ApiMakerResponse<R>>, options?: CommonHandlerOptions): (request: NextRequest, props?: ApiControllerProps) => Promise<Response>; /** * Tipo genérico que representa cualquier acción generada por makeServerAction */ type GenericAction = ((...args: any[]) => Promise<AsyncState<any, ReturnType<ServerError['toJSON']>>>) | (() => Promise<AsyncState<any, ReturnType<ServerError['toJSON']>>>); /** * Extrae los parámetros de entrada de una acción */ type InferActionInput<T extends GenericAction> = T extends (...args: infer P) => any ? P extends [infer First] ? First : P extends [] ? void : P : never; /** * Extrae el tipo de datos de respuesta exitosa de una acción */ type InferActionOutput<T extends GenericAction> = T extends (...args: any[]) => Promise<AsyncState<infer R, any>> ? R : never; /** * Extrae el tipo de error de una acción */ type InferActionError<T extends GenericAction> = T extends (...args: any[]) => Promise<AsyncState<any, infer E>> ? E : never; /** * Tipo de error estándar para todas las acciones */ type ActionError = ReturnType<ServerError['toJSON']>; /** * Helper type para verificar si una acción requiere parámetros */ type ActionRequiresInput<T extends GenericAction> = InferActionInput<T> extends void ? false : true; export { type ActionError, type ActionRequiresInput, type CommonHandlerOptions, type CommonHandlerOptionsWithSchema, type GenericAction, type InferActionError, type InferActionInput, type InferActionOutput, type LogEntry, type LogFormatter, LogLevel, type LogTransport, Logger, type LoggerConfig, ParseServerErrorCode, type ParseServerErrorOptions, type RequestLogData, RequestLogger, ServerError, type ValidationResult, createLogger, createRequestLogger, defaultLogger, handleError, makeApiController, makeServerAction, parseServerError, requestLogger, serverLogger, validateInput };