blaizejs 0.3.4 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/chunk-GP5NAYQS.js +11 -0
  2. package/dist/chunk-GP5NAYQS.js.map +1 -0
  3. package/dist/{chunk-EE2VJ6JY.js → chunk-LI53MJIF.js} +3 -3
  4. package/dist/chunk-LI53MJIF.js.map +1 -0
  5. package/dist/{chunk-HSLLYUVO.js → chunk-LMTJAVHX.js} +3 -3
  6. package/dist/chunk-LMTJAVHX.js.map +1 -0
  7. package/dist/{chunk-TL4GIFTB.js → chunk-N7F6OHDX.js} +3 -3
  8. package/dist/chunk-N7F6OHDX.js.map +1 -0
  9. package/dist/{chunk-VLVWNGUO.js → chunk-ORFAFXHX.js} +3 -3
  10. package/dist/chunk-ORFAFXHX.js.map +1 -0
  11. package/dist/index.cjs +9 -9
  12. package/dist/index.cjs.map +1 -1
  13. package/dist/index.d.cts +654 -139
  14. package/dist/index.d.ts +654 -139
  15. package/dist/index.js +9 -9
  16. package/dist/index.js.map +1 -1
  17. package/dist/{internal-server-error-GWBNT3OO.js → internal-server-error-DAEFNRNG.js} +3 -3
  18. package/dist/{payload-too-large-error-EBM5BNWG.js → payload-too-large-error-YO3MSQJF.js} +3 -3
  19. package/dist/{unsupported-media-type-error-YQ7GCZ32.js → unsupported-media-type-error-GW2UC37Q.js} +3 -3
  20. package/dist/{validation-error-6JDCGV2S.js → validation-error-SJTLEIZZ.js} +3 -3
  21. package/package.json +4 -4
  22. package/dist/chunk-DTDGIBMA.js +0 -11
  23. package/dist/chunk-DTDGIBMA.js.map +0 -1
  24. package/dist/chunk-EE2VJ6JY.js.map +0 -1
  25. package/dist/chunk-HSLLYUVO.js.map +0 -1
  26. package/dist/chunk-TL4GIFTB.js.map +0 -1
  27. package/dist/chunk-VLVWNGUO.js.map +0 -1
  28. /package/dist/{internal-server-error-GWBNT3OO.js.map → internal-server-error-DAEFNRNG.js.map} +0 -0
  29. /package/dist/{payload-too-large-error-EBM5BNWG.js.map → payload-too-large-error-YO3MSQJF.js.map} +0 -0
  30. /package/dist/{unsupported-media-type-error-YQ7GCZ32.js.map → unsupported-media-type-error-GW2UC37Q.js.map} +0 -0
  31. /package/dist/{validation-error-6JDCGV2S.js.map → validation-error-SJTLEIZZ.js.map} +0 -0
@@ -0,0 +1,11 @@
1
+
2
+ /**
3
+ * blaizejs v0.4.0
4
+ * A blazing-fast, TypeScript-first Node.js framework with HTTP/2 support, file-based routing, powerful middleware system, and end-to-end type safety for building modern APIs.
5
+ *
6
+ * Copyright (c) 2025 BlaizeJS Contributors
7
+ * @license MIT
8
+ */
9
+
10
+ var R=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import{AsyncLocalStorage as d}from"node:async_hooks";var a={headerName:"x-correlation-id",generator:c},s={...a},u=new d;function c(){let e=Date.now().toString(36),t=Math.random().toString(36).substr(2,9);return`req_${e}_${t}`}function _(e,t){s={headerName:e||a.headerName,generator:t||a.generator}}function I(){return s.headerName}function m(){return s.generator()}function h(){let e=u.getStore();return e&&e.trim()?e:"unknown"}function O(e,t){return u.run(e,t)}function y(e){let t=s.headerName,n=e[t],i;return Array.isArray(n)?i=n[0]:typeof n=="string"&&(i=n),i&&i.trim()?i:m()}var p=(r=>(r.VALIDATION_ERROR="VALIDATION_ERROR",r.NOT_FOUND="NOT_FOUND",r.UNAUTHORIZED="UNAUTHORIZED",r.FORBIDDEN="FORBIDDEN",r.CONFLICT="CONFLICT",r.RATE_LIMITED="RATE_LIMITED",r.INTERNAL_SERVER_ERROR="INTERNAL_SERVER_ERROR",r.PAYLOAD_TOO_LARGE="PAYLOAD_TOO_LARGE",r.UNSUPPORTED_MEDIA_TYPE="UNSUPPORTED_MEDIA_TYPE",r.UPLOAD_TIMEOUT="UPLOAD_TIMEOUT",r.UNPROCESSABLE_ENTITY="UNPROCESSABLE_ENTITY",r.NETWORK_ERROR="NETWORK_ERROR",r.TIMEOUT_ERROR="TIMEOUT_ERROR",r.PARSE_ERROR="PARSE_ERROR",r.HTTP_ERROR="HTTP_ERROR",r))(p||{}),f=(o=>(o.LOW="low",o.MEDIUM="medium",o.HIGH="high",o.CRITICAL="critical",o))(f||{}),g=class extends Error{type;title;status;correlationId;timestamp;details;constructor(t,n,i,o,l){super(n),this.name=this.constructor.name,this.type=t,this.title=n,this.status=i,this.correlationId=o,this.timestamp=new Date,this.details=l,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){let t={type:this.type,title:this.title,status:this.status,correlationId:this.correlationId,timestamp:this.timestamp.toISOString()};return this.details!==void 0?{...t,details:this.details}:t}toString(){return`${this.name}: ${this.title} [${this.correlationId}]`}};function x(e){return typeof e=="object"&&e!==null&&"type"in e&&"message"in e&&"error"in e&&typeof e.type=="string"&&typeof e.message=="string"}export{R as a,_ as b,I as c,h as d,O as e,y as f,p as g,f as h,g as i,x as j};
11
+ //# sourceMappingURL=chunk-GP5NAYQS.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/tracing/correlation.ts","../../blaize-types/src/errors.ts"],"sourcesContent":["/**\n * Correlation ID system for request tracing across async operations\n *\n * This module provides utilities for generating, storing, and accessing\n * correlation IDs that follow requests through the entire application stack.\n * Uses AsyncLocalStorage for automatic context propagation.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\nimport type { CorrelationConfig } from '@blaize-types/tracing';\n\n/**\n * Default configuration values\n * @internal\n */\nconst DEFAULT_CONFIG: CorrelationConfig = {\n headerName: 'x-correlation-id',\n generator: defaultCorrelationIdGenerator,\n};\n\n/**\n * Current configuration (mutable for server customization)\n * @internal\n */\nlet currentConfig: CorrelationConfig = { ...DEFAULT_CONFIG };\n\n/**\n * AsyncLocalStorage instance for storing correlation IDs\n * Separate from the main context storage to allow independent lifecycle management\n */\nconst correlationStorage = new AsyncLocalStorage<string>();\n\n/**\n * Default correlation ID generator\n *\n * Format: req_[timestamp_base36]_[random_base36]\n * Example: req_k3x2m1_9z8y7w6v\n *\n * @internal\n */\nfunction defaultCorrelationIdGenerator(): string {\n const timestamp = Date.now().toString(36); // Base36 encoded timestamp\n const random = Math.random().toString(36).substr(2, 9); // Base36 random string\n return `req_${timestamp}_${random}`;\n}\n\n/**\n * Sets the correlation configuration (internal use only)\n *\n * This function is called by the server during initialization to configure\n * the correlation ID system. It should not be called directly by application code.\n *\n * @param headerName - The HTTP header name to use for correlation IDs\n * @param generator - Custom correlation ID generator function\n * @internal\n */\nexport function _setCorrelationConfig(headerName?: string, generator?: () => string): void {\n currentConfig = {\n headerName: headerName || DEFAULT_CONFIG.headerName,\n generator: generator || DEFAULT_CONFIG.generator,\n };\n}\n\n/**\n * Gets the configured correlation header name\n *\n * @returns The configured header name (defaults to 'x-correlation-id')\n * @internal\n */\nexport function getCorrelationHeaderName(): string {\n return currentConfig.headerName;\n}\n\n/**\n * Resets the correlation configuration to defaults\n *\n * Primarily used for testing to ensure clean state between tests\n *\n * @internal\n */\nexport function _resetCorrelationConfig(): void {\n currentConfig = { ...DEFAULT_CONFIG };\n}\n\n/**\n * Generates a new unique correlation ID\n *\n * Uses the configured generator function, which defaults to the format:\n * req_[timestamp_base36]_[random_base36]\n * Example: req_k3x2m1_9z8y7w6v\n *\n * @returns A unique correlation ID string\n */\nexport function generateCorrelationId(): string {\n return currentConfig.generator();\n}\n\n/**\n * Gets the current correlation ID from AsyncLocalStorage\n *\n * @returns The current correlation ID, or 'unknown' if none is set\n */\nexport function getCorrelationId(): string {\n const stored = correlationStorage.getStore();\n return stored && stored.trim() ? stored : 'unknown';\n}\n\n/**\n * Sets the correlation ID in the current AsyncLocalStorage context\n *\n * This will affect the current execution context and any subsequent\n * async operations that inherit from it.\n *\n * @param correlationId - The correlation ID to set\n */\nexport function setCorrelationId(correlationId: string): void {\n correlationStorage.enterWith(correlationId);\n}\n\n/**\n * Runs a function with a specific correlation ID\n *\n * Creates a new AsyncLocalStorage context with the provided correlation ID.\n * The correlation ID will be available to the function and any async operations\n * it spawns, but will not affect the parent context.\n *\n * @param correlationId - The correlation ID to use for this context\n * @param fn - The function to run with the correlation ID\n * @returns The result of the function\n *\n * @example\n * ```typescript\n * const result = await withCorrelationId('req_123', async () => {\n * console.log(getCurrentCorrelationId()); // 'req_123'\n * return await processRequest();\n * });\n * ```\n */\nexport function withCorrelationId<T>(\n correlationId: string,\n fn: () => T | Promise<T>\n): T | Promise<T> {\n return correlationStorage.run(correlationId, fn);\n}\n\n/**\n * Extracts correlation ID from headers or generates a new one\n *\n * Looks for the configured correlation header (default: 'x-correlation-id').\n * If not found, empty, or undefined, generates a new correlation ID.\n * Supports both string and string[] header values for compatibility.\n *\n * @param headers - HTTP headers object\n * @returns A correlation ID (either from headers or newly generated)\n *\n * @example\n * ```typescript\n * // From incoming request headers\n * const correlationId = getOrGenerateCorrelationId(request.headers);\n *\n * // Use in request processing\n * await withCorrelationId(correlationId, async () => {\n * // Process request with correlation tracking\n * });\n * ```\n */\nexport function createCorrelationIdFromHeaders(\n headers: Record<string, string | string[] | undefined>\n): string {\n const headerName = currentConfig.headerName;\n const headerValue = headers[headerName];\n\n // Handle both string and string[] header values\n let correlationId: string | undefined;\n\n if (Array.isArray(headerValue)) {\n // Take the first value if it's an array\n correlationId = headerValue[0];\n } else if (typeof headerValue === 'string') {\n correlationId = headerValue;\n }\n\n // Use header value if it exists and is not empty\n if (correlationId && correlationId.trim()) {\n return correlationId;\n }\n\n // Generate new correlation ID if header is missing or empty\n return generateCorrelationId();\n}\n\n// Note: Correlation middleware is not needed since we're integrating\n// at the request handler level (see Task T6). The request handler\n// will directly use getOrGenerateCorrelationId() and withCorrelationId()\n// to establish correlation context for the entire request lifecycle.\n\n/**\n * Type-safe wrapper for functions that need correlation ID context\n *\n * Ensures that a function always has access to a correlation ID,\n * either from the current context or by generating a new one.\n *\n * @param fn - Function that requires correlation ID context\n * @returns Wrapped function that guarantees correlation ID availability\n */\nexport function withEnsuredCorrelation<T extends any[], R>(\n fn: (...args: T) => R | Promise<R>\n): (...args: T) => R | Promise<R> {\n return (...args: T): R | Promise<R> => {\n const currentCorrelationId = getCorrelationId();\n\n // If we already have a correlation ID, just run the function\n if (currentCorrelationId !== 'unknown') {\n return fn(...args);\n }\n\n // Generate new correlation ID and run function in that context\n const newCorrelationId = generateCorrelationId();\n return withCorrelationId(newCorrelationId, () => fn(...args));\n };\n}\n\n/**\n * Debugging utility to get correlation storage information\n *\n * @internal This is for debugging purposes only\n */\nexport function _getCorrelationStorageInfo() {\n return {\n hasActiveStore: correlationStorage.getStore() !== undefined,\n currentCorrelationId: correlationStorage.getStore() ?? null,\n config: {\n headerName: currentConfig.headerName,\n generatorType:\n currentConfig.generator === defaultCorrelationIdGenerator ? 'default' : 'custom',\n },\n };\n}\n","/**\n * Error type definitions and interfaces for the BlaizeJS framework\n *\n * This module contains all the type definitions used for error handling\n * across the BlaizeJS framework, including server-side errors, client-side\n * errors, and HTTP response formats.\n */\n\n/**\n * Structure of error responses sent over HTTP\n *\n * This interface defines the JSON format used for all error responses\n * from BlaizeJS servers. It matches the structure returned by BlaizeError.toJSON()\n *\n * @example\n * ```json\n * {\n * \"type\": \"VALIDATION_ERROR\",\n * \"title\": \"Request validation failed\",\n * \"status\": 400,\n * \"correlationId\": \"req_abc123\",\n * \"timestamp\": \"2024-01-15T10:30:00.000Z\",\n * \"details\": {\n * \"fields\": [\"email\", \"password\"]\n * }\n * }\n * ```\n */\nexport interface BlaizeErrorResponse {\n /** Error type from the ErrorType enum */\n type: ErrorType;\n\n /** Human-readable error message */\n title: string;\n\n /** HTTP status code */\n status: number;\n\n /** Correlation ID for request tracing */\n correlationId: string;\n\n /** ISO timestamp when error occurred */\n timestamp: string;\n\n /** Optional error-specific details */\n details?: unknown;\n}\n\n/**\n * Context information for network-related errors\n *\n * Used by client-side error classes to provide additional context\n * about network failures, timeouts, and connection issues.\n */\nexport interface NetworkErrorContext {\n /** The URL that failed */\n url: string;\n\n /** HTTP method being attempted */\n method: string;\n\n /** Correlation ID for tracing */\n correlationId: string;\n\n /** Timeout value if applicable */\n timeout?: number;\n\n /** The original error that caused the network failure */\n originalError: Error;\n\n /** Additional network-specific details */\n networkDetails?: {\n /** Whether this was a connection timeout */\n isTimeout?: boolean;\n\n /** Whether this was a DNS resolution failure */\n isDnsFailure?: boolean;\n\n /** Whether this was a connection refused error */\n isConnectionRefused?: boolean;\n\n /** HTTP status code if received before failure */\n statusCode?: number;\n };\n}\n\n/**\n * Context information for request timeout errors\n *\n * Specialized context for timeout-specific errors with timing information.\n */\nexport interface TimeoutErrorContext {\n /** The URL that timed out */\n url: string;\n\n /** HTTP method being attempted */\n method: string;\n\n /** Correlation ID for tracing */\n correlationId: string;\n\n /** Configured timeout value in milliseconds */\n timeoutMs: number;\n\n /** Actual duration before timeout in milliseconds */\n elapsedMs: number;\n\n /** Type of timeout (request, connection, etc.) */\n timeoutType: 'request' | 'connection' | 'response' | 'idle';\n}\n\n/**\n * Context information for response parsing errors\n *\n * Used when the client receives a response but cannot parse it properly.\n */\nexport interface ParseErrorContext {\n /** The URL that returned unparseable content */\n url: string;\n\n /** HTTP method used */\n method: string;\n\n /** Correlation ID for tracing */\n correlationId: string;\n\n /** HTTP status code received */\n statusCode: number;\n\n /** Content-Type header if available */\n contentType?: string;\n\n /** Expected response format */\n expectedFormat: 'json' | 'text' | 'binary';\n\n /** Sample of the actual response content (truncated for safety) */\n responseSample?: string;\n\n /** The original parsing error */\n originalError: Error;\n}\n\n/**\n * Validation error field details\n *\n * Structure for field-level validation errors with multiple error messages\n * per field.\n */\nexport interface ValidationFieldError {\n /** Field name or path (e.g., \"email\", \"user.profile.name\") */\n field: string;\n\n /** Array of error messages for this field */\n messages: string[];\n\n /** The invalid value that caused the error */\n rejectedValue?: unknown;\n\n /** Expected type or format */\n expectedType?: string;\n}\n\n/**\n * Validation error details structure\n *\n * Used by ValidationError to provide structured information about\n * what fields failed validation and why.\n */\nexport interface ValidationErrorDetails {\n /** Array of field-level errors */\n fields: ValidationFieldError[];\n\n /** Total number of validation errors */\n errorCount: number;\n\n /** The section that failed validation */\n section: 'params' | 'query' | 'body' | 'response';\n\n /** Schema name if available */\n schemaName?: string;\n}\n\n/**\n * All available error types in the BlaizeJS framework\n *\n * This enum provides both compile-time type safety and runtime values\n * for error type identification across server and client packages.\n *\n * @example Type-safe error handling:\n * ```typescript\n * function handleError(errorType: ErrorType) {\n * switch (errorType) {\n * case ErrorType.VALIDATION_ERROR:\n * // Handle validation error\n * break;\n * case ErrorType.NOT_FOUND:\n * // Handle not found error\n * break;\n * // TypeScript ensures all cases are covered\n * }\n * }\n * ```\n */\nexport enum ErrorType {\n // Server-side business logic errors\n /** Request validation failed (400) */\n VALIDATION_ERROR = 'VALIDATION_ERROR',\n\n /** Resource not found (404) */\n NOT_FOUND = 'NOT_FOUND',\n\n /** Authentication required (401) */\n UNAUTHORIZED = 'UNAUTHORIZED',\n\n /** Access forbidden (403) */\n FORBIDDEN = 'FORBIDDEN',\n\n /** Resource conflict (409) */\n CONFLICT = 'CONFLICT',\n\n /** Rate limit exceeded (429) */\n RATE_LIMITED = 'RATE_LIMITED',\n\n /** Internal server error (500) */\n INTERNAL_SERVER_ERROR = 'INTERNAL_SERVER_ERROR',\n\n /** File/Request Too Large (413) */\n PAYLOAD_TOO_LARGE = 'PAYLOAD_TOO_LARGE',\n\n /** Wrong Content Type (415) */\n UNSUPPORTED_MEDIA_TYPE = 'UNSUPPORTED_MEDIA_TYPE',\n\n /** Upload Timeout (408) */\n UPLOAD_TIMEOUT = 'UPLOAD_TIMEOUT',\n\n /** Valid Format Invalid Semantics (422) */\n UNPROCESSABLE_ENTITY = 'UNPROCESSABLE_ENTITY',\n\n // Client-side errors\n /** Network connectivity failure (0) */\n NETWORK_ERROR = 'NETWORK_ERROR',\n\n /** Request or response timeout (0) */\n TIMEOUT_ERROR = 'TIMEOUT_ERROR',\n\n /** Response parsing failure (0) */\n PARSE_ERROR = 'PARSE_ERROR',\n\n /** Generic HTTP error (varies) */\n HTTP_ERROR = 'HTTP_ERROR',\n}\n\n/**\n * Error severity levels for logging and monitoring\n *\n * Provides a way to categorize errors by their impact and urgency.\n */\nexport enum ErrorSeverity {\n /** Low impact, often user errors */\n LOW = 'low',\n\n /** Medium impact, application errors */\n MEDIUM = 'medium',\n\n /** High impact, system errors */\n HIGH = 'high',\n\n /** Critical impact, service disruption */\n CRITICAL = 'critical',\n}\n\n/**\n * Abstract base class for all BlaizeJS errors\n *\n * This class provides the foundation for all error types in the BlaizeJS framework.\n * It extends JavaScript's built-in Error class and adds framework-specific properties\n * for consistent error handling across server and client.\n *\n * @example\n * ```typescript\n * import { ErrorType } from './types';\n *\n * class NotFoundError extends BlaizeError<{ resourceId: string }> {\n * constructor(message = 'Resource not found', details?: { resourceId: string }) {\n * super(ErrorType.NOT_FOUND, message, 404, getCurrentCorrelationId(), details);\n * }\n * }\n * ```\n *\n * @template TDetails - Type for error-specific details object\n */\nexport abstract class BlaizeError<TDetails = unknown> extends Error {\n /**\n * Error type identifier from the ErrorType enum\n * Used for programmatic error handling and client-side error routing\n */\n readonly type: ErrorType;\n\n /**\n * Human-readable error title/message\n * Should be descriptive enough for debugging but safe for end users\n */\n readonly title: string;\n\n /**\n * HTTP status code associated with this error\n * Used by the error boundary to set appropriate response status\n */\n readonly status: number;\n\n /**\n * Correlation ID for request tracing\n * Links this error to the specific request that generated it\n */\n readonly correlationId: string;\n\n /**\n * Timestamp when the error occurred\n * Useful for debugging and log correlation\n */\n readonly timestamp: Date;\n\n /**\n * Additional error-specific details\n * Type-safe error context that varies by error type\n */\n readonly details?: TDetails | undefined;\n\n /**\n * Creates a new BlaizeError instance\n *\n * @param type - Error type from the ErrorType enum\n * @param title - Human-readable error message\n * @param status - HTTP status code\n * @param correlationId - Request correlation ID for tracing\n * @param details - Optional error-specific details\n */\n protected constructor(\n type: ErrorType,\n title: string,\n status: number,\n correlationId: string,\n details?: TDetails | undefined\n ) {\n super(title);\n\n // Set the error name to the class name for better stack traces\n this.name = this.constructor.name;\n\n // Framework-specific properties\n this.type = type;\n this.title = title;\n this.status = status;\n this.correlationId = correlationId;\n this.timestamp = new Date();\n this.details = details;\n\n // Maintain proper prototype chain for instanceof checks\n Object.setPrototypeOf(this, new.target.prototype);\n\n // Capture stack trace if available (V8 feature)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n /**\n * Serializes the error to a plain object suitable for HTTP responses\n *\n * @returns Object representation of the error\n */\n toJSON() {\n const base = {\n type: this.type,\n title: this.title,\n status: this.status,\n correlationId: this.correlationId,\n timestamp: this.timestamp.toISOString(),\n };\n\n // Only include details if they are not undefined\n if (this.details !== undefined) {\n return { ...base, details: this.details };\n }\n\n return base;\n }\n\n /**\n * Returns a string representation of the error\n * Includes correlation ID for easier debugging\n */\n toString(): string {\n return `${this.name}: ${this.title} [${this.correlationId}]`;\n }\n}\n\n/**\n * Interface for payload too large error details\n */\nexport interface PayloadTooLargeErrorDetails {\n fileCount?: number;\n maxFiles?: number;\n filename?: string;\n field?: string;\n contentType?: string;\n currentSize?: number;\n maxSize?: number;\n}\n\n/**\n * Interface for unsupported media type error details\n */\nexport interface UnsupportedMediaTypeErrorDetails {\n receivedMimeType?: string;\n allowedMimeTypes?: string[];\n filename?: string;\n}\n\n/**\n * Interface for authentication error details\n */\nexport interface UnauthorizedErrorDetails {\n /** Reason for authentication failure */\n reason?:\n | 'missing_token'\n | 'invalid_token'\n | 'expired_token'\n | 'malformed_token'\n | 'insufficient_scope'\n | string;\n\n /** Authentication scheme (Bearer, Basic, etc.) */\n authScheme?: string;\n\n /** Authentication realm */\n realm?: string;\n\n /** Detailed error description */\n error_description?: string;\n\n /** Required scopes or permissions */\n requiredScopes?: string[];\n\n /** Login URL for interactive authentication */\n loginUrl?: string;\n\n /** Additional context */\n [key: string]: unknown;\n}\n\n/**\n * Interface for authorization/permission error details\n */\nexport interface ForbiddenErrorDetails {\n /** Required permission or role */\n requiredPermission?: string;\n\n /** User's current permissions */\n userPermissions?: string[];\n\n /** Resource being accessed */\n resource?: string;\n\n /** Action being attempted */\n action?: string;\n\n /** Reason for access denial */\n reason?: 'insufficient_permissions' | 'account_suspended' | 'resource_locked' | string;\n\n /** Additional context */\n [key: string]: unknown;\n}\n\n/**\n * Interface for resource conflict error details\n */\nexport interface ConflictErrorDetails {\n /** Type of conflict */\n conflictType?:\n | 'duplicate_key'\n | 'version_mismatch'\n | 'concurrent_modification'\n | 'business_rule'\n | string;\n\n /** Field that caused the conflict */\n field?: string;\n\n /** Existing value that conflicts */\n existingValue?: unknown;\n\n /** Provided value that conflicts */\n providedValue?: unknown;\n\n /** Resource that has the conflicting value */\n conflictingResource?: string;\n\n /** Current version/etag of the resource */\n currentVersion?: string;\n\n /** Expected version/etag */\n expectedVersion?: string;\n\n /** Suggested resolution */\n resolution?: string;\n\n /** Additional context */\n [key: string]: unknown;\n}\n\n/**\n * Interface for rate limiting error details\n */\nexport interface RateLimitErrorDetails {\n /** Maximum requests allowed in the time window */\n limit?: number;\n\n /** Remaining requests in current window */\n remaining?: number;\n\n /** When the rate limit resets */\n resetTime?: Date;\n\n /** Seconds until the rate limit resets */\n retryAfter?: number;\n\n /** Time window for the rate limit */\n window?: string;\n\n /** Identifier used for rate limiting (IP, user ID, etc.) */\n identifier?: string;\n\n /** Type of rate limit hit */\n limitType?: 'global' | 'per_user' | 'per_ip' | 'per_endpoint' | string;\n\n /** Additional context */\n [key: string]: unknown;\n}\n\n/**\n * Interface for internal server error details\n */\nexport interface InternalServerErrorDetails {\n /** Original error message (for debugging) */\n originalError?: string;\n\n /** Stack trace (for debugging) */\n stackTrace?: string;\n\n /** Component where the error occurred */\n component?: string;\n\n /** Operation being performed */\n operation?: string;\n\n /** Internal error code */\n internalErrorCode?: string;\n\n /** When the error occurred */\n timestamp?: Date;\n\n /** Whether this error should be retryable */\n retryable?: boolean;\n\n /** Additional debugging context */\n [key: string]: unknown;\n}\n\n/**\n * Interface for NotFound error details\n * Provides context about the missing resource\n */\nexport interface NotFoundErrorDetails {\n /** Type of resource that was not found */\n resourceType?: string;\n\n /** ID or identifier of the resource */\n resourceId?: string;\n\n /** Collection or table where the resource was searched */\n collection?: string;\n\n /** Search criteria that was used */\n query?: Record<string, unknown>;\n\n /** Search criteria that was used (for backward compatibility) */\n searchCriteria?: Record<string, unknown>;\n\n /** The path that was attempted */\n path?: string;\n\n /** HTTP method used (for API endpoints) */\n method?: string;\n\n /** The path that was attempted (for backward compatibility) */\n attemptedPath?: string;\n\n /** Parent resource information for nested resources */\n parentResource?: {\n type: string;\n id: string;\n };\n\n /** Helpful suggestion for the user */\n suggestion?: string;\n\n /** Additional context */\n [key: string]: unknown;\n}\n\n// TODO: This can potentiall be removed\n/**\n * Interface for body parsing errors stored in context state\n */\nexport interface BodyParseError {\n /**\n * Type of parsing error that occurred\n */\n readonly type:\n | 'json_parse_error'\n | 'form_parse_error'\n | 'multipart_parse_error'\n | 'body_read_error';\n\n /**\n * Human-readable error message\n */\n readonly message: string;\n\n /**\n * Original error object or details\n */\n readonly error: unknown;\n}\n\n/**\n * Type guard to check if an object is a BodyParseError\n */\nexport function isBodyParseError(error: unknown): error is BodyParseError {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'type' in error &&\n 'message' in error &&\n 'error' in error &&\n typeof (error as any).type === 'string' &&\n typeof (error as any).message === 'string'\n );\n}\n\n/**\n * Context information for error transformation\n */\nexport interface ErrorTransformContext {\n url: string;\n method: string;\n correlationId: string;\n timeoutMs?: number;\n elapsedMs?: number;\n statusCode?: number;\n contentType?: string;\n responseSample?: string;\n [key: string]: unknown;\n}\n"],"mappings":";;;;;;;;;yPAQA,OAAS,qBAAAA,MAAyB,mBAQlC,IAAMC,EAAoC,CACxC,WAAY,mBACZ,UAAWC,CACb,EAMIC,EAAmC,CAAE,GAAGF,CAAe,EAMrDG,EAAqB,IAAIJ,EAU/B,SAASE,GAAwC,CAC/C,IAAMG,EAAY,KAAK,IAAI,EAAE,SAAS,EAAE,EAClCC,EAAS,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,OAAO,EAAG,CAAC,EACrD,MAAO,OAAOD,CAAS,IAAIC,CAAM,EACnC,CAYO,SAASC,EAAsBC,EAAqBC,EAAgC,CACzFN,EAAgB,CACd,WAAYK,GAAcP,EAAe,WACzC,UAAWQ,GAAaR,EAAe,SACzC,CACF,CAQO,SAASS,GAAmC,CACjD,OAAOP,EAAc,UACvB,CAsBO,SAASQ,GAAgC,CAC9C,OAAOC,EAAc,UAAU,CACjC,CAOO,SAASC,GAA2B,CACzC,IAAMC,EAASC,EAAmB,SAAS,EAC3C,OAAOD,GAAUA,EAAO,KAAK,EAAIA,EAAS,SAC5C,CAiCO,SAASE,EACdC,EACAC,EACgB,CAChB,OAAOC,EAAmB,IAAIF,EAAeC,CAAE,CACjD,CAuBO,SAASE,EACdC,EACQ,CACR,IAAMC,EAAaC,EAAc,WAC3BC,EAAcH,EAAQC,CAAU,EAGlCL,EAUJ,OARI,MAAM,QAAQO,CAAW,EAE3BP,EAAgBO,EAAY,CAAC,EACpB,OAAOA,GAAgB,WAChCP,EAAgBO,GAIdP,GAAiBA,EAAc,KAAK,EAC/BA,EAIFQ,EAAsB,CAC/B,CCaO,IAAKC,OAGVA,EAAA,iBAAmB,mBAGnBA,EAAA,UAAY,YAGZA,EAAA,aAAe,eAGfA,EAAA,UAAY,YAGZA,EAAA,SAAW,WAGXA,EAAA,aAAe,eAGfA,EAAA,sBAAwB,wBAGxBA,EAAA,kBAAoB,oBAGpBA,EAAA,uBAAyB,yBAGzBA,EAAA,eAAiB,iBAGjBA,EAAA,qBAAuB,uBAIvBA,EAAA,cAAgB,gBAGhBA,EAAA,cAAgB,gBAGhBA,EAAA,YAAc,cAGdA,EAAA,WAAa,aA9CHA,OAAA,IAsDAC,OAEVA,EAAA,IAAM,MAGNA,EAAA,OAAS,SAGTA,EAAA,KAAO,OAGPA,EAAA,SAAW,WAXDA,OAAA,IAkCUC,EAAf,cAAuD,KAAM,CAKzD,KAMA,MAMA,OAMA,cAMA,UAMA,QAWC,YACRC,EACAC,EACAC,EACAC,EACAC,EACA,CACA,MAAMH,CAAK,EAGX,KAAK,KAAO,KAAK,YAAY,KAG7B,KAAK,KAAOD,EACZ,KAAK,MAAQC,EACb,KAAK,OAASC,EACd,KAAK,cAAgBC,EACrB,KAAK,UAAY,IAAI,KACrB,KAAK,QAAUC,EAGf,OAAO,eAAe,KAAM,WAAW,SAAS,EAG5C,MAAM,mBACR,MAAM,kBAAkB,KAAM,KAAK,WAAW,CAElD,CAOA,QAAS,CACP,IAAMC,EAAO,CACX,KAAM,KAAK,KACX,MAAO,KAAK,MACZ,OAAQ,KAAK,OACb,cAAe,KAAK,cACpB,UAAW,KAAK,UAAU,YAAY,CACxC,EAGA,OAAI,KAAK,UAAY,OACZ,CAAE,GAAGA,EAAM,QAAS,KAAK,OAAQ,EAGnCA,CACT,CAMA,UAAmB,CACjB,MAAO,GAAG,KAAK,IAAI,KAAK,KAAK,KAAK,KAAK,KAAK,aAAa,GAC3D,CACF,EAoPO,SAASC,EAAiBC,EAAyC,CACxE,OACE,OAAOA,GAAU,UACjBA,IAAU,MACV,SAAUA,GACV,YAAaA,GACb,UAAWA,GACX,OAAQA,EAAc,MAAS,UAC/B,OAAQA,EAAc,SAAY,QAEtC","names":["AsyncLocalStorage","DEFAULT_CONFIG","defaultCorrelationIdGenerator","currentConfig","correlationStorage","timestamp","random","_setCorrelationConfig","headerName","generator","getCorrelationHeaderName","generateCorrelationId","currentConfig","getCorrelationId","stored","correlationStorage","withCorrelationId","correlationId","fn","correlationStorage","createCorrelationIdFromHeaders","headers","headerName","currentConfig","headerValue","generateCorrelationId","ErrorType","ErrorSeverity","BlaizeError","type","title","status","correlationId","details","base","isBodyParseError","error"]}
@@ -1,11 +1,11 @@
1
1
 
