All files / coherent.js/packages/api/types index.d.ts

0% Statements 0/17
100% Branches 1/1
100% Functions 1/1
0% Lines 0/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
/**
 * Coherent.js API Types
 * TypeScript definitions for the API framework
 * 
 * @version 1.1.1
 */
 
import { IncomingMessage, ServerResponse } from 'http';
 
// ============================================================================
// HTTP Types
// ============================================================================
 
/** HTTP methods */
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS' | 'HEAD';
 
/** HTTP status codes */
export type HttpStatusCode = number;
 
/** Request headers */
export interface RequestHeaders {
  [key: string]: string | string[] | undefined;
  'content-type'?: string;
  'authorization'?: string;
  'accept'?: string;
  'user-agent'?: string;
  'x-api-key'?: string;
}
 
/** Response headers */
export interface ResponseHeaders {
  [key: string]: string | number | string[];
  'content-type'?: string;
  'cache-control'?: string;
  'access-control-allow-origin'?: string;
}
 
/** Query parameters */
export interface QueryParams {
  [key: string]: string | string[] | undefined;
}
 
/** URL parameters */
export interface UrlParams {
  [key: string]: string | undefined;
}
 
/** Request body types */
export type RequestBody = any;
 
// ============================================================================
// API Request and Response
// ============================================================================
 
/** Enhanced API request object */
export interface ApiRequest extends IncomingMessage {
  method: HttpMethod;
  url: string;
  headers: RequestHeaders;
  query: QueryParams;
  params: UrlParams;
  body: RequestBody;
  originalUrl?: string;
  path?: string;
  protocol?: string;
  secure?: boolean;
  ip?: string;
  ips?: string[];
  hostname?: string;
  fresh?: boolean;
  stale?: boolean;
  xhr?: boolean;
  user?: any;
  session?: any;
  cookies?: Record<string, string>;
  signedCookies?: Record<string, string>;
}
 
/** Enhanced API response object */
export interface ApiResponse extends ServerResponse {
  json(obj: any): ApiResponse;
  send(body: any): ApiResponse;
  status(code: HttpStatusCode): ApiResponse;
  set(field: string, val: string | string[]): ApiResponse;
  set(field: ResponseHeaders): ApiResponse;
  get(field: string): string | undefined;
  header(field: string, val: string | string[]): ApiResponse;
  header(field: ResponseHeaders): ApiResponse;
  type(type: string): ApiResponse;
  format(obj: Record<string, Function>): ApiResponse;
  attachment(filename?: string): ApiResponse;
  sendFile(path: string, options?: any, fn?: Function): void;
  download(path: string, filename?: string, options?: any, fn?: Function): void;
  contentType(type: string): ApiResponse;
  sendStatus(code: HttpStatusCode): ApiResponse;
  links(links: Record<string, string>): ApiResponse;
  location(url: string): ApiResponse;
  redirect(status: number, url: string): void;
  redirect(url: string): void;
  vary(field: string): ApiResponse;
  render(view: string, locals?: any, callback?: Function): void;
}
 
// ============================================================================
// Route Handler Types
// ============================================================================
 
/** Route handler function */
export type RouteHandler = (
  req: ApiRequest,
  res: ApiResponse,
  next?: NextFunction
) => void | Promise<void> | any;
 
/** Next function for middleware */
export interface NextFunction {
  (err?: any): void;
}
 
/** Middleware function */
export type Middleware = (
  req: ApiRequest,
  res: ApiResponse,
  next: NextFunction
) => void | Promise<void>;
 
/** Error handling middleware */
export type ErrorMiddleware = (
  err: any,
  req: ApiRequest,
  res: ApiResponse,
  next: NextFunction
) => void | Promise<void>;
 
// ============================================================================
// Object-Based Routing
// ============================================================================
 
