connectic
Version:
Connectic is a javascript library for pub sub messaging, event handling, and data synchronization in real-time applications.
1,442 lines (1,426 loc) • 57.1 kB
text/typescript
/**
* Configuration for creating a bus instance
*/
interface BusConfig {
/** Unique identifier for the bus instance */
name: string;
/** Enable debug logging for development */
debug?: boolean;
/** Default caching configuration */
cache?: CacheConfig;
}
/**
* Cache configuration options
*/
interface CacheConfig {
/** Default TTL for cached items in milliseconds */
defaultTtl?: number;
/** Maximum number of items to store in cache */
maxSize?: number;
/** Default caching strategy */
strategy?: CacheStrategy;
}
/**
* Available caching strategies
*/
type CacheStrategy = 'cache-first' | 'network-first' | 'stale-while-revalidate' | 'cache-only';
/**
* Cache options for individual requests
*/
interface CacheOptions {
/** Time to live for this specific cache entry */
ttl?: number;
/** Custom cache key (defaults to event + payload hash) */
key?: string;
/** Caching strategy for this request */
strategy?: CacheStrategy;
}
/**
* Options for request/response communication
*/
interface RequestOptions {
/** Request timeout in milliseconds (default: 10000) */
timeout?: number;
/** Number of retry attempts on failure (default: 0) */
retries?: number;
/** Request priority for ordering */
priority?: 'low' | 'normal' | 'high';
/** Caching configuration for this request */
cache?: CacheOptions;
/** AbortSignal for request cancellation */
signal?: AbortSignal;
}
/**
* Options for collecting multiple responses
*/
interface RequestManyOptions extends RequestOptions {
/** Minimum number of responses before resolving */
minResponses?: number;
/** Maximum number of responses to collect */
maxResponses?: number;
}
/**
* Format for batch request arrays
* [eventName, payload?, options?]
*/
type BatchRequest = [string, any?, RequestOptions?];
/**
* Plugin interface for extending bus functionality
*/
interface BusPlugin<T extends Record<string, any> = any> {
/** Unique plugin name */
name: string;
/** Called when plugin is installed on a bus */
install(bus: MFEBus$1<T>): void;
/** Called when plugin is removed (optional) */
uninstall?(bus: MFEBus$1<T>): void;
}
/**
* Available lifecycle hook types
*/
type HookType = 'beforeEmit' | 'afterEmit' | 'beforeOn' | 'afterOn';
/**
* Hook handler function signature
*/
type HookHandler = (event: string, payload?: any) => void;
/**
* Reactive shared state interface
*/
interface SharedState<T> {
/** Get current state value */
get(): T;
/** Set new state value and notify subscribers */
set(value: T): void;
/** Subscribe to state changes */
subscribe(callback: (value: T) => void): () => void;
/** Clean up and destroy state */
destroy(): void;
}
/**
* Computed/derived state interface
*/
interface ComputedState<T> {
/** Get current computed value */
get(): T;
/** Subscribe to computed value changes */
subscribe(callback: (value: T) => void): () => void;
/** Clean up and destroy computed state */
destroy(): void;
}
/**
* Function for intercepting and transforming requests
*/
type RequestInterceptor = (event: string, payload: any) => any;
/**
* Function for intercepting and transforming responses
*/
type ResponseInterceptor = (event: string, response: any) => any;
/**
* Bus statistics and metrics
*/
interface BusStats {
/** Total number of events emitted */
totalEvents: number;
/** Total number of requests made */
totalRequests: number;
/** Current number of active listeners */
activeListeners: number;
/** Current cache size */
cacheSize: number;
/** Approximate memory usage in bytes */
memoryUsage: number;
}
/**
* Middleware function for responder chains
*/
type MiddlewareFunction = (payload: any, next: () => void, cancel: (reason?: string) => void) => void | Promise<void>;
/**
* Builder interface for setting up responders with middleware
*/
interface ResponderBuilder$1<K> {
/** Add middleware to the responder chain */
use(middleware: MiddlewareFunction): ResponderBuilder$1<K>;
/** Set the final handler function */
handler(handlerFn: (payload: any) => any | Promise<any>): void;
/** Destroy the responder and clean up event listeners */
destroy?(): void;
}
/**
* Cache management interface
*/
interface CacheManager$1 {
/** Get value from cache */
get(key: string): any;
/** Set value in cache with optional TTL */
set(key: string, value: any, ttl?: number): void;
/** Remove specific cache entry */
invalidate(key: string): boolean;
/** Remove cache entries matching pattern */
invalidatePattern(pattern: string): number;
/** Clear entire cache */
clear(): void;
}
/**
* Main bus interface combining all functionality
*/
interface MFEBus$1<TEventMap extends Record<string, any> = {}, TRequestMap extends Record<string, any> = {}> {
/** Emit an event to all subscribers */
emit<K extends keyof TEventMap>(event: K, payload: TEventMap[K]): void;
/** Subscribe to an event */
on<K extends keyof TEventMap>(event: K, handler: (payload: TEventMap[K]) => void): () => void;
/** Subscribe to an event for one-time execution */
once<K extends keyof TEventMap>(event: K, handler: (payload: TEventMap[K]) => void): () => void;
/** Remove specific event handler */
off<K extends keyof TEventMap>(event: K, handler: Function): void;
/** Remove all listeners for an event */
removeAllListeners<K extends keyof TEventMap>(event?: K): void;
/** Make an async request and wait for response */
request<K extends keyof TRequestMap>(event: K, payload?: TRequestMap[K] extends {
request: infer R;
} ? R : any, options?: RequestOptions): Promise<TRequestMap[K] extends {
response: infer R;
} ? R : any>;
/** Collect multiple responses within timeout window */
requestMany<K extends keyof TRequestMap>(event: K, payload?: TRequestMap[K] extends {
request: infer R;
} ? R : any, options?: RequestManyOptions): Promise<Array<TRequestMap[K] extends {
response: infer R;
} ? R : any>>;
/** Execute multiple requests in parallel */
requestBatch(requests: BatchRequest[]): Promise<any[]>;
/** Set up a responder for handling requests */
respond<K extends keyof TRequestMap>(event: K): ResponderBuilder$1<K>;
/** Create reactive shared state */
createState<T>(key: string, initialValue: T): SharedState<T>;
/** Create computed/derived state */
createComputed<T>(computeFn: () => T): ComputedState<T>;
/** Set state value directly */
setState<K extends keyof TEventMap>(key: K, value: TEventMap[K]): void;
/** Get current state value */
getState<K extends keyof TEventMap>(key: K): TEventMap[K] | undefined;
/** Remove state */
removeState<K extends keyof TEventMap>(key: K): void;
/** Add a plugin to extend functionality */
use(plugin: BusPlugin): this;
/** Add a lifecycle hook */
addHook(type: HookType, handler: HookHandler): void;
/** Remove a lifecycle hook */
removeHook(type: HookType, handler: HookHandler): void;
/** Create a namespaced bus instance */
namespace(name: string): MFEBus$1<TEventMap, TRequestMap>;
/** Cache management interface */
cache: CacheManager$1;
/** Intercept and transform outgoing requests */
interceptRequest(interceptor: RequestInterceptor): void;
/** Intercept and transform incoming responses */
interceptResponse(interceptor: ResponseInterceptor): void;
/** Get number of listeners for an event */
getListenerCount<K extends keyof TEventMap>(event: K): number;
/** Check if event has any listeners */
hasListeners<K extends keyof TEventMap>(event: K): boolean;
/** Get bus statistics and metrics */
getStats(): BusStats;
/** Clean up and destroy bus instance */
destroy(): void;
}
/**
* Event map type constraint
*/
type EventMap = Record<string, any>;
/**
* Request map type constraint - each key maps to {request, response} pair
*/
type RequestMap = Record<string, {
request?: any;
response?: any;
}>;
/**
* connectic - Error Classes and Codes
*
* This file defines all error types and status codes used throughout connectic.
* Error codes follow HTTP status code conventions for familiarity.
*/
/**
* Bus-specific error codes following HTTP status conventions
*/
declare enum BusErrorCode {
/** No responders available for the requested event */
NOT_FOUND = 404,
/** Middleware validation failed or access denied */
FORBIDDEN = 403,
/** Request timed out waiting for response */
TIMEOUT = 408,
/** Multiple responders when expecting single response */
CONFLICT = 409,
/** Event payload exceeds configured size limits */
PAYLOAD_TOO_LARGE = 413,
/** Rate limiting threshold exceeded */
TOO_MANY_REQUESTS = 429,
/** Internal bus error or unexpected failure */
INTERNAL_ERROR = 500,
/** Invalid request format or malformed event name */
BAD_REQUEST = 400,
/** Responder was available but is now offline/destroyed */
GONE = 410,
/** Responder exists but temporarily unavailable */
SERVICE_UNAVAILABLE = 503,
/** Payload structure valid but business logic rejects it */
UNPROCESSABLE_ENTITY = 422
}
/**
* Custom error class for all bus-related errors
* Provides structured error information with specific error codes
*/
declare class BusError extends Error {
readonly busCode: BusErrorCode;
readonly details?: any | undefined;
/**
* Creates a new BusError instance
* @param message Human-readable error description
* @param busCode Specific error code for programmatic handling
* @param details Additional error context and debugging information
*/
constructor(message: string, busCode: BusErrorCode, details?: any | undefined);
/**
* Returns a JSON representation of the error
* Useful for logging and debugging
*/
toJSON(): object;
/**
* Returns a string representation including error code
*/
toString(): string;
/**
* Check if this error indicates a temporary failure that might be retried
*/
isRetryable(): boolean;
/**
* Check if this error indicates a client-side issue
*/
isClientError(): boolean;
/**
* Check if this error indicates a server-side issue
*/
isServerError(): boolean;
}
/**
* Factory functions for creating common error types
*/
declare class BusErrorFactory {
/**
* Creates a NOT_FOUND error when no responders are available
*/
static notFound(event: string, details?: any): BusError;
/**
* Creates a TIMEOUT error when requests exceed timeout limit
*/
static timeout(event: string, timeoutMs: number, details?: any): BusError;
/**
* Creates a FORBIDDEN error when middleware validation fails
*/
static forbidden(event: string, reason: string, details?: any): BusError;
/**
* Creates a CONFLICT error when multiple responders exist
*/
static conflict(event: string, responderCount: number, details?: any): BusError;
/**
* Creates a PAYLOAD_TOO_LARGE error when payload exceeds limits
*/
static payloadTooLarge(event: string, size: number, limit: number, details?: any): BusError;
/**
* Creates a TOO_MANY_REQUESTS error when rate limiting is triggered
*/
static tooManyRequests(event: string, limit: number, window: number, details?: any): BusError;
/**
* Creates an INTERNAL_ERROR for unexpected failures
*/
static internal(message: string, originalError?: Error, details?: any): BusError;
/**
* Creates a BAD_REQUEST error for malformed requests
*/
static badRequest(event: string, reason: string, details?: any): BusError;
/**
* Creates a GONE error when responder was available but is now offline
*/
static gone(event: string, details?: any): BusError;
/**
* Creates a SERVICE_UNAVAILABLE error for temporary responder issues
*/
static serviceUnavailable(event: string, retryAfter?: number, details?: any): BusError;
/**
* Creates an UNPROCESSABLE_ENTITY error for valid but rejected payloads
*/
static unprocessableEntity(event: string, reason: string, details?: any): BusError;
}
/**
* Type guard to check if an error is a BusError
*/
declare function isBusError(error: any): error is BusError;
/**
* Type guard to check if error has a specific bus error code
*/
declare function hasBusErrorCode(error: any, code: BusErrorCode): error is BusError;
/**
* Utility function to wrap unknown errors as BusError
*/
declare function wrapError(error: unknown, event?: string): BusError;
/**
* Error message templates for consistent error formatting
*/
declare const ErrorMessages: {
readonly INVALID_EVENT_NAME: "Event name must be a non-empty string";
readonly INVALID_PAYLOAD: "Event payload must be serializable";
readonly INVALID_HANDLER: "Event handler must be a function";
readonly INVALID_TIMEOUT: "Timeout must be a positive number";
readonly INVALID_RETRIES: "Retries must be a non-negative number";
readonly BUS_DESTROYED: "Bus instance has been destroyed";
readonly MIDDLEWARE_ERROR: "Middleware execution failed";
readonly CACHE_ERROR: "Cache operation failed";
readonly STATE_NOT_FOUND: "State key not found";
readonly COMPUTED_CIRCULAR_DEPENDENCY: "Circular dependency detected in computed state";
};
/**
* connectic - Core Event Bus Implementation
*
* This file contains the foundational event bus that provides pub/sub functionality.
* All other communication patterns are built on top of this core infrastructure.
*/
/**
* Core event bus providing pub/sub functionality
* This is the foundation that all other communication patterns build upon
*/
declare class EventBus {
private listeners;
private stats;
private isDestroyed;
private maxListeners;
/**
* Emits an event to all registered listeners
* @param event Event name to emit
* @param payload Data to send with the event
*/
emit(event: string, payload: any): void;
/**
* Subscribes to an event
* @param event Event name to listen for
* @param handler Function to call when event is emitted
* @returns Unsubscribe function
*/
on(event: string, handler: Function): () => void;
/**
* Subscribes to an event for one-time execution
* @param event Event name to listen for
* @param handler Function to call when event is emitted (once)
* @returns Unsubscribe function
*/
once(event: string, handler: Function): () => void;
/**
* Removes a specific event handler
* @param event Event name
* @param handler Handler function to remove
*/
off(event: string, handler: Function): void;
/**
* Removes all listeners for an event, or all listeners if no event specified
* @param event Optional event name to target specific event
*/
removeAllListeners(event?: string): void;
/**
* Gets the number of listeners for a specific event
* @param event Event name
* @returns Number of listeners
*/
getListenerCount(event: string): number;
/**
* Checks if an event has any listeners
* @param event Event name
* @returns True if event has listeners
*/
hasListeners(event: string): boolean;
/**
* Gets all event names that have listeners
* @returns Array of event names
*/
getEventNames(): string[];
/**
* Gets comprehensive statistics about the event bus
* @returns Bus statistics object
*/
getStats(): BusStats;
/**
* Gets detailed internal statistics for debugging
* @returns Extended statistics object
*/
getDetailedStats(): object;
/**
* Sets the maximum number of listeners per event
* @param max Maximum listeners (default: 100)
*/
setMaxListeners(max: number): void;
/**
* Gets the current maximum listeners setting
* @returns Maximum listeners per event
*/
getMaxListeners(): number;
/**
* Checks if the event bus has been destroyed
* @returns True if destroyed
*/
isDestroyedState(): boolean;
/**
* Destroys the event bus and cleans up all resources
* This operation is irreversible
*/
destroy(): void;
/**
* Creates a filtered view of the event bus for a specific namespace
* @param namespace Namespace prefix to filter events
* @returns Namespaced event bus wrapper
*/
createNamespace(namespace: string): NamespacedEventBus;
/**
* Throws an error if the bus has been destroyed
* @private
*/
private throwIfDestroyed;
}
/**
* Namespaced wrapper around EventBus that automatically prefixes events
*/
declare class NamespacedEventBus {
private eventBus;
private namespace;
constructor(eventBus: EventBus, namespace: string);
isDestroyed: boolean;
/**
* Emits a namespaced event
* @param event Event name (will be prefixed with namespace)
* @param payload Event payload
*/
emit(event: string, payload: any): void;
/**
* Subscribes to a namespaced event
* @param event Event name (will be prefixed with namespace)
* @param handler Event handler
* @returns Unsubscribe function
*/
on(event: string, handler: Function): () => void;
/**
* Subscribes to a namespaced event for one-time execution
* @param event Event name (will be prefixed with namespace)
* @param handler Event handler
* @returns Unsubscribe function
*/
once(event: string, handler: Function): () => void;
/**
* Removes a specific handler from a namespaced event
* @param event Event name (will be prefixed with namespace)
* @param handler Handler to remove
*/
off(event: string, handler: Function): void;
/**
* Removes all listeners for a namespaced event
* @param event Optional event name (will be prefixed with namespace)
*/
removeAllListeners(event?: string): void;
/**
* Gets listener count for a namespaced event
* @param event Event name (will be prefixed with namespace)
* @returns Number of listeners
*/
getListenerCount(event: string): number;
/**
* Checks if a namespaced event has listeners
* @param event Event name (will be prefixed with namespace)
* @returns True if event has listeners
*/
hasListeners(event: string): boolean;
/**
* Gets all event names within this namespace
* @returns Array of event names (without namespace prefix)
*/
getEventNames(): string[];
/**
* Gets the namespace prefix
* @returns Namespace string
*/
getNamespace(): string;
private throwIfDestroyed;
/**
* Creates a sub-namespace
* @param subNamespace Sub-namespace name
* @returns Nested namespaced event bus
*/
/**
* Destroys this namespaced view (removes all listeners in namespace)
*/
destroy(): void;
}
/**
* connectic - Middleware and Plugin System
*
* This file implements the plugin architecture and middleware system for connectic.
* It provides lifecycle hooks and extensible middleware chains for responders.
*/
/**
* Builder for creating responders with middleware chains
*/
declare class ResponderBuilder<K> {
private eventName;
private bus;
private middlewares;
private handlerFn;
private isInstalled;
private composedHandler;
constructor(eventName: string, bus: EventBus);
/**
* Adds middleware to the responder chain
* @param middleware Middleware function to add
* @returns This builder for chaining
*/
use(middleware: MiddlewareFunction): ResponderBuilder<K>;
/**
* Sets the final handler function and installs the responder
* @param handlerFn Handler function for processing requests
*/
handler(handlerFn: (payload: any) => any | Promise<any>): void;
destroy(): void;
/**
* Installs the responder with middleware chain on the bus
* @private
*/
private installResponder;
/**
* Executes the middleware chain
* @param payload Initial payload
* @returns Processed payload after middleware
* @private
*/
private executeMiddleware;
/**
* Gets information about this responder
* @returns Responder information
*/
getInfo(): object;
}
/**
* Built-in middleware functions for common use cases
*/
declare class BuiltinMiddleware {
/**
* Creates a logging middleware
* @param options Logging options
* @returns Middleware function
*/
static logger(options?: {
logPayload?: boolean;
prefix?: string;
}): MiddlewareFunction;
/**
* Creates a validation middleware using a validation function
* @param validator Validation function
* @returns Middleware function
*/
static validator(validator: (payload: any) => boolean | string): MiddlewareFunction;
/**
* Creates a rate limiting middleware
* @param options Rate limiting options
* @returns Middleware function
*/
static rateLimit(options: {
maxRequests: number;
windowMs: number;
}): MiddlewareFunction;
/**
* Creates a timeout middleware
* @param timeoutMs Timeout in milliseconds
* @returns Middleware function
*/
static timeout(timeoutMs: number): MiddlewareFunction;
}
/**
* connectic - Shared State Management
*
* This file implements reactive shared state that automatically synchronizes
* across components and applications using the event bus.
*/
/**
* Manages shared state instances for a bus
*/
declare class SharedStateManager {
private bus;
private states;
private isDestroyed;
private dependencyGraph;
private currentAccessStack;
constructor(bus: EventBus);
/**
* Creates a new shared state instance
* @param key Unique state identifier
* @param initialValue Initial state value
* @returns SharedState instance
*/
createState<T>(key: string, initialValue: T): SharedState<T>;
/**
* Gets an existing shared state instance
* @param key State identifier
* @returns SharedState instance or undefined
*/
getState<T>(key: string): SharedState<T> | undefined;
/**
* Gets current value of a state without subscribing
* @param key State identifier
* @returns Current state value or undefined
*/
getStateValue<T>(key: string): T | undefined;
/**
* Sets state value directly (creates state if it doesn't exist)
* @param key State identifier
* @param value New state value
*/
setState<T>(key: string, value: T): void;
/**
* Removes a state instance
* @param key State identifier
* @returns True if state was removed
*/
removeState(key: string): boolean;
/**
* Gets all state keys
* @returns Array of state keys
*/
getStateKeys(): string[];
/**
* Gets statistics about state usage
* @returns State manager statistics
*/
getStats(): object;
/**
* Destroys the state manager and all states
*/
destroy(): void;
/**
* Internal method to handle state destruction
* @param key State key that was destroyed
* @internal
*/
_handleStateDestroyed(key: string): void;
/**
* Tracks state access for circular dependency detection
* @internal
*/
_trackStateAccess(sourceKey: string, targetKey: string): void;
/**
* Detects circular dependencies using DFS
* @private
*/
private hasCircularDependency;
/**
* Begins tracking access for a state
* @internal
*/
_beginStateAccess(key: string): void;
/**
* Ends tracking access for a state
* @internal
*/
_endStateAccess(key: string): void;
/**
* Checks if state manager is destroyed
* @returns True if destroyed
*/
isDestroyedState(): boolean;
/**
* Throws error if state manager is destroyed
* @private
*/
private throwIfDestroyed;
}
/**
* Utility functions for working with shared state
*/
declare class SharedStateUtils {
/**
* Creates a state that persists to localStorage (browser only)
* @param manager State manager instance
* @param key State key
* @param initialValue Initial value
* @param storageKey Optional localStorage key (defaults to state key)
* @returns Shared state with localStorage persistence
*/
static createPersistedState<T>(manager: SharedStateManager, key: string, initialValue: T, storageKey?: string): SharedState<T>;
/**
* Creates a computed state that derives from multiple source states
* @param manager State manager instance
* @param sources Array of state keys to depend on
* @param computeFn Function to compute derived value
* @returns Shared state with computed value
*/
static createDerivedState<T>(manager: SharedStateManager, sources: string[], computeFn: (...values: any[]) => T): SharedState<T>;
/**
* Creates a debounced state that only updates after a delay
* @param manager State manager instance
* @param key State key
* @param initialValue Initial value
* @param delayMs Debounce delay in milliseconds
* @returns Debounced shared state
*/
static createDebouncedState<T>(manager: SharedStateManager, key: string, initialValue: T, delayMs: number): SharedState<T>;
}
/**
* Manages computed state instances for a bus
*/
declare class ComputedStateManager {
private computedStates;
private isDestroyed;
constructor();
/**
* Creates a new computed state instance
* @param computeFn Function that computes the derived value
* @returns ComputedState instance
*/
createComputed<T>(computeFn: () => T): ComputedState<T>;
/**
* Gets statistics about computed state usage
* @returns Computed state manager statistics
*/
getStats(): object;
/**
* Destroys the computed state manager and all computed states
*/
destroy(): void;
/**
* Internal method to handle computed state destruction
* @param computed Computed state that was destroyed
* @internal
*/
_handleComputedDestroyed(computed: ComputedStateImpl<any>): void;
/**
* Checks if computed state manager is destroyed
* @returns True if destroyed
*/
isDestroyedState(): boolean;
/**
* Throws error if computed state manager is destroyed
* @private
*/
private throwIfDestroyed;
}
/**
* Implementation of computed/derived state with automatic dependency tracking
*/
declare class ComputedStateImpl<T> implements ComputedState<T> {
private computeFn;
private managerRef;
private cachedValue;
private isStale;
private isComputing;
private dependencies;
private dependencyUnsubscribers;
private subscribers;
private isDestroyed;
private computationCount;
private lastComputeTime;
constructor(computeFn: () => T, managerRef: WeakRef<ComputedStateManager>);
/**
* Gets the current computed value, recalculating if stale
* @returns Current computed value
*/
get(): T;
/**
* Subscribes to computed value changes
* @param callback Function to call when computed value changes
* @returns Unsubscribe function
*/
subscribe(callback: (value: T) => void): () => void;
/**
* Forces recomputation of the value
* @returns Newly computed value
*/
refresh(): T;
/**
* Gets statistics about this computed state
* @returns Computed state statistics
*/
getStats(): object;
/**
* Destroys the computed state and cleans up resources
*/
destroy(): void;
/**
* Checks if computed state is destroyed
* @returns True if destroyed
*/
isDestroyedState(): boolean;
/**
* Recomputes the value and updates dependencies
* @private
*/
private recompute;
/**
* Tracks state dependencies during computation
* @private
*/
private trackDependencies;
/**
* Updates dependency subscriptions
* @private
*/
private updateDependencies;
/**
* Marks the computed value as stale and triggers recomputation
* @private
*/
private invalidate;
/**
* Notifies all subscribers of a value change
* @private
*/
private notifySubscribers;
/**
* Creates a deep clone of a value to prevent mutation issues
* @private
*/
private cloneValue;
/**
* Compares two values for equality
* @private
*/
private valuesEqual;
/**
* Throws error if computed state is destroyed
* @private
*/
private throwIfDestroyed;
}
/**
* Utility functions for working with computed state
*/
declare class ComputedStateUtils {
/**
* Creates a memoized computed state that only recalculates when dependencies actually change
* @param manager Computed state manager
* @param computeFn Computation function
* @param equalityFn Custom equality function for optimization
* @returns Memoized computed state
*/
static createMemoized<T>(manager: ComputedStateManager, computeFn: () => T, equalityFn?: (a: T, b: T) => boolean): ComputedState<T>;
/**
* Creates a computed state that combines multiple computed states
* @param manager Computed state manager
* @param computedStates Array of computed states to combine
* @param combiner Function to combine the values
* @returns Combined computed state
*/
static combine<T extends any[], R>(manager: ComputedStateManager, computedStates: {
[K in keyof T]: ComputedState<T[K]>;
}, combiner: (...values: T) => R): ComputedState<R>;
/**
* Creates a computed state that filters an array based on a predicate
* @param manager Computed state manager
* @param arrayComputed Computed state containing an array
* @param predicate Filter predicate function
* @returns Filtered computed state
*/
static filter<T>(manager: ComputedStateManager, arrayComputed: ComputedState<T[]>, predicate: (item: T, index: number) => boolean): ComputedState<T[]>;
/**
* Creates a computed state that maps an array to a new form
* @param manager Computed state manager
* @param arrayComputed Computed state containing an array
* @param mapper Mapping function
* @returns Mapped computed state
*/
static map<T, R>(manager: ComputedStateManager, arrayComputed: ComputedState<T[]>, mapper: (item: T, index: number) => R): ComputedState<R[]>;
/**
* Creates a computed state that reduces an array to a single value
* @param manager Computed state manager
* @param arrayComputed Computed state containing an array
* @param reducer Reducer function
* @param initialValue Initial value for reduction
* @returns Reduced computed state
*/
static reduce<T, R>(manager: ComputedStateManager, arrayComputed: ComputedState<T[]>, reducer: (accumulator: R, current: T, index: number) => R, initialValue: R): ComputedState<R>;
/**
* Creates a computed state with async computation (returns Promise)
* @param manager Computed state manager
* @param asyncComputeFn Async computation function
* @param initialValue Initial value while async computation is pending
* @returns Computed state that handles async values
*/
static createAsync<T>(manager: ComputedStateManager, stateManager: SharedStateManager, asyncComputeFn: () => Promise<T>, initialValue: T): ComputedState<{
value: T;
loading: boolean;
error: Error | null;
}>;
/**
* Creates a computed state that debounces rapid changes
* @param manager Computed state manager
* @param sourceComputed Source computed state
* @param delayMs Debounce delay in milliseconds
* @returns Debounced computed state
*/
static debounce<T>(manager: ComputedStateManager, sourceComputed: ComputedState<T>, delayMs: number): ComputedState<T>;
/**
* Creates a computed state that only updates when value passes validation
* @param manager Computed state manager
* @param sourceComputed Source computed state
* @param validator Validation function
* @param fallbackValue Value to use when validation fails
* @returns Validated computed state
*/
static validate<T>(manager: ComputedStateManager, sourceComputed: ComputedState<T>, validator: (value: T) => boolean, fallbackValue: T): ComputedState<T>;
/**
* Creates a computed state that caches expensive computations
* @param manager Computed state manager
* @param computeFn Expensive computation function
* @param cacheKey Function to generate cache key from dependencies
* @param maxCacheSize Maximum number of cached results
* @returns Cached computed state
*/
static cached<T>(manager: ComputedStateManager, computeFn: () => T, cacheKey: () => string, maxCacheSize?: number): ComputedState<T>;
}
/**
* connectic - Cache Management
*
* This file implements intelligent caching for request/response patterns
* with TTL, invalidation patterns, and multiple caching strategies.
*/
/**
* Cache manager with TTL, LRU eviction, and pattern-based invalidation
*/
declare class CacheManager {
private cache;
private config;
private cleanupTimer;
private accessOrder;
private accessCounter;
private stats;
private isDestroyed;
constructor(config?: CacheConfig);
/**
* Gets a value from cache
* @param key Cache key
* @returns Cached value or undefined if not found/expired
*/
get(key: string): any;
/**
* Sets a value in cache with optional TTL
* @param key Cache key
* @param value Value to cache
* @param ttl Time to live in milliseconds (optional)
*/
set(key: string, value: any, ttl?: number): void;
/**
* Removes a specific cache entry
* @param key Cache key to remove
* @returns True if key was removed, false if not found
*/
invalidate(key: string): boolean;
/**
* Removes cache entries matching a pattern
* @param pattern Pattern to match (supports wildcards with *)
* @returns Number of entries removed
*/
invalidatePattern(pattern: string): number;
/**
* Clears entire cache
*/
clear(): void;
/**
* Gets current cache size
* @returns Number of cached entries
*/
getSize(): number;
/**
* Gets cache statistics
* @returns Cache statistics object
*/
getStats(): object;
/**
* Gets detailed cache information for debugging
* @returns Detailed cache information
*/
getDetailedInfo(): object;
/**
* Implements cache-aware request handling based on strategy
* @param key Request cache key
* @param networkFn Function to execute network request
* @param strategy Caching strategy to use
* @param ttl Custom TTL for this request
* @returns Cached or fresh value
*/
handleRequest<T>(key: string, networkFn: () => Promise<T>, strategy?: CacheStrategy, ttl?: number): Promise<T>;
/**
* Creates a cache key for event and payload
* @param event Event name
* @param payload Request payload
* @returns Cache key
*/
createKey(event: string, payload?: any): string;
/**
* Destroys the cache manager and cleans up resources
*/
destroy(): void;
/**
* Checks if cache manager is destroyed
* @returns True if destroyed
*/
isDestroyedState(): boolean;
/**
* Cache-first strategy: return cache if available, otherwise network
* @private
*/
private cacheFirstStrategy;
/**
* Network-first strategy: try network first, fallback to cache
* @private
*/
private networkFirstStrategy;
/**
* Stale-while-revalidate strategy: return cache immediately, update in background
* @private
*/
private staleWhileRevalidateStrategy;
/**
* Cache-only strategy: only return cached values, never go to network
* @private
*/
private cacheOnlyStrategy;
/**
* Evicts least recently used entries when cache is full
* @private
*/
private evictLRU;
/**
* Converts wildcard pattern to regex
* @private
*/
private patternToRegex;
/**
* Estimates total memory usage of cache
* @private
*/
private estimateMemoryUsage;
/**
* Removes expired entries from cache
* @private
*/
private cleanup;
/**
* Starts the periodic cleanup timer
* @private
*/
private startCleanupTimer;
/**
* Stops the cleanup timer
* @private
*/
private stopCleanupTimer;
/**
* Throws error if cache manager is destroyed
* @private
*/
private throwIfDestroyed;
}
/**
* Utility functions for cache management
*/
declare class CacheUtils {
/**
* Creates a cache key with namespace prefix
* @param namespace Namespace prefix
* @param event Event name
* @param payload Optional payload
* @returns Namespaced cache key
*/
static createNamespacedKey(namespace: string, event: string, payload?: any): string;
/**
* Extracts event name from cache key
* @param key Cache key
* @returns Event name or null if not extractable
*/
static extractEventFromKey(key: string): string | null;
/**
* Estimates optimal TTL based on data characteristics
* @param data Data to analyze
* @returns Suggested TTL in milliseconds
*/
static suggestTTL(data: any): number;
/**
* Creates a cache warming function
* @param cache Cache manager instance
* @param keys Array of cache keys to warm
* @param dataFetcher Function to fetch data for each key
* @returns Promise that resolves when warming is complete
*/
static warmCache(cache: CacheManager, keys: string[], dataFetcher: (key: string) => Promise<any>): Promise<void>;
/**
* Creates a cache key with versioning support
* @param event Event name
* @param payload Payload
* @param version Version identifier
* @returns Versioned cache key
*/
static createVersionedKey(event: string, payload: any, version: string): string;
/**
* Migrates cache entries from one version to another
* @param cache Cache manager instance
* @param oldVersion Old version identifier
* @param newVersion New version identifier
* @param migrator Function to migrate data
* @returns Number of entries migrated
*/
static migrateVersion(cache: CacheManager, oldVersion: string, newVersion: string, migrator: (oldData: any) => any): number;
}
/**
* connectic - Request/Response Management
*
* This file implements async request/response patterns over the event system
* using correlation IDs, timeouts, retries, and intelligent caching.
*/
/**
* Utility functions for request/response patterns
*/
declare class RequestResponseUtils {
/**
* Creates a timeout wrapper for any async function
* @param fn Async function to wrap
* @param timeoutMs Timeout in milliseconds
* @returns Wrapped function with timeout
*/
static withTimeout<T>(fn: () => Promise<T>, timeoutMs: number): () => Promise<T>;
/**
* Creates a retry wrapper for any async function
* @param fn Async function to wrap
* @param maxRetries Maximum number of retries
* @param backoffMs Base backoff delay
* @returns Wrapped function with retry logic
*/
static withRetries<T>(fn: () => Promise<T>, maxRetries: number, backoffMs?: number): () => Promise<T>;
/**
* Creates a circuit breaker for requests
* @param failureThreshold Number of failures before opening circuit
* @param resetTimeoutMs Time before attempting to close circuit
* @returns Circuit breaker function
*/
static createCircuitBreaker<T>(failureThreshold: number, resetTimeoutMs: number): (fn: () => Promise<T>) => Promise<T>;
}
/**
* connectic - Interceptor Management
*
* This file implements request and response interceptors for transforming
* data flowing through the bus system.
*/
/**
* Built-in interceptor functions for common use cases
*/
declare class BuiltinInterceptors {
/**
* Creates an interceptor that adds timestamp to all requests
* @param field Field name to add timestamp (default: 'timestamp')
* @returns Request interceptor
*/
static addTimestamp(field?: string): RequestInterceptor;
/**
* Creates an interceptor that validates response payloads
* @param validator Validation function
* @returns Response interceptor
*/
static validateResponse(validator: (event: string, response: any) => boolean | string): ResponseInterceptor;
/**
* Creates an interceptor that transforms response data
* @param transformer Transformation function
* @returns Response interceptor
*/
static transformResponse(transformer: (event: string, response: any) => any): ResponseInterceptor;
/**
* Creates an interceptor that logs all responses
* @param logger Logging function (defaults to console.log)
* @param options Logging options
* @returns Response interceptor
*/
static logResponses(logger?: (message: string, data?: any) => void, options?: {
includeResponse?: boolean;
prefix?: string;
}): ResponseInterceptor;
/**
* Creates an interceptor that adds metadata to responses
* @param metadata Metadata to add
* @returns Response interceptor
*/
static addResponseMetadata(metadata: Record<string, any> | ((event: string, response: any) => Record<string, any>)): ResponseInterceptor;
/**
* Creates an interceptor that normalizes response format
* @param format Response format configuration
* @returns Response interceptor
*/
static normalizeResponse(format?: {
dataField?: string;
errorField?: string;
successField?: string;
}): ResponseInterceptor;
/**
* Creates an interceptor that handles errors in responses
* @param errorHandler Error handling function
* @returns Response interceptor
*/
static handleResponseErrors(errorHandler: (event: string, error: any) => any): ResponseInterceptor;
/**
* Creates an interceptor that filters sensitive data from requests
* @param sensitiveFields Array of field names to filter
* @param replacement Replacement value (default: '[FILTERED]')
* @returns Request interceptor
*/
static filterSensitiveData(sensitiveFields: string[], replacement?: any): RequestInterceptor;
/**
* Creates an interceptor that adds retry information to requests
* @param getRetryCount Function to get current retry count
* @returns Request interceptor
*/
static addRetryInfo(getRetryCount: (event: string) => number): RequestInterceptor;
/**
* Creates an interceptor that adds performance metrics
* @param performanceTracker Performance tracking function
* @returns Response interceptor
*/
static addPerformanceMetrics(performanceTracker: (event: string, startTime: number, endTime: number) => void): ResponseInterceptor;
/**
* Creates an interceptor that implements rate limiting
* @param limit Number of requests per window
* @param windowMs Time window in milliseconds
* @returns Request interceptor
*/
static rateLimit(limit: number, windowMs: number): RequestInterceptor;
/**
* Creates an interceptor that implements circuit breaker pattern
* @param failureThreshold Number of failures before opening circuit
* @param resetTimeoutMs Time before attempting to close circuit
* @returns Request interceptor
*/
static circuitBreaker(_failureThreshold: number, resetTimeoutMs: number): RequestInterceptor;
}
/**
* Utility functions for working with interceptors
*/
declare class InterceptorUtils {
/**
* Combines multiple request interceptors into a single interceptor
* @param interceptors Array of request interceptors
* @returns Combined request interceptor
*/
static combineRequestInterceptors(interceptors: RequestInterceptor[]): RequestInterceptor;
/**
* Combines multiple response interceptors into a single interceptor
* @param interceptors Array of response interceptors
* @returns Combined response interceptor
*/
static combineResponseInterceptors(interceptors: ResponseInterceptor[]): ResponseInterceptor;
/**
* Creates a conditional interceptor that only runs for specific events
* @param condition Event matcher (string, regex, or function)
* @param interceptor Interceptor to run conditionally
* @returns Conditional request interceptor
*/
static conditionalRequest(condition: string | RegExp | ((event: string) => boolean), interceptor: RequestInterceptor): RequestInterceptor;
/**
* Creates a conditional response interceptor
* @param condition Event matcher (string, regex, or function)
* @param interceptor Interceptor to run conditionally
* @returns Conditional response interceptor
*/
static conditionalResponse(condition: string | RegExp | ((event: string) => boolean), interceptor: ResponseInterceptor): ResponseInterceptor;
/**
* Creates an event matcher function from various condition types
* @private
*/
private static createEventMatcher;
/**
* Creates an interceptor that only runs once per event
* @param interceptor Interceptor to run once
* @returns One-time interceptor
*/
static once<T extends RequestInterceptor | ResponseInterceptor>(interceptor: T): T;
/**
* Creates a debounced interceptor that only runs after a delay
* @param interceptor Interceptor to debounce
* @param delayMs Debounce delay in milliseconds
* @returns Debounced interceptor
*/
static debounce<T extends RequestInterceptor | ResponseInterceptor>(interceptor: T, delayMs: number): T;
/**
* Creates an interceptor that adds a timestamp to all requests
* @param field Field name for timestamp (default: 'timestamp')
* @returns Request interceptor
*/
static addTimestamp(field?: string): RequestInterceptor;
/**
* Creates an interceptor that adds request ID to all requests
* @param field Field name for request ID (default: 'requestId')
* @returns Request interceptor
*/
static addRequestId(field?: string): RequestInterceptor;
/**
* Creates an interceptor that adds authentication headers
* @param getToken Function to get authentication token
* @param field Field name for auth token (default: 'authToken')
* @returns Request interceptor
*/
static addAuthentication(getToken: () => string | null, field?: string): RequestInterceptor;
/**
* Creates an interceptor that validates request payloads
* @param validator Validation function
* @returns Request interceptor
*/
static validateRequest(validator: (event: string, payload: any) => boolean | string): RequestInterceptor;
/**
* Creates an interceptor that transforms request data
* @param transformer Transformation function
* @returns Request interceptor
*/
static transformRequest(transformer: (event: string, payload: any) => any): RequestInterceptor;
/**
* Creates an interceptor that logs all requests
* @param logger Logging function (defaults to console.log)
* @param options Logging options
* @returns Request interceptor
*/
static logRequests(logger?: (message: string, data?: any) => void, options?: {
includePayload?: boolean;
prefix?: string;
}): RequestInterceptor;
}
/**
* connectic - Main Entry Point
*
* This is the main entry point for the connectic library.
* It provides the unified MFEBus class and factory functions.
*/
/**
* Main bus class that combines all connectic functionality
*/
declare class MFEBus<TEventMap extends Record<string, any> = {}, TRequestMap extends Record<string, any> = {}> implements MFEBus$1<TEventMap, TRequestMap> {
private eventBus;
private middleware;
private stateManager;
private computedManager;
private cacheManager;
private requestManager;
private interceptorManager;
private config;
private namespacePath;
private namespacedEventCache;
private isDestroyed;
constructor(config: BusConfig, namespacePath?: string);
emit<K extends keyof TEventMap>(event: K, payload: TEventMap[K]): void;
on<K extends keyof TEventMap>(event: K, handler: (payload: TEventMap[K]) => void): () => void;
once<K extends keyof TEventMap>(event: K, handler: (payload: TEventMap[K]) => void): () => void;
off<K extends keyof TEventMap>(event: K, handler: Function): void;
removeAllListeners<K extends keyof TEventMap>(event?: K): void;
request<K extends keyof TRequestMap>(event: K, payload?: TRequestMap[K] extends {
request: infer R;
} ? R : any, options?: RequestOptions): Promise<TRequestMap[K] extends {
response: infer R;
} ? R : any>;
requestMany<K extends keyof TRequestMap>(event: K, payload?: TRequestMap[K] extends {
request: infer R;
} ?