"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.unsafeRunSyncExitEffect = exports.unsafeRunSyncExit = exports.unsafeRunSyncEffect = exports.unsafeRunSync = exports.unsafeRunPromiseExitEffect = exports.unsafeRunPromiseExit = exports.unsafeRunPromiseEffect = exports.unsafeRunPromise = exports.unsafeRunEffect = exports.unsafeRunCallback = exports.unsafeForkEffect = exports.unsafeFork = exports.runtime = exports.make = exports.isFiberFailure = exports.isAsyncFiberException = exports.fiberFailure = exports.defaultRuntimeFlags = exports.defaultRuntime = exports.asyncEffect = exports.RuntimeImpl = exports.FiberFailureId = exports.FiberFailureCauseId = void 0;
var Context = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/Context"));
var _Inspectable = /*#__PURE__*/require("@effect/data/Inspectable");
var Option = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/Option"));
var _Pipeable = /*#__PURE__*/require("@effect/data/Pipeable");
var Predicate = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/Predicate"));
var Exit = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/Exit"));
var Fiber = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/Fiber"));
var FiberId = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/FiberId"));
var FiberRefs = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/FiberRefs"));
var InternalCause = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/internal/cause"));
var core = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/internal/core"));
var FiberRuntime = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/internal/fiberRuntime"));
var fiberScope = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/internal/fiberScope"));
var OpCodes = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/internal/opCodes/effect"));
var runtimeFlags = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/internal/runtimeFlags"));
var _supervisor = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/internal/supervisor"));
var _scheduler = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/io/Scheduler"));
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/** @internal */
const unsafeFork = runtime => (self, options) => {
  const fiberId = FiberId.unsafeMake();
  const effect = self;
  let fiberRefs = FiberRefs.updatedAs(runtime.fiberRefs, {
    fiberId,
    fiberRef: core.currentContext,
    value: runtime.context
  });
  if (options?.scheduler) {
    fiberRefs = FiberRefs.updatedAs(fiberRefs, {
      fiberId,
      fiberRef: _scheduler.currentScheduler,
      value: options.scheduler
    });
  }
  if (options?.updateRefs) {
    fiberRefs = options.updateRefs(fiberRefs, fiberId);
  }
  const fiberRuntime = new FiberRuntime.FiberRuntime(fiberId, FiberRefs.forkAs(fiberRefs, fiberId), runtime.runtimeFlags);
  const supervisor = fiberRuntime._supervisor;
  if (supervisor !== _supervisor.none) {
    supervisor.onStart(runtime.context, effect, Option.none(), fiberRuntime);
    fiberRuntime.addObserver(exit => supervisor.onEnd(exit, fiberRuntime));
  }
  fiberScope.globalScope.add(runtime.runtimeFlags, fiberRuntime);
  fiberRuntime.start(effect);
  return fiberRuntime;
};
/** @internal */
exports.unsafeFork = unsafeFork;
const unsafeRunCallback = runtime => (effect, onExit) => {
  const fiberRuntime = unsafeFork(runtime)(effect);
  if (onExit) {
    fiberRuntime.addObserver(exit => {
      onExit(exit);
    });
  }
  return (id, onExitInterrupt) => unsafeRunCallback(runtime)(Fiber.interruptAs(id ?? FiberId.none)(fiberRuntime), onExitInterrupt ? exit => onExitInterrupt(Exit.flatten(exit)) : void 0);
};
/** @internal */
exports.unsafeRunCallback = unsafeRunCallback;
const unsafeRunSync = runtime => effect => {
  const result = unsafeRunSyncExit(runtime)(effect);
  if (result._tag === "Failure") {
    throw fiberFailure(result.i0);
  } else {
    return result.i0;
  }
};
/** @internal */
exports.unsafeRunSync = unsafeRunSync;
const asyncFiberException = fiber => {
  const limit = Error.stackTraceLimit;
  Error.stackTraceLimit = 0;
  const error = new Error();
  Error.stackTraceLimit = limit;
  const message = `Fiber #${fiber.id().id} cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work`;
  const _tag = "AsyncFiberException";
  Object.defineProperties(error, {
    _tag: {
      value: _tag
    },
    message: {
      value: message
    },
    name: {
      value: _tag
    },
    toString: {
      get() {
        return () => message;
      }
    },
    [_Inspectable.NodeInspectSymbol]: {
      get() {
        return () => message;
      }
    }
  });
  return error;
};
/** @internal */
const isAsyncFiberException = u => Predicate.isTagged(u, "AsyncFiberException") && "fiber" in u;
/** @internal */
exports.isAsyncFiberException = isAsyncFiberException;
const FiberFailureId = /*#__PURE__*/Symbol.for("@effect/io/Runtime/FiberFailure");
/** @internal */
exports.FiberFailureId = FiberFailureId;
const FiberFailureCauseId = /*#__PURE__*/Symbol.for("@effect/io/Runtime/FiberFailure/Cause");
/** @internal */
exports.FiberFailureCauseId = FiberFailureCauseId;
const fiberFailure = cause => {
  const limit = Error.stackTraceLimit;
  Error.stackTraceLimit = 0;
  const error = new Error();
  Error.stackTraceLimit = limit;
  const prettyErrors = InternalCause.prettyErrors(cause);
  if (prettyErrors.length > 0) {
    const head = prettyErrors[0];
    error.name = head.message.split(":")[0];
    error.message = head.message.substring(error.name.length + 2);
    error.stack = `${error.name}: ${error.message}\n${head.stack}`;
  }
  error[FiberFailureId] = FiberFailureId;
  error[FiberFailureCauseId] = cause;
  error.toJSON = () => {
    return {
      _id: "FiberFailure",
      cause: cause.toJSON()
    };
  };
  error.toString = () => {
    return (0, _Inspectable.toString)(error.toJSON());
  };
  error[_Inspectable.NodeInspectSymbol] = () => {
    return error.toJSON();
  };
  return error;
};
/** @internal */
exports.fiberFailure = fiberFailure;
const isFiberFailure = u => typeof u === "object" && u !== null && FiberFailureId in u;
exports.isFiberFailure = isFiberFailure;
const fastPath = effect => {
  const op = effect;
  switch (op._tag) {
    case "Failure":
    case "Success":
      {
        // @ts-expect-error
        return op;
      }
    case "Left":
      {
        return core.exitFail(op.left);
      }
    case "Right":
      {
        return core.exitSucceed(op.right);
      }
    case "Some":
      {
        return core.exitSucceed(op.value);
      }
    case "None":
      {
        // @ts-expect-error
        return core.exitFail((0, InternalCause.NoSuchElementException)());
      }
  }
};
/** @internal */
const unsafeRunSyncExit = runtime => effect => {
  const op = fastPath(effect);
  if (op) {
    return op;
  }
  const scheduler = new _scheduler.SyncScheduler();
  const fiberRuntime = unsafeFork(runtime)(effect, {
    scheduler
  });
  scheduler.flush();
  const result = fiberRuntime.unsafePoll();
  if (result) {
    return result;
  }
  throw asyncFiberException(fiberRuntime);
};
/** @internal */
exports.unsafeRunSyncExit = unsafeRunSyncExit;
const unsafeRunPromise = runtime => effect => unsafeRunPromiseExit(runtime)(effect).then(result => {
  switch (result._tag) {
    case OpCodes.OP_SUCCESS:
      {
        return result.i0;
      }
    case OpCodes.OP_FAILURE:
      {
        throw fiberFailure(result.i0);
      }
  }
});
/** @internal */
exports.unsafeRunPromise = unsafeRunPromise;
const unsafeRunPromiseExit = runtime => effect => new Promise(resolve => {
  const op = fastPath(effect);
  if (op) {
    resolve(op);
  }
  unsafeFork(runtime)(effect).addObserver(exit => {
    resolve(exit);
  });
});
/** @internal */
exports.unsafeRunPromiseExit = unsafeRunPromiseExit;
class RuntimeImpl {
  constructor(context, runtimeFlags, fiberRefs) {
    this.context = context;
    this.runtimeFlags = runtimeFlags;
    this.fiberRefs = fiberRefs;
  }
  pipe() {
    return (0, _Pipeable.pipeArguments)(this, arguments);
  }
}
/** @internal */
exports.RuntimeImpl = RuntimeImpl;
const make = options => new RuntimeImpl(options.context, options.runtimeFlags, options.fiberRefs);
/** @internal */
exports.make = make;
const runtime = () => core.withFiberRuntime((state, status) => core.succeed(new RuntimeImpl(state.getFiberRef(core.currentContext), status.runtimeFlags, state.getFiberRefs())));
/** @internal */
exports.runtime = runtime;
const defaultRuntimeFlags = /*#__PURE__*/runtimeFlags.make(runtimeFlags.Interruption, runtimeFlags.CooperativeYielding, runtimeFlags.RuntimeMetrics);
/** @internal */
exports.defaultRuntimeFlags = defaultRuntimeFlags;
const defaultRuntime = /*#__PURE__*/make({
  context: /*#__PURE__*/Context.empty(),
  runtimeFlags: defaultRuntimeFlags,
  fiberRefs: /*#__PURE__*/FiberRefs.unsafeMake( /*#__PURE__*/new Map())
});
/** @internal */
exports.defaultRuntime = defaultRuntime;
const unsafeRunEffect = /*#__PURE__*/unsafeRunCallback(defaultRuntime);
/** @internal */
exports.unsafeRunEffect = unsafeRunEffect;
const unsafeForkEffect = /*#__PURE__*/unsafeFork(defaultRuntime);
/** @internal */
exports.unsafeForkEffect = unsafeForkEffect;
const unsafeRunPromiseEffect = /*#__PURE__*/unsafeRunPromise(defaultRuntime);
/** @internal */
exports.unsafeRunPromiseEffect = unsafeRunPromiseEffect;
const unsafeRunPromiseExitEffect = /*#__PURE__*/unsafeRunPromiseExit(defaultRuntime);
/** @internal */
exports.unsafeRunPromiseExitEffect = unsafeRunPromiseExitEffect;
const unsafeRunSyncEffect = /*#__PURE__*/unsafeRunSync(defaultRuntime);
/** @internal */
exports.unsafeRunSyncEffect = unsafeRunSyncEffect;
const unsafeRunSyncExitEffect = /*#__PURE__*/unsafeRunSyncExit(defaultRuntime);
// circular with Effect
/** @internal */
exports.unsafeRunSyncExitEffect = unsafeRunSyncExitEffect;
const asyncEffect = register => core.flatMap(core.deferredMake(), deferred => core.flatMap(runtime(), runtime => core.uninterruptibleMask(restore => core.zipRight(FiberRuntime.fork(restore(core.catchAllCause(register(cb => unsafeRunCallback(runtime)(core.intoDeferred(cb, deferred))), cause => core.deferredFailCause(deferred, cause)))), restore(core.deferredAwait(deferred))))));
exports.asyncEffect = asyncEffect;
//# sourceMappingURL=runtime.js.map