/** Route definition for object-based routing */
export interface RouteDefinition {
  GET?: RouteHandler;
  POST?: RouteHandler;
  PUT?: RouteHandler;
  DELETE?: RouteHandler;
  PATCH?: RouteHandler;
  OPTIONS?: RouteHandler;
  HEAD?: RouteHandler;
  middleware?: Middleware | Middleware[];
  validation?: ValidationSchema;
  serialization?: SerializationConfig;
  auth?: AuthConfig;
  rateLimit?: RateLimitConfig;
  cache?: CacheConfig;
}
 
/** Nested route object */
export interface RouteObject {
  [path: string]: RouteDefinition | RouteObject;
}
 
/** Router configuration */
export interface RouterConfig {
  prefix?: string;
  middleware?: Middleware[];
  errorHandler?: ErrorMiddleware;
  notFoundHandler?: RouteHandler;
  caseSensitive?: boolean;
  mergeParams?: boolean;
  strict?: boolean;
}
 
/** Object router interface */
export interface ObjectRouter {
  routes: RouteObject;
  config: RouterConfig;
  addRoute(path: string, definition: RouteDefinition): void;
  addRoutes(routes: RouteObject): void;
  use(middleware: Middleware): void;
  use(path: string, middleware: Middleware): void;
  handle(req: ApiRequest, res: ApiResponse, next?: NextFunction): void;
  getRoutes(): RouteObject;
  mount(app: any): void;
}
 
// ============================================================================
// Validation
// ============================================================================
 
/** Field validation rule */
export interface ValidationRule {
  type?: 'string' | 'number' | 'boolean' | 'array' | 'object' | 'email' | 'url' | 'date';
  required?: boolean;
  min?: number;
  max?: number;
  minLength?: number;
  maxLength?: number;
  pattern?: RegExp | string;
  enum?: any[];
  custom?: (value: any, field: string, data: any) => boolean | string;
  message?: string;
  transform?: (value: any) => any;
}
 
/** Validation schema */
export interface ValidationSchema {
  [field: string]: ValidationRule | ValidationSchema;
}
 
/** Validation result */
export interface ValidationResult {
  valid: boolean;
  errors: ValidationError[];
  data: any;
}
 
/** Validation error */
export interface ValidationError {
  field: string;
  message: string;
  value: any;
  rule: string;
}
 
/** Validation options */
export interface ValidationOptions {
  abortEarly?: boolean;
  stripUnknown?: boolean;
  allowUnknown?: boolean;
  skipMissing?: boolean;
  context?: any;
}
 
// ============================================================================
// Authentication and Authorization
// ============================================================================
 
/** Authentication configuration */
export interface AuthConfig {
  required?: boolean;
  roles?: string[];
  permissions?: string[];
  strategy?: 'jwt' | 'session' | 'basic' | 'custom';
  verify?: (req: ApiRequest) => Promise<any> | any;
}
 
/** JWT options */
export interface JwtOptions {
  secret: string;
  algorithm?: string;
  expiresIn?: string | number;
  issuer?: string;
  audience?: string;
}
 
/** User authentication info */
export interface AuthUser {
  id: string | number;
  username?: string;
  email?: string;
  roles?: string[];
  permissions?: string[];
  [key: string]: any;
}
 
// ============================================================================
// Rate Limiting
// ============================================================================
 
/** Rate limit configuration */
export interface RateLimitConfig {
  windowMs?: number;
  max?: number;
  keyGenerator?: (req: ApiRequest) => string;
  handler?: RouteHandler;
  skip?: (req: ApiRequest) => boolean;
  message?: string | any;
}
 
// ============================================================================
// Caching
// ============================================================================
 
/** Cache configuration */
export interface CacheConfig {
  ttl?: number;
  key?: string | ((req: ApiRequest) => string);
  varies?: string[];
  condition?: (req: ApiRequest, res: ApiResponse) => boolean;
}
 
// ============================================================================
// Serialization
// ============================================================================
 
/** Serialization configuration */
export interface SerializationConfig {
  include?: string[];
  exclude?: string[];
  transform?: Record<string, (value: any) => any>;
  dateFormat?: string;
  nullValues?: boolean;
  undefinedValues?: boolean;
}
 