2
2
  /**
3
- * blaizejs v0.3.4
3
+ * blaizejs v0.4.0
4
4
  * A blazing-fast, TypeScript-first Node.js framework with HTTP/2 support, file-based routing, powerful middleware system, and end-to-end type safety for building modern APIs.
5
5
  *
6
6
  * Copyright (c) 2025 BlaizeJS Contributors
7
7
  * @license MIT
8
8
  */
9
9
 
10
- import{d as r,g as o}from"./chunk-DTDGIBMA.js";var e=class extends r{constructor(t,a,i){super("PAYLOAD_TOO_LARGE",t,413,i??o(),a)}};export{e as a};
11
- //# sourceMappingURL=chunk-EE2VJ6JY.js.map
10
+ import{d as r,i as o}from"./chunk-GP5NAYQS.js";var e=class extends o{constructor(t,a,i){super("PAYLOAD_TOO_LARGE",t,413,i??r(),a)}};export{e as a};
11
+ //# sourceMappingURL=chunk-LI53MJIF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors/payload-too-large-error.ts"],"sourcesContent":["import { BlaizeError, ErrorType } from '../../../blaize-types/src/errors';\nimport { getCorrelationId } from '../tracing/correlation';\n\nimport type { PayloadTooLargeErrorDetails } from '@blaize-types/errors';\n\nexport class PayloadTooLargeError extends BlaizeError<PayloadTooLargeErrorDetails> {\n constructor(\n title: string,\n details?: PayloadTooLargeErrorDetails | undefined,\n correlationId?: string\n ) {\n super(\n ErrorType.PAYLOAD_TOO_LARGE,\n title,\n 413,\n correlationId ?? getCorrelationId(),\n details\n );\n }\n}\n"],"mappings":";;;;;;;;;+CAKO,IAAMA,EAAN,cAAmCC,CAAyC,CACjF,YACEC,EACAC,EACAC,EACA,CACA,0BAEEF,EACA,IACAE,GAAiBC,EAAiB,EAClCF,CACF,CACF,CACF","names":["PayloadTooLargeError","BlaizeError","title","details","correlationId","getCorrelationId"]}
@@ -1,11 +1,11 @@
1
1
 
2
2
  /**
3
- * blaizejs v0.3.4
3
+ * blaizejs v0.4.0
4
4
  * A blazing-fast, TypeScript-first Node.js framework with HTTP/2 support, file-based routing, powerful middleware system, and end-to-end type safety for building modern APIs.
5
5
  *
6
6
  * Copyright (c) 2025 BlaizeJS Contributors
7
7
  * @license MIT
8
8
  */
9
9
 
10
- import{d as r,g as e}from"./chunk-DTDGIBMA.js";var t=class extends r{constructor(n,o=void 0,i=void 0){super("INTERNAL_SERVER_ERROR",n,500,i??e(),o)}};export{t as a};
11
- //# sourceMappingURL=chunk-HSLLYUVO.js.map
10
+ import{d as r,i as e}from"./chunk-GP5NAYQS.js";var t=class extends e{constructor(n,o=void 0,i=void 0){super("INTERNAL_SERVER_ERROR",n,500,i??r(),o)}};export{t as a};
11
+ //# sourceMappingURL=chunk-LMTJAVHX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors/internal-server-error.ts"],"sourcesContent":["/**\n * InternalServerError class for server-side errors\n *\n * This error is thrown for unexpected server-side errors that are not\n * the client's fault. It provides debugging context while protecting\n * sensitive information in production.\n */\n\nimport { BlaizeError, ErrorType } from '@blaize-types/errors';\n\nimport { getCorrelationId } from '../tracing/correlation';\n\nimport type { InternalServerErrorDetails } from '@blaize-types/errors';\n/**\n * Error thrown for internal server errors\n *\n * Automatically sets HTTP status to 500 and provides debugging context.\n * Note: In production, sensitive details should be filtered by error boundary.\n *\n * @example Basic usage:\n * ```typescript\n * throw new InternalServerError('Something went wrong');\n * ```\n *\n * @example With debugging details:\n * ```typescript\n * throw new InternalServerError('Database error', {\n * originalError: error.message,\n * component: 'user-service',\n * operation: 'createUser',\n * retryable: true\n * });\n * ```\n *\n * @example Wrapping an existing error:\n * ```typescript\n * try {\n * await database.connect();\n * } catch (error) {\n * throw new InternalServerError('Database connection failed', {\n * originalError: error.message,\n * stackTrace: error.stack,\n * component: 'database',\n * retryable: true\n * });\n * }\n * ```\n */\nexport class InternalServerError extends BlaizeError<InternalServerErrorDetails> {\n /**\n * Creates a new InternalServerError instance\n *\n * @param title - Human-readable error message\n * @param details - Optional debugging context\n * @param correlationId - Optional correlation ID (uses current context if not provided)\n */\n constructor(\n title: string,\n details: InternalServerErrorDetails | undefined = undefined,\n correlationId: string | undefined = undefined\n ) {\n super(\n ErrorType.INTERNAL_SERVER_ERROR,\n title,\n 500, // HTTP 500 Internal Server Error\n correlationId ?? getCorrelationId(),\n details\n );\n }\n}\n"],"mappings":";;;;;;;;;+CAgDO,IAAMA,EAAN,cAAkCC,CAAwC,CAQ/E,YACEC,EACAC,EAAkD,OAClDC,EAAoC,OACpC,CACA,8BAEEF,EACA,IACAE,GAAiBC,EAAiB,EAClCF,CACF,CACF,CACF","names":["InternalServerError","BlaizeError","title","details","correlationId","getCorrelationId"]}
@@ -1,11 +1,11 @@
1
1
 
2
2
  /**
3
- * blaizejs v0.3.4
3
+ * blaizejs v0.4.0
4
4
  * A blazing-fast, TypeScript-first Node.js framework with HTTP/2 support, file-based routing, powerful middleware system, and end-to-end type safety for building modern APIs.
5
5
  *
6
6
  * Copyright (c) 2025 BlaizeJS Contributors
7
7
  * @license MIT
8
8
  */
9
9
 
10
- import{d as r,g as e}from"./chunk-DTDGIBMA.js";var i=class extends r{constructor(t,o=void 0,n=void 0){super("VALIDATION_ERROR",t,400,n??e(),o)}};export{i as a};
11
- //# sourceMappingURL=chunk-TL4GIFTB.js.map
10
+ import{d as r,i as e}from"./chunk-GP5NAYQS.js";var i=class extends e{constructor(o,t=void 0,n=void 0){super("VALIDATION_ERROR",o,400,n??r(),t)}};export{i as a};
11
+ //# sourceMappingURL=chunk-N7F6OHDX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors/validation-error.ts"],"sourcesContent":["/**\n * ValidationError class for request validation failures\n *\n * This error is thrown when request validation fails (params, query, body, or response).\n * It provides structured information about which fields failed validation and why.\n */\n\nimport { BlaizeError, ErrorType } from '@blaize-types/errors';\n\nimport { getCorrelationId } from '../tracing/correlation';\n\nimport type { ValidationErrorDetails } from '@blaize-types/errors';\n\n/**\n * Error thrown when request validation fails\n *\n * Automatically sets HTTP status to 400 and provides structured\n * validation error information for better client debugging.\n *\n * @example Basic usage:\n * ```typescript\n * throw new ValidationError('Email is required');\n * ```\n *\n * @example With detailed field information:\n * ```typescript\n * throw new ValidationError('Validation failed', {\n * fields: [\n * {\n * field: 'email',\n * messages: ['Email is required', 'Email must be valid'],\n * rejectedValue: '',\n * expectedType: 'string'\n * }\n * ],\n * errorCount: 1,\n * section: 'body'\n * });\n * ```\n */\nexport class ValidationError extends BlaizeError<ValidationErrorDetails> {\n /**\n * Creates a new ValidationError instance\n *\n * @param title - Human-readable error message\n * @param details - Optional structured validation details\n * @param correlationId - Optional correlation ID (uses current context if not provided)\n */\n constructor(\n title: string,\n details: ValidationErrorDetails | undefined = undefined,\n correlationId: string | undefined = undefined\n ) {\n super(\n ErrorType.VALIDATION_ERROR,\n title,\n 400, // HTTP 400 Bad Request\n correlationId ?? getCorrelationId(),\n details\n );\n }\n}\n"],"mappings":";;;;;;;;;+CAwCO,IAAMA,EAAN,cAA8BC,CAAoC,CAQvE,YACEC,EACAC,EAA8C,OAC9CC,EAAoC,OACpC,CACA,yBAEEF,EACA,IACAE,GAAiBC,EAAiB,EAClCF,CACF,CACF,CACF","names":["ValidationError","BlaizeError","title","details","correlationId","getCorrelationId"]}
@@ -1,11 +1,11 @@
1
1
 
2
2
  /**
3
- * blaizejs v0.3.4
3
+ * blaizejs v0.4.0
4
4
  * A blazing-fast, TypeScript-first Node.js framework with HTTP/2 support, file-based routing, powerful middleware system, and end-to-end type safety for building modern APIs.
5
5
  *
6
6
  * Copyright (c) 2025 BlaizeJS Contributors
7
7
  * @license MIT
8
8
  */
9
9
 
