// ets_tracing: off
import * as A from "../../Collections/Immutable/Chunk";
import * as Tp from "../../Collections/Immutable/Tuple";
import { pipe } from "../../Function";
import * as O from "../../Option";
import * as T from "../_internal/effect";
import * as M from "../_internal/managed";
import * as Ref from "../_internal/ref";
import * as Pull from "../Pull";
import { Stream } from "./definitions";
/**
 * Creates a single-valued stream from a managed resource
 */

export function managed(self) {
  return new Stream(M.map_(M.let_(M.bind_(M.bind_(M.do, "doneRef", () => Ref.makeManagedRef(false)), "finalizer", () => M.makeManagedReleaseMap(T.sequential)), "pull", ({
    doneRef,
    finalizer
  }) => T.uninterruptibleMask(({
    restore
  }) => T.chain_(doneRef.get, done => done ? Pull.end : T.mapError_(T.map_(T.tap_(T.bind_(T.do, "a", () => T.onError_(restore(T.provideSome_(T.map_(self.effect, ({
    tuple: [_, __]
  }) => __), r => Tp.tuple(r, finalizer))), () => doneRef.set(true))), () => doneRef.set(true)), ({
    a
  }) => A.single(a)), O.some)))), ({
    pull
  }) => pull));
}
//# sourceMappingURL=managed.js.map