const fileName_1 = "(@effect/core) _src/stream/Channel/operations/runScoped.ts";
import * as tsplus_module_1 from "@effect/core/io/Effect/operations/suspendSucceed";
import * as tsplus_module_2 from "@tsplus/stdlib/data/Function";
import * as tsplus_module_3 from "@effect/core/io/Effect/operations/succeed";
import * as tsplus_module_4 from "@effect/core/io/Effect/operations/unit";
import * as tsplus_module_5 from "@effect/core/io/Effect/operations/acquireReleaseExit";
import * as tsplus_module_6 from "@effect/core/io/Effect/operations/flatMap";
import * as tsplus_module_7 from "@effect/core/io/Effect/operations/zipRight";
import * as tsplus_module_8 from "@effect/core/io/Effect/operations/done";
import { ChannelExecutor, readUpstream } from "@effect/core/stream/Channel/ChannelExecutor";
import { concreteChannelState } from "@effect/core/stream/Channel/ChannelState";
/**
 * Runs a channel until the end is received.
 *
 * @tsplus getter ets/Channel runScoped
 */

export function runScoped(self) {
  return tsplus_module_6.flatMap_(tsplus_module_5.acquireReleaseExit(() => tsplus_module_3.succeed(() => new ChannelExecutor(() => self, undefined, tsplus_module_2.identity), fileName_1 + ":14:19"), (exec, exit) => {
    const finalize = exec.close(exit, fileName_1 + ":16:34");
    return finalize != null ? finalize : tsplus_module_4.unit;
  }, fileName_1 + ":13:35"), exec => tsplus_module_1.suspendSucceed(() => interpret(exec.run(), exec), fileName_1 + ":19:44"), fileName_1 + ":19:12");
}

function interpret(channelState, exec) {
  // eslint-disable-next-line no-constant-condition
  while (1) {
    void 0;

    switch (channelState._tag) {
      case "Effect":
        {
          return tsplus_module_7.zipRight_(channelState.effect, () => interpret(exec.run(), exec), fileName_1 + ":31:44");
        }

      case "Emit":
        {
          channelState = exec.run();
          break;
        }

      case "Done":
        {
          return tsplus_module_8.done(() => exec.getDone(), fileName_1 + ":40:27");
        }

      case "Read":
        {
          return readUpstream(channelState, () => interpret(exec.run(), exec), fileName_1 + ":43:28");
        }
    }
  }

  throw new Error("Bug");
}
//# sourceMappingURL=runScoped.mjs.map