import * as Chunk from "@effect/data/Chunk";
import * as Context from "@effect/data/Context";
import * as Duration from "@effect/data/Duration";
import * as Either from "@effect/data/Either";
import { constFalse, constTrue, constVoid, dual, identity } from "@effect/data/Function";
import * as HashMap from "@effect/data/HashMap";
import * as HashSet from "@effect/data/HashSet";
import * as List from "@effect/data/List";
import * as Option from "@effect/data/Option";
import * as ReadonlyArray from "@effect/data/ReadonlyArray";
import * as Clock from "@effect/io/Clock";
import * as FiberId from "@effect/io/Fiber/Id";
import * as FiberRefs from "@effect/io/FiberRefs";
import * as internalCause from "@effect/io/internal/cause";
import * as core from "@effect/io/internal/core";
import * as defaultServices from "@effect/io/internal/defaultServices";
import * as fiberRefsPatch from "@effect/io/internal/fiberRefs/patch";
import * as metricLabel from "@effect/io/internal/metric/label";
import * as SingleShotGen from "@effect/io/internal/singleShotGen";
import * as LogLevel from "@effect/io/Logger/Level";
import * as LogSpan from "@effect/io/Logger/Span";
import * as Ref from "@effect/io/Ref";
import * as Tracer from "@effect/io/Tracer";
/* @internal */
export const annotateLogs = /*#__PURE__*/dual(3, (effect, key, value) => core.flatMap(core.fiberRefGet(core.currentLogAnnotations), annotations => core.suspend(() => core.fiberRefLocally(core.currentLogAnnotations, HashMap.set(annotations, key, value))(effect))));
/* @internal */
export const annotateSpans = /*#__PURE__*/dual(3, (self, key, value) => core.flatMap(core.fiberRefGet(core.currentTracerSpanAnnotations), annotations => core.suspend(() => core.fiberRefLocally(core.currentTracerSpanAnnotations, HashMap.set(annotations, key, value))(self))));
/* @internal */
export const asSome = self => core.map(self, Option.some);
/* @internal */
export const asSomeError = self => core.mapError(self, Option.some);
/* @internal */
export const asyncOption = (register, blockingOn = FiberId.none) => core.asyncInterruptEither(cb => {
  const option = register(cb);
  switch (option._tag) {
    case "None":
      {
        return Either.left(core.unit);
      }
    case "Some":
      {
        return Either.right(option.value);
      }
  }
}, blockingOn);
/* @internal */
export const try_ = arg => {
  let evaluate;
  let onFailure = undefined;
  if (typeof arg === "function") {
    evaluate = arg;
  } else {
    evaluate = arg.try;
    onFailure = arg.catch;
  }
  return core.sync(() => {
    try {
      return evaluate();
    } catch (error) {
      throw core.makeEffectError(internalCause.fail(onFailure ? onFailure(error) : error));
    }
  });
};
/* @internal */
export const _catch = /*#__PURE__*/dual(
// @ts-expect-error
3, (self, tag, options) => core.catchAll(self, e => {
  if (typeof e === "object" && e != null && tag in e && e[tag] === options.failure) {
    return options.onFailure(e);
  }
  return core.fail(e);
}));
/* @internal */
export const catchAllDefect = /*#__PURE__*/dual(2, (self, f) => core.catchAllCause(self, core.unified(cause => {
  const option = internalCause.find(cause, _ => internalCause.isDieType(_) ? Option.some(_) : Option.none());
  switch (option._tag) {
    case "None":
      {
        return core.failCause(cause);
      }
    case "Some":
      {
        return f(option.value.defect);
      }
  }
})));
/* @internal */
export const catchSomeCause = /*#__PURE__*/dual(2, (self, f) => core.matchCauseEffect(self, {
  onFailure: cause => {
    const option = f(cause);
    switch (option._tag) {
      case "None":
        {
          return core.failCause(cause);
        }
      case "Some":
        {
          return option.value;
        }
    }
  },
  onSuccess: core.succeed
}));
/* @internal */
export const catchSomeDefect = /*#__PURE__*/dual(2, (self, pf) => core.catchAllCause(self, core.unified(cause => {
  const option = internalCause.find(cause, _ => internalCause.isDieType(_) ? Option.some(_) : Option.none());
  switch (option._tag) {
    case "None":
      {
        return core.failCause(cause);
      }
    case "Some":
      {
        const optionEffect = pf(option.value.defect);
        return optionEffect._tag === "Some" ? optionEffect.value : core.failCause(cause);
      }
  }
})));
/* @internal */
export const catchTag = /*#__PURE__*/dual(3, (self, k, f) => core.catchAll(self, e => {
  if ("_tag" in e && e["_tag"] === k) {
    return f(e);
  }
  return core.fail(e);
}));
/** @internal */
export const catchTags = /*#__PURE__*/dual(2, (self, cases) => core.catchAll(self, e => {
  const keys = Object.keys(cases);
  if ("_tag" in e && keys.includes(e["_tag"])) {
    return cases[e["_tag"]](e);
  }
  return core.fail(e);
}));
/* @internal */
export const cause = self => core.matchCause(self, {
  onFailure: identity,
  onSuccess: () => internalCause.empty
});
/* @internal */
export const clockWith = Clock.clockWith;
/* @internal */
export const clock = /*#__PURE__*/clockWith(core.succeed);
/* @internal */
export const currentSpan = /*#__PURE__*/core.map( /*#__PURE__*/core.fiberRefGet(core.currentTracerSpan), List.head);
/* @internal */
export const delay = /*#__PURE__*/dual(2, (self, duration) => core.zipRight(Clock.sleep(duration), self));
/* @internal */
export const descriptorWith = f => core.withFiberRuntime((state, status) => f({
  id: state.id(),
  status,
  interruptors: internalCause.interruptors(state.getFiberRef(core.currentInterruptedCause))
}));
/* @internal */
export const allowInterrupt = /*#__PURE__*/descriptorWith(descriptor => HashSet.size(descriptor.interruptors) > 0 ? core.interrupt : core.unit);
/* @internal */
export const descriptor = /*#__PURE__*/descriptorWith(core.succeed);
/* @internal */
export const diffFiberRefs = self => summarized(self, getFiberRefs, fiberRefsPatch.diff);
/* @internal */
export const Do = /*#__PURE__*/core.succeed({});
/* @internal */
export const bind = /*#__PURE__*/dual(3, (self, tag, f) => core.flatMap(self, k => core.map(f(k), a => ({
  ...k,
  [tag]: a
}))));
/* @internal */
export const bindTo = /*#__PURE__*/dual(2, (self, tag) => core.map(self, a => ({
  [tag]: a
})));
/* @internal */
export const bindValue = /*#__PURE__*/dual(3, (self, tag, f) => core.map(self, k => ({
  ...k,
  [tag]: f(k)
})));
/* @internal */
export const dropUntil = /*#__PURE__*/dual(2, (elements, predicate) => core.suspend(() => {
  const iterator = elements[Symbol.iterator]();
  const builder = [];
  let next;
  let dropping = core.succeed(false);
  let i = 0;
  while ((next = iterator.next()) && !next.done) {
    const a = next.value;
    const index = i++;
    dropping = core.flatMap(dropping, bool => {
      if (bool) {
        builder.push(a);
        return core.succeed(true);
      }
      return predicate(a, index);
    });
  }
  return core.map(dropping, () => builder);
}));
/* @internal */
export const dropWhile = /*#__PURE__*/dual(2, (elements, f) => core.suspend(() => {
  const iterator = elements[Symbol.iterator]();
  const builder = [];
  let next;
  let dropping = core.succeed(true);
  let i = 0;
  while ((next = iterator.next()) && !next.done) {
    const a = next.value;
    const index = i++;
    dropping = core.flatMap(dropping, d => core.map(d ? f(a, index) : core.succeed(false), b => {
      if (!b) {
        builder.push(a);
      }
      return b;
    }));
  }
  return core.map(dropping, () => builder);
}));
/* @internal */
export const contextWith = f => core.map(core.context(), f);
/* @internal */
export const eventually = self => core.orElse(self, () => core.flatMap(core.yieldNow(), () => eventually(self)));
/* @internal */
export const filterMap = /*#__PURE__*/dual(2, (elements, pf) => core.map(core.forEachSequential(elements, identity), ReadonlyArray.filterMap(pf)));
/* @internal */
export const filterOrDie = /*#__PURE__*/dual(3, (self, filter, orDieWith) => filterOrElse(self, filter, () => core.dieSync(orDieWith)));
/* @internal */
export const filterOrDieMessage = /*#__PURE__*/dual(3, (self, filter, message) => filterOrElse(self, filter, () => core.dieMessage(message)));
/* @internal */
export const filterOrElse = /*#__PURE__*/dual(3, (self, filter, orElse) => core.flatMap(self, a => filter(a) ? core.succeed(a) : orElse(a)));
/* @internal */
export const filterOrFail = /*#__PURE__*/dual(3, (self, filter, orFailWith) => filterOrElse(self, filter, a => core.failSync(() => orFailWith(a))));
/* @internal */
export const findFirst = /*#__PURE__*/dual(2, (elements, f) => core.suspend(() => {
  const iterator = elements[Symbol.iterator]();
  const next = iterator.next();
  if (!next.done) {
    return findLoop(iterator, 0, f, next.value);
  }
  return core.succeed(Option.none());
}));
const findLoop = (iterator, index, f, value) => core.flatMap(f(value, index), result => {
  if (result) {
    return core.succeed(Option.some(value));
  }
  const next = iterator.next();
  if (!next.done) {
    return findLoop(iterator, index + 1, f, next.value);
  }
  return core.succeed(Option.none());
});
/* @internal */
export const firstSuccessOf = effects => core.suspend(() => {
  const list = Chunk.fromIterable(effects);
  if (!Chunk.isNonEmpty(list)) {
    return core.dieSync(() => internalCause.IllegalArgumentException(`Received an empty collection of effects`));
  }
  return ReadonlyArray.reduce(Chunk.headNonEmpty(list), (left, right) => core.orElse(left, () => right))(Chunk.tailNonEmpty(list));
});
/* @internal */
export const flipWith = /*#__PURE__*/dual(2, (self, f) => core.flip(f(core.flip(self))));
/* @internal */
export const match = /*#__PURE__*/dual(2, (self, {
  onFailure,
  onSuccess
}) => core.matchEffect(self, {
  onFailure: e => core.succeed(onFailure(e)),
  onSuccess: a => core.succeed(onSuccess(a))
}));
/* @internal */
export const every = /*#__PURE__*/dual(2, (elements, f) => core.suspend(() => forAllLoop(elements[Symbol.iterator](), 0, f)));
const forAllLoop = (iterator, index, f) => {
  const next = iterator.next();
  return next.done ? core.succeed(true) : core.flatMap(f(next.value, index), b => b ? forAllLoop(iterator, index + 1, f) : core.succeed(b));
};
/* @internal */
export const forever = self => {
  const loop = core.flatMap(core.flatMap(self, () => core.yieldNow()), () => loop);
  return loop;
};
/** @internal */
class EffectGen {
  constructor(value) {
    this.value = value;
  }
  [Symbol.iterator]() {
    return new SingleShotGen.SingleShotGen(this);
  }
}
const adapter = function () {
  let x = arguments[0];
  for (let i = 1; i < arguments.length; i++) {
    x = arguments[i](x);
  }
  return new EffectGen(x);
};
/**
 * Inspired by https://github.com/tusharmath/qio/pull/22 (revised)
  @internal */
