const flatten = (values) => [].concat(...values), noop = function noop() {
    return Promise.resolve();
};
export function functionList(list, ...args) {
    const arrayList = Symbol.iterator in list ? Array.from(list) : [list];
    return arrayList.map((x) => {
        return (_, next) => Promise.resolve(x(...args)).then(next);
    });
}
class Executor {
    constructor(mw, continuation) {
        this.mw = mw;
        this.continuation = continuation;
    }
    tryInvokeMiddleware(context, middleware, next = noop) {
        try {
            const resolved = middleware ? middleware(context, next) : context;
            return Promise.resolve(resolved);
        }
        catch (error) {
            return Promise.reject(error);
        }
    }
    get middleware() {
        return (context, next) => {
            return this.tryInvokeMiddleware(context, this.mw, this.continuation.bind(null, context, next));
        };
    }
}
/**
 * Create a function to invoke all passed middleware functions
 * with a single argument <T>context
 * @param middleware
 */
export function compose(...middleware) {
    return flatten(middleware)
        .filter((x) => {
        if ('function' !== typeof x) {
            throw new TypeError(`${x}, must be a middleware function accepting (context, next) arguments`);
        }
        return x;
    })
        .reduceRight((composed, mw) => {
        return new Executor(mw, composed).middleware;
    }, Executor.prototype.tryInvokeMiddleware);
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29tcG9zZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9jb21wb3NlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQVFBLE1BQU0sT0FBTyxHQUFHLENBQUksTUFBMkIsRUFBRSxFQUFFLENBQUUsRUFBVSxDQUFDLE1BQU0sQ0FBQyxHQUFHLE1BQU0sQ0FBUSxFQUN0RixJQUFJLEdBQUcsU0FBUyxJQUFJO0lBQ2xCLE9BQU8sT0FBTyxDQUFDLE9BQU8sRUFBRSxDQUFBO0FBQzFCLENBQUMsQ0FBQTtBQUVILE1BQU0sVUFBVSxZQUFZLENBQzFCLElBQTJCLEVBQzNCLEdBQUcsSUFBVztJQUVkLE1BQU0sU0FBUyxHQUFHLE1BQU0sQ0FBQyxRQUFRLElBQUksSUFB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