/** Serialization options */
export interface SerializationOptions {
  space?: number;
  replacer?: (key: string, value: any) => any;
  dateHandler?: (date: Date) => any;
  errorHandler?: (error: Error) => any;
}
 
// ============================================================================
// Error Handling
// ============================================================================
 
/** Base API error */
export class ApiError extends Error {
  constructor(message: string, statusCode?: number, code?: string);
  statusCode: number;
  code: string;
  details?: any;
  toJSON(): object;
}
 
/** Validation error class */
export class ValidationError extends ApiError {
  constructor(message: string, errors?: ValidationError[]);
  errors: ValidationError[];
}
 
/** Authentication error class */
export class AuthenticationError extends ApiError {
  constructor(message?: string);
}
 
/** Authorization error class */
export class AuthorizationError extends ApiError {
  constructor(message?: string);
}
 
/** Not found error class */
export class NotFoundError extends ApiError {
  constructor(message?: string);
}
 
/** Conflict error class */
export class ConflictError extends ApiError {
  constructor(message?: string);
}
 
/** Error handler options */
export interface ErrorHandlerOptions {
  includeStack?: boolean;
  logger?: (error: Error, req: ApiRequest) => void;
  transform?: (error: Error) => any;
}
 
// ============================================================================
// Middleware Types
// ============================================================================
 
/** CORS configuration */
export interface CorsConfig {
  origin?: string | string[] | boolean | ((req: ApiRequest) => boolean);
  methods?: HttpMethod[];
  allowedHeaders?: string[];
  exposedHeaders?: string[];
  credentials?: boolean;
  maxAge?: number;
  preflightContinue?: boolean;
  optionsSuccessStatus?: number;
}
 
/** Body parser options */
export interface BodyParserOptions {
  limit?: string;
  extended?: boolean;
  inflate?: boolean;
  strict?: boolean;
  type?: string | string[] | ((req: ApiRequest) => boolean);
  verify?: (req: ApiRequest, res: ApiResponse, buf: Buffer, encoding: string) => void;
}
 
/** Security headers configuration */
export interface SecurityConfig {
  contentSecurityPolicy?: string | boolean;
  crossOriginEmbedderPolicy?: boolean;
  crossOriginOpenerPolicy?: boolean;
  crossOriginResourcePolicy?: string | boolean;
  dnsPrefetchControl?: boolean;
  expectCt?: boolean;
  frameguard?: boolean | string;
  hidePoweredBy?: boolean;
  hsts?: boolean | object;
  ieNoOpen?: boolean;
  noSniff?: boolean;
  originAgentCluster?: boolean;
  permittedCrossDomainPolicies?: boolean | string;
  referrerPolicy?: boolean | string;
  xssFilter?: boolean;
}
 
// ============================================================================
// OpenAPI/Swagger Types
// ============================================================================
 
/** OpenAPI specification */
export interface OpenAPISpec {
  openapi: string;
  info: OpenAPIInfo;
  paths: OpenAPIPaths;
  components?: OpenAPIComponents;
  security?: OpenAPISecurityRequirement[];
  tags?: OpenAPITag[];
  servers?: OpenAPIServer[];
}
 
/** OpenAPI info object */
export interface OpenAPIInfo {
  title: string;
  version: string;
  description?: string;
  contact?: OpenAPIContact;
  license?: OpenAPILicense;
}
 
/** OpenAPI contact object */
export interface OpenAPIContact {
  name?: string;
  url?: string;
  email?: string;
}
 
/** OpenAPI license object */
export interface OpenAPILicense {
  name: string;
  url?: string;
}
 
/** OpenAPI paths object */
export interface OpenAPIPaths {
  [path: string]: OpenAPIPathItem;
}
 
