export async function applyMiddlewares(middlewares, ctx) {
    let index = -1;
    async function dispatch(position) {
        if (position <= index) {
            throw new Error("next() called multiple times");
        }
        index = position;
        if (position === middlewares.length) {
            return;
        }
        const middleware = middlewares[position];
        if (typeof middleware !== "function") {
            throw new Error(`Invalid ACP middleware at index ${position}`);
        }
        await middleware(ctx, () => dispatch(position + 1));
    }
    await dispatch(0);
}
