ai-patterns
Version:
Production-ready TypeScript patterns to build solid and robust AI applications. Retry logic, circuit breakers, rate limiting, human-in-the-loop escalation, prompt versioning, response validation, context window management, and more—all with complete type
63 lines • 1.97 kB
JavaScript
;
/**
* Compose Pattern - Middleware-based composition
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.compose = compose;
/**
* Compose multiple middlewares together
*
* Middlewares are applied from right to left (innermost first), similar to
* function composition in mathematics: compose([f, g, h])(x) = f(g(h(x)))
*
* @example
* ```typescript
* import { compose, withTimeout, withRetry, withCircuitBreaker } from 'ai-patterns';
*
* const robustAPI = compose([
* withCircuitBreaker({ failureThreshold: 5 }),
* withTimeout({ duration: 5000 }),
* withRetry({ maxAttempts: 3 })
* ]);
*
* const result = await robustAPI(
* async () => fetch('/api/data').then(r => r.json()),
* undefined
* );
* ```
*
* @param middlewares - Array of middlewares to compose
* @param config - Optional configuration
* @returns Composed function that applies all middlewares
*/
function compose(middlewares, config) {
return async (execute, input) => {
const startTime = Date.now();
if (config?.onStart) {
await config.onStart();
}
try {
// Build the middleware chain from right to left
let wrappedFn = async (inp) => {
return await execute(inp);
};
// Apply middlewares from right to left (last middleware wraps first)
for (let i = middlewares.length - 1; i >= 0; i--) {
wrappedFn = middlewares[i](wrappedFn);
}
const result = await wrappedFn(input);
if (config?.onComplete) {
const duration = Date.now() - startTime;
await config.onComplete(result, duration);
}
return result;
}
catch (error) {
if (config?.onError) {
await config.onError(error);
}
throw error;
}
};
}
//# sourceMappingURL=compose.js.map