/** OpenAPI path item */
export interface OpenAPIPathItem {
  summary?: string;
  description?: string;
  get?: OpenAPIOperation;
  post?: OpenAPIOperation;
  put?: OpenAPIOperation;
  delete?: OpenAPIOperation;
  options?: OpenAPIOperation;
  head?: OpenAPIOperation;
  patch?: OpenAPIOperation;
  parameters?: OpenAPIParameter[];
}
 
/** OpenAPI operation */
export interface OpenAPIOperation {
  tags?: string[];
  summary?: string;
  description?: string;
  operationId?: string;
  parameters?: OpenAPIParameter[];
  requestBody?: OpenAPIRequestBody;
  responses: OpenAPIResponses;
  security?: OpenAPISecurityRequirement[];
  deprecated?: boolean;
}
 
/** OpenAPI parameter */
export interface OpenAPIParameter {
  name: string;
  in: 'query' | 'header' | 'path' | 'cookie';
  description?: string;
  required?: boolean;
  deprecated?: boolean;
  schema?: OpenAPISchema;
}
 
/** OpenAPI request body */
export interface OpenAPIRequestBody {
  description?: string;
  content: OpenAPIMediaType;
  required?: boolean;
}
 
/** OpenAPI responses */
export interface OpenAPIResponses {
  [statusCode: string]: OpenAPIResponse;
}
 
/** OpenAPI response */
export interface OpenAPIResponse {
  description: string;
  headers?: Record<string, OpenAPIHeader>;
  content?: OpenAPIMediaType;
}
 
/** OpenAPI header */
export interface OpenAPIHeader {
  description?: string;
  schema?: OpenAPISchema;
}
 
/** OpenAPI media type */
export interface OpenAPIMediaType {
  [mediaType: string]: {
    schema?: OpenAPISchema;
    example?: any;
    examples?: Record<string, OpenAPIExample>;
  };
}
 
/** OpenAPI example */
export interface OpenAPIExample {
  summary?: string;
  description?: string;
  value?: any;
  externalValue?: string;
}
 
/** OpenAPI schema */
export interface OpenAPISchema {
  type?: string;
  format?: string;
  title?: string;
  description?: string;
  default?: any;
  example?: any;
  enum?: any[];
  const?: any;
  minimum?: number;
  maximum?: number;
  exclusiveMinimum?: number;
  exclusiveMaximum?: number;
  minLength?: number;
  maxLength?: number;
  pattern?: string;
  minItems?: number;
  maxItems?: number;
  uniqueItems?: boolean;
  minProperties?: number;
  maxProperties?: number;
  required?: string[];
  properties?: Record<string, OpenAPISchema>;
  additionalProperties?: boolean | OpenAPISchema;
  items?: OpenAPISchema;
  allOf?: OpenAPISchema[];
  oneOf?: OpenAPISchema[];
  anyOf?: OpenAPISchema[];
  not?: OpenAPISchema;
  nullable?: boolean;
  readOnly?: boolean;
  writeOnly?: boolean;
  deprecated?: boolean;
}
 
/** OpenAPI components */
export interface OpenAPIComponents {
  schemas?: Record<string, OpenAPISchema>;
  responses?: Record<string, OpenAPIResponse>;
  parameters?: Record<string, OpenAPIParameter>;
  requestBodies?: Record<string, OpenAPIRequestBody>;
  headers?: Record<string, OpenAPIHeader>;
  securitySchemes?: Record<string, OpenAPISecurityScheme>;
}
 
/** OpenAPI security scheme */
export interface OpenAPISecurityScheme {
  type: 'apiKey' | 'http' | 'oauth2' | 'openIdConnect';
  description?: string;
  name?: string;
  in?: 'query' | 'header' | 'cookie';
  scheme?: string;
  bearerFormat?: string;
}
 
/** OpenAPI security requirement */
export interface OpenAPISecurityRequirement {
  [name: string]: string[];
}
 
/** OpenAPI tag */
export interface OpenAPITag {
  name: string;
  description?: string;
}
 
/** OpenAPI server */
export interface OpenAPIServer {
  url: string;
  description?: string;
  variables?: Record<string, OpenAPIServerVariable>;
}
 