10
- import{d as r,g as o}from"./chunk-DTDGIBMA.js";var t=class extends r{constructor(n,e,s){super("UNSUPPORTED_MEDIA_TYPE",n,415,s??o(),e)}};export{t as a};
11
- //# sourceMappingURL=chunk-VLVWNGUO.js.map
10
+ import{d as r,i as o}from"./chunk-GP5NAYQS.js";var t=class extends o{constructor(n,s,e){super("UNSUPPORTED_MEDIA_TYPE",n,415,e??r(),s)}};export{t as a};
11
+ //# sourceMappingURL=chunk-ORFAFXHX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors/unsupported-media-type-error.ts"],"sourcesContent":["import { BlaizeError, ErrorType } from '../../../blaize-types/src/errors';\nimport { getCorrelationId } from '../tracing/correlation';\n\nexport class UnsupportedMediaTypeError extends BlaizeError {\n constructor(title: string, details?: unknown, correlationId?: string) {\n super(\n ErrorType.UNSUPPORTED_MEDIA_TYPE,\n title,\n 415,\n correlationId ?? getCorrelationId(),\n details\n );\n }\n}\n"],"mappings":";;;;;;;;;+CAGO,IAAMA,EAAN,cAAwCC,CAAY,CACzD,YAAYC,EAAeC,EAAmBC,EAAwB,CACpE,+BAEEF,EACA,IACAE,GAAiBC,EAAiB,EAClCF,CACF,CACF,CACF","names":["UnsupportedMediaTypeError","BlaizeError","title","details","correlationId","getCorrelationId"]}
package/dist/index.cjs CHANGED
@@ -1,18 +1,18 @@
1
1
 
2
2
  /**
3
- * blaizejs v0.3.4
3
+ * blaizejs v0.4.0
4
4
  * A blazing-fast, TypeScript-first Node.js framework with HTTP/2 support, file-based routing, powerful middleware system, and end-to-end type safety for building modern APIs.
5
5
  *
6
6
  * Copyright (c) 2025 BlaizeJS Contributors
7
7
  * @license MIT
8
8
  */
9
9
 