export const gen = f => core.suspend(() => {
  const iterator = f(adapter);
  const state = iterator.next();
  const run = state => state.done ? core.succeed(state.value) : core.flatMap(val => run(iterator.next(val)))(state.value.value);
  return run(state);
});
/* @internal */
export const getFiberRefs = /*#__PURE__*/core.withFiberRuntime(state => core.succeed(state.unsafeGetFiberRefs()));
/* @internal */
export const head = self => core.matchEffect(self, {
  onFailure: e => core.fail(Option.some(e)),
  onSuccess: as => {
    const iterator = as[Symbol.iterator]();
    const next = iterator.next();
    if (next.done) {
      return core.fail(Option.none());
    }
    return core.succeed(next.value);
  }
});
/* @internal */
export const ignore = self => match(self, {
  onFailure: constVoid,
  onSuccess: constVoid
});
/* @internal */
export const ignoreLogged = self => core.matchCauseEffect(self, {
  onFailure: cause => logCause(cause, "Debug", {
    message: "An error was silently ignored because it is not anticipated to be useful"
  }),
  onSuccess: () => core.unit
});
/* @internal */
export const inheritFiberRefs = childFiberRefs => updateFiberRefs((parentFiberId, parentFiberRefs) => FiberRefs.joinAs(parentFiberRefs, parentFiberId, childFiberRefs));
/* @internal */
export const isFailure = self => match(self, {
  onFailure: constTrue,
  onSuccess: constFalse
});
/* @internal */
export const isSuccess = self => match(self, {
  onFailure: constFalse,
  onSuccess: constTrue
});
/* @internal */
export const iterate = (initial, options) => core.suspend(() => {
  if (options.while(initial)) {
    return core.flatMap(options.body(initial), z2 => iterate(z2, options));
  }
  return core.succeed(initial);
});
/* @internal */
export const log = (message, level, options) => core.withFiberRuntime(fiberState => {
  fiberState.log(message, options?.cause ?? internalCause.empty, level ? Option.some(LogLevel.fromLiteral(level)) : Option.none());
  return core.unit;
});
/* @internal */
export const logCause = /*#__PURE__*/dual(args => internalCause.isCause(args[0]), (cause, level, options) => core.withFiberRuntime(fiberState => {
  fiberState.log(options?.message ?? "", cause, level ? Option.some(LogLevel.fromLiteral(level)) : Option.none());
  return core.unit;
}));
/* @internal */
export const withLog = /*#__PURE__*/dual(args => core.isEffect(args[0]), (self, message, level, options) => core.zipLeft(self, log(message, level, options)));
/* @internal */
export const withLogCause = /*#__PURE__*/dual(args => core.isEffect(args[0]), (self, level, options) => tapErrorCause(self, logCause(level, options)));
/* @internal */
export const withLogSpan = /*#__PURE__*/dual(2, (effect, label) => core.flatMap(core.fiberRefGet(core.currentLogSpan), stack => core.flatMap(Clock.currentTimeMillis, now => core.suspend(() => core.fiberRefLocally(core.currentLogSpan, List.prepend(stack, LogSpan.make(label, now)))(effect)))));
/* @internal */
export const logAnnotations = /*#__PURE__*/core.fiberRefGet(core.currentLogAnnotations);
/* @internal */
// @ts-expect-error
export const loop = (initial, options) => options.discard ? loopDiscard(initial, options.while, options.step, options.body) : core.map(loopInternal(initial, options.while, options.step, options.body), x => Array.from(x));
const loopInternal = (initial, cont, inc, body) => core.suspend(() => cont(initial) ? core.flatMap(body(initial), a => core.map(loopInternal(inc(initial), cont, inc, body), List.prepend(a))) : core.sync(() => List.empty()));
const loopDiscard = (initial, cont, inc, body) => core.suspend(() => cont(initial) ? core.flatMap(body(initial), () => loopDiscard(inc(initial), cont, inc, body)) : core.unit);
/* @internal */
export const mapAccum = /*#__PURE__*/dual(3, (elements, zero, f) => core.suspend(() => {
  const iterator = elements[Symbol.iterator]();
  const builder = [];
  let result = core.succeed(zero);
  let next;
  let i = 0;
  while (!(next = iterator.next()).done) {
    const index = i++;
    result = core.flatMap(result, state => core.map(f(state, next.value, index), ([z, b]) => {
      builder.push(b);
      return z;
    }));
  }
  return core.map(result, z => [z, builder]);
}));
/* @internal */
export const mapErrorCause = /*#__PURE__*/dual(2, (self, f) => core.matchCauseEffect(self, {
  onFailure: c => core.failCauseSync(() => f(c)),
  onSuccess: core.succeed
}));
/* @internal */
export const memoize = self => core.flatMap(deferred => core.map(complete => core.zipRight(complete, core.flatMap(([patch, a]) => core.as(patchFiberRefs(patch), a))(core.deferredAwait(deferred))))(once(core.intoDeferred(deferred)(diffFiberRefs(self)))))(core.deferredMake());
/* @internal */
export const merge = self => core.matchEffect(self, {
  onFailure: e => core.succeed(e),
  onSuccess: core.succeed
});
/* @internal */
export const negate = self => core.map(self, b => !b);
/* @internal */
export const none = self => core.matchEffect(self, {
  onFailure: e => core.fail(Option.some(e)),
  onSuccess: option => {
    switch (option._tag) {
      case "None":
        {
          return core.unit;
        }
      case "Some":
        {
          return core.fail(Option.none());
        }
    }
  }
});
/* @internal */
export const once = self => core.map(Ref.make(true), ref => core.asUnit(core.whenEffect(self, Ref.getAndSet(ref, false))));
/* @internal */
export const option = self => core.matchEffect(self, {
  onFailure: () => core.succeed(Option.none()),
  onSuccess: a => core.succeed(Option.some(a))
});
/* @internal */
export const orElseFail = /*#__PURE__*/dual(2, (self, evaluate) => core.orElse(self, () => core.failSync(evaluate)));
/* @internal */
export const orElseSucceed = /*#__PURE__*/dual(2, (self, evaluate) => core.orElse(self, () => core.sync(evaluate)));
/* @internal */
export const parallelErrors = self => core.matchCauseEffect(self, {
  onFailure: cause => {
    const errors = Array.from(internalCause.failures(cause));
    return errors.length === 0 ? core.failCause(cause) : core.fail(errors);
  },
  onSuccess: core.succeed
});
/* @internal */
export const patchFiberRefs = patch => updateFiberRefs((fiberId, fiberRefs) => fiberRefsPatch.patch(fiberId, fiberRefs)(patch));
/* @internal */
export const promise = evaluate => core.async(resolve => {
  evaluate().then(a => resolve(core.exitSucceed(a))).catch(e => resolve(core.exitDie(e)));
});
/* @internal */
export const promiseInterrupt = evaluate => core.asyncInterruptEither(resolve => {
  const controller = new AbortController();
  evaluate(controller.signal).then(a => resolve(core.exitSucceed(a))).catch(e => resolve(core.exitDie(e)));
  return Either.left(core.sync(() => controller.abort()));
});
/* @internal */
export const provideService = /*#__PURE__*/dual(3, (self, tag, service) => provideServiceEffect(self, tag, core.succeed(service)));
/* @internal */
export const provideServiceEffect = /*#__PURE__*/dual(3, (self, tag, effect) => core.contextWithEffect(env => core.flatMap(effect, service => core.provideContext(self, Context.add(tag, service)(env)))));
/* @internal */
export const random = /*#__PURE__*/defaultServices.randomWith(core.succeed);
/* @internal */
export const reduce = /*#__PURE__*/dual(3, (elements, zero, f) => ReadonlyArray.fromIterable(elements).reduce((acc, el, i) => core.flatMap(acc, a => f(a, el, i)), core.succeed(zero)));
/* @internal */
export const reduceRight = /*#__PURE__*/dual(3, (elements, zero, f) => ReadonlyArray.fromIterable(elements).reduceRight((acc, el, i) => core.flatMap(acc, a => f(el, a, i)), core.succeed(zero)));
/* @internal */
export const reduceWhile = /*#__PURE__*/dual(3, (elements, zero, options) => core.flatMap(core.sync(() => elements[Symbol.iterator]()), iterator => reduceWhileLoop(iterator, 0, zero, options.while, options.body)));
const reduceWhileLoop = (iterator, index, state, predicate, f) => {
  const next = iterator.next();
  if (!next.done && predicate(state)) {
    return core.flatMap(f(state, next.value, index), nextState => reduceWhileLoop(iterator, index + 1, nextState, predicate, f));
  }
  return core.succeed(state);
};
/* @internal */
export const repeatN = /*#__PURE__*/dual(2, (self, n) => core.suspend(() => repeatNLoop(self, n)));
/* @internal */
const repeatNLoop = (self, n) => core.flatMap(self, a => n <= 0 ? core.succeed(a) : core.zipRight(core.yieldNow(), repeatNLoop(self, n - 1)));
/* @internal */
export const sandbox = self => core.matchCauseEffect(self, {
  onFailure: core.fail,
  onSuccess: core.succeed
});
/* @internal */
export const setFiberRefs = fiberRefs => core.suspend(() => FiberRefs.setAll(fiberRefs));
/* @internal */
export const sleep = Clock.sleep;
/* @internal */
export const some = self => core.matchEffect(self, {
  onFailure: e => core.fail(Option.some(e)),
  onSuccess: option => {
    switch (option._tag) {
      case "None":
        {
          return core.fail(Option.none());
        }
      case "Some":
        {
          return core.succeed(option.value);
        }
    }
  }
});
/* @internal */
export const succeedNone = /*#__PURE__*/core.succeed( /*#__PURE__*/Option.none());
/* @internal */
export const succeedSome = value => core.succeed(Option.some(value));
/* @internal */
export const summarized = /*#__PURE__*/dual(3, (self, summary, f) => core.flatMap(summary, start => core.flatMap(self, value => core.map(summary, end => [f(start, end), value]))));
/* @internal */
export const tagMetrics = /*#__PURE__*/dual(3, (self, key, value) => labelMetrics(self, [metricLabel.make(key, value)]));
/* @internal */
export const labelMetrics = /*#__PURE__*/dual(2, (self, labels) => labelMetricsSet(self, HashSet.fromIterable(labels)));
/* @internal */
export const labelMetricsSet = /*#__PURE__*/dual(2, (self, labels) => core.fiberRefLocallyWith(core.currentMetricLabels, set => HashSet.union(labels)(set))(self));
/* @internal */
export const takeUntil = /*#__PURE__*/dual(2, (elements, predicate) => core.suspend(() => {
  const iterator = elements[Symbol.iterator]();
  const builder = [];
  let next;
  let effect = core.succeed(false);
  let i = 0;
  while ((next = iterator.next()) && !next.done) {
    const a = next.value;
    const index = i++;
    effect = core.flatMap(effect, bool => {
      if (bool) {
        return core.succeed(true);
      }
      builder.push(a);
      return predicate(a, index);
    });
  }
  return core.map(effect, () => builder);
}));
/* @internal */
export const takeWhile = /*#__PURE__*/dual(2, (elements, predicate) => core.suspend(() => {
  const iterator = elements[Symbol.iterator]();
  const builder = [];
  let next;
  let taking = core.succeed(true);
  let i = 0;
  while ((next = iterator.next()) && !next.done) {
    const a = next.value;
    const index = i++;
    taking = core.flatMap(taking, taking => core.map(bool => {
      if (bool) {
        builder.push(a);
      }
      return bool;
    })(taking ? predicate(a, index) : core.succeed(false)));
  }
  return core.map(taking, () => builder);
}));
/* @internal */
export const tapBoth = /*#__PURE__*/dual(2, (self, {
  onFailure,
  onSuccess
}) => core.matchCauseEffect(self, {
  onFailure: cause => {
    const either = internalCause.failureOrCause(cause);
    switch (either._tag) {
      case "Left":
        {
          return core.zipRight(onFailure(either.left), core.failCause(cause));
        }
      case "Right":
        {
          return core.failCause(cause);
        }
    }
  },
  onSuccess: a => core.as(onSuccess(a), a)
}));
/* @internal */
export const tapDefect = /*#__PURE__*/dual(2, (self, f) => core.catchAllCause(self, cause => Option.match(internalCause.keepDefects(cause), {
  onNone: () => core.failCause(cause),
  onSome: a => core.zipRight(f(a), core.failCause(cause))
})));
/* @internal */
export const tapError = /*#__PURE__*/dual(2, (self, f) => core.matchCauseEffect(self, {
  onFailure: cause => {
    const either = internalCause.failureOrCause(cause);
    switch (either._tag) {
      case "Left":
        {
          return core.zipRight(f(either.left), core.failCause(cause));
        }
      case "Right":
        {
          return core.failCause(cause);
        }
    }
  },
  onSuccess: core.succeed
}));
/* @internal */
export const tapErrorCause = /*#__PURE__*/dual(2, (self, f) => core.matchCauseEffect(self, {
  onFailure: cause => core.zipRight(f(cause), core.failCause(cause)),
  onSuccess: core.succeed
}));
/* @internal */
export const timed = self => timedWith(self, Clock.currentTimeNanos);
/* @internal */
export const timedWith = /*#__PURE__*/dual(2, (self, nanos) => summarized(self, nanos, (start, end) => Duration.nanos(end - start)));
/* @internal */
export const tracerWith = Tracer.tracerWith;
/** @internal */
export const tracer = /*#__PURE__*/tracerWith(core.succeed);
/* @internal */
export const tryPromise = arg => core.flatMap(try_(arg), promise => core.async(resolve => {
  promise.then(a => resolve(core.exitSucceed(a))).catch(e => resolve(core.exitFail("catch" in arg ? arg.catch(e) : e)));
}));
/* @internal */
export const tryPromiseInterrupt = arg => {
  const hasCatch = ("catch" in arg);
  const evaluate = () => {
    const controller = new AbortController();
    return [controller, hasCatch ? arg.try(controller.signal) : arg(controller.signal)];
  };
  return core.flatMap(hasCatch ? try_({
    try: evaluate,
    catch: arg.catch
  }) : try_(evaluate), ([controller, promise]) => core.asyncInterruptEither(resolve => {
    promise.then(a => resolve(core.exitSucceed(a))).catch(e => resolve(core.exitFail(hasCatch ? arg.catch(e) : e)));
    return Either.left(core.sync(() => controller.abort()));
  }));
};
/* @internal */
export const tryMap = /*#__PURE__*/dual(2, (self, options) => core.flatMap(self, a => try_({
  try: () => options.try(a),
  catch: options.catch
})));
/* @internal */
export const tryMapPromise = /*#__PURE__*/dual(2, (self, options) => core.flatMap(self, a => tryPromise({
  try: () => options.try(a),
  catch: options.catch
})));
/* @internal */
export const tryMapPromiseInterrupt = /*#__PURE__*/dual(2, (self, options) => core.flatMap(self, a => tryPromiseInterrupt({
  try: signal => options.try(a, signal),
  catch: options.catch
})));
/* @internal */
export const unless = /*#__PURE__*/dual(2, (self, predicate) => core.suspend(() => predicate() ? succeedNone : asSome(self)));
/* @internal */
export const unlessEffect = /*#__PURE__*/dual(2, (self, predicate) => core.flatMap(predicate, b => b ? succeedNone : asSome(self)));
/* @internal */
export const unsandbox = self => mapErrorCause(self, internalCause.flatten);
/* @internal */
export const updateFiberRefs = f => core.withFiberRuntime(state => {
  state.setFiberRefs(f(state.id(), state.unsafeGetFiberRefs()));
  return core.unit;
});
/* @internal */
export const updateService = /*#__PURE__*/dual(3, (self, tag, f) => core.mapInputContext(self, context => Context.add(context, tag, f(Context.unsafeGet(context, tag)))));
/** @internal */
export const useSpan = (name, ...args) => {
  const options = args.length === 1 ? undefined : args[0];
  const evaluate = args[args.length - 1];
  return core.acquireUseRelease(tracerWith(tracer => core.flatMap(options?.parent ? core.succeed(Option.some(options.parent)) : options?.root ? core.succeed(Option.none()) : core.map(core.fiberRefGet(core.currentTracerSpan), List.head), parent => core.flatMap(core.fiberRefGet(core.currentTracerSpanAnnotations), annotations => core.flatMap(Clock.currentTimeNanos, startTime => core.sync(() => {
    const span = tracer.span(name, parent, options?.context ?? Context.empty(), startTime);
    HashMap.forEach(annotations, (value, key) => span.attribute(key, value));
    Object.entries(options?.attributes ?? {}).forEach(([k, v]) => {
      span.attribute(k, v);
    });
    return span;
  }))))), evaluate, (span, exit) => core.flatMap(Clock.clockWith(clock => clock.currentTimeNanos), endTime => core.sync(() => span.end(endTime, exit))));
};
/* @internal */
export const when = /*#__PURE__*/dual(2, (self, predicate) => core.suspend(() => predicate() ? core.map(self, Option.some) : core.succeed(Option.none())));
/* @internal */
export const whenFiberRef = /*#__PURE__*/dual(3, (self, fiberRef, predicate) => core.flatMap(core.fiberRefGet(fiberRef), s => predicate(s) ? core.map(self, a => [s, Option.some(a)]) : core.succeed([s, Option.none()])));
/* @internal */
export const whenRef = /*#__PURE__*/dual(3, (self, ref, predicate) => core.flatMap(Ref.get(ref), s => predicate(s) ? core.map(self, a => [s, Option.some(a)]) : core.succeed([s, Option.none()])));
/* @internal */
export const withMetric = /*#__PURE__*/dual(2, (self, metric) => metric(self));
/** @internal */
export const withSpan = /*#__PURE__*/dual(args => typeof args[0] !== "string", (self, name, options) => useSpan(name, options ?? {}, span => core.flatMap(core.fiberRefGet(core.currentTracerSpan), stack => core.fiberRefLocally(self, core.currentTracerSpan, List.prepend(stack, span)))));
/* @internal */
export const spanAnnotations = /*#__PURE__*/core.fiberRefGet(core.currentTracerSpanAnnotations);
/** @internal */
export const serviceFunctionEffect = (service, f) => (...args) => core.flatMap(service, a => f(a)(...args));
/** @internal */
export const serviceFunction = (service, f) => (...args) => core.map(service, a => f(a)(...args));
//# sourceMappingURL=effect.mjs.map