/** OpenAPI server variable */
export interface OpenAPIServerVariable {
  enum?: string[];
  default: string;
  description?: string;
}
 
// ============================================================================
// Main Functions
// ============================================================================
 
/** Create an object-based router */
export function createObjectRouter(routes: RouteObject, config?: RouterConfig): ObjectRouter;
 
/** Error handling HOC */
export function withErrorHandling(options?: ErrorHandlerOptions): (handler: RouteHandler) => RouteHandler;
 
/** Create error handler middleware */
export function createErrorHandler(options?: ErrorHandlerOptions): ErrorMiddleware;
 
/** Validate against schema */
export function validateAgainstSchema(
  schema: ValidationSchema,
  data: any,
  options?: ValidationOptions
): ValidationResult;
 
/** Validate a single field */
export function validateField(
  rule: ValidationRule,
  value: any,
  field: string,
  data?: any
): ValidationError | null;
 
/** Validation middleware */
export function withValidation(schema: ValidationSchema): Middleware;
 
/** Query validation middleware */
export function withQueryValidation(schema: ValidationSchema): Middleware;
 
/** Params validation middleware */
export function withParamsValidation(schema: ValidationSchema): Middleware;
 
/** Authentication middleware */
export function withAuth(config?: AuthConfig): Middleware;
 
/** Role-based authorization middleware */
export function withRole(roles: string | string[]): Middleware;
 
/** Input validation middleware */
export function withInputValidation(schema: ValidationSchema): Middleware;
 
/** Hash password */
export function hashPassword(password: string, saltRounds?: number): Promise<string>;
 
/** Verify password */
export function verifyPassword(password: string, hash: string): Promise<boolean>;
 
/** Generate JWT token */
export function generateToken(payload: any, options?: JwtOptions): string;
 
/** Serialization middleware */
export function withSerialization(config: SerializationConfig): Middleware;
 
/** Serialize for JSON */
export function serializeForJSON(obj: any, options?: SerializationOptions): any;
 
/** Serialize date */
export function serializeDate(date: Date): string;
 
/** Deserialize date */
export function deserializeDate(dateString: string): Date;
 
/** Serialize Map */
export function serializeMap(map: Map<any, any>): any;
 
/** Deserialize Map */
export function deserializeMap(obj: any): Map<any, any>;
 
/** Serialize Set */
export function serializeSet(set: Set<any>): any;
 
/** Deserialize Set */
export function deserializeSet(arr: any[]): Set<any>;
 
// ============================================================================
// Default Export
// ============================================================================
 
declare const coherentApi: {
  createObjectRouter: typeof createObjectRouter;
  ApiError: typeof ApiError;
  ValidationError: typeof ValidationError;
  AuthenticationError: typeof AuthenticationError;
  AuthorizationError: typeof AuthorizationError;
  NotFoundError: typeof NotFoundError;
  ConflictError: typeof ConflictError;
  withErrorHandling: typeof withErrorHandling;
  createErrorHandler: typeof createErrorHandler;
  validateAgainstSchema: typeof validateAgainstSchema;
  validateField: typeof validateField;
  withValidation: typeof withValidation;
  withQueryValidation: typeof withQueryValidation;
  withParamsValidation: typeof withParamsValidation;
  serializeDate: typeof serializeDate;
  deserializeDate: typeof deserializeDate;
  serializeMap: typeof serializeMap;
  deserializeMap: typeof deserializeMap;
  serializeSet: typeof serializeSet;
  deserializeSet: typeof deserializeSet;
  withSerialization: typeof withSerialization;
  serializeForJSON: typeof serializeForJSON;
  withAuth: typeof withAuth;
  withRole: typeof withRole;
  hashPassword: typeof hashPassword;
  verifyPassword: typeof verifyPassword;
  generateToken: typeof generateToken;
  withInputValidation: typeof withInputValidation;
};
 
export default coherentApi;