10
- "use strict";var lr=Object.create;var te=Object.defineProperty;var cr=Object.getOwnPropertyDescriptor;var dr=Object.getOwnPropertyNames;var pr=Object.getPrototypeOf,fr=Object.prototype.hasOwnProperty;var q=(e,t)=>()=>(e&&(t=e(e=0)),t);var Q=(e,t)=>{for(var r in t)te(e,r,{get:t[r],enumerable:!0})},Ye=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of dr(t))!fr.call(e,n)&&n!==r&&te(e,n,{get:()=>t[n],enumerable:!(o=cr(t,n))||o.enumerable});return e};var T=(e,t,r)=>(r=e!=null?lr(pr(e)):{},Ye(t||!e||!e.__esModule?te(r,"default",{value:e,enumerable:!0}):r,e)),mr=e=>Ye(te({},"__esModule",{value:!0}),e);function Er(e){return typeof e=="object"&&e!==null&&"type"in e&&"message"in e&&"error"in e&&typeof e.type=="string"&&typeof e.message=="string"}var P,dt,h,x=q(()=>{"use strict";P=(d=>(d.VALIDATION_ERROR="VALIDATION_ERROR",d.NOT_FOUND="NOT_FOUND",d.UNAUTHORIZED="UNAUTHORIZED",d.FORBIDDEN="FORBIDDEN",d.CONFLICT="CONFLICT",d.RATE_LIMITED="RATE_LIMITED",d.INTERNAL_SERVER_ERROR="INTERNAL_SERVER_ERROR",d.PAYLOAD_TOO_LARGE="PAYLOAD_TOO_LARGE",d.UNSUPPORTED_MEDIA_TYPE="UNSUPPORTED_MEDIA_TYPE",d.UPLOAD_TIMEOUT="UPLOAD_TIMEOUT",d.UNPROCESSABLE_ENTITY="UNPROCESSABLE_ENTITY",d.NETWORK_ERROR="NETWORK_ERROR",d.TIMEOUT_ERROR="TIMEOUT_ERROR",d.PARSE_ERROR="PARSE_ERROR",d.HTTP_ERROR="HTTP_ERROR",d))(P||{}),dt=(n=>(n.LOW="low",n.MEDIUM="medium",n.HIGH="high",n.CRITICAL="critical",n))(dt||{}),h=class extends Error{type;title;status;correlationId;timestamp;details;constructor(t,r,o,n,i){super(r),this.name=this.constructor.name,this.type=t,this.title=r,this.status=o,this.correlationId=n,this.timestamp=new Date,this.details=i,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){let t={type:this.type,title:this.title,status:this.status,correlationId:this.correlationId,timestamp:this.timestamp.toISOString()};return this.details!==void 0?{...t,details:this.details}:t}toString(){return`${this.name}: ${this.title} [${this.correlationId}]`}}});function De(){let e=Date.now().toString(36),t=Math.random().toString(36).substr(2,9);return`req_${e}_${t}`}function R(){let e=xr.getStore();return e&&e.trim()?e:"unknown"}var pt,xr,v=q(()=>{"use strict";pt=require("async_hooks"),xr=new pt.AsyncLocalStorage});var ft={};Q(ft,{InternalServerError:()=>D});var D,W=q(()=>{"use strict";x();v();D=class extends h{constructor(t,r=void 0,o=void 0){super("INTERNAL_SERVER_ERROR",t,500,o??R(),r)}}});var H={};Q(H,{ValidationError:()=>k});var k,z=q(()=>{"use strict";x();v();k=class extends h{constructor(t,r=void 0,o=void 0){super("VALIDATION_ERROR",t,400,o??R(),r)}}});var ke={};Q(ke,{PayloadTooLargeError:()=>G});var G,le=q(()=>{"use strict";v();x();G=class extends h{constructor(t,r,o){super("PAYLOAD_TOO_LARGE",t,413,o??R(),r)}}});var ze={};Q(ze,{UnsupportedMediaTypeError:()=>Z});var Z,ce=q(()=>{"use strict";v();x();Z=class extends h{constructor(t,r,o){super("UNSUPPORTED_MEDIA_TYPE",t,415,o??R(),r)}}});var Uo={};Q(Uo,{Blaize:()=>Ao,BlaizeError:()=>h,ConflictError:()=>Se,ErrorSeverity:()=>dt,ErrorType:()=>P,ForbiddenError:()=>Re,InternalServerError:()=>D,MiddlewareAPI:()=>ar,NotFoundError:()=>$,PayloadTooLargeError:()=>G,PluginsAPI:()=>ur,RateLimitError:()=>Te,RequestTimeoutError:()=>Ee,RouterAPI:()=>sr,ServerAPI:()=>ir,UnauthorizedError:()=>we,UnprocessableEntityError:()=>xe,UnsupportedMediaTypeError:()=>Z,VERSION:()=>nr,ValidationError:()=>k,compose:()=>A,createDeleteRoute:()=>Ce,createGetRoute:()=>be,createHeadRoute:()=>Me,createMiddleware:()=>re,createOptionsRoute:()=>Oe,createPatchRoute:()=>Fe,createPlugin:()=>oe,createPostRoute:()=>Pe,createPutRoute:()=>ve,createServer:()=>he,isBodyParseError:()=>Er});module.exports=mr(Uo);function Ke(e,t,r){if(!e||e.skip&&e.skip(t))return Promise.resolve(r());try{let o=e.execute(t,r);return o instanceof Promise?o:Promise.resolve(o)}catch(o){return Promise.reject(o)}}function A(e){return e.length===0?async(t,r)=>{await Promise.resolve(r())}:async function(t,r){let o=new Set,n=async i=>{if(i>=e.length)return Promise.resolve(r());let s=e[i];return Ke(s,t,()=>{if(o.has(i))throw new Error("next() called multiple times");return o.add(i),n(i+1)})};return n(0)}}function re(e){if(typeof e=="function")return{name:"anonymous",execute:e,debug:!1};let{name:t="anonymous",handler:r,skip:o,debug:n=!1}=e,i={name:t,execute:r,debug:n};return o!==void 0?{...i,skip:o}:i}function oe(e,t,r,o={}){if(!e||typeof e!="string")throw new Error("Plugin name must be a non-empty string");if(!t||typeof t!="string")throw new Error("Plugin version must be a non-empty string");if(typeof r!="function")throw new Error("Plugin setup must be a function");return function(i){let s={...o,...i},a={name:e,version:t,register:async u=>{let c=await r(u,s);c&&typeof c=="object"&&Object.assign(a,c)}};return a}}var rt=require("url");var ne={};function Xe(e){ne={...ne,...e}}function et(){if(!ne.routesDir)throw new Error("Routes directory not configured. Make sure server is properly initialized.");return ne.routesDir}var tt=T(require("path"),1);function ie(e,t){e.startsWith("file://")&&(e=e.replace("file://","")),t.startsWith("file://")&&(t=t.replace("file://",""));let r=e.replace(/\\/g,"/"),o=t.replace(/\\/g,"/"),n=o.endsWith("/")?o:`${o}/`,i=r;r.startsWith(n)?i=r.substring(n.length):r.startsWith(o)?(i=r.substring(o.length),i.startsWith("/")&&(i=i.substring(1))):i=tt.relative(o,r).replace(/\\/g,"/"),i=i.replace(/\.[^.]+$/,"");let s=i.split("/").filter(Boolean),a=[],u=s.map(S=>{if(S.startsWith("[")&&S.endsWith("]")){let p=S.slice(1,-1);return a.push(p),`:${p}`}return S}),c=u.length>0?`/${u.join("/")}`:"/";return c.endsWith("/index")&&(c=c.slice(0,-6)||"/"),{filePath:e,routePath:c,params:a}}function gr(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(n,i)=>i;let r=new Error().stack[3];if(!r||typeof r.getFileName!="function")throw new Error("Unable to determine caller file frame");let o=r.getFileName();if(!o)throw new Error("Unable to determine caller file name");return o.startsWith("file://")?(0,rt.fileURLToPath)(o):o}finally{Error.prepareStackTrace=e}}function U(){let e=gr(),t=et(),r=ie(e,t);return console.log(`\u{1F50E} Parsed route path: ${r.routePath} from file: ${e}`),r.routePath}var be=e=>{L("GET",e);let t=U();return{GET:e,path:t}},Pe=e=>{L("POST",e);let t=U();return{POST:e,path:t}},ve=e=>{L("PUT",e);let t=U();return{PUT:e,path:t}},Ce=e=>{L("DELETE",e);let t=U();return{DELETE:e,path:t}},Fe=e=>{L("PATCH",e);let t=U();return{PATCH:e,path:t}},Me=e=>{L("HEAD",e);let t=U();return{HEAD:e,path:t}},Oe=e=>{L("OPTIONS",e);let t=U();return{OPTIONS:e,path:t}};function L(e,t){if(!t.handler||typeof t.handler!="function")throw new Error(`Handler for method ${e} must be a function`);if(t.middleware&&!Array.isArray(t.middleware))throw new Error(`Middleware for method ${e} must be an array`);switch(t.schema&&yr(e,t.schema),e){case"GET":case"HEAD":case"DELETE":t.schema?.body&&console.warn(`Warning: ${e} requests typically don't have request bodies`);break}}function yr(e,t){let{params:r,query:o,body:n,response:i}=t;if(r&&(!r._def||typeof r.parse!="function"))throw new Error(`Params schema for ${e} must be a valid Zod schema`);if(o&&(!o._def||typeof o.parse!="function"))throw new Error(`Query schema for ${e} must be a valid Zod schema`);if(n&&(!n._def||typeof n.parse!="function"))throw new Error(`Body schema for ${e} must be a valid Zod schema`);if(i&&(!i._def||typeof i.parse!="function"))throw new Error(`Response schema for ${e} must be a valid Zod schema`)}var rr=require("async_hooks"),or=T(require("events"),1);var Ne=T(require("fs"),1),Ft=T(require("http"),1),Mt=T(require("http2"),1);var O=T(require("fs"),1),se=T(require("path"),1),ot=T(require("selfsigned"),1);async function nt(){let e=se.join(process.cwd(),".blaizejs","certs"),t=se.join(e,"dev.key"),r=se.join(e,"dev.cert");if(O.existsSync(t)&&O.existsSync(r))return{keyFile:t,certFile:r};O.existsSync(e)||O.mkdirSync(e,{recursive:!0});let i=ot.generate([{name:"commonName",value:"localhost"}],{days:365,algorithm:"sha256",keySize:2048,extensions:[{name:"basicConstraints",cA:!0},{name:"keyUsage",keyCertSign:!0,digitalSignature:!0,nonRepudiation:!0,keyEncipherment:!0,dataEncipherment:!0},{name:"extKeyUsage",serverAuth:!0,clientAuth:!0},{name:"subjectAltName",altNames:[{type:2,value:"localhost"},{type:7,ip:"127.0.0.1"}]}]});return O.writeFileSync(t,Buffer.from(i.private,"utf-8")),O.writeFileSync(r,Buffer.from(i.cert,"utf-8")),console.log(`
10
+ "use strict";var Tr=Object.create;var oe=Object.defineProperty;var xr=Object.getOwnPropertyDescriptor;var Rr=Object.getOwnPropertyNames;var vr=Object.getPrototypeOf,Er=Object.prototype.hasOwnProperty;var j=(e,t)=>()=>(e&&(t=e(e=0)),t);var W=(e,t)=>{for(var r in t)oe(e,r,{get:t[r],enumerable:!0})},st=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Rr(t))!Er.call(e,o)&&o!==r&&oe(e,o,{get:()=>t[o],enumerable:!(n=xr(t,o))||n.enumerable});return e};var R=(e,t,r)=>(r=e!=null?Tr(vr(e)):{},st(t||!e||!e.__esModule?oe(r,"default",{value:e,enumerable:!0}):r,e)),Pr=e=>st(oe({},"__esModule",{value:!0}),e);function Fr(){let e=Date.now().toString(36),t=Math.random().toString(36).substr(2,9);return`req_${e}_${t}`}function St(e,t){Te={headerName:e||$e.headerName,generator:t||$e.generator}}function H(){return Te.headerName}function kr(){return Te.generator()}function y(){let e=ht.getStore();return e&&e.trim()?e:"unknown"}function wt(e,t){return ht.run(e,t)}function xe(e){let t=Te.headerName,r=e[t],n;return Array.isArray(r)?n=r[0]:typeof r=="string"&&(n=r),n&&n.trim()?n:kr()}var yt,$e,Te,ht,v=j(()=>{"use strict";yt=require("async_hooks"),$e={headerName:"x-correlation-id",generator:Fr},Te={...$e},ht=new yt.AsyncLocalStorage});function zr(e){return typeof e=="object"&&e!==null&&"type"in e&&"message"in e&&"error"in e&&typeof e.type=="string"&&typeof e.message=="string"}var b,Et,h,P=j(()=>{"use strict";b=(d=>(d.VALIDATION_ERROR="VALIDATION_ERROR",d.NOT_FOUND="NOT_FOUND",d.UNAUTHORIZED="UNAUTHORIZED",d.FORBIDDEN="FORBIDDEN",d.CONFLICT="CONFLICT",d.RATE_LIMITED="RATE_LIMITED",d.INTERNAL_SERVER_ERROR="INTERNAL_SERVER_ERROR",d.PAYLOAD_TOO_LARGE="PAYLOAD_TOO_LARGE",d.UNSUPPORTED_MEDIA_TYPE="UNSUPPORTED_MEDIA_TYPE",d.UPLOAD_TIMEOUT="UPLOAD_TIMEOUT",d.UNPROCESSABLE_ENTITY="UNPROCESSABLE_ENTITY",d.NETWORK_ERROR="NETWORK_ERROR",d.TIMEOUT_ERROR="TIMEOUT_ERROR",d.PARSE_ERROR="PARSE_ERROR",d.HTTP_ERROR="HTTP_ERROR",d))(b||{}),Et=(o=>(o.LOW="low",o.MEDIUM="medium",o.HIGH="high",o.CRITICAL="critical",o))(Et||{}),h=class extends Error{type;title;status;correlationId;timestamp;details;constructor(t,r,n,o,i){super(r),this.name=this.constructor.name,this.type=t,this.title=r,this.status=n,this.correlationId=o,this.timestamp=new Date,this.details=i,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){let t={type:this.type,title:this.title,status:this.status,correlationId:this.correlationId,timestamp:this.timestamp.toISOString()};return this.details!==void 0?{...t,details:this.details}:t}toString(){return`${this.name}: ${this.title} [${this.correlationId}]`}}});var Pt={};W(Pt,{InternalServerError:()=>O});var O,Z=j(()=>{"use strict";P();v();O=class extends h{constructor(t,r=void 0,n=void 0){super("INTERNAL_SERVER_ERROR",t,500,n??y(),r)}}});var q={};W(q,{ValidationError:()=>I});var I,N=j(()=>{"use strict";P();v();I=class extends h{constructor(t,r=void 0,n=void 0){super("VALIDATION_ERROR",t,400,n??y(),r)}}});var _e={};W(_e,{PayloadTooLargeError:()=>J});var J,Re=j(()=>{"use strict";P();v();J=class extends h{constructor(t,r,n){super("PAYLOAD_TOO_LARGE",t,413,n??y(),r)}}});var Ue={};W(Ue,{UnsupportedMediaTypeError:()=>Y});var Y,ve=j(()=>{"use strict";P();v();Y=class extends h{constructor(t,r,n){super("UNSUPPORTED_MEDIA_TYPE",t,415,n??y(),r)}}});var so={};W(so,{Blaize:()=>io,BlaizeError:()=>h,ConflictError:()=>Ne,ErrorSeverity:()=>Et,ErrorType:()=>b,ForbiddenError:()=>Ie,InternalServerError:()=>O,MiddlewareAPI:()=>Sr,NotFoundError:()=>z,PayloadTooLargeError:()=>J,PluginsAPI:()=>wr,RateLimitError:()=>De,RequestTimeoutError:()=>ze,RouterAPI:()=>hr,ServerAPI:()=>yr,UnauthorizedError:()=>Oe,UnprocessableEntityError:()=>Be,UnsupportedMediaTypeError:()=>Y,VERSION:()=>gr,ValidationError:()=>I,asMiddlewareArray:()=>to,asPluginArray:()=>ro,compose:()=>_,createDeleteRoute:()=>fe,createGetRoute:()=>le,createHeadRoute:()=>ge,createMiddleware:()=>V,createMiddlewareArray:()=>no,createOptionsRoute:()=>ye,createPatchRoute:()=>me,createPlugin:()=>ae,createPluginArray:()=>oo,createPostRoute:()=>de,createPutRoute:()=>pe,createRouteFactory:()=>Ae,createServer:()=>ke,createServiceMiddleware:()=>se,createStateMiddleware:()=>ie,getCorrelationId:()=>y,inferContext:()=>it,isBodyParseError:()=>zr,isMiddleware:()=>Xn,isPlugin:()=>eo});module.exports=Pr(so);function at(e,t,r){if(!e||e.skip&&e.skip(t))return Promise.resolve(r());try{let n=e.execute(t,r);return n instanceof Promise?n:Promise.resolve(n)}catch(n){return Promise.reject(n)}}function _(e){return e.length===0?async(t,r)=>{await Promise.resolve(r())}:async function(t,r){let n=new Set,o=async i=>{if(i>=e.length)return Promise.resolve(r());let s=e[i];return at(s,t,()=>{if(n.has(i))throw new Error("next() called multiple times");return n.add(i),o(i+1)})};return o(0)}}function V(e){if(typeof e=="function")return{name:"anonymous",execute:e,debug:!1};let{name:t="anonymous",handler:r,skip:n,debug:o=!1}=e;return{name:t,execute:r,debug:o,...n!==void 0&&{skip:n}}}function ie(e){return V({name:"state-middleware",handler:e})}function se(e){return V({name:"service-middleware",handler:e})}function ae(e,t,r,n={}){if(!e||typeof e!="string")throw new Error("Plugin name must be a non-empty string");if(!t||typeof t!="string")throw new Error("Plugin version must be a non-empty string");if(typeof r!="function")throw new Error("Plugin setup must be a function");return function(i){let s={...n,...i},a={name:e,version:t,register:async u=>{let l=await r(u,s);l&&typeof l=="object"&&Object.assign(a,l)}};return a}}var dt=require("url");var ue={};function ut(e){ue={...ue,...e}}function ct(){if(!ue.routesDir)throw new Error("Routes directory not configured. Make sure server is properly initialized.");return ue.routesDir}var lt=R(require("path"),1);function ce(e,t){e.startsWith("file://")&&(e=e.replace("file://","")),t.startsWith("file://")&&(t=t.replace("file://",""));let r=e.replace(/\\/g,"/"),n=t.replace(/\\/g,"/"),o=n.endsWith("/")?n:`${n}/`,i=r;r.startsWith(o)?i=r.substring(o.length):r.startsWith(n)?(i=r.substring(n.length),i.startsWith("/")&&(i=i.substring(1))):i=lt.relative(n,r).replace(/\\/g,"/"),i=i.replace(/\.[^.]+$/,"");let s=i.split("/").filter(Boolean),a=[],u=s.map(T=>{if(T.startsWith("[")&&T.endsWith("]")){let p=T.slice(1,-1);return a.push(p),`:${p}`}return T}),l=u.length>0?`/${u.join("/")}`:"/";return l.endsWith("/index")&&(l=l.slice(0,-6)||"/"),{filePath:e,routePath:l,params:a}}function br(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(o,i)=>i;let r=new Error().stack[3];if(!r||typeof r.getFileName!="function")throw new Error("Unable to determine caller file frame");let n=r.getFileName();if(!n)throw new Error("Unable to determine caller file name");return n.startsWith("file://")?(0,dt.fileURLToPath)(n):n}finally{Error.prepareStackTrace=e}}function U(){let e=br(),t=ct(),r=ce(e,t);return console.log(`\u{1F50E} Parsed route path: ${r.routePath} from file: ${e}`),r.routePath}var le=()=>e=>{L("GET",e);let t=U();return{GET:e,path:t}},de=()=>e=>{L("POST",e);let t=U();return{POST:e,path:t}},pe=()=>e=>{L("PUT",e);let t=U();return{PUT:e,path:t}},fe=()=>e=>{L("DELETE",e);let t=U();return{DELETE:e,path:t}},me=()=>e=>{L("PATCH",e);let t=U();return{PATCH:e,path:t}},ge=()=>e=>{L("HEAD",e);let t=U();return{HEAD:e,path:t}},ye=()=>e=>{L("OPTIONS",e);let t=U();return{OPTIONS:e,path:t}};function L(e,t){if(!t.handler||typeof t.handler!="function")throw new Error(`Handler for method ${e} must be a function`);if(t.middleware&&!Array.isArray(t.middleware))throw new Error(`Middleware for method ${e} must be an array`);switch(t.schema&&Cr(e,t.schema),e){case"GET":case"HEAD":case"DELETE":t.schema?.body&&console.warn(`Warning: ${e} requests typically don't have request bodies`);break}}function Cr(e,t){let{params:r,query:n,body:o,response:i}=t;if(r&&(!r._def||typeof r.parse!="function"))throw new Error(`Params schema for ${e} must be a valid Zod schema`);if(n&&(!n._def||typeof n.parse!="function"))throw new Error(`Query schema for ${e} must be a valid Zod schema`);if(o&&(!o._def||typeof o.parse!="function"))throw new Error(`Body schema for ${e} must be a valid Zod schema`);if(i&&(!i._def||typeof i.parse!="function"))throw new Error(`Response schema for ${e} must be a valid Zod schema`)}function Ae(){return{get:le(),post:de(),put:pe(),delete:fe(),patch:me(),head:ge(),options:ye()}}var fr=require("async_hooks"),mr=R(require("events"),1);var qe=R(require("fs"),1),Ut=R(require("http"),1),Lt=R(require("http2"),1);var k=R(require("fs"),1),he=R(require("path"),1),pt=R(require("selfsigned"),1);async function ft(){let e=he.join(process.cwd(),".blaizejs","certs"),t=he.join(e,"dev.key"),r=he.join(e,"dev.cert");if(k.existsSync(t)&&k.existsSync(r))return{keyFile:t,certFile:r};k.existsSync(e)||k.mkdirSync(e,{recursive:!0});let i=pt.generate([{name:"commonName",value:"localhost"}],{days:365,algorithm:"sha256",keySize:2048,extensions:[{name:"basicConstraints",cA:!0},{name:"keyUsage",keyCertSign:!0,digitalSignature:!0,nonRepudiation:!0,keyEncipherment:!0,dataEncipherment:!0},{name:"extKeyUsage",serverAuth:!0,clientAuth:!0},{name:"subjectAltName",altNames:[{type:2,value:"localhost"},{type:7,ip:"127.0.0.1"}]}]});return k.writeFileSync(t,Buffer.from(i.private,"utf-8")),k.writeFileSync(r,Buffer.from(i.cert,"utf-8")),console.log(`
11
11
  \u{1F512} Generated self-signed certificates for development at ${e}
12
- `),{keyFile:t,certFile:r}}var C=class extends Error{constructor(t="\u274C Response has already been sent"){super(t),this.name="ResponseSentError"}},V=class extends C{constructor(t="Cannot set header after response has been sent"){super(t)}},ae=class extends C{constructor(t="Cannot set content type after response has been sent"){super(t)}},ue=class extends C{constructor(t="Invalide URL"){super(t)}};var it=require("async_hooks"),hr=new it.AsyncLocalStorage;function st(e,t){return hr.run(e,t)}var mt=T(require("crypto"),1),gt=require("fs"),yt=require("os"),ht=require("path"),Be=require("stream");var wr=/boundary=([^;]+)/i,Rr=/Content-Disposition:\s*form-data;\s*name="([^"]+)"(?:;[\s\r\n]*filename="([^"]*)")?/i,Sr=/Content-Type:\s*([^\r\n]+)/i,Tr=/multipart\/form-data/i;function at(e){let t=e.match(wr);if(!t||!t[1])return null;let r=t[1].trim();return r.startsWith('"')&&r.endsWith('"')&&(r=r.slice(1,-1)),r||null}function ut(e){let t=e.match(Rr);return!t||!t[1]?null:{name:t[1],filename:t[2]!==void 0?t[2]:void 0}}function lt(e){let t=e.match(Sr);return t&&t[1]?.trim()?t[1].trim():"application/octet-stream"}function ct(e){return Tr.test(e)}var br={maxFileSize:10*1024*1024,maxFiles:10,maxFieldSize:1*1024*1024,allowedMimeTypes:[],allowedExtensions:[],strategy:"stream",tempDir:(0,yt.tmpdir)(),computeHash:!1};function Pr(e,t={}){return{boundary:Buffer.from(`--${e}`),options:{...br,...t},fields:new Map,files:new Map,buffer:Buffer.alloc(0),stage:"boundary",currentHeaders:"",currentField:null,currentFilename:void 0,currentMimetype:"application/octet-stream",currentContentLength:0,fileCount:0,fieldCount:0,currentBufferChunks:[],currentStream:null,currentTempPath:null,currentWriteStream:null,streamController:null,cleanupTasks:[],hasFoundValidBoundary:!1,hasProcessedAnyPart:!1,isFinished:!1}}async function vr(e,t){let r=Buffer.concat([e.buffer,t]),o={...e,buffer:r};for(;o.buffer.length>0&&!o.isFinished;){let n=await Cr(o);if(n===o)break;o=n}return o}async function Cr(e){switch(e.stage){case"boundary":return Fr(e);case"headers":return Mr(e);case"content":return Or(e);default:{let{InternalServerError:t}=await Promise.resolve().then(()=>(W(),ft));throw new t("Invalid parser stage",{operation:e.stage})}}}function Fr(e){let t=e.buffer.indexOf(e.boundary);if(t===-1)return e;let r=!0,o=e.buffer.subarray(t+e.boundary.length);return o.length>=2&&o.subarray(0,2).equals(Buffer.from("--"))?{...e,buffer:o,hasFoundValidBoundary:r,isFinished:!0,stage:"boundary"}:(o.length>=2&&o.subarray(0,2).equals(Buffer.from(`\r
13
- `))&&(o=o.subarray(2)),{...e,buffer:o,hasFoundValidBoundary:r,stage:"headers",currentHeaders:""})}async function Mr(e){let t=e.buffer.indexOf(`\r
12
+ `),{keyFile:t,certFile:r}}var C=class extends Error{constructor(t="\u274C Response has already been sent"){super(t),this.name="ResponseSentError"}},G=class extends C{constructor(t="Cannot set header after response has been sent"){super(t)}},Se=class extends C{constructor(t="Cannot set content type after response has been sent"){super(t)}},we=class extends C{constructor(t="Invalide URL"){super(t)}};var mt=require("async_hooks"),Mr=new mt.AsyncLocalStorage;function gt(e,t){return Mr.run(e,t)}v();var bt=R(require("crypto"),1),Ct=require("fs"),Mt=require("os"),Ft=require("path"),Le=require("stream");var Or=/boundary=([^;]+)/i,Ir=/Content-Disposition:\s*form-data;\s*name="([^"]+)"(?:;[\s\r\n]*filename="([^"]*)")?/i,Nr=/Content-Type:\s*([^\r\n]+)/i,Dr=/multipart\/form-data/i;function Tt(e){let t=e.match(Or);if(!t||!t[1])return null;let r=t[1].trim();return r.startsWith('"')&&r.endsWith('"')&&(r=r.slice(1,-1)),r||null}function xt(e){let t=e.match(Ir);return!t||!t[1]?null:{name:t[1],filename:t[2]!==void 0?t[2]:void 0}}function Rt(e){let t=e.match(Nr);return t&&t[1]?.trim()?t[1].trim():"application/octet-stream"}function vt(e){return Dr.test(e)}var Br={maxFileSize:10*1024*1024,maxFiles:10,maxFieldSize:1*1024*1024,allowedMimeTypes:[],allowedExtensions:[],strategy:"stream",tempDir:(0,Mt.tmpdir)(),computeHash:!1};function Ar(e,t={}){return{boundary:Buffer.from(`--${e}`),options:{...Br,...t},fields:new Map,files:new Map,buffer:Buffer.alloc(0),stage:"boundary",currentHeaders:"",currentField:null,currentFilename:void 0,currentMimetype:"application/octet-stream",currentContentLength:0,fileCount:0,fieldCount:0,currentBufferChunks:[],currentStream:null,currentTempPath:null,currentWriteStream:null,streamController:null,cleanupTasks:[],hasFoundValidBoundary:!1,hasProcessedAnyPart:!1,isFinished:!1}}async function $r(e,t){let r=Buffer.concat([e.buffer,t]),n={...e,buffer:r};for(;n.buffer.length>0&&!n.isFinished;){let o=await _r(n);if(o===n)break;n=o}return n}async function _r(e){switch(e.stage){case"boundary":return Ur(e);case"headers":return Lr(e);case"content":return Hr(e);default:{let{InternalServerError:t}=await Promise.resolve().then(()=>(Z(),Pt));throw new t("Invalid parser stage",{operation:e.stage})}}}function Ur(e){let t=e.buffer.indexOf(e.boundary);if(t===-1)return e;let r=!0,n=e.buffer.subarray(t+e.boundary.length);return n.length>=2&&n.subarray(0,2).equals(Buffer.from("--"))?{...e,buffer:n,hasFoundValidBoundary:r,isFinished:!0,stage:"boundary"}:(n.length>=2&&n.subarray(0,2).equals(Buffer.from(`\r
13
+ `))&&(n=n.subarray(2)),{...e,buffer:n,hasFoundValidBoundary:r,stage:"headers",currentHeaders:""})}async function Lr(e){let t=e.buffer.indexOf(`\r
14
14
  \r
15
- `);if(t===-1)return e;let r=e.buffer.subarray(0,t).toString("utf8"),o=e.buffer.subarray(t+4),n=ut(r);if(!n){let{ValidationError:a}=await Promise.resolve().then(()=>(z(),H));throw new a("Missing or invalid Content-Disposition header")}let i=lt(r),s=n.filename!==void 0;if(s&&e.fileCount>=e.options.maxFiles){let{PayloadTooLargeError:a}=await Promise.resolve().then(()=>(le(),ke));throw new a("Too many files in upload",{fileCount:e.fileCount+1,maxFiles:e.options.maxFiles,filename:n.filename})}if(s&&e.options.allowedMimeTypes.length>0&&!e.options.allowedMimeTypes.includes(i)){let{UnsupportedMediaTypeError:a}=await Promise.resolve().then(()=>(ce(),ze));throw new a("File type not allowed",{receivedMimeType:i,allowedMimeTypes:e.options.allowedMimeTypes,filename:n.filename})}return{...e,buffer:o,stage:"content",currentHeaders:r,currentField:n.name,currentFilename:n.filename,currentMimetype:i,currentContentLength:0,fileCount:s?e.fileCount+1:e.fileCount,fieldCount:s?e.fieldCount:e.fieldCount+1,currentBufferChunks:[]}}async function Or(e){let t=e.buffer.indexOf(e.boundary),r,o=!1,n=e.buffer;if(t===-1){let s=Math.max(0,e.buffer.length-e.boundary.length);if(s===0)return e;r=e.buffer.subarray(0,s),n=e.buffer.subarray(s)}else{let s=Math.max(0,t-2);r=e.buffer.subarray(0,s),n=e.buffer.subarray(t),o=!0}let i={...e,buffer:n};return r.length>0&&(i=await Dr(i,r)),o&&(i=await Br(i),i={...i,stage:"boundary",hasProcessedAnyPart:!0}),i}async function Dr(e,t){let r=e.currentContentLength+t.length,o=e.currentFilename!==void 0?e.options.maxFileSize:e.options.maxFieldSize;if(r>o){let n=e.currentFilename!==void 0,{PayloadTooLargeError:i}=await Promise.resolve().then(()=>(le(),ke)),s=e.currentField?{contentType:n?"file":"field",currentSize:r,maxSize:o,field:e.currentField,filename:e.currentFilename}:{contentType:n?"file":"field",currentSize:r,maxSize:o,filename:e.currentFilename};throw new i(`${n?"File":"Field"} size exceeds limit`,s)}return e.currentFilename!==void 0?kr(e,t,r):{...e,currentContentLength:r,currentBufferChunks:[...e.currentBufferChunks,t]}}async function kr(e,t,r){switch(e.options.strategy){case"memory":return{...e,currentContentLength:r,currentBufferChunks:[...e.currentBufferChunks,t]};case"stream":return e.streamController&&e.streamController.enqueue(t),{...e,currentContentLength:r};case"temp":return e.currentWriteStream&&await Ar(e.currentWriteStream,t),{...e,currentContentLength:r};default:{let{ValidationError:o}=await Promise.resolve().then(()=>(z(),H));throw new o("Invalid parsing strategy")}}}async function zr(e){if(e.currentFilename===void 0)return e;switch(e.options.strategy){case"memory":return{...e,currentBufferChunks:[]};case"stream":{let t=null,r=new ReadableStream({start:o=>{t=o}});return{...e,currentStream:r,streamController:t}}case"temp":{let t=(0,ht.join)(e.options.tempDir,`upload-${mt.randomUUID()}`),r=(0,gt.createWriteStream)(t),o=async()=>{try{let{unlink:n}=await import("fs/promises");await n(t)}catch(n){console.warn(`Failed to cleanup temp file: ${t}`,n)}};return{...e,currentTempPath:t,currentWriteStream:r,cleanupTasks:[...e.cleanupTasks,o]}}default:{let{ValidationError:t}=await Promise.resolve().then(()=>(z(),H));throw new t("Invalid file processing strategy")}}}async function Br(e){return e.currentField?e.currentFilename!==void 0?$r(e):Nr(e):J(e)}async function $r(e){if(!e.currentField||e.currentFilename===void 0)return J(e);let t,r,o;switch(e.options.strategy){case"memory":r=Buffer.concat(e.currentBufferChunks),t=Be.Readable.from(r);break;case"stream":e.streamController&&e.streamController.close(),t=e.currentStream;break;case"temp":e.currentWriteStream&&await Rt(e.currentWriteStream),o=e.currentTempPath,t=Be.Readable.from(Buffer.alloc(0));break;default:{let{ValidationError:s}=await Promise.resolve().then(()=>(z(),H));throw new s("Invalid file finalization strategy")}}let n={filename:e.currentFilename,fieldname:e.currentField,mimetype:e.currentMimetype,size:e.currentContentLength,stream:t,buffer:r,tempPath:o},i=wt(e.files,e.currentField,n);return{...J(e),files:i}}function Nr(e){if(!e.currentField)return J(e);let t=Buffer.concat(e.currentBufferChunks).toString("utf8"),r=wt(e.fields,e.currentField,t);return{...J(e),fields:r}}function J(e){return{...e,currentField:null,currentFilename:void 0,currentContentLength:0,currentBufferChunks:[],currentStream:null,streamController:null,currentTempPath:null,currentWriteStream:null}}function wt(e,t,r){let o=new Map(e),n=o.get(t)||[];return o.set(t,[...n,r]),o}async function Ir(e){if(!e.hasFoundValidBoundary){let{ValidationError:o}=await Promise.resolve().then(()=>(z(),H));throw new o("No valid multipart boundary found")}if(e.hasFoundValidBoundary&&!e.hasProcessedAnyPart){let{ValidationError:o}=await Promise.resolve().then(()=>(z(),H));throw new o("Empty multipart request")}let t={};for(let[o,n]of e.fields.entries())t[o]=n.length===1?n[0]:n;let r={};for(let[o,n]of e.files.entries())r[o]=n.length===1?n[0]:n;return{fields:t,files:r}}async function _r(e){await Promise.allSettled(e.cleanupTasks.map(t=>t())),e.streamController&&e.streamController.close(),e.currentWriteStream&&await Rt(e.currentWriteStream)}async function Ar(e,t){return new Promise((r,o)=>{e.write(t,n=>{n?o(n):r()})})}async function Rt(e){return new Promise(t=>{e.end(()=>t())})}async function St(e,t={}){let r=e.headers["content-type"]||"",o=at(r);if(!o){let{UnsupportedMediaTypeError:i}=await Promise.resolve().then(()=>(ce(),ze));throw new i("Missing boundary in multipart content-type",{receivedContentType:r,expectedFormat:"multipart/form-data; boundary=..."})}let n=Pr(o,t);n.currentFilename!==void 0&&(n=await zr(n));try{for await(let i of e)n=await vr(n,i);return Ir(n)}finally{await _r(n)}}var Y="Content-Type",B={json:512*1024,form:1024*1024,text:5*1024*1024,multipart:{maxFileSize:50*1024*1024,maxTotalSize:100*1024*1024,maxFiles:10,maxFieldSize:1024*1024},raw:10*1024*1024};function Ur(e){let t=e.url||"/",r=e.headers.host||"localhost",n=`${e.socket&&e.socket.encrypted?"https":"http"}://${r}${t.startsWith("/")?"":"/"}${t}`;try{let i=new URL(n),s=i.pathname,a={};return i.searchParams.forEach((u,c)=>{a[c]!==void 0?Array.isArray(a[c])?a[c].push(u):a[c]=[a[c],u]:a[c]=u}),{path:s,url:i,query:a}}catch(i){throw console.warn(`Invalid URL: ${n}`,i),new ue(`Invalid URL: ${n}`)}}function Lr(e){return"stream"in e||"httpVersionMajor"in e&&e.httpVersionMajor===2}function Hr(e){let t=e.socket&&e.socket.encrypted,r=e.headers["x-forwarded-proto"];return r?Array.isArray(r)?r[0]?.split(",")[0]?.trim()||"http":r.split(",")[0]?.trim()||"http":t?"https":"http"}async function Tt(e,t,r={}){let{path:o,url:n,query:i}=Ur(e),s=e.method||"GET",a=Lr(e),u=Hr(e),c={},S={...r.initialState||{}},p={sent:!1},g={request:qr(e,{path:o,url:n,query:i,params:c,method:s,isHttp2:a,protocol:u}),response:{},state:S};return g.response=Qr(t,p,g),r.parseBody&&await to(e,g,r),g}function qr(e,t){return{raw:e,...t,header:Et(e),headers:jr(e),body:void 0}}function Et(e){return t=>{let r=e.headers[t.toLowerCase()];return Array.isArray(r)?r.join(", "):r||void 0}}function jr(e){let t=Et(e);return r=>r&&Array.isArray(r)&&r.length>0?r.reduce((o,n)=>(o[n]=t(n),o),{}):Object.entries(e.headers).reduce((o,[n,i])=>(o[n]=Array.isArray(i)?i.join(", "):i||void 0,o),{})}function Qr(e,t,r){return{raw:e,get sent(){return t.sent},status:Vr(e,t,r),header:Wr(e,t,r),headers:Gr(e,t,r),type:Zr(e,t,r),json:Jr(e,t),text:Yr(e,t),html:Kr(e,t),redirect:Xr(e,t),stream:eo(e,t)}}function Vr(e,t,r){return function(n){if(t.sent)throw new C;return e.statusCode=n,r.response}}function Wr(e,t,r){return function(n,i){if(t.sent)throw new V;return e.setHeader(n,i),r.response}}function Gr(e,t,r){return function(n){if(t.sent)throw new V;for(let[i,s]of Object.entries(n))e.setHeader(i,s);return r.response}}function Zr(e,t,r){return function(n){if(t.sent)throw new ae;return e.setHeader(Y,n),r.response}}function Jr(e,t){return function(o,n){if(t.sent)throw new C;n!==void 0&&(e.statusCode=n),e.setHeader(Y,"application/json"),e.end(JSON.stringify(o)),t.sent=!0}}function Yr(e,t){return function(o,n){if(t.sent)throw new C;n!==void 0&&(e.statusCode=n),e.setHeader(Y,"text/plain"),e.end(o),t.sent=!0}}function Kr(e,t){return function(o,n){if(t.sent)throw new C;n!==void 0&&(e.statusCode=n),e.setHeader(Y,"text/html"),e.end(o),t.sent=!0}}function Xr(e,t){return function(o,n=302){if(t.sent)throw new C;e.statusCode=n,e.setHeader("Location",o),e.end(),t.sent=!0}}function eo(e,t){return function(o,n={}){if(t.sent)throw new C;if(n.status!==void 0&&(e.statusCode=n.status),n.contentType&&e.setHeader(Y,n.contentType),n.headers)for(let[i,s]of Object.entries(n.headers))e.setHeader(i,s);o.pipe(e),o.on("end",()=>{t.sent=!0}),o.on("error",i=>{console.error("Stream error:",i),t.sent||(e.statusCode=500,e.end("Stream error"),t.sent=!0)})}}async function to(e,t,r={}){if(ro(e.method))return;let o=e.headers["content-type"]||"",n=parseInt(e.headers["content-length"]||"0",10);if(n===0)return;let i={json:r.bodyLimits?.json??B.json,form:r.bodyLimits?.form??B.form,text:r.bodyLimits?.text??B.text,raw:r.bodyLimits?.raw??B.raw,multipart:{maxFileSize:r.bodyLimits?.multipart?.maxFileSize??B.multipart.maxFileSize,maxFiles:r.bodyLimits?.multipart?.maxFiles??B.multipart.maxFiles,maxFieldSize:r.bodyLimits?.multipart?.maxFieldSize??B.multipart.maxFieldSize,maxTotalSize:r.bodyLimits?.multipart?.maxTotalSize??B.multipart.maxTotalSize}};try{if(o.includes("application/json")){if(n>i.json)throw new Error(`JSON body too large: ${n} > ${i.json} bytes`);await oo(e,t)}else if(o.includes("application/x-www-form-urlencoded")){if(n>i.form)throw new Error(`Form body too large: ${n} > ${i.form} bytes`);await no(e,t)}else if(o.includes("text/")){if(n>i.text)throw new Error(`Text body too large: ${n} > ${i.text} bytes`);await so(e,t)}else if(ct(o))await ao(e,t,i.multipart);else{if(n>i.raw)throw new Error(`Request body too large: ${n} > ${i.raw} bytes`);return}}catch(s){let a=o.includes("multipart")?"multipart_parse_error":"body_read_error";de(t,a,"Error reading request body",s)}}function ro(e){return["GET","HEAD","OPTIONS"].includes(e||"GET")}async function oo(e,t){let r=await $e(e);if(!r){console.warn("Empty body, skipping JSON parsing");return}if(r.trim()==="null"){console.warn('Body is the string "null"'),t.request.body=null;return}try{let o=JSON.parse(r);t.request.body=o}catch(o){t.request.body=null,de(t,"json_parse_error","Invalid JSON in request body",o)}}async function no(e,t){let r=await $e(e);if(r)try{t.request.body=io(r)}catch(o){t.request.body=null,de(t,"form_parse_error","Invalid form data in request body",o)}}function io(e){let t=new URLSearchParams(e),r={};return t.forEach((o,n)=>{r[n]!==void 0?Array.isArray(r[n])?r[n].push(o):r[n]=[r[n],o]:r[n]=o}),r}async function so(e,t){let r=await $e(e);r&&(t.request.body=r)}async function ao(e,t,r){try{let o=r||B.multipart,n=await St(e,{strategy:"stream",maxFileSize:o.maxFileSize,maxFiles:o.maxFiles,maxFieldSize:o.maxFieldSize});t.request.multipart=n,t.request.files=n.files,t.request.body=n.fields}catch(o){t.request.body=null,de(t,"multipart_parse_error","Failed to parse multipart data",o)}}function de(e,t,r,o){let n={type:t,message:r,error:o};e.state._bodyError=n}async function $e(e){return new Promise((t,r)=>{let o=[];e.on("data",n=>{o.push(Buffer.isBuffer(n)?n:Buffer.from(n))}),e.on("end",()=>{t(Buffer.concat(o).toString("utf8"))}),e.on("error",n=>{r(n)})})}x();v();var $=class extends h{constructor(t,r=void 0,o=void 0){super("NOT_FOUND",t,404,o??R(),r)}};x();v();W();function uo(e){return e instanceof h}function xt(e){if(uo(e))return{type:e.type,title:e.title,status:e.status,correlationId:e.correlationId,timestamp:e.timestamp.toISOString(),details:e.details};let t=De(),r;e instanceof Error?r=e.message:e==null?r="Unknown error occurred":r=String(e);let o=new D("Internal Server Error",{originalMessage:r},t);return{type:o.type,title:o.title,status:o.status,correlationId:o.correlationId,timestamp:o.timestamp.toISOString(),details:o.details}}function bt(e){return e("x-correlation-id")??De()}function Pt(e,t){e("x-correlation-id",t)}function vt(e={}){let{debug:t=!1}=e;return{name:"ErrorBoundary",execute:async(o,n)=>{try{await n()}catch(i){if(o.response.sent){t&&console.error("Error occurred after response was sent:",i);return}t&&console.error("Error boundary caught error:",i);let s=bt(o.request.header),a=xt(i);a.correlationId=s,Pt(o.response.header,s),o.response.status(a.status).json(a)}},debug:t}}function Ct(e){return async(t,r)=>{try{let o=await Tt(t,r,{parseBody:!0}),i=[vt(),...e.middleware],s=A(i);await st(o,async()=>{await s(o,async()=>{if(!o.response.sent&&(await e.router.handleRequest(o),!o.response.sent))throw new $(`Route not found: ${o.request.method} ${o.request.path}`)})})}catch(o){console.error("Error creating context:",o),r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Internal Server Error",message:"Failed to process request"}))}}}async function lo(e){if(!e.enabled)return{};let{keyFile:t,certFile:r}=e,o=process.env.NODE_ENV==="development",n=!t||!r;if(n&&o)return await nt();if(n)throw new Error("HTTP/2 requires SSL certificates. Provide keyFile and certFile in http2 options. In development, set NODE_ENV=development to generate them automatically.");return{keyFile:t,certFile:r}}function co(e,t){if(!e)return Ft.createServer();let r={allowHTTP1:!0};try{t.keyFile&&(r.key=Ne.readFileSync(t.keyFile)),t.certFile&&(r.cert=Ne.readFileSync(t.certFile))}catch(o){throw new Error(`Failed to read certificate files: ${o instanceof Error?o.message:String(o)}`)}return Mt.createSecureServer(r)}function po(e,t,r,o){return new Promise((n,i)=>{e.listen(t,r,()=>{let a=`${o?"https":"http"}://${r}:${t}`;console.log(`
15
+ `);if(t===-1)return e;let r=e.buffer.subarray(0,t).toString("utf8"),n=e.buffer.subarray(t+4),o=xt(r);if(!o){let{ValidationError:a}=await Promise.resolve().then(()=>(N(),q));throw new a("Missing or invalid Content-Disposition header")}let i=Rt(r),s=o.filename!==void 0;if(s&&e.fileCount>=e.options.maxFiles){let{PayloadTooLargeError:a}=await Promise.resolve().then(()=>(Re(),_e));throw new a("Too many files in upload",{fileCount:e.fileCount+1,maxFiles:e.options.maxFiles,filename:o.filename})}if(s&&e.options.allowedMimeTypes.length>0&&!e.options.allowedMimeTypes.includes(i)){let{UnsupportedMediaTypeError:a}=await Promise.resolve().then(()=>(ve(),Ue));throw new a("File type not allowed",{receivedMimeType:i,allowedMimeTypes:e.options.allowedMimeTypes,filename:o.filename})}return{...e,buffer:n,stage:"content",currentHeaders:r,currentField:o.name,currentFilename:o.filename,currentMimetype:i,currentContentLength:0,fileCount:s?e.fileCount+1:e.fileCount,fieldCount:s?e.fieldCount:e.fieldCount+1,currentBufferChunks:[]}}async function Hr(e){let t=e.buffer.indexOf(e.boundary),r,n=!1,o=e.buffer;if(t===-1){let s=Math.max(0,e.buffer.length-e.boundary.length);if(s===0)return e;r=e.buffer.subarray(0,s),o=e.buffer.subarray(s)}else{let s=Math.max(0,t-2);r=e.buffer.subarray(0,s),o=e.buffer.subarray(t),n=!0}let i={...e,buffer:o};return r.length>0&&(i=await qr(i,r)),n&&(i=await Qr(i),i={...i,stage:"boundary",hasProcessedAnyPart:!0}),i}async function qr(e,t){let r=e.currentContentLength+t.length,n=e.currentFilename!==void 0?e.options.maxFileSize:e.options.maxFieldSize;if(r>n){let o=e.currentFilename!==void 0,{PayloadTooLargeError:i}=await Promise.resolve().then(()=>(Re(),_e)),s=e.currentField?{contentType:o?"file":"field",currentSize:r,maxSize:n,field:e.currentField,filename:e.currentFilename}:{contentType:o?"file":"field",currentSize:r,maxSize:n,filename:e.currentFilename};throw new i(`${o?"File":"Field"} size exceeds limit`,s)}return e.currentFilename!==void 0?jr(e,t,r):{...e,currentContentLength:r,currentBufferChunks:[...e.currentBufferChunks,t]}}async function jr(e,t,r){switch(e.options.strategy){case"memory":return{...e,currentContentLength:r,currentBufferChunks:[...e.currentBufferChunks,t]};case"stream":return e.streamController&&e.streamController.enqueue(t),{...e,currentContentLength:r};case"temp":return e.currentWriteStream&&await Yr(e.currentWriteStream,t),{...e,currentContentLength:r};default:{let{ValidationError:n}=await Promise.resolve().then(()=>(N(),q));throw new n("Invalid parsing strategy")}}}async function Vr(e){if(e.currentFilename===void 0)return e;switch(e.options.strategy){case"memory":return{...e,currentBufferChunks:[]};case"stream":{let t=null,r=new ReadableStream({start:n=>{t=n}});return{...e,currentStream:r,streamController:t}}case"temp":{let t=(0,Ft.join)(e.options.tempDir,`upload-${bt.randomUUID()}`),r=(0,Ct.createWriteStream)(t),n=async()=>{try{let{unlink:o}=await import("fs/promises");await o(t)}catch(o){console.warn(`Failed to cleanup temp file: ${t}`,o)}};return{...e,currentTempPath:t,currentWriteStream:r,cleanupTasks:[...e.cleanupTasks,n]}}default:{let{ValidationError:t}=await Promise.resolve().then(()=>(N(),q));throw new t("Invalid file processing strategy")}}}async function Qr(e){return e.currentField?e.currentFilename!==void 0?Wr(e):Gr(e):K(e)}async function Wr(e){if(!e.currentField||e.currentFilename===void 0)return K(e);let t,r,n;switch(e.options.strategy){case"memory":r=Buffer.concat(e.currentBufferChunks),t=Le.Readable.from(r);break;case"stream":e.streamController&&e.streamController.close(),t=e.currentStream;break;case"temp":e.currentWriteStream&&await Ot(e.currentWriteStream),n=e.currentTempPath,t=Le.Readable.from(Buffer.alloc(0));break;default:{let{ValidationError:s}=await Promise.resolve().then(()=>(N(),q));throw new s("Invalid file finalization strategy")}}let o={filename:e.currentFilename,fieldname:e.currentField,mimetype:e.currentMimetype,size:e.currentContentLength,stream:t,buffer:r,tempPath:n},i=kt(e.files,e.currentField,o);return{...K(e),files:i}}function Gr(e){if(!e.currentField)return K(e);let t=Buffer.concat(e.currentBufferChunks).toString("utf8"),r=kt(e.fields,e.currentField,t);return{...K(e),fields:r}}function K(e){return{...e,currentField:null,currentFilename:void 0,currentContentLength:0,currentBufferChunks:[],currentStream:null,streamController:null,currentTempPath:null,currentWriteStream:null}}function kt(e,t,r){let n=new Map(e),o=n.get(t)||[];return n.set(t,[...o,r]),n}async function Zr(e){if(!e.hasFoundValidBoundary){let{ValidationError:n}=await Promise.resolve().then(()=>(N(),q));throw new n("No valid multipart boundary found")}if(e.hasFoundValidBoundary&&!e.hasProcessedAnyPart){let{ValidationError:n}=await Promise.resolve().then(()=>(N(),q));throw new n("Empty multipart request")}let t={};for(let[n,o]of e.fields.entries())t[n]=o.length===1?o[0]:o;let r={};for(let[n,o]of e.files.entries())r[n]=o.length===1?o[0]:o;return{fields:t,files:r}}async function Jr(e){await Promise.allSettled(e.cleanupTasks.map(t=>t())),e.streamController&&e.streamController.close(),e.currentWriteStream&&await Ot(e.currentWriteStream)}async function Yr(e,t){return new Promise((r,n)=>{e.write(t,o=>{o?n(o):r()})})}async function Ot(e){return new Promise(t=>{e.end(()=>t())})}async function It(e,t={}){let r=e.headers["content-type"]||"",n=Tt(r);if(!n){let{UnsupportedMediaTypeError:i}=await Promise.resolve().then(()=>(ve(),Ue));throw new i("Missing boundary in multipart content-type",{receivedContentType:r,expectedFormat:"multipart/form-data; boundary=..."})}let o=Ar(n,t);o.currentFilename!==void 0&&(o=await Vr(o));try{for await(let i of e)o=await $r(o,i);return Zr(o)}finally{await Jr(o)}}var X="Content-Type",D={json:512*1024,form:1024*1024,text:5*1024*1024,multipart:{maxFileSize:50*1024*1024,maxTotalSize:100*1024*1024,maxFiles:10,maxFieldSize:1024*1024},raw:10*1024*1024};function Kr(e){let t=e.url||"/",r=e.headers.host||"localhost",o=`${e.socket&&e.socket.encrypted?"https":"http"}://${r}${t.startsWith("/")?"":"/"}${t}`;try{let i=new URL(o),s=i.pathname,a={};return i.searchParams.forEach((u,l)=>{a[l]!==void 0?Array.isArray(a[l])?a[l].push(u):a[l]=[a[l],u]:a[l]=u}),{path:s,url:i,query:a}}catch(i){throw console.warn(`Invalid URL: ${o}`,i),new we(`Invalid URL: ${o}`)}}function Xr(e){return"stream"in e||"httpVersionMajor"in e&&e.httpVersionMajor===2}function en(e){let t=e.socket&&e.socket.encrypted,r=e.headers["x-forwarded-proto"];return r?Array.isArray(r)?r[0]?.split(",")[0]?.trim()||"http":r.split(",")[0]?.trim()||"http":t?"https":"http"}async function Nt(e,t,r={}){let{path:n,url:o,query:i}=Kr(e),s=e.method||"GET",a=Xr(e),u=en(e),l={},T={...r.initialState||{}},p={...r.initialServices||{}},S={sent:!1},m={request:tn(e,{path:n,url:o,query:i,params:l,method:s,isHttp2:a,protocol:u}),response:{},state:T,services:p};return m.response=nn(t,S,m),r.parseBody&&await mn(e,m,r),m}function tn(e,t){return{raw:e,...t,header:Dt(e),headers:rn(e),body:void 0}}function Dt(e){return t=>{let r=e.headers[t.toLowerCase()];return Array.isArray(r)?r.join(", "):r||void 0}}function rn(e){let t=Dt(e);return r=>r&&Array.isArray(r)&&r.length>0?r.reduce((n,o)=>(n[o]=t(o),n),{}):Object.entries(e.headers).reduce((n,[o,i])=>(n[o]=Array.isArray(i)?i.join(", "):i||void 0,n),{})}function ee(e,t){if(t.correlationId){let r=H(),n=String(t.correlationId);e.setHeader(r,n)}}function nn(e,t,r){return{raw:e,get statusCode(){return e.statusCode||200},get sent(){return t.sent},status:on(e,t,r),header:sn(e,t,r),headers:an(e,t,r),type:un(e,t,r),json:cn(e,t,r.state),text:ln(e,t,r.state),html:dn(e,t,r.state),redirect:pn(e,t,r.state),stream:fn(e,t,r.state)}}function on(e,t,r){return function(o){if(t.sent)throw new C;return e.statusCode=o,r.response}}function sn(e,t,r){return function(o,i){if(t.sent)throw new G;return e.setHeader(o,i),r.response}}function an(e,t,r){return function(o){if(t.sent)throw new G;for(let[i,s]of Object.entries(o))e.setHeader(i,s);return r.response}}function un(e,t,r){return function(o){if(t.sent)throw new Se;return e.setHeader(X,o),r.response}}function cn(e,t,r){return function(o,i){if(t.sent)throw new C;i!==void 0&&(e.statusCode=i),ee(e,r),e.setHeader(X,"application/json"),e.end(JSON.stringify(o)),t.sent=!0}}function ln(e,t,r){return function(o,i){if(t.sent)throw new C;i!==void 0&&(e.statusCode=i),ee(e,r),e.setHeader(X,"text/plain"),e.end(o),t.sent=!0}}function dn(e,t,r){return function(o,i){if(t.sent)throw new C;i!==void 0&&(e.statusCode=i),ee(e,r),e.setHeader(X,"text/html"),e.end(o),t.sent=!0}}function pn(e,t,r){return function(o,i=302){if(t.sent)throw new C;ee(e,r),e.statusCode=i,e.setHeader("Location",o),e.end(),t.sent=!0}}function fn(e,t,r){return function(o,i={}){if(t.sent)throw new C;if(i.status!==void 0&&(e.statusCode=i.status),ee(e,r),i.contentType&&e.setHeader(X,i.contentType),i.headers)for(let[s,a]of Object.entries(i.headers))e.setHeader(s,a);o.pipe(e),o.on("end",()=>{t.sent=!0}),o.on("error",s=>{console.error("Stream error:",s),t.sent||(e.statusCode=500,e.end("Stream error"),t.sent=!0)})}}async function mn(e,t,r={}){if(gn(e.method))return;let n=e.headers["content-type"]||"",o=parseInt(e.headers["content-length"]||"0",10);if(o===0)return;let i={json:r.bodyLimits?.json??D.json,form:r.bodyLimits?.form??D.form,text:r.bodyLimits?.text??D.text,raw:r.bodyLimits?.raw??D.raw,multipart:{maxFileSize:r.bodyLimits?.multipart?.maxFileSize??D.multipart.maxFileSize,maxFiles:r.bodyLimits?.multipart?.maxFiles??D.multipart.maxFiles,maxFieldSize:r.bodyLimits?.multipart?.maxFieldSize??D.multipart.maxFieldSize,maxTotalSize:r.bodyLimits?.multipart?.maxTotalSize??D.multipart.maxTotalSize}};try{if(n.includes("application/json")){if(o>i.json)throw new Error(`JSON body too large: ${o} > ${i.json} bytes`);await yn(e,t)}else if(n.includes("application/x-www-form-urlencoded")){if(o>i.form)throw new Error(`Form body too large: ${o} > ${i.form} bytes`);await hn(e,t)}else if(n.includes("text/")){if(o>i.text)throw new Error(`Text body too large: ${o} > ${i.text} bytes`);await wn(e,t)}else if(vt(n))await Tn(e,t,i.multipart);else{if(o>i.raw)throw new Error(`Request body too large: ${o} > ${i.raw} bytes`);return}}catch(s){let a=n.includes("multipart")?"multipart_parse_error":"body_read_error";Ee(t,a,"Error reading request body",s)}}function gn(e){return["GET","HEAD","OPTIONS"].includes(e||"GET")}async function yn(e,t){let r=await He(e);if(!r){console.warn("Empty body, skipping JSON parsing");return}if(r.trim()==="null"){console.warn('Body is the string "null"'),t.request.body=null;return}try{let n=JSON.parse(r);t.request.body=n}catch(n){t.request.body=null,Ee(t,"json_parse_error","Invalid JSON in request body",n)}}async function hn(e,t){let r=await He(e);if(r)try{t.request.body=Sn(r)}catch(n){t.request.body=null,Ee(t,"form_parse_error","Invalid form data in request body",n)}}function Sn(e){let t=new URLSearchParams(e),r={};return t.forEach((n,o)=>{r[o]!==void 0?Array.isArray(r[o])?r[o].push(n):r[o]=[r[o],n]:r[o]=n}),r}async function wn(e,t){let r=await He(e);r&&(t.request.body=r)}async function Tn(e,t,r){try{let n=r||D.multipart,o=await It(e,{strategy:"stream",maxFileSize:n.maxFileSize,maxFiles:n.maxFiles,maxFieldSize:n.maxFieldSize});t.request.multipart=o,t.request.files=o.files,t.request.body=o.fields}catch(n){t.request.body=null,Ee(t,"multipart_parse_error","Failed to parse multipart data",n)}}function Ee(e,t,r,n){let o={type:t,message:r,error:n};e.state._bodyError=o}async function He(e){return new Promise((t,r)=>{let n=[];e.on("data",o=>{n.push(Buffer.isBuffer(o)?o:Buffer.from(o))}),e.on("end",()=>{t(Buffer.concat(n).toString("utf8"))}),e.on("error",o=>{r(o)})})}P();v();var z=class extends h{constructor(t,r=void 0,n=void 0){super("NOT_FOUND",t,404,n??y(),r)}};P();Z();v();function xn(e){return e instanceof h}function zt(e){if(xn(e))return{type:e.type,title:e.title,status:e.status,correlationId:e.correlationId,timestamp:e.timestamp.toISOString(),details:e.details};let t=y(),r;e instanceof Error?r=e.message:e==null?r="Unknown error occurred":r=String(e);let n=new O("Internal Server Error",{originalMessage:r},t);return{type:n.type,title:n.title,status:n.status,correlationId:n.correlationId,timestamp:n.timestamp.toISOString(),details:n.details}}function Bt(e){let t=H(),r={[t]:e(t)};return xe(r)}function At(e,t){let r=H();e(r,t)}function $t(e={}){let{debug:t=!1}=e;return{name:"ErrorBoundary",execute:async(n,o)=>{try{await o()}catch(i){if(n.response.sent){t&&console.error("Error occurred after response was sent:",i);return}t&&console.error("Error boundary caught error:",i);let s=Bt(n.request.header),a=zt(i);a.correlationId=s,At(n.response.header,s),n.response.status(a.status).json(a)}},debug:t}}v();function _t(e){return async(t,r)=>{let n=xe(t.headers);try{await wt(n,async()=>{let o=await Nt(t,r,{parseBody:!0,initialState:{correlationId:n}}),s=[$t(),...e.middleware],a=_(s);await gt(o,async()=>{await a(o,async()=>{if(!o.response.sent&&(await e.router.handleRequest(o),!o.response.sent))throw new z(`Route not found: ${o.request.method} ${o.request.path}`)})})})}catch(o){console.error("Error creating context:",o);let i=H();"stream"in r&&typeof r.stream?.respond=="function"?(r.stream.respond({":status":500,"content-type":"application/json",[i.toLowerCase()]:n}),r.stream.end(JSON.stringify({error:"Internal Server Error",message:"Failed to process request",correlationId:n}))):(r.setHeader(i,n),r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Internal Server Error",message:"Failed to process request",correlationId:n})))}}}async function Rn(e){if(!e.enabled)return{};let{keyFile:t,certFile:r}=e,n=process.env.NODE_ENV==="development",o=!t||!r;if(o&&n)return await ft();if(o)throw new Error("HTTP/2 requires SSL certificates. Provide keyFile and certFile in http2 options. In development, set NODE_ENV=development to generate them automatically.");return{keyFile:t,certFile:r}}function vn(e,t){if(!e)return Ut.createServer();let r={allowHTTP1:!0};try{t.keyFile&&(r.key=qe.readFileSync(t.keyFile)),t.certFile&&(r.cert=qe.readFileSync(t.certFile))}catch(n){throw new Error(`Failed to read certificate files: ${n instanceof Error?n.message:String(n)}`)}return Lt.createSecureServer(r)}function En(e,t,r,n){return new Promise((o,i)=>{e.listen(t,r,()=>{let a=`${n?"https":"http"}://${r}:${t}`;console.log(`
16
16
  \u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}
17
17
 
18
18
  \u26A1 BlaizeJS DEVELOPMENT SERVER HOT AND READY \u26A1
@@ -24,8 +24,8 @@
24
24
  Time to build something amazing! \u{1F680}
25
25
 
26
26
  \u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}
