@revealui/resilience 0.2.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.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025-2026 RevealUI Studio
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
@@ -0,0 +1,112 @@
1
+ RevealUI Commercial License
2
+ Version 1.0, February 2026
3
+
4
+ Copyright (c) 2025-2026 RevealUI Studio (founder@revealui.com)
5
+
6
+ TERMS AND CONDITIONS
7
+
8
+ 1. DEFINITIONS
9
+
10
+ "Software" means the RevealUI source code, documentation, and associated
11
+ files contained in directories and packages designated as commercial,
12
+ including but not limited to: packages/ai, packages/mcp, packages/editors,
13
+ packages/services, packages/harnesses, and any directory named "ee" within
14
+ the repository.
15
+
16
+ "License Key" means a valid RevealUI license key obtained through an active
17
+ paid subscription at https://revealui.com.
18
+
19
+ "Licensee" means the individual or organization that holds a valid License
20
+ Key through an active subscription.
21
+
22
+ "Production Use" means any use of the Software beyond local development and
23
+ evaluation, including but not limited to: deploying the Software to serve
24
+ end users, integrating the Software into a product or service, or using the
25
+ Software in a revenue-generating capacity.
26
+
27
+ 2. GRANT OF RIGHTS
28
+
29
+ Subject to the terms of this License and a valid License Key, the Licensee
30
+ is granted a non-exclusive, non-transferable, revocable license to:
31
+
32
+ (a) Use the Software for internal development and Production Use.
33
+ (b) Modify the Software for internal use.
34
+ (c) Deploy the Software on infrastructure controlled by the Licensee.
35
+
36
+ Enterprise License holders are additionally granted the right to:
37
+
38
+ (d) Deploy the Software in a self-hosted environment.
39
+ (e) Remove or replace RevealUI branding (white-label).
40
+ (f) Use the Software for multiple tenants within the Licensee's
41
+ organization or customer base.
42
+
43
+ 3. RESTRICTIONS
44
+
45
+ The Licensee SHALL NOT:
46
+
47
+ (a) Provide the Software, or any portion of it, to third parties as a
48
+ hosted or managed service that competes with RevealUI.
49
+ (b) Redistribute, sublicense, sell, or otherwise transfer the Software
50
+ or any portion of it to third parties.
51
+ (c) Remove, alter, or circumvent the license key verification
52
+ functionality of the Software.
53
+ (d) Use the Software in Production without a valid License Key.
54
+ (e) Share, publish, or make the License Key available to unauthorized
55
+ parties.
56
+
57
+ 4. EVALUATION
58
+
59
+ The Software may be used for evaluation and local development purposes
60
+ without a License Key. Evaluation use does not grant any rights to
61
+ Production Use.
62
+
63
+ 5. SUBSCRIPTION AND PAYMENT
64
+
65
+ This License is valid only during the term of an active paid subscription.
66
+ Upon cancellation or expiration of the subscription:
67
+
68
+ (a) The License terminates automatically.
69
+ (b) A grace period of fourteen (14) days is provided for the Licensee
70
+ to transition away from Production Use.
71
+ (c) After the grace period, the Licensee must cease all Production Use
72
+ of the Software.
73
+
74
+ 6. INTELLECTUAL PROPERTY
75
+
76
+ The Software is and remains the intellectual property of RevealUI Studio.
77
+ This License does not grant any ownership rights. Contributions to
78
+ commercial portions of the Software require a Contributor License Agreement.
79
+
80
+ 7. OPEN SOURCE COMPONENTS
81
+
82
+ This License applies only to files and directories designated as commercial.
83
+ Files under the MIT License (as indicated in the root LICENSE file) are not
84
+ subject to this commercial license and may be used freely under MIT terms.
85
+
86
+ 8. DISCLAIMER OF WARRANTY
87
+
88
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
89
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
90
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
91
+
92
+ 9. LIMITATION OF LIABILITY
93
+
94
+ IN NO EVENT SHALL REVEALUI STUDIO BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
95
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
96
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
97
+ DEALINGS IN THE SOFTWARE, EXCEEDING THE AMOUNT PAID BY THE LICENSEE IN
98
+ THE TWELVE (12) MONTHS PRECEDING THE CLAIM.
99
+
100
+ 10. GOVERNING LAW
101
+
102
+ This License shall be governed by the laws of the State of California,
103
+ United States of America, without regard to its conflict of law provisions.
104
+
105
+ 11. ENTIRE AGREEMENT
106
+
107
+ This License constitutes the entire agreement between the parties with
108
+ respect to the commercial portions of the Software and supersedes all
109
+ prior agreements, understandings, and communications.
110
+
111
+ For licensing inquiries: founder@revealui.com
112
+ For pricing and subscriptions: https://revealui.com/pricing
@@ -0,0 +1,477 @@
1
+ /**
2
+ * Circuit Breaker Pattern
3
+ *
4
+ * Prevents cascading failures by stopping requests to failing services
5
+ */
6
+ type CircuitState = 'closed' | 'open' | 'half-open';
7
+ interface CircuitBreakerConfig {
8
+ failureThreshold?: number;
9
+ successThreshold?: number;
10
+ timeout?: number;
11
+ resetTimeout?: number;
12
+ volumeThreshold?: number;
13
+ errorFilter?: (error: Error) => boolean;
14
+ onStateChange?: (state: CircuitState) => void;
15
+ onTrip?: () => void;
16
+ onReset?: () => void;
17
+ }
18
+ interface CircuitBreakerStats {
19
+ [key: string]: unknown;
20
+ state: CircuitState;
21
+ failures: number;
22
+ successes: number;
23
+ consecutiveFailures: number;
24
+ consecutiveSuccesses: number;
25
+ totalCalls: number;
26
+ totalFailures: number;
27
+ totalSuccesses: number;
28
+ lastFailureTime?: number;
29
+ lastSuccessTime?: number;
30
+ stateChangedAt: number;
31
+ }
32
+ /**
33
+ * Circuit Breaker implementation
34
+ */
35
+ declare class CircuitBreaker {
36
+ private state;
37
+ private failures;
38
+ private successes;
39
+ private consecutiveFailures;
40
+ private consecutiveSuccesses;
41
+ private totalCalls;
42
+ private totalFailures;
43
+ private totalSuccesses;
44
+ private lastFailureTime?;
45
+ private lastSuccessTime?;
46
+ private stateChangedAt;
47
+ private resetTimer?;
48
+ protected config: Required<CircuitBreakerConfig>;
49
+ constructor(config?: CircuitBreakerConfig);
50
+ /**
51
+ * Execute function with circuit breaker
52
+ */
53
+ execute<T>(fn: () => Promise<T>): Promise<T>;
54
+ /**
55
+ * Handle successful execution
56
+ */
57
+ private onSuccess;
58
+ /**
59
+ * Handle failed execution
60
+ */
61
+ private onFailure;
62
+ /**
63
+ * Transition to new state
64
+ */
65
+ private transitionTo;
66
+ /**
67
+ * Get current state
68
+ */
69
+ getState(): CircuitState;
70
+ /**
71
+ * Get statistics
72
+ */
73
+ getStats(): CircuitBreakerStats;
74
+ /**
75
+ * Manually open circuit
76
+ */
77
+ trip(): void;
78
+ /**
79
+ * Manually close circuit
80
+ */
81
+ reset(): void;
82
+ /**
83
+ * Force state to half-open
84
+ */
85
+ halfOpen(): void;
86
+ /**
87
+ * Check if circuit is open
88
+ */
89
+ isOpen(): boolean;
90
+ /**
91
+ * Check if circuit is closed
92
+ */
93
+ isClosed(): boolean;
94
+ /**
95
+ * Check if circuit is half-open
96
+ */
97
+ isHalfOpen(): boolean;
98
+ /**
99
+ * Get failure rate
100
+ */
101
+ getFailureRate(): number;
102
+ /**
103
+ * Get success rate
104
+ */
105
+ getSuccessRate(): number;
106
+ /**
107
+ * Cleanup
108
+ */
109
+ destroy(): void;
110
+ }
111
+ /**
112
+ * Circuit breaker open error
113
+ */
114
+ declare class CircuitBreakerOpenError extends Error {
115
+ constructor(message?: string);
116
+ }
117
+ /**
118
+ * Circuit breaker registry
119
+ */
120
+ declare class CircuitBreakerRegistry {
121
+ private breakers;
122
+ /**
123
+ * Get or create circuit breaker
124
+ */
125
+ get(name: string, config?: CircuitBreakerConfig): CircuitBreaker;
126
+ /**
127
+ * Check if breaker exists
128
+ */
129
+ has(name: string): boolean;
130
+ /**
131
+ * Remove circuit breaker
132
+ */
133
+ remove(name: string): boolean;
134
+ /**
135
+ * Get all breakers
136
+ */
137
+ getAll(): Map<string, CircuitBreaker>;
138
+ /**
139
+ * Get all statistics
140
+ */
141
+ getAllStats(): Record<string, CircuitBreakerStats>;
142
+ /**
143
+ * Reset all breakers
144
+ */
145
+ resetAll(): void;
146
+ /**
147
+ * Clear all breakers
148
+ */
149
+ clear(): void;
150
+ }
151
+ /**
152
+ * Global circuit breaker registry
153
+ */
154
+ declare const circuitBreakerRegistry: CircuitBreakerRegistry;
155
+ /**
156
+ * Create circuit breaker decorator
157
+ */
158
+ declare function CircuitBreak(nameOrConfig?: string | CircuitBreakerConfig): (target: object, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
159
+ /**
160
+ * Execute with circuit breaker
161
+ */
162
+ declare function withCircuitBreaker<T>(name: string, fn: () => Promise<T>, config?: CircuitBreakerConfig): Promise<T>;
163
+ /**
164
+ * Create circuit breaker middleware
165
+ */
166
+ declare function createCircuitBreakerMiddleware<TRequest = unknown, TResponse = unknown>(name: string, config?: CircuitBreakerConfig): (_request: TRequest, next: () => Promise<TResponse>) => Promise<TResponse>;
167
+ /**
168
+ * Circuit breaker for fetch
169
+ */
170
+ declare function fetchWithCircuitBreaker(name: string, url: string, init?: RequestInit, config?: CircuitBreakerConfig): Promise<Response>;
171
+ /**
172
+ * Adaptive circuit breaker with dynamic thresholds
173
+ */
174
+ declare class AdaptiveCircuitBreaker extends CircuitBreaker {
175
+ private errorRateWindow;
176
+ private windowSize;
177
+ private adaptiveThreshold;
178
+ constructor(config?: CircuitBreakerConfig);
179
+ /**
180
+ * Execute with adaptive thresholds
181
+ */
182
+ execute<T>(fn: () => Promise<T>): Promise<T>;
183
+ /**
184
+ * Record success in window
185
+ */
186
+ private recordSuccess;
187
+ /**
188
+ * Record failure in window
189
+ */
190
+ private recordFailure;
191
+ /**
192
+ * Trim window to size
193
+ */
194
+ private trimWindow;
195
+ /**
196
+ * Adjust threshold based on error rate
197
+ */
198
+ private adjustThreshold;
199
+ /**
200
+ * Get error rate in window
201
+ */
202
+ private getWindowErrorRate;
203
+ /**
204
+ * Get adaptive threshold
205
+ */
206
+ getAdaptiveThreshold(): number;
207
+ }
208
+ /**
209
+ * Bulkhead pattern - limit concurrent executions
210
+ */
211
+ declare class Bulkhead {
212
+ private activeRequests;
213
+ private queue;
214
+ private maxConcurrent;
215
+ private maxQueue;
216
+ constructor(maxConcurrent?: number, maxQueue?: number);
217
+ /**
218
+ * Execute with bulkhead
219
+ */
220
+ execute<T>(fn: () => Promise<T>): Promise<T>;
221
+ /**
222
+ * Get active requests
223
+ */
224
+ getActiveRequests(): number;
225
+ /**
226
+ * Get queue size
227
+ */
228
+ getQueueSize(): number;
229
+ /**
230
+ * Get statistics
231
+ */
232
+ getStats(): {
233
+ activeRequests: number;
234
+ queueSize: number;
235
+ maxConcurrent: number;
236
+ maxQueue: number;
237
+ };
238
+ }
239
+ /**
240
+ * Combined resilience wrapper
241
+ */
242
+ declare class ResilientOperation<T> {
243
+ private fn;
244
+ private circuitBreaker?;
245
+ private bulkhead?;
246
+ constructor(fn: () => Promise<T>, circuitBreaker?: CircuitBreaker | undefined, bulkhead?: Bulkhead | undefined);
247
+ /**
248
+ * Execute with all resilience patterns
249
+ */
250
+ execute(): Promise<T>;
251
+ }
252
+ /**
253
+ * Create resilient function
254
+ */
255
+ declare function createResilientFunction<T>(fn: () => Promise<T>, options?: {
256
+ circuitBreaker?: CircuitBreakerConfig;
257
+ bulkhead?: {
258
+ maxConcurrent: number;
259
+ maxQueue: number;
260
+ };
261
+ }): () => Promise<T>;
262
+
263
+ /**
264
+ * Internal logger for @revealui/resilience.
265
+ *
266
+ * Defaults to `console`. Consumers should call `configureResilienceLogger()`
267
+ * to supply a structured logger (e.g. from `@revealui/utils/logger`).
268
+ */
269
+ interface ResilienceLogger {
270
+ warn(message: string, ...args: unknown[]): void;
271
+ error(message: string, ...args: unknown[]): void;
272
+ info(message: string, ...args: unknown[]): void;
273
+ debug(message: string, ...args: unknown[]): void;
274
+ }
275
+ /**
276
+ * Replace the default console logger with a structured logger.
277
+ */
278
+ declare function configureResilienceLogger(logger: ResilienceLogger): void;
279
+ /**
280
+ * Get the current resilience logger instance.
281
+ */
282
+ declare function getResilienceLogger(): ResilienceLogger;
283
+
284
+ /**
285
+ * Retry Logic for API Calls
286
+ *
287
+ * Implements exponential backoff and retry strategies
288
+ */
289
+ interface HttpError extends Error {
290
+ statusCode?: number;
291
+ response?: Response;
292
+ }
293
+ interface RetryConfig {
294
+ maxRetries?: number;
295
+ baseDelay?: number;
296
+ maxDelay?: number;
297
+ exponentialBackoff?: boolean;
298
+ jitter?: boolean;
299
+ retryableErrors?: (error: Error) => boolean;
300
+ onRetry?: (error: Error, attempt: number) => void;
301
+ }
302
+ interface RetryOptions {
303
+ signal?: AbortSignal;
304
+ }
305
+ /**
306
+ * Retry a function with exponential backoff
307
+ */
308
+ declare function retry<T>(fn: () => Promise<T>, config?: RetryConfig, options?: RetryOptions): Promise<T>;
309
+ /**
310
+ * Calculate retry delay with exponential backoff
311
+ */
312
+ declare function calculateDelay(attempt: number, baseDelay: number, maxDelay: number, exponentialBackoff: boolean, jitter: boolean): number;
313
+ /**
314
+ * Sleep with abort support
315
+ */
316
+ declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
317
+ /**
318
+ * Retry wrapper for fetch
319
+ */
320
+ declare function fetchWithRetry(url: string, init?: RequestInit, config?: RetryConfig): Promise<Response>;
321
+ /**
322
+ * Retry wrapper class
323
+ */
324
+ declare class RetryableOperation<T> {
325
+ private fn;
326
+ private config;
327
+ private abortController;
328
+ private attempts;
329
+ private lastError?;
330
+ constructor(fn: () => Promise<T>, config?: RetryConfig);
331
+ /**
332
+ * Execute with retry
333
+ */
334
+ execute(): Promise<T>;
335
+ /**
336
+ * Abort operation
337
+ */
338
+ abort(): void;
339
+ /**
340
+ * Get retry statistics
341
+ */
342
+ getStats(): {
343
+ attempts: number;
344
+ lastError?: Error;
345
+ };
346
+ }
347
+ /**
348
+ * Retry decorator
349
+ */
350
+ declare function Retryable(config?: RetryConfig): (_target: object, _propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
351
+ /**
352
+ * Create retry middleware for API client
353
+ */
354
+ declare function createRetryMiddleware<TRequest = unknown, TResponse = unknown>(config?: RetryConfig): (_request: TRequest, next: () => Promise<TResponse>) => Promise<TResponse>;
355
+ /**
356
+ * Batch retry - retry multiple operations
357
+ */
358
+ declare function retryBatch<T>(operations: Array<() => Promise<T>>, config?: RetryConfig): Promise<Array<T | Error>>;
359
+ /**
360
+ * Retry with fallback
361
+ */
362
+ declare function retryWithFallback<T>(primary: () => Promise<T>, fallback: () => Promise<T>, config?: RetryConfig): Promise<T>;
363
+ /**
364
+ * Conditional retry - only retry if condition is met
365
+ */
366
+ declare function retryIf<T>(fn: () => Promise<T>, condition: (error: Error, attempt: number) => boolean, config?: RetryConfig): Promise<T>;
367
+ /**
368
+ * Retry until condition is met
369
+ */
370
+ declare function retryUntil<T>(fn: () => Promise<T>, predicate: (result: T) => boolean, config?: RetryConfig, maxAttempts?: number): Promise<T>;
371
+ /**
372
+ * Exponential backoff iterator
373
+ */
374
+ declare class ExponentialBackoff implements AsyncIterable<number> {
375
+ private baseDelay;
376
+ private maxDelay;
377
+ private maxAttempts;
378
+ private jitter;
379
+ constructor(baseDelay?: number, maxDelay?: number, maxAttempts?: number, jitter?: boolean);
380
+ [Symbol.asyncIterator](): AsyncIterator<number>;
381
+ }
382
+ /**
383
+ * Retry policy builder
384
+ */
385
+ declare class RetryPolicyBuilder {
386
+ private config;
387
+ /**
388
+ * Set max retries
389
+ */
390
+ maxRetries(count: number): this;
391
+ /**
392
+ * Set base delay
393
+ */
394
+ baseDelay(ms: number): this;
395
+ /**
396
+ * Set max delay
397
+ */
398
+ maxDelay(ms: number): this;
399
+ /**
400
+ * Enable/disable exponential backoff
401
+ */
402
+ exponentialBackoff(enabled?: boolean): this;
403
+ /**
404
+ * Enable/disable jitter
405
+ */
406
+ jitter(enabled?: boolean): this;
407
+ /**
408
+ * Set custom retryable errors function
409
+ */
410
+ retryOn(fn: (error: Error) => boolean): this;
411
+ /**
412
+ * Set retry callback
413
+ */
414
+ onRetry(fn: (error: Error, attempt: number) => void): this;
415
+ /**
416
+ * Build retry config
417
+ */
418
+ build(): RetryConfig;
419
+ /**
420
+ * Execute function with built policy
421
+ */
422
+ execute<T>(fn: () => Promise<T>): Promise<T>;
423
+ }
424
+ /**
425
+ * Common retry policies
426
+ */
427
+ declare const RetryPolicies: {
428
+ /**
429
+ * Default policy - 3 retries with exponential backoff
430
+ */
431
+ default: () => RetryConfig;
432
+ /**
433
+ * Aggressive policy - more retries, faster backoff
434
+ */
435
+ aggressive: () => RetryConfig;
436
+ /**
437
+ * Conservative policy - fewer retries, longer backoff
438
+ */
439
+ conservative: () => RetryConfig;
440
+ /**
441
+ * Linear backoff policy
442
+ */
443
+ linear: () => RetryConfig;
444
+ /**
445
+ * Immediate retry policy - no delay
446
+ */
447
+ immediate: () => RetryConfig;
448
+ /**
449
+ * Network error only policy
450
+ */
451
+ networkOnly: () => RetryConfig;
452
+ /**
453
+ * Idempotent operations policy (safe to retry)
454
+ */
455
+ idempotent: () => RetryConfig;
456
+ };
457
+ /**
458
+ * Global retry configuration
459
+ */
460
+ declare class GlobalRetryConfig {
461
+ private config;
462
+ /**
463
+ * Set global retry config
464
+ */
465
+ setConfig(config: RetryConfig): void;
466
+ /**
467
+ * Get global retry config
468
+ */
469
+ getConfig(): RetryConfig;
470
+ /**
471
+ * Reset to default config
472
+ */
473
+ reset(): void;
474
+ }
475
+ declare const globalRetryConfig: GlobalRetryConfig;
476
+
477
+ export { AdaptiveCircuitBreaker, Bulkhead, CircuitBreak, CircuitBreaker, type CircuitBreakerConfig, CircuitBreakerOpenError, CircuitBreakerRegistry, type CircuitBreakerStats, type CircuitState, ExponentialBackoff, type HttpError, type ResilienceLogger, ResilientOperation, type RetryConfig, type RetryOptions, RetryPolicies, RetryPolicyBuilder, Retryable, RetryableOperation, calculateDelay, circuitBreakerRegistry, configureResilienceLogger, createCircuitBreakerMiddleware, createResilientFunction, createRetryMiddleware, fetchWithCircuitBreaker, fetchWithRetry, getResilienceLogger, globalRetryConfig, retry, retryBatch, retryIf, retryUntil, retryWithFallback, sleep, withCircuitBreaker };