27
- `),n()}),e.on("error",s=>{console.error("Server error:",s),i(s)})})}async function fo(e){for(let t of e.plugins)typeof t.initialize=="function"&&await t.initialize(e)}async function Ot(e,t){if(!e.server)try{let r=t.port,o=t.host;await fo(e);let n=t.http2||{enabled:!0},i=!!n.enabled,s=await lo(n);t.http2&&s.keyFile&&s.certFile&&(t.http2.keyFile=s.keyFile,t.http2.certFile=s.certFile);let a=co(i,s);e.server=a,e.port=r,e.host=o;let u=Ct(e);a.on("request",u),await po(a,r,o,i)}catch(r){throw console.error("Failed to start server:",r),r}}var pe=!1;async function Dt(e,t={}){let r=e.server,o=e.events;if(pe){console.log("\u26A0\uFE0F Shutdown already in progress, ignoring duplicate shutdown request");return}if(!r)return;pe=!0;let n=t.timeout||5e3;try{if(t.onStopping&&await t.onStopping(),o.emit("stopping"),e.router&&typeof e.router.close=="function"){console.log("\u{1F50C} Closing router watchers...");try{await Promise.race([e.router.close(),new Promise((a,u)=>setTimeout(()=>u(new Error("Router close timeout")),2e3))]),console.log("\u2705 Router watchers closed")}catch(a){console.error("\u274C Error closing router watchers:",a)}}try{await Promise.race([e.pluginManager.onServerStop(e,r),new Promise((a,u)=>setTimeout(()=>u(new Error("Plugin stop timeout")),2e3))])}catch(a){console.error("\u274C Plugin stop timeout:",a)}let i=new Promise((a,u)=>{r.close(c=>{if(c)return u(c);a()})}),s=new Promise((a,u)=>{setTimeout(()=>{u(new Error("Server shutdown timeout"))},n)});await Promise.race([i,s]);try{await Promise.race([e.pluginManager.terminatePlugins(e),new Promise((a,u)=>setTimeout(()=>u(new Error("Plugin terminate timeout")),1e3))])}catch(a){console.error("\u274C Plugin terminate timeout:",a)}t.onStopped&&await t.onStopped(),o.emit("stopped"),e.server=null,console.log("\u2705 Graceful shutdown completed"),pe=!1}catch(i){throw pe=!1,console.error("\u26A0\uFE0F Shutdown error (forcing exit):",i),r&&typeof r.close=="function"&&r.close(),process.env.NODE_ENV==="development"&&(console.log("\u{1F504} Forcing exit for development restart..."),process.exit(0)),o.emit("error",i),i}}function kt(e){if(process.env.NODE_ENV==="development"){let r=()=>{console.log("\u{1F4E4} SIGINT received, forcing exit for development restart..."),process.exit(0)},o=()=>{console.log("\u{1F4E4} SIGTERM received, forcing exit for development restart..."),process.exit(0)};return process.on("SIGINT",r),process.on("SIGTERM",o),{unregister:()=>{process.removeListener("SIGINT",r),process.removeListener("SIGTERM",o)}}}else{let r=()=>{console.log("\u{1F4E4} SIGINT received, starting graceful shutdown..."),e().catch(console.error)},o=()=>{console.log("\u{1F4E4} SIGTERM received, starting graceful shutdown..."),e().catch(console.error)};return process.on("SIGINT",r),process.on("SIGTERM",o),{unregister:()=>{process.removeListener("SIGINT",r),process.removeListener("SIGTERM",o)}}}}var b=require("zod"),mo=b.z.custom(e=>e!==null&&typeof e=="object"&&"execute"in e&&typeof e.execute=="function",{message:"Expected middleware to have an execute function"}),go=b.z.custom(e=>e!==null&&typeof e=="object"&&"register"in e&&typeof e.register=="function",{message:"Expected a valid plugin object with a register method"}),yo=b.z.object({enabled:b.z.boolean().optional().default(!0),keyFile:b.z.string().optional(),certFile:b.z.string().optional()}).refine(e=>e.enabled&&process.env.NODE_ENV==="production"?e.keyFile&&e.certFile:!0,{message:"When HTTP/2 is enabled (outside of development mode), both keyFile and certFile must be provided"}),ho=b.z.object({port:b.z.number().int().positive().optional().default(3e3),host:b.z.string().optional().default("localhost"),routesDir:b.z.string().optional().default("./routes"),http2:yo.optional().default({enabled:!0}),middleware:b.z.array(mo).optional().default([]),plugins:b.z.array(go).optional().default([])});function zt(e){try{return ho.parse(e)}catch(t){if(t instanceof b.z.ZodError){let r=t.format();throw new Error(`Invalid server options: ${JSON.stringify(r,null,2)}`)}throw new Error(`Invalid server options: ${String(t)}`)}}function Bt(e={}){let{continueOnError:t=!0,debug:r=!1,onError:o}=e;function n(s,...a){r&&console.log(`[PluginLifecycle] ${s}`,...a)}function i(s,a,u){let c=`Plugin ${s.name} failed during ${a}: ${u.message}`;if(o?o(s,a,u):console.error(c,u),!t)throw new Error(c)}return{async initializePlugins(s){n("Initializing plugins...");for(let a of s.plugins)if(a.initialize)try{n(`Initializing plugin: ${a.name}`),await a.initialize(s)}catch(u){i(a,"initialize",u)}n(`Initialized ${s.plugins.length} plugins`)},async terminatePlugins(s){n("Terminating plugins...");let a=[...s.plugins].reverse();for(let u of a)if(u.terminate)try{n(`Terminating plugin: ${u.name}`),await u.terminate(s)}catch(c){i(u,"terminate",c)}n(`Terminated ${a.length} plugins`)},async onServerStart(s,a){n("Notifying plugins of server start...");for(let u of s.plugins)if(u.onServerStart)try{n(`Notifying plugin of server start: ${u.name}`),await u.onServerStart(a)}catch(c){i(u,"onServerStart",c)}},async onServerStop(s,a){n("Notifying plugins of server stop...");let u=[...s.plugins].reverse();for(let c of u)if(c.onServerStop)try{n(`Notifying plugin of server stop: ${c.name}`),await c.onServerStop(a)}catch(S){i(c,"onServerStop",S)}}}}var F=class extends Error{constructor(r,o){super(`Plugin validation error${r?` for "${r}"`:""}: ${o}`);this.pluginName=r;this.name="PluginValidationError"}};var wo=new Set(["core","server","router","middleware","context","blaize","blaizejs"]),Ro=/^[a-z]([a-z0-9-]*[a-z0-9])?$/,So=/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9-.]+)?(?:\+[a-zA-Z0-9-.]+)?$/;function $t(e,t={}){let{requireVersion:r=!0,validateNameFormat:o=!0,checkReservedNames:n=!0}=t;if(!e||typeof e!="object")throw new F("","Plugin must be an object");let i=e;if(!i.name||typeof i.name!="string")throw new F("","Plugin must have a name (string)");if(o&&!Ro.test(i.name))throw new F(i.name,"Plugin name must be lowercase letters, numbers, and hyphens only");if(n&&wo.has(i.name.toLowerCase()))throw new F(i.name,`Plugin name "${i.name}" is reserved`);if(r){if(!i.version||typeof i.version!="string")throw new F(i.name,"Plugin must have a version (string)");if(!So.test(i.version))throw new F(i.name,'Plugin version must follow semantic versioning (e.g., "1.0.0")')}if(!i.register||typeof i.register!="function")throw new F(i.name,"Plugin must have a register method (function)");let s=["initialize","terminate","onServerStart","onServerStop"];for(let a of s)if(i[a]&&typeof i[a]!="function")throw new F(i.name,`Plugin ${a} must be a function if provided`)}var It=T(require("crypto"),1),_t=T(require("fs/promises"),1),At=require("module"),Ut=T(require("path"),1);async function To(e){let t=`?t=${Date.now()}`,r=e+t;try{let o=await import(r);return console.log("\u2705 Successfully imported module"),o}catch(o){let n=o instanceof Error?o.message:String(o);return console.log("\u26A0\uFE0F Error importing with cache buster, trying original path:",n),import(e)}}async function Nt(e,t){try{let r=ie(e,t),o=await To(e);console.log("\u{1F4E6} Module exports:",Object.keys(o));let n=[];if(o.default&&typeof o.default=="object"){let i={...o.default,path:r.routePath};n.push(i)}return Object.entries(o).forEach(([i,s])=>{if(i==="default"||!s||typeof s!="object")return;let a=s;if(Eo(a)){let u={...a,path:r.routePath};n.push(u)}}),n.length===0?(console.warn(`Route file ${e} does not export any valid route definitions`),[]):(console.log(`\u2705 Successfully Loaded ${n.length} route(s)`),n)}catch(r){return console.error(`Failed to load route module ${e}:`,r),[]}}function Eo(e){return!e||typeof e!="object"?!1:["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"].some(o=>e[o]&&typeof e[o]=="object"&&e[o].handler)}var bo={},K=new Map;async function X(e,t,r=!0){let n=(await _t.stat(e)).mtime.getTime(),i=K.get(e);if(r&&i&&i.timestamp===n)return i.routes;xo(e);let s=await Nt(e,t);if(r){let a=Ht(s);K.set(e,{routes:s,timestamp:n,hash:a})}return s}function Lt(e,t){let r=K.get(e);if(!r)return!0;let o=Ht(t);return r.hash!==o}function Ie(e){e?K.delete(e):K.clear()}function Ht(e){let t=e.map(n=>({path:n.path,methods:Object.keys(n).filter(i=>i!=="path").sort().map(i=>{let s=n[i],a=s?.handler?s.handler.toString():null;return{method:i,handler:a,middleware:s?.middleware?s.middleware.length:0,hasSchema:!!s?.schema,schemaKeys:s?.schema?Object.keys(s.schema).sort():[]}})})),r=JSON.stringify(t);return It.createHash("md5").update(r).digest("hex")}function xo(e){try{let t=Ut.resolve(e);if(typeof require<"u"){delete require.cache[t];try{let r=require.resolve(t);delete require.cache[r]}catch(r){let o=r instanceof Error?r.message:String(r);console.log(`\u26A0\uFE0F Could not resolve path: ${o}`)}}else try{let r=(0,At.createRequire)(bo.url);delete r.cache[t];try{let o=r.resolve(t);delete r.cache[o]}catch{console.log("\u26A0\uFE0F Could not resolve ESM path")}}catch{console.log("\u26A0\uFE0F createRequire not available in pure ESM")}}catch(t){console.log(`\u26A0\uFE0F Error during module cache invalidation for ${e}:`,t)}}var qt=T(require("os"),1);var fe=T(require("fs/promises"),1),j=T(require("path"),1);async function me(e,t={}){let r=j.isAbsolute(e)?e:j.resolve(process.cwd(),e);console.log("Creating router with routes directory:",r);try{if(!(await fe.stat(r)).isDirectory())throw new Error(`Route directory is not a directory: ${r}`)}catch(s){throw s.code==="ENOENT"?new Error(`Route directory not found: ${r}`):s}let o=[],n=t.ignore||["node_modules",".git"];async function i(s){let a=await fe.readdir(s,{withFileTypes:!0});for(let u of a){let c=j.join(s,u.name);u.isDirectory()&&n.includes(u.name)||(u.isDirectory()?await i(c):Po(u.name)&&o.push(c))}}return await i(r),o}function Po(e){return!e.startsWith("_")&&(e.endsWith(".ts")||e.endsWith(".js"))}async function vo(e,t,r=Math.max(1,Math.floor(qt.cpus().length/2))){let o=Co(e,r),n=[];for(let i of o){let a=(await Promise.allSettled(i.map(u=>t(u)))).filter(u=>u.status==="fulfilled").map(u=>u.value);n.push(...a)}return n}async function jt(e){let t=await me(e);return(await vo(t,o=>X(o,e))).flat()}function Co(e,t){let r=[];for(let o=0;o<e.length;o+=t)r.push(e.slice(o,o+t));return r}var N={fileChanges:0,totalReloadTime:0,averageReloadTime:0,slowReloads:[]};function Qt(e,t){let r=Date.now()-t;if(N.fileChanges++,N.totalReloadTime+=r,N.averageReloadTime=N.totalReloadTime/N.fileChanges,r>100&&(N.slowReloads.push({file:e,time:r}),N.slowReloads.length>10&&N.slowReloads.shift()),process.env.NODE_ENV==="development"){let o=r<50?"\u26A1":r<100?"\u{1F504}":"\u{1F40C}";console.log(`${o} Route reload: ${e} (${r}ms)`)}}function _e(e,t){return console.log(`Tracking performance for: ${t}`),async(...r)=>{let o=Date.now();try{let n=await e(...r);return Qt(t,o),n}catch(n){throw Qt(t,o),n}}}var Ae=T(require("path"),1),Vt=require("chokidar");function Ue(e,t={}){let r=t.debounceMs||16,o=new Map;function n(p,g){return(...y)=>{let l=o.get(g);l&&clearTimeout(l);let d=setTimeout(()=>{p(...y),o.delete(g)},r);o.set(g,d)}}let i=new Map;async function s(){try{let p=await me(e,{ignore:t.ignore});for(let g of p)await a(g)}catch(p){c(p)}}async function a(p){try{let g=i.get(p),y=await X(p,e,!1);if(!y||y.length===0||g&&!Lt(p,y))return;await X(p,e,!0);let l=Ae.normalize(p);g?(i.set(p,y),t.onRouteChanged&&t.onRouteChanged(l,y)):(i.set(p,y),t.onRouteAdded&&t.onRouteAdded(l,y))}catch(g){console.log(`\u26A0\uFE0F Error processing file ${p}:`,g),c(g)}}function u(p){let g=Ae.normalize(p),y=i.get(g);y&&y.length>0&&t.onRouteRemoved&&t.onRouteRemoved(g,y),i.delete(g)}function c(p){t.onError&&p instanceof Error?t.onError(p):console.error("\u26A0\uFE0F Route watcher error:",p)}let S=(0,Vt.watch)(e,{awaitWriteFinish:{stabilityThreshold:50,pollInterval:10},usePolling:!1,atomic:!0,followSymlinks:!1,depth:10,ignored:[/(^|[/\\])\../,/node_modules/,/\.git/,/\.DS_Store/,/Thumbs\.db/,/\.(test|spec)\.(ts|js)$/,/\.d\.ts$/,/\.map$/,/~$/,...t.ignore||[]]});return S.on("add",p=>{n(a,p)(p)}).on("change",p=>{n(a,p)(p)}).on("unlink",p=>{n(u,p)(p)}).on("error",c),s().catch(c),{close:()=>(o.forEach(p=>clearTimeout(p)),o.clear(),S.close()),getRoutes:()=>{let p=[];for(let g of i.values())p.push(...g);return p},getRoutesByFile:()=>new Map(i)}}var Yt=require("zod");var Wt=require("zod");function Le(e,t){return t instanceof Wt.z.ZodObject?t.strict().parse(e):t.parse(e)}var Gt=require("zod");function He(e,t){return t instanceof Gt.z.ZodObject?t.strict().parse(e):t.parse(e)}var Zt=require("zod");function qe(e,t){return t instanceof Zt.z.ZodObject?t.strict().parse(e):t.parse(e)}var Jt=require("zod");function je(e,t){return t instanceof Jt.z.ZodObject?t.strict().parse(e):t.parse(e)}W();z();function Qe(e,t=!1){return{name:"RequestValidator",execute:async(o,n)=>{if(e.params&&o.request.params)try{o.request.params=He(o.request.params,e.params)}catch(i){let s=ge(i),a=s.reduce((u,c)=>u+c.messages.length,0);throw new k("Request validation failed",{fields:s,errorCount:a,section:"params"})}if(e.query&&o.request.query)try{o.request.query=qe(o.request.query,e.query)}catch(i){let s=ge(i),a=s.reduce((u,c)=>u+c.messages.length,0);throw new k("Request validation failed",{fields:s,errorCount:a,section:"query"})}if(e.body)try{o.request.body=Le(o.request.body,e.body)}catch(i){let s=ge(i),a=s.reduce((u,c)=>u+c.messages.length,0);throw new k("Request validation failed",{fields:s,errorCount:a,section:"body"})}await n()},debug:t}}function Ve(e,t=!1){return{name:"ResponseValidator",execute:async(o,n)=>{let i=o.response.json;o.response.json=(s,a)=>{try{let u=je(s,e);return o.response.json=i,i.call(o.response,u,a)}catch(u){throw o.response.json=i,new D("Response validation failed",{responseSchema:e.description||"Unknown schema",validationError:ge(u),originalResponse:s})}},await n()},debug:t}}function ge(e){if(e instanceof Yt.z.ZodError){let t=new Map;for(let r of e.issues){let o=r.path.length>0?r.path.join("."):"root";t.has(o)||t.set(o,[]),t.get(o).push(r.message)}return Array.from(t.entries()).map(([r,o])=>({field:r,messages:o}))}return e instanceof Error?[{field:"unknown",messages:[e.message]}]:[{field:"unknown",messages:[String(e)]}]}async function We(e,t,r){let o=[...t.middleware||[]];t.schema&&((t.schema.params||t.schema.query||t.schema.body)&&o.unshift(Qe(t.schema)),t.schema.response&&o.push(Ve(t.schema.response))),await A([...o])(e,async()=>{let i=await t.handler(e,r);!e.response.sent&&i!==void 0&&e.response.json(i)})}function ye(e,t,r){let o=t.exec(e);if(!o)return{};let n={};for(let i=0;i<r.length;i++)n[r[i]]=o[i+1]||"";return n}function Ge(e){let t=[];if(e==="/")return{pattern:/^\/$/,paramNames:[]};let r=e.replace(/([.+*?^$(){}|\\])/g,"\\$1");return r=r.replace(/\/:([^/]+)/g,(n,i)=>(t.push(i),"/([^/]+)")).replace(/\/\[([^\]]+)\]/g,(n,i)=>(t.push(i),"/([^/]+)")),r=`${r}(?:/)?`,{pattern:new RegExp(`^${r}$`),paramNames:t}}function Ze(){let e=[];return{add(t,r,o){let{pattern:n,paramNames:i}=Ge(t),s={path:t,method:r,pattern:n,paramNames:i,routeOptions:o},a=e.findIndex(u=>i.length<u.paramNames.length);a===-1?e.push(s):e.splice(a,0,s)},remove(t){for(let r=e.length-1;r>=0;r--)e[r].path===t&&e.splice(r,1)},clear(){e.length=0},match(t,r){let o=t.split("?")[0];if(!o)return null;for(let i of e){if(i.method!==r)continue;if(i.pattern.exec(o)){let a=ye(t,i.pattern,i.paramNames);return{route:i.routeOptions,params:a}}}return e.find(i=>i.method!==r&&i.pattern.test(t))?{route:null,params:{},methodNotAllowed:!0,allowedMethods:e.filter(i=>i.pattern.test(t)).map(i=>i.method)}:null},getRoutes(){return e.map(t=>({path:t.path,method:t.method}))},findRoutes(t){return e.filter(r=>r.pattern.test(t)).map(r=>({path:r.path,method:r.method,params:ye(t,r.pattern,r.paramNames)}))}}}function Kt(){return{routesByPath:new Map,routesByFile:new Map,pathToFile:new Map}}function I(e,t,r){console.log(`Updating routes from file: ${t}`);let o=e.routesByFile.get(t)||new Set,n=new Set(r.map(c=>c.path)),i=r.filter(c=>!o.has(c.path)),s=Array.from(o).filter(c=>!n.has(c)),u=r.filter(c=>o.has(c.path)).filter(c=>{let S=e.routesByPath.get(c.path);return!S||!Mo(S,c)});return Fo(e,t,{added:i,removed:s,changed:u}),{added:i,removed:s,changed:u}}function Xt(e){return Array.from(e.routesByPath.values())}function Fo(e,t,r){let{added:o,removed:n,changed:i}=r;n.forEach(a=>{e.routesByPath.delete(a),e.pathToFile.delete(a)}),[...o,...i].forEach(a=>{e.routesByPath.set(a.path,a),e.pathToFile.set(a.path,t)});let s=new Set([...o.map(a=>a.path),...i.map(a=>a.path),...Array.from(e.routesByFile.get(t)||[]).filter(a=>!n.includes(a))]);s.size>0?e.routesByFile.set(t,s):e.routesByFile.delete(t)}function Mo(e,t){if(e.path!==t.path)return!1;let r=Object.keys(e).filter(n=>n!=="path").sort(),o=Object.keys(t).filter(n=>n!=="path").sort();return r.length!==o.length?!1:r.every(n=>{let i=e[n],s=t[n];return typeof i==typeof s})}function Je(e,t){Object.entries(e).forEach(([r,o])=>{r==="path"||!o||t.add(e.path,r,o)})}function ee(e,t){"remove"in t&&typeof t.remove=="function"?t.remove(e):console.warn("Matcher does not support selective removal, consider adding remove() method")}function er(e,t){ee(e.path,t),Je(e,t)}var Oo={routesDir:"./routes",basePath:"/",watchMode:process.env.NODE_ENV==="development"};function tr(e){let t={...Oo,...e};e.basePath&&!e.basePath.startsWith("/")&&console.warn("Base path does nothing");let r=Kt(),o=Ze(),n=!1,i=null,s=null,a=new Set([t.routesDir]);function u(l){console.log(`
28
- \u{1F527} APPLYING MATCHER CHANGES:`),console.log(` Adding ${l.added.length} routes`),console.log(` Removing ${l.removed.length} routes`),console.log(` Updating ${l.changed.length} routes`),l.removed.forEach(d=>{console.log(` \u2796 Removing: ${d}`),ee(d,o)}),l.added.forEach(d=>{let m=Object.keys(d).filter(f=>f!=="path");console.log(` \u2795 Adding: ${d.path} [${m.join(", ")}]`),Je(d,o)}),l.changed.forEach(d=>{let m=Object.keys(d).filter(f=>f!=="path");console.log(` \u{1F504} Updating: ${d.path} [${m.join(", ")}]`),er(d,o)}),console.log(`\u2705 Matcher changes applied
29
- `)}function c(l,d){try{let m=I(r,d,l);return u(m),m}catch(m){throw console.error(`\u26A0\uFE0F Route conflicts from ${d}:`,m),m}}async function S(l,d,m){try{let f=await jt(l),w=f.map(M=>m?{...M,path:`${m}${M.path}`}:M),E=c(w,d);console.log(`Loaded ${f.length} routes from ${d}${m?` with prefix ${m}`:""} (${E.added.length} added, ${E.changed.length} changed, ${E.removed.length} removed)`)}catch(f){throw console.error(`\u26A0\uFE0F Failed to load routes from ${d}:`,f),f}}async function p(){return n||i||(i=(async()=>{try{await Promise.all(Array.from(a).map(l=>S(l,l))),t.watchMode&&g(),n=!0}catch(l){throw console.error("\u26A0\uFE0F Failed to initialize router:",l),l}})()),i}function g(){s||(s=new Map);for(let l of a)if(!s.has(l)){let d=Ue(l,{debounceMs:16,ignore:["node_modules",".git"],onRouteAdded:(m,f)=>{try{let w=I(r,m,f);u(w)}catch(w){console.error(`Error adding routes from ${l}:`,w)}},onRouteChanged:_e(async(m,f)=>{try{console.log(`Processing changes for ${m}`);let w=I(r,m,f);console.log(`Changes detected: ${w.added.length} added, ${w.changed.length} changed, ${w.removed.length} removed`),u(w),console.log(`Route changes applied: ${w.added.length} added, ${w.changed.length} changed, ${w.removed.length} removed`)}catch(w){console.error(`\u26A0\uFE0F Error updating routes from ${l}:`,w)}},l),onRouteRemoved:(m,f)=>{console.log(`File removed: ${m} with ${f.length} routes`);try{f.forEach(w=>{ee(w.path,o)}),Ie(m)}catch(w){console.error(`\u26A0\uFE0F Error removing routes from ${m}:`,w)}},onError:m=>{console.error(`\u26A0\uFE0F Route watcher error for ${l}:`,m)}});s.set(l,d)}}function y(l,d){s||(s=new Map);let m=Ue(l,{debounceMs:16,ignore:["node_modules",".git"],onRouteAdded:(f,w)=>{try{let E=w.map(_=>d?{..._,path:`${d}${_.path}`}:_),M=I(r,f,E);u(M)}catch(E){console.error(`\u26A0\uFE0F Error adding routes from ${l}:`,E)}},onRouteChanged:_e(async(f,w)=>{try{let E=w.map(_=>d?{..._,path:`${d}${_.path}`}:_),M=I(r,f,E);u(M)}catch(E){console.error(`\u26A0\uFE0F Error updating routes from ${l}:`,E)}},l),onRouteRemoved:(f,w)=>{try{w.forEach(E=>{let M=d?`${d}${E.path}`:E.path;ee(M,o)}),Ie(f)}catch(E){console.error(`Error removing routes from ${f}:`,E)}},onError:f=>{console.error(`\u26A0\uFE0F Route watcher error for ${l}:`,f)}});return s.set(l,m),m}return p().catch(l=>{console.error("\u26A0\uFE0F Failed to initialize router on creation:",l)}),{async handleRequest(l){n||(console.log("\u{1F504} Router not initialized, initializing..."),await p());let{method:d,path:m}=l.request;console.log(`
30
- \u{1F4E5} Handling request: ${d} ${m}`);let f=o.match(m,d);if(!f)throw console.log(`\u274C No match found for: ${d} ${m}`),new $("Not found");if(console.log(`\u2705 Route matched: ${d} ${m}`),console.log(` Params: ${JSON.stringify(f.params)}`),f.methodNotAllowed){l.response.status(405).json({error:"\u274C Method Not Allowed",allowed:f.allowedMethods}),f.allowedMethods&&f.allowedMethods.length>0&&l.response.header("Allow",f.allowedMethods.join(", "));return}l.request.params=f.params,await We(l,f.route,f.params)},getRoutes(){return Xt(r)},addRoute(l){let d=I(r,"programmatic",[l]);u(d)},addRoutes(l){let d=I(r,"programmatic",l);return u(d),d},async addRouteDirectory(l,d={}){if(a.has(l)){console.warn(`Route directory ${l} already registered`);return}a.add(l),n&&(await S(l,l,d.prefix),t.watchMode&&y(l,d.prefix))},getRouteConflicts(){return[]},async close(){if(s){for(let l of s.values())await l.close();s.clear()}}}}var Do={port:3e3,host:"localhost",routesDir:"./routes",http2:{enabled:!0},middleware:[],plugins:[]};function ko(e={}){let t={...Do};return Xe({routesDir:e.routesDir||t.routesDir}),{port:e.port??t.port,host:e.host??t.host,routesDir:e.routesDir??t.routesDir,http2:{enabled:e.http2?.enabled??t.http2?.enabled,keyFile:e.http2?.keyFile??t.http2?.keyFile,certFile:e.http2?.certFile??t.http2?.certFile},middleware:[...t.middleware||[],...e.middleware||[]],plugins:[...t.plugins||[],...e.plugins||[]]}}function zo(e,t,r,o){return async()=>(await Bo(e,r,o),await e.pluginManager.initializePlugins(e),await Ot(e,t),await e.pluginManager.onServerStart(e,e.server),$o(e),e)}async function Bo(e,t,r){for(let o of t)e.use(o);for(let o of r)await e.register(o)}function $o(e){let t=kt(()=>e.close());e._signalHandlers=t,e.events.emit("started")}function No(e){return async t=>{if(!e.server)return;let r={...t};e._signalHandlers&&(e._signalHandlers.unregister(),delete e._signalHandlers),await Dt(e,r)}}function Io(e){return t=>{let r=Array.isArray(t)?t:[t];return e.middleware.push(...r),e}}function _o(e){return async t=>($t(t),e.plugins.push(t),await t.register(e),e)}function he(e={}){let t=ko(e),r;try{r=zt(t)}catch(l){throw l instanceof Error?new Error(`Failed to create server: ${l.message}`):new Error(`Failed to create server: ${String(l)}`)}let{port:o,host:n,middleware:i,plugins:s}=r,a=Array.isArray(i)?[...i]:[],u=Array.isArray(s)?[...s]:[],c=new rr.AsyncLocalStorage,S=tr({routesDir:r.routesDir,watchMode:process.env.NODE_ENV==="development"}),p=Bt({debug:process.env.NODE_ENV==="development",continueOnError:!0}),g=new or.default,y={server:null,port:o,host:n,context:c,events:g,plugins:[],middleware:[],_signalHandlers:{unregister:()=>{}},use:()=>y,register:async()=>y,listen:async()=>y,close:async()=>{},router:S,pluginManager:p};return y.listen=zo(y,r,a,u),y.close=No(y),y.use=Io(y),y.register=_o(y),y}x();z();x();v();var we=class extends h{constructor(t,r=void 0,o=void 0){super("UNAUTHORIZED",t,401,o??R(),r)}};x();v();var Re=class extends h{constructor(t,r=void 0,o=void 0){super("FORBIDDEN",t,403,o??R(),r)}};x();v();var Se=class extends h{constructor(t,r=void 0,o=void 0){super("CONFLICT",t,409,o??R(),r)}};x();v();var Te=class extends h{constructor(t,r=void 0,o=void 0){super("RATE_LIMITED",t,429,o??R(),r)}};W();le();v();x();var Ee=class extends h{constructor(t,r,o){super("UPLOAD_TIMEOUT",t,408,o??R(),r)}};ce();v();x();var xe=class extends h{constructor(t,r,o){super("UNPROCESSABLE_ENTITY",t,422,o??R(),r)}};var nr="0.1.0",ir={createServer:he},sr={createDeleteRoute:Ce,createGetRoute:be,createHeadRoute:Me,createOptionsRoute:Oe,createPatchRoute:Fe,createPostRoute:Pe,createPutRoute:ve},ar={createMiddleware:re,compose:A},ur={createPlugin:oe},Ao={createServer:he,createMiddleware:re,createPlugin:oe,Server:ir,Router:sr,Middleware:ar,Plugins:ur,VERSION:nr};0&&(module.exports={Blaize,BlaizeError,ConflictError,ErrorSeverity,ErrorType,ForbiddenError,InternalServerError,MiddlewareAPI,NotFoundError,PayloadTooLargeError,PluginsAPI,RateLimitError,RequestTimeoutError,RouterAPI,ServerAPI,UnauthorizedError,UnprocessableEntityError,UnsupportedMediaTypeError,VERSION,ValidationError,compose,createDeleteRoute,createGetRoute,createHeadRoute,createMiddleware,createOptionsRoute,createPatchRoute,createPlugin,createPostRoute,createPutRoute,createServer,isBodyParseError});
27
+ `),o()}),e.on("error",s=>{console.error("Server error:",s),i(s)})})}async function Pn(e){for(let t of e.plugins)typeof t.initialize=="function"&&await t.initialize(e)}async function Ht(e,t){if(!e.server)try{let r=t.port,n=t.host;await Pn(e);let o=t.http2||{enabled:!0},i=!!o.enabled,s=await Rn(o);t.http2&&s.keyFile&&s.certFile&&(t.http2.keyFile=s.keyFile,t.http2.certFile=s.certFile);let a=vn(i,s);e.server=a,e.port=r,e.host=n;let u=_t(e);a.on("request",u),await En(a,r,n,i)}catch(r){throw console.error("Failed to start server:",r),r}}var Pe=!1;async function qt(e,t={}){let r=e.server,n=e.events;if(Pe){console.log("\u26A0\uFE0F Shutdown already in progress, ignoring duplicate shutdown request");return}if(!r)return;Pe=!0;let o=t.timeout||5e3;try{if(t.onStopping&&await t.onStopping(),n.emit("stopping"),e.router&&typeof e.router.close=="function"){console.log("\u{1F50C} Closing router watchers...");try{await Promise.race([e.router.close(),new Promise((a,u)=>setTimeout(()=>u(new Error("Router close timeout")),2e3))]),console.log("\u2705 Router watchers closed")}catch(a){console.error("\u274C Error closing router watchers:",a)}}try{await Promise.race([e.pluginManager.onServerStop(e,r),new Promise((a,u)=>setTimeout(()=>u(new Error("Plugin stop timeout")),2e3))])}catch(a){console.error("\u274C Plugin stop timeout:",a)}let i=new Promise((a,u)=>{r.close(l=>{if(l)return u(l);a()})}),s=new Promise((a,u)=>{setTimeout(()=>{u(new Error("Server shutdown timeout"))},o)});await Promise.race([i,s]);try{await Promise.race([e.pluginManager.terminatePlugins(e),new Promise((a,u)=>setTimeout(()=>u(new Error("Plugin terminate timeout")),1e3))])}catch(a){console.error("\u274C Plugin terminate timeout:",a)}t.onStopped&&await t.onStopped(),n.emit("stopped"),e.server=null,console.log("\u2705 Graceful shutdown completed"),Pe=!1}catch(i){throw Pe=!1,console.error("\u26A0\uFE0F Shutdown error (forcing exit):",i),r&&typeof r.close=="function"&&r.close(),process.env.NODE_ENV==="development"&&(console.log("\u{1F504} Forcing exit for development restart..."),process.exit(0)),n.emit("error",i),i}}function jt(e){if(process.env.NODE_ENV==="development"){let r=()=>{console.log("\u{1F4E4} SIGINT received, forcing exit for development restart..."),process.exit(0)},n=()=>{console.log("\u{1F4E4} SIGTERM received, forcing exit for development restart..."),process.exit(0)};return process.on("SIGINT",r),process.on("SIGTERM",n),{unregister:()=>{process.removeListener("SIGINT",r),process.removeListener("SIGTERM",n)}}}else{let r=()=>{console.log("\u{1F4E4} SIGINT received, starting graceful shutdown..."),e().catch(console.error)},n=()=>{console.log("\u{1F4E4} SIGTERM received, starting graceful shutdown..."),e().catch(console.error)};return process.on("SIGINT",r),process.on("SIGTERM",n),{unregister:()=>{process.removeListener("SIGINT",r),process.removeListener("SIGTERM",n)}}}}var x=require("zod"),bn=x.z.custom(e=>e!==null&&typeof e=="object"&&"execute"in e&&typeof e.execute=="function",{message:"Expected middleware to have an execute function"}),Cn=x.z.custom(e=>e!==null&&typeof e=="object"&&"register"in e&&typeof e.register=="function",{message:"Expected a valid plugin object with a register method"}),Mn=x.z.object({enabled:x.z.boolean().optional().default(!0),keyFile:x.z.string().optional(),certFile:x.z.string().optional()}).refine(e=>e.enabled&&process.env.NODE_ENV==="production"?e.keyFile&&e.certFile:!0,{message:"When HTTP/2 is enabled (outside of development mode), both keyFile and certFile must be provided"}),Fn=x.z.object({headerName:x.z.string().regex(/^[a-z][a-z0-9-]*$/,{message:"Header name must start with a letter and contain only lowercase letters, numbers, and hyphens"}).optional(),generator:x.z.function().args().returns(x.z.string()).optional()}).optional(),kn=x.z.object({port:x.z.number().int().positive().optional().default(3e3),host:x.z.string().optional().default("localhost"),routesDir:x.z.string().optional().default("./routes"),http2:Mn.optional().default({enabled:!0}),middleware:x.z.array(bn).optional().default([]),plugins:x.z.array(Cn).optional().default([]),correlation:Fn});function Vt(e){try{return kn.parse(e)}catch(t){if(t instanceof x.z.ZodError){let r=t.format();throw new Error(`Invalid server options: ${JSON.stringify(r,null,2)}`)}throw new Error(`Invalid server options: ${String(t)}`)}}function Qt(e={}){let{continueOnError:t=!0,debug:r=!1,onError:n}=e;function o(s,...a){r&&console.log(`[PluginLifecycle] ${s}`,...a)}function i(s,a,u){let l=`Plugin ${s.name} failed during ${a}: ${u.message}`;if(n?n(s,a,u):console.error(l,u),!t)throw new Error(l)}return{async initializePlugins(s){o("Initializing plugins...");for(let a of s.plugins)if(a.initialize)try{o(`Initializing plugin: ${a.name}`),await a.initialize(s)}catch(u){i(a,"initialize",u)}o(`Initialized ${s.plugins.length} plugins`)},async terminatePlugins(s){o("Terminating plugins...");let a=[...s.plugins].reverse();for(let u of a)if(u.terminate)try{o(`Terminating plugin: ${u.name}`),await u.terminate(s)}catch(l){i(u,"terminate",l)}o(`Terminated ${a.length} plugins`)},async onServerStart(s,a){o("Notifying plugins of server start...");for(let u of s.plugins)if(u.onServerStart)try{o(`Notifying plugin of server start: ${u.name}`),await u.onServerStart(a)}catch(l){i(u,"onServerStart",l)}},async onServerStop(s,a){o("Notifying plugins of server stop...");let u=[...s.plugins].reverse();for(let l of u)if(l.onServerStop)try{o(`Notifying plugin of server stop: ${l.name}`),await l.onServerStop(a)}catch(T){i(l,"onServerStop",T)}}}}var M=class extends Error{constructor(r,n){super(`Plugin validation error${r?` for "${r}"`:""}: ${n}`);this.pluginName=r;this.name="PluginValidationError"}};var On=new Set(["core","server","router","middleware","context","blaize","blaizejs"]),In=/^[a-z]([a-z0-9-]*[a-z0-9])?$/,Nn=/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9-.]+)?(?:\+[a-zA-Z0-9-.]+)?$/;function je(e,t={}){let{requireVersion:r=!0,validateNameFormat:n=!0,checkReservedNames:o=!0}=t;if(!e||typeof e!="object")throw new M("","Plugin must be an object");let i=e;if(!i.name||typeof i.name!="string")throw new M("","Plugin must have a name (string)");if(n&&!In.test(i.name))throw new M(i.name,"Plugin name must be lowercase letters, numbers, and hyphens only");if(o&&On.has(i.name.toLowerCase()))throw new M(i.name,`Plugin name "${i.name}" is reserved`);if(r){if(!i.version||typeof i.version!="string")throw new M(i.name,"Plugin must have a version (string)");if(!Nn.test(i.version))throw new M(i.name,'Plugin version must follow semantic versioning (e.g., "1.0.0")')}if(!i.register||typeof i.register!="function")throw new M(i.name,"Plugin must have a register method (function)");let s=["initialize","terminate","onServerStart","onServerStop"];for(let a of s)if(i[a]&&typeof i[a]!="function")throw new M(i.name,`Plugin ${a} must be a function if provided`)}var Gt=R(require("crypto"),1),Zt=R(require("fs/promises"),1),Jt=require("module"),Yt=R(require("path"),1);async function Dn(e){let t=`?t=${Date.now()}`,r=e+t;try{let n=await import(r);return console.log("\u2705 Successfully imported module"),n}catch(n){let o=n instanceof Error?n.message:String(n);return console.log("\u26A0\uFE0F Error importing with cache buster, trying original path:",o),import(e)}}async function Wt(e,t){try{let r=ce(e,t),n=await Dn(e);console.log("\u{1F4E6} Module exports:",Object.keys(n));let o=[];if(n.default&&typeof n.default=="object"){let i={...n.default,path:r.routePath};o.push(i)}return Object.entries(n).forEach(([i,s])=>{if(i==="default"||!s||typeof s!="object")return;let a=s;if(zn(a)){let u={...a,path:r.routePath};o.push(u)}}),o.length===0?(console.warn(`Route file ${e} does not export any valid route definitions`),[]):(console.log(`\u2705 Successfully Loaded ${o.length} route(s)`),o)}catch(r){return console.error(`Failed to load route module ${e}:`,r),[]}}function zn(e){return!e||typeof e!="object"?!1:["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"].some(n=>e[n]&&typeof e[n]=="object"&&e[n].handler)}var An={},te=new Map;async function re(e,t,r=!0){let o=(await Zt.stat(e)).mtime.getTime(),i=te.get(e);if(r&&i&&i.timestamp===o)return i.routes;Bn(e);let s=await Wt(e,t);if(r){let a=Xt(s);te.set(e,{routes:s,timestamp:o,hash:a})}return s}function Kt(e,t){let r=te.get(e);if(!r)return!0;let n=Xt(t);return r.hash!==n}function Ve(e){e?te.delete(e):te.clear()}function Xt(e){let t=e.map(o=>({path:o.path,methods:Object.keys(o).filter(i=>i!=="path").sort().map(i=>{let s=o[i],a=s?.handler?s.handler.toString():null;return{method:i,handler:a,middleware:s?.middleware?s.middleware.length:0,hasSchema:!!s?.schema,schemaKeys:s?.schema?Object.keys(s.schema).sort():[]}})})),r=JSON.stringify(t);return Gt.createHash("md5").update(r).digest("hex")}function Bn(e){try{let t=Yt.resolve(e);if(typeof require<"u"){delete require.cache[t];try{let r=require.resolve(t);delete require.cache[r]}catch(r){let n=r instanceof Error?r.message:String(r);console.log(`\u26A0\uFE0F Could not resolve path: ${n}`)}}else try{let r=(0,Jt.createRequire)(An.url);delete r.cache[t];try{let n=r.resolve(t);delete r.cache[n]}catch{console.log("\u26A0\uFE0F Could not resolve ESM path")}}catch{console.log("\u26A0\uFE0F createRequire not available in pure ESM")}}catch(t){console.log(`\u26A0\uFE0F Error during module cache invalidation for ${e}:`,t)}}var er=R(require("os"),1);var be=R(require("fs/promises"),1),Q=R(require("path"),1);async function Ce(e,t={}){let r=Q.isAbsolute(e)?e:Q.resolve(process.cwd(),e);console.log("Creating router with routes directory:",r);try{if(!(await be.stat(r)).isDirectory())throw new Error(`Route directory is not a directory: ${r}`)}catch(s){throw s.code==="ENOENT"?new Error(`Route directory not found: ${r}`):s}let n=[],o=t.ignore||["node_modules",".git"];async function i(s){let a=await be.readdir(s,{withFileTypes:!0});for(let u of a){let l=Q.join(s,u.name);u.isDirectory()&&o.includes(u.name)||(u.isDirectory()?await i(l):$n(u.name)&&n.push(l))}}return await i(r),n}function $n(e){return!e.startsWith("_")&&(e.endsWith(".ts")||e.endsWith(".js"))}async function _n(e,t,r=Math.max(1,Math.floor(er.cpus().length/2))){let n=Un(e,r),o=[];for(let i of n){let a=(await Promise.allSettled(i.map(u=>t(u)))).filter(u=>u.status==="fulfilled").map(u=>u.value);o.push(...a)}return o}async function tr(e){let t=await Ce(e);return(await _n(t,n=>re(n,e))).flat()}function Un(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}var B={fileChanges:0,totalReloadTime:0,averageReloadTime:0,slowReloads:[]};function rr(e,t){let r=Date.now()-t;if(B.fileChanges++,B.totalReloadTime+=r,B.averageReloadTime=B.totalReloadTime/B.fileChanges,r>100&&(B.slowReloads.push({file:e,time:r}),B.slowReloads.length>10&&B.slowReloads.shift()),process.env.NODE_ENV==="development"){let n=r<50?"\u26A1":r<100?"\u{1F504}":"\u{1F40C}";console.log(`${n} Route reload: ${e} (${r}ms)`)}}function Qe(e,t){return console.log(`Tracking performance for: ${t}`),async(...r)=>{let n=Date.now();try{let o=await e(...r);return rr(t,n),o}catch(o){throw rr(t,n),o}}}var We=R(require("path"),1),nr=require("chokidar");function Ge(e,t={}){let r=t.debounceMs||16,n=new Map;function o(p,S){return(...m)=>{let c=n.get(S);c&&clearTimeout(c);let d=setTimeout(()=>{p(...m),n.delete(S)},r);n.set(S,d)}}let i=new Map;async function s(){try{let p=await Ce(e,{ignore:t.ignore});for(let S of p)await a(S)}catch(p){l(p)}}async function a(p){try{let S=i.get(p),m=await re(p,e,!1);if(!m||m.length===0||S&&!Kt(p,m))return;await re(p,e,!0);let c=We.normalize(p);S?(i.set(p,m),t.onRouteChanged&&t.onRouteChanged(c,m)):(i.set(p,m),t.onRouteAdded&&t.onRouteAdded(c,m))}catch(S){console.log(`\u26A0\uFE0F Error processing file ${p}:`,S),l(S)}}function u(p){let S=We.normalize(p),m=i.get(S);m&&m.length>0&&t.onRouteRemoved&&t.onRouteRemoved(S,m),i.delete(S)}function l(p){t.onError&&p instanceof Error?t.onError(p):console.error("\u26A0\uFE0F Route watcher error:",p)}let T=(0,nr.watch)(e,{awaitWriteFinish:{stabilityThreshold:50,pollInterval:10},usePolling:!1,atomic:!0,followSymlinks:!1,depth:10,ignored:[/(^|[/\\])\../,/node_modules/,/\.git/,/\.DS_Store/,/Thumbs\.db/,/\.(test|spec)\.(ts|js)$/,/\.d\.ts$/,/\.map$/,/~$/,...t.ignore||[]]});return T.on("add",p=>{o(a,p)(p)}).on("change",p=>{o(a,p)(p)}).on("unlink",p=>{o(u,p)(p)}).on("error",l),s().catch(l),{close:()=>(n.forEach(p=>clearTimeout(p)),n.clear(),T.close()),getRoutes:()=>{let p=[];for(let S of i.values())p.push(...S);return p},getRoutesByFile:()=>new Map(i)}}var ur=require("zod");var or=require("zod");function Ze(e,t){return t instanceof or.z.ZodObject?t.strict().parse(e):t.parse(e)}var ir=require("zod");function Je(e,t){return t instanceof ir.z.ZodObject?t.strict().parse(e):t.parse(e)}var sr=require("zod");function Ye(e,t){return t instanceof sr.z.ZodObject?t.strict().parse(e):t.parse(e)}var ar=require("zod");function Ke(e,t){return t instanceof ar.z.ZodObject?t.strict().parse(e):t.parse(e)}Z();N();function Xe(e,t=!1){return{name:"RequestValidator",execute:async(n,o)=>{if(e.params&&n.request.params)try{n.request.params=Je(n.request.params,e.params)}catch(i){let s=Me(i),a=s.reduce((u,l)=>u+l.messages.length,0);throw new I("Request validation failed",{fields:s,errorCount:a,section:"params"})}if(e.query&&n.request.query)try{n.request.query=Ye(n.request.query,e.query)}catch(i){let s=Me(i),a=s.reduce((u,l)=>u+l.messages.length,0);throw new I("Request validation failed",{fields:s,errorCount:a,section:"query"})}if(e.body)try{n.request.body=Ze(n.request.body,e.body)}catch(i){let s=Me(i),a=s.reduce((u,l)=>u+l.messages.length,0);throw new I("Request validation failed",{fields:s,errorCount:a,section:"body"})}await o()},debug:t}}function et(e,t=!1){return{name:"ResponseValidator",execute:async(n,o)=>{let i=n.response.json;n.response.json=(s,a)=>{try{let u=Ke(s,e);return n.response.json=i,i.call(n.response,u,a)}catch(u){throw n.response.json=i,new O("Response validation failed",{responseSchema:e.description||"Unknown schema",validationError:Me(u),originalResponse:s})}},await o()},debug:t}}function Me(e){if(e instanceof ur.z.ZodError){let t=new Map;for(let r of e.issues){let n=r.path.length>0?r.path.join("."):"root";t.has(n)||t.set(n,[]),t.get(n).push(r.message)}return Array.from(t.entries()).map(([r,n])=>({field:r,messages:n}))}return e instanceof Error?[{field:"unknown",messages:[e.message]}]:[{field:"unknown",messages:[String(e)]}]}async function tt(e,t,r){let n=[...t.middleware||[]];t.schema&&((t.schema.params||t.schema.query||t.schema.body)&&n.unshift(Xe(t.schema)),t.schema.response&&n.push(et(t.schema.response))),await _([...n])(e,async()=>{let i=await t.handler(e,r);!e.response.sent&&i!==void 0&&e.response.json(i)})}function Fe(e,t,r){let n=t.exec(e);if(!n)return{};let o={};for(let i=0;i<r.length;i++)o[r[i]]=n[i+1]||"";return o}function rt(e){let t=[];if(e==="/")return{pattern:/^\/$/,paramNames:[]};let r=e.replace(/([.+*?^$(){}|\\])/g,"\\$1");return r=r.replace(/\/:([^/]+)/g,(o,i)=>(t.push(i),"/([^/]+)")).replace(/\/\[([^\]]+)\]/g,(o,i)=>(t.push(i),"/([^/]+)")),r=`${r}(?:/)?`,{pattern:new RegExp(`^${r}$`),paramNames:t}}function nt(){let e=[];return{add(t,r,n){let{pattern:o,paramNames:i}=rt(t),s={path:t,method:r,pattern:o,paramNames:i,routeOptions:n},a=e.findIndex(u=>i.length<u.paramNames.length);a===-1?e.push(s):e.splice(a,0,s)},remove(t){for(let r=e.length-1;r>=0;r--)e[r].path===t&&e.splice(r,1)},clear(){e.length=0},match(t,r){let n=t.split("?")[0];if(!n)return null;for(let i of e){if(i.method!==r)continue;if(i.pattern.exec(n)){let a=Fe(t,i.pattern,i.paramNames);return{route:i.routeOptions,params:a}}}return e.find(i=>i.method!==r&&i.pattern.test(t))?{route:null,params:{},methodNotAllowed:!0,allowedMethods:e.filter(i=>i.pattern.test(t)).map(i=>i.method)}:null},getRoutes(){return e.map(t=>({path:t.path,method:t.method}))},findRoutes(t){return e.filter(r=>r.pattern.test(t)).map(r=>({path:r.path,method:r.method,params:Fe(t,r.pattern,r.paramNames)}))}}}function cr(){return{routesByPath:new Map,routesByFile:new Map,pathToFile:new Map}}function A(e,t,r){console.log(`Updating routes from file: ${t}`);let n=e.routesByFile.get(t)||new Set,o=new Set(r.map(l=>l.path)),i=r.filter(l=>!n.has(l.path)),s=Array.from(n).filter(l=>!o.has(l)),u=r.filter(l=>n.has(l.path)).filter(l=>{let T=e.routesByPath.get(l.path);return!T||!Hn(T,l)});return Ln(e,t,{added:i,removed:s,changed:u}),{added:i,removed:s,changed:u}}function lr(e){return Array.from(e.routesByPath.values())}function Ln(e,t,r){let{added:n,removed:o,changed:i}=r;o.forEach(a=>{e.routesByPath.delete(a),e.pathToFile.delete(a)}),[...n,...i].forEach(a=>{e.routesByPath.set(a.path,a),e.pathToFile.set(a.path,t)});let s=new Set([...n.map(a=>a.path),...i.map(a=>a.path),...Array.from(e.routesByFile.get(t)||[]).filter(a=>!o.includes(a))]);s.size>0?e.routesByFile.set(t,s):e.routesByFile.delete(t)}function Hn(e,t){if(e.path!==t.path)return!1;let r=Object.keys(e).filter(o=>o!=="path").sort(),n=Object.keys(t).filter(o=>o!=="path").sort();return r.length!==n.length?!1:r.every(o=>{let i=e[o],s=t[o];return typeof i==typeof s})}function ot(e,t){Object.entries(e).forEach(([r,n])=>{r==="path"||!n||t.add(e.path,r,n)})}function ne(e,t){"remove"in t&&typeof t.remove=="function"?t.remove(e):console.warn("Matcher does not support selective removal, consider adding remove() method")}function dr(e,t){ne(e.path,t),ot(e,t)}var qn={routesDir:"./routes",basePath:"/",watchMode:process.env.NODE_ENV==="development"};function pr(e){let t={...qn,...e};e.basePath&&!e.basePath.startsWith("/")&&console.warn("Base path does nothing");let r=cr(),n=nt(),o=!1,i=null,s=null,a=new Set([t.routesDir]);function u(c){console.log(`
28
+ \u{1F527} APPLYING MATCHER CHANGES:`),console.log(` Adding ${c.added.length} routes`),console.log(` Removing ${c.removed.length} routes`),console.log(` Updating ${c.changed.length} routes`),c.removed.forEach(d=>{console.log(` \u2796 Removing: ${d}`),ne(d,n)}),c.added.forEach(d=>{let g=Object.keys(d).filter(f=>f!=="path");console.log(` \u2795 Adding: ${d.path} [${g.join(", ")}]`),ot(d,n)}),c.changed.forEach(d=>{let g=Object.keys(d).filter(f=>f!=="path");console.log(` \u{1F504} Updating: ${d.path} [${g.join(", ")}]`),dr(d,n)}),console.log(`\u2705 Matcher changes applied
29
+ `)}function l(c,d){try{let g=A(r,d,c);return u(g),g}catch(g){throw console.error(`\u26A0\uFE0F Route conflicts from ${d}:`,g),g}}async function T(c,d,g){try{let f=await tr(c),w=f.map(F=>g?{...F,path:`${g}${F.path}`}:F),E=l(w,d);console.log(`Loaded ${f.length} routes from ${d}${g?` with prefix ${g}`:""} (${E.added.length} added, ${E.changed.length} changed, ${E.removed.length} removed)`)}catch(f){throw console.error(`\u26A0\uFE0F Failed to load routes from ${d}:`,f),f}}async function p(){return o||i||(i=(async()=>{try{await Promise.all(Array.from(a).map(c=>T(c,c))),t.watchMode&&S(),o=!0}catch(c){throw console.error("\u26A0\uFE0F Failed to initialize router:",c),c}})()),i}function S(){s||(s=new Map);for(let c of a)if(!s.has(c)){let d=Ge(c,{debounceMs:16,ignore:["node_modules",".git"],onRouteAdded:(g,f)=>{try{let w=A(r,g,f);u(w)}catch(w){console.error(`Error adding routes from ${c}:`,w)}},onRouteChanged:Qe(async(g,f)=>{try{console.log(`Processing changes for ${g}`);let w=A(r,g,f);console.log(`Changes detected: ${w.added.length} added, ${w.changed.length} changed, ${w.removed.length} removed`),u(w),console.log(`Route changes applied: ${w.added.length} added, ${w.changed.length} changed, ${w.removed.length} removed`)}catch(w){console.error(`\u26A0\uFE0F Error updating routes from ${c}:`,w)}},c),onRouteRemoved:(g,f)=>{console.log(`File removed: ${g} with ${f.length} routes`);try{f.forEach(w=>{ne(w.path,n)}),Ve(g)}catch(w){console.error(`\u26A0\uFE0F Error removing routes from ${g}:`,w)}},onError:g=>{console.error(`\u26A0\uFE0F Route watcher error for ${c}:`,g)}});s.set(c,d)}}function m(c,d){s||(s=new Map);let g=Ge(c,{debounceMs:16,ignore:["node_modules",".git"],onRouteAdded:(f,w)=>{try{let E=w.map($=>d?{...$,path:`${d}${$.path}`}:$),F=A(r,f,E);u(F)}catch(E){console.error(`\u26A0\uFE0F Error adding routes from ${c}:`,E)}},onRouteChanged:Qe(async(f,w)=>{try{let E=w.map($=>d?{...$,path:`${d}${$.path}`}:$),F=A(r,f,E);u(F)}catch(E){console.error(`\u26A0\uFE0F Error updating routes from ${c}:`,E)}},c),onRouteRemoved:(f,w)=>{try{w.forEach(E=>{let F=d?`${d}${E.path}`:E.path;ne(F,n)}),Ve(f)}catch(E){console.error(`Error removing routes from ${f}:`,E)}},onError:f=>{console.error(`\u26A0\uFE0F Route watcher error for ${c}:`,f)}});return s.set(c,g),g}return p().catch(c=>{console.error("\u26A0\uFE0F Failed to initialize router on creation:",c)}),{async handleRequest(c){o||(console.log("\u{1F504} Router not initialized, initializing..."),await p());let{method:d,path:g}=c.request;console.log(`
30
+ \u{1F4E5} Handling request: ${d} ${g}`);let f=n.match(g,d);if(!f)throw console.log(`\u274C No match found for: ${d} ${g}`),new z("Not found");if(console.log(`\u2705 Route matched: ${d} ${g}`),console.log(` Params: ${JSON.stringify(f.params)}`),f.methodNotAllowed){c.response.status(405).json({error:"\u274C Method Not Allowed",allowed:f.allowedMethods}),f.allowedMethods&&f.allowedMethods.length>0&&c.response.header("Allow",f.allowedMethods.join(", "));return}c.request.params=f.params,await tt(c,f.route,f.params)},getRoutes(){return lr(r)},addRoute(c){let d=A(r,"programmatic",[c]);u(d)},addRoutes(c){let d=A(r,"programmatic",c);return u(d),d},async addRouteDirectory(c,d={}){if(a.has(c)){console.warn(`Route directory ${c} already registered`);return}a.add(c),o&&(await T(c,c,d.prefix),t.watchMode&&m(c,d.prefix))},getRouteConflicts(){return[]},async close(){if(s){for(let c of s.values())await c.close();s.clear()}}}}v();var jn={port:3e3,host:"localhost",routesDir:"./routes",http2:{enabled:!0},middleware:[],plugins:[]};function Vn(e={}){let t={...jn};return ut({routesDir:e.routesDir||t.routesDir}),{port:e.port??t.port,host:e.host??t.host,routesDir:e.routesDir??t.routesDir,http2:{enabled:e.http2?.enabled??t.http2?.enabled,keyFile:e.http2?.keyFile??t.http2?.keyFile,certFile:e.http2?.certFile??t.http2?.certFile},middleware:[...t.middleware||[],...e.middleware||[]],plugins:[...t.plugins||[],...e.plugins||[]],correlation:e.correlation}}function Qn(e){e.correlation&&St(e.correlation.headerName,e.correlation.generator)}function Wn(e,t){return async()=>(Qn(t),await Gn(e),await e.pluginManager.initializePlugins(e),await Ht(e,t),await e.pluginManager.onServerStart(e,e.server),Zn(e),e)}async function Gn(e){for(let t of e.plugins)await t.register(e)}function Zn(e){let t=jt(()=>e.close());e._signalHandlers=t,e.events.emit("started")}function Jn(e){return async t=>{if(!e.server)return;let r={...t};e._signalHandlers&&(e._signalHandlers.unregister(),delete e._signalHandlers),await qt(e,r)}}function Yn(e){return t=>{let r=Array.isArray(t)?t:[t];return e.middleware.push(...r),e}}function Kn(e){return async t=>{if(Array.isArray(t))for(let r of t)je(r),e.plugins.push(r),await r.register(e);else je(t),e.plugins.push(t),await t.register(e);return e}}function ke(e={}){let t=Vn(e),r;try{r=Vt(t)}catch(c){throw c instanceof Error?new Error(`Failed to create server: ${c.message}`):new Error(`Failed to create server: ${String(c)}`)}let{port:n,host:o,middleware:i,plugins:s}=r,a=Array.isArray(i)?[...i]:[],u=Array.isArray(s)?[...s]:[],l=new fr.AsyncLocalStorage,T=pr({routesDir:r.routesDir,watchMode:process.env.NODE_ENV==="development"}),p=Qt({debug:process.env.NODE_ENV==="development",continueOnError:!0}),S=new mr.default,m={server:null,port:n,host:o,context:l,events:S,plugins:[...u],middleware:[...a],_signalHandlers:{unregister:()=>{}},use:()=>m,register:async()=>m,listen:async()=>m,close:async()=>{},router:T,pluginManager:p};return m.listen=Wn(m,r),m.close=Jn(m),m.use=Yn(m),m.register=Kn(m),m}function it(e){return{}}v();function Xn(e){return typeof e=="object"&&e!==null&&"name"in e&&"execute"in e&&typeof e.name=="string"&&typeof e.execute=="function"}function eo(e){return typeof e=="object"&&e!==null&&"name"in e&&"version"in e&&"register"in e&&typeof e.name=="string"&&typeof e.version=="string"&&typeof e.register=="function"}function to(e){return e}function ro(e){return e}function no(...e){return e}function oo(...e){return e}P();N();P();v();var Oe=class extends h{constructor(t,r=void 0,n=void 0){super("UNAUTHORIZED",t,401,n??y(),r)}};P();v();var Ie=class extends h{constructor(t,r=void 0,n=void 0){super("FORBIDDEN",t,403,n??y(),r)}};P();v();var Ne=class extends h{constructor(t,r=void 0,n=void 0){super("CONFLICT",t,409,n??y(),r)}};P();v();var De=class extends h{constructor(t,r=void 0,n=void 0){super("RATE_LIMITED",t,429,n??y(),r)}};Z();Re();P();v();var ze=class extends h{constructor(t,r,n){super("UPLOAD_TIMEOUT",t,408,n??y(),r)}};ve();P();v();var Be=class extends h{constructor(t,r,n){super("UNPROCESSABLE_ENTITY",t,422,n??y(),r)}};var gr="0.1.0",yr={createServer:ke,inferContext:it},hr={createDeleteRoute:fe,createGetRoute:le,createHeadRoute:ge,createOptionsRoute:ye,createPatchRoute:me,createPostRoute:de,createPutRoute:pe,createRouteFactory:Ae},Sr={createMiddleware:V,createServiceMiddleware:se,createStateMiddleware:ie,compose:_},wr={createPlugin:ae},io={createServer:ke,createMiddleware:V,createServiceMiddleware:se,createStateMiddleware:ie,createPlugin:ae,getCorrelationId:y,Server:yr,Router:hr,Middleware:Sr,Plugins:wr,VERSION:gr};0&&(module.exports={Blaize,BlaizeError,ConflictError,ErrorSeverity,ErrorType,ForbiddenError,InternalServerError,MiddlewareAPI,NotFoundError,PayloadTooLargeError,PluginsAPI,RateLimitError,RequestTimeoutError,RouterAPI,ServerAPI,UnauthorizedError,UnprocessableEntityError,UnsupportedMediaTypeError,VERSION,ValidationError,asMiddlewareArray,asPluginArray,compose,createDeleteRoute,createGetRoute,createHeadRoute,createMiddleware,createMiddlewareArray,createOptionsRoute,createPatchRoute,createPlugin,createPluginArray,createPostRoute,createPutRoute,createRouteFactory,createServer,createServiceMiddleware,createStateMiddleware,getCorrelationId,inferContext,isBodyParseError,isMiddleware,isPlugin});
31
31
  //# sourceMappingURL=index.cjs.map