clanka 0.7.3 → 0.7.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/Acp.d.ts +10 -0
  2. package/dist/Acp.d.ts.map +1 -1
  3. package/dist/Acp.js +1 -2
  4. package/dist/Acp.js.map +1 -1
  5. package/dist/AgentTools.d.ts.map +1 -1
  6. package/dist/AgentTools.js +1 -2
  7. package/dist/AgentTools.js.map +1 -1
  8. package/dist/GlobalWebSocket.d.ts +15 -0
  9. package/dist/GlobalWebSocket.d.ts.map +1 -0
  10. package/dist/GlobalWebSocket.js +26 -0
  11. package/dist/GlobalWebSocket.js.map +1 -0
  12. package/dist/WebToMarkdown.d.ts.map +1 -1
  13. package/dist/WebToMarkdown.js +8 -4
  14. package/dist/WebToMarkdown.js.map +1 -1
  15. package/dist/bin/Effect-DdkIoNCD.mjs +5058 -0
  16. package/dist/bin/Effect-DdkIoNCD.mjs.map +1 -0
  17. package/dist/bin/{McpClient-D6vFD-wP.mjs → McpClient-CJ0Vugoi.mjs} +582 -2896
  18. package/dist/bin/{McpClient-D6vFD-wP.mjs.map → McpClient-CJ0Vugoi.mjs.map} +1 -1
  19. package/dist/bin/OutputFormatter-DN8OGwuK.mjs +575 -0
  20. package/dist/bin/OutputFormatter-DN8OGwuK.mjs.map +1 -0
  21. package/dist/bin/Schema-BALIXGp7.mjs +5475 -0
  22. package/dist/bin/Schema-BALIXGp7.mjs.map +1 -0
  23. package/dist/bin/{SemanticSearch-D9iZ_Mi9.mjs → SemanticSearch-O6PZBRfd.mjs} +147 -1160
  24. package/dist/bin/{SemanticSearch-D9iZ_Mi9.mjs.map → SemanticSearch-O6PZBRfd.mjs.map} +1 -1
  25. package/dist/bin/Stream-B5ebASRi.mjs +2090 -0
  26. package/dist/bin/Stream-B5ebASRi.mjs.map +1 -0
  27. package/dist/bin/cli.mjs +9628 -41430
  28. package/dist/bin/cli.mjs.map +1 -1
  29. package/dist/bin/index.min-CI3qqohw.mjs +3300 -0
  30. package/dist/bin/index.min-CI3qqohw.mjs.map +1 -0
  31. package/dist/bin/turndown.cjs-usmCKZ4b.mjs +15195 -0
  32. package/dist/bin/turndown.cjs-usmCKZ4b.mjs.map +1 -0
  33. package/dist/cli.js +9 -5
  34. package/dist/cli.js.map +1 -1
  35. package/dist/index.d.ts +4 -0
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +4 -0
  38. package/dist/index.js.map +1 -1
  39. package/package.json +2 -4
  40. package/src/Acp.ts +1 -2
  41. package/src/AgentTools.ts +3 -2
  42. package/src/GlobalWebSocket.ts +40 -0
  43. package/src/WebToMarkdown.ts +17 -7
  44. package/src/cli.ts +14 -5
  45. package/src/index.ts +5 -0
  46. package/dist/bin/Schema-D6y3R-At.mjs +0 -28728
  47. package/dist/bin/Schema-D6y3R-At.mjs.map +0 -1
  48. package/dist/bin/Undici-ChB4UBDa.mjs +0 -28
  49. package/dist/bin/Undici-ChB4UBDa.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Effect-DdkIoNCD.mjs","names":["Prototype","Class","symbol","withVisitedTracking","equals","Hash.hash","emptyContext","format","Predicate.hasProperty","Predicate.hasProperty","Predicate.isFunction","format","Class","format","Hash.symbol","Hash.structureKeys","Equal.symbol","Equal.equals","isEffect","isExit","isCause","Hash.array","isFailReason","Hash.combine","Hash.string","Hash.hash","withFiber","Error","TaggedError","NoSuchElementError","isDone","Done","done","make","TypeId","CommonProto","Equal.symbol","isOption","isSome","Equal.equals","Hash.symbol","Hash.combine","Hash.hash","format","isNone","none","some","TypeId","Equal.symbol","isSuccess","Equal.equals","Hash.symbol","Hash.combine","Hash.hash","format","isFailure","fail","succeed","make","Number","BigInt","Date","min","option.none","option.some","option.isOption","option.isNone","option.isSome","match","getOrElse","fromNullishOr","getOrUndefined","map","flatMap","flatMapNullishOr","flatten","all","make","withFiber","TypeId","flatten","makeUnsafe","Equal.symbol","Equal.equals","Hash.symbol","Hash.number","empty","getOrUndefined","getUnsafe","Option.some","Option.none","merge","mergeAll","TypeId","bigint0","make","Hash.symbol","Hash.hash","Hash.number","Hash.structure","Equal.symbol","match","min","isArrayNonEmpty","succeed","result.succeed","fail","result.fail","try_","isFailure","result.isFailure","isSuccess","result.isSuccess","map","match","findFirst","O.some","O.isSome","O.none","empty","Array","match","internalArray.isArrayNonEmpty","Option.some","Option.none","moduleIterable.findFirst","Option.isSome","empty","map","flatMap","Equivalence.Array","Class","Pipeable.Class","TaggedClass","Predicate.isTagged","Error","core.Error","core.TaggedError","Result.fail","Result.succeed","Result.map","make","Option.getOrUndefined","Encoding.randomHex","TracerTimingEnabled","CurrentLogAnnotations","MinimumLogLevel","CurrentLogSpans","Equal.symbol","Hash.symbol","Hash.combine","Hash.string","Hash.random","makeInterruptReason","isFailReason","Result.succeed","Result.fail","findError","hasInterrupts","Result.isFailure","hasInterruptsOnly","hash","Hash.hash","Equal.equals","CauseStackTrace","Context.get","Context.make","failCause","flatMap","Context.empty","yieldNow","Context.hasSameCache","Context.getOrUndefinedUnsafe","Tracer.TracerKey","Scheduler.Scheduler","Tracer.ParentSpanKey","MinimumLogLevel","InternalMetric.FiberRuntimeMetricsKey","Scheduler.MaxOpsBeforeYield","Scheduler.PreventSchedulerYield","Context.makeUnsafe","succeed","callback","sync","withFiber","Context.merge","asVoid","Arr.empty","fail","suspend","fromOption","Option.isOption","Option.isNone","NoSuchElementError","fromResult","Option.some","succeedNone","failCauseSync","die","void_","try_","UnknownError","promise","tryPromise","never","gen","fnUntraced","fn","isEffect","updateService","useSpan","fnUntracedEager","as","asSome","map","andThen","tap","uninterruptible","forkUnsafe","raceFirst","flatMapEager","flatten","mapEager","mapErrorEager","mapError","mapBothEager","catchEager","catch_","serviceOption","Context.getOption","updateContext","onExitPrimitive","Context.getUnsafe","Context.add","context","contextWith","provideContext","provideService","zipWith","all","filterOrFail","when","forever","whileLoop","catchCause","catchNoSuchElement","matchEffect","catchDefect","tapCause","catchIf","catchFilter","catchTag","catchTags","catchReason","orDie","orElseSucceed","ignore","matchCauseEffect","option","match","Option.none","result","matchCauseEager","exit","delay","sleep","timeoutOrElse","TimeoutError","Duration.format","timeout","Duration.fromInputUnsafe","scope","scoped","scopedWith","onExit","acquireRelease","uninterruptibleMask","addFinalizer","ensuring","onError","onInterrupt","acquireUseRelease","Duration.toMillis","cachedWithTTL","cached","interrupt","interruptible","forEach","Arr.fromIterable","forkChild","forkIn","forkScoped","runForkWith","runFork","Scheduler.MixedScheduler","runSyncExit","runSync","Tracer.DisablePropagation","Option.getOrUndefined","Tracer.Tracer","TracerTimingEnabled","Tracer.CurrentTraceLevel","Option.isSome","Tracer.MinimumTraceLevel","makeSpanScoped","Tracer.ParentSpan","withParentSpan","withSpan","annotateCurrentSpan","clockWith","isTimeoutError","IllegalArgumentError","Order.Number","isCause","CurrentLogSpans","CurrentLogAnnotations","undefined_","core.isExit","succeed","core.exitSucceed","failCause","core.exitFailCause","fail","core.exitFail","die","core.exitDie","interrupt","effect.exitInterrupt","void_","effect.exitVoid","effect.exitIsSuccess","effect.exitIsFailure","TypeId","makeUnsafe","internalEffect.callback","internalEffect.sync","done","failCause","core.exitFailCause","internalEffect.causeInterrupt","isDone","internalEffect.uninterruptibleMask","internalEffect.flatMap","internalEffect.exit","references.CurrentLogAnnotations","references.CurrentLogSpans","references.MinimumLogLevel","references.TracerTimingEnabled","effect.scopeTag","effect.scopeMake","effect.scopeMakeUnsafe","provide","effect.provideScope","effect.scopeAddFinalizerExit","addFinalizer","effect.scopeAddFinalizer","effect.scopeForkUnsafe","effect.scopeClose","TypeId","internalEffect.andThen","internalEffect.scopeAddFinalizerExit","Scope.forkUnsafe","internalEffect.onExit","Scope.close","internalEffect.void","Scope.makeUnsafe","Deferred.makeUnsafe","Deferred.await","internalEffect.suspend","internalEffect.flatMap","Deferred.done","Context.getOrUndefined","internalEffect.provideService","internalEffect.map","Context.add","core.withFiber","succeed","Context.make","internalEffect.succeed","Scope.provide","internalEffect.as","Context.empty","flatMap","Context.get","internalEffect.forEach","Context.mergeAll","internalEffect.provideContext","provide","Context.merge","orDie","internalEffect.orDie","internalEffect.die","core.isCause","core.isCauseReason","core.isFailReason","core.causeFromReasons","fail","core.causeFail","die","core.causeDie","core.Fail","core.Die","effect.makeInterruptReason","effect.hasInterruptsOnly","map","effect.causeMap","effect.causeSquash","effect.findError","effect.hasInterrupts","effect.causeInterruptors","effect.causeFilterInterruptors","effect.causePretty","core.NoSuchElementError","core.isDone","core.Done","core.done","effect.isTimeoutError","effect.TimeoutError","effect.IllegalArgumentError","effect.UnknownError","internalEffect.catchCauseFilter","Cause.isDone","Result.fail","Cause.fromReasons","Result.succeed","Result.isFailure","Exit.succeed","Exit.failCause","matchEffect","internalEffect.matchCauseEffect","TypeId","Duration.zero","effect.map","effect.catchCause","effect.succeed","effect.failCause","effect.clockWith","effect.suspend","effect.flatMap","effect.as","effect.sleep","effect.all","effect.forEach","Pull.matchEffect","effect.undefined","Cause.done","Duration.min","Duration.toMillis","Duration.fromInputUnsafe","Duration.millis","millis","isEffect","forever","effect.scopedWith","effect.flatMap","Layer.buildWithMemoMap","Layer.makeMemoMapUnsafe","Layer.buildWithScope","effect.provideContext","provide","isEffect","Context.isContext","Layer.mergeAll","effect.flatMap","Schedule.toStepWithMetadata","effect.catch_","effect.forever","effect.tap","effect.suspend","effect.provideService","Schedule.CurrentMetadata","effect.sync","core.isDone","effect.succeed","Option.none","Option.some","Pull.catchDone","repeat","Schedule.isSchedule","effect.fail","retry","Schedule.forever","Schedule.passthrough","Schedule.while","core.isEffect","effect.map","core.StructuralProto","request","effect.callback","effect.getCurrentFiber","isEffect","effect.flatMap","effect.suspend","effect.onExit","effect.void","effect.runForkWith","effect.exitInterrupt","effect.sync","core.isEffect","internal.all","internal.forEach","internal.whileLoop","internal.promise","internal.tryPromise","internal.succeed","internal.succeedNone","internal.suspend","internal.sync","internal.void","internal.undefined","internal.callback","internal.never","internal.gen","internal.fail","internal.failCause","internal.failCauseSync","internal.die","internal.try","internal.yieldNow","core.withFiber","internal.fromResult","internal.fromOption","internal.flatMap","internal.flatten","internal.andThen","internal.tap","internal.result","internal.option","internal.exit","internal.map","internal.as","internal.asSome","internal.asVoid","internal.zipWith","internal.catch_","internal.catchTag","internal.catchTags","internal.catchReason","internal.catchCause","internal.catchDefect","internal.catchIf","internal.catchFilter","internal.catchNoSuchElement","internal.mapError","internal.orDie","internal.tapCause","internalSchedule.retry","internal.ignore","internal.orElseSucceed","internal.timeout","internal.timeoutOrElse","internal.delay","internal.sleep","internal.raceFirst","internal.filterOrFail","internal.when","internal.match","internal.matchCauseEager","internal.matchCauseEffect","internal.matchEffect","internal.context","internal.contextWith","internalLayer.provide","internal.provideContext","internal.serviceOption","internal.updateContext","internal.updateService","internal.provideService","internal.scope","internal.scoped","internal.scopedWith","internal.acquireRelease","internal.acquireUseRelease","internal.addFinalizer","internal.ensuring","internal.onError","internal.onExitPrimitive","internal.onExit","internal.cached","internal.cachedWithTTL","internal.interrupt","internal.interruptible","internal.onInterrupt","internal.uninterruptible","internal.uninterruptibleMask","internal.forever","internalSchedule.repeat","internal.annotateCurrentSpan","internal.makeSpanScoped","internal.useSpan","internal.withSpan","internal.withParentSpan","internalRequest.request","internal.forkChild","internal.forkIn","internal.forkScoped","internal.runFork","internal.runForkWith","internal.runSync","internal.runSyncExit","internal.fnUntraced","internal.fn","internal.clockWith","internal.currentTimeMillis","internal.mapEager","internal.mapErrorEager","internal.mapBothEager","internal.flatMapEager","internal.catchEager","internal.fnUntracedEager"],"sources":["../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Pipeable.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Function.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/internal/equal.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Predicate.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Hash.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Equal.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Redactable.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Formatter.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Inspectable.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/internal/stackTraceLimit.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Utils.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/internal/record.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/internal/core.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Effectable.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Equivalence.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/internal/option.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/internal/result.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Order.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Option.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Context.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Duration.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/internal/array.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Result.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Iterable.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Array.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Scheduler.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Data.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Encoding.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Tracer.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/internal/metric.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/internal/references.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/internal/tracer.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/internal/effect.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Exit.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Deferred.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/References.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Scope.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Layer.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Cause.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/internal/random.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Pull.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Schedule.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/internal/layer.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/internal/schedule.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Request.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/internal/request.js","../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Effect.js"],"sourcesContent":["/**\n * The `Pipeable` module defines the shared interface and implementation helpers\n * for values that support Effect-style method chaining with `.pipe(...)`.\n *\n * A `Pipeable` value can pass itself through a sequence of unary functions from\n * left to right, so code can be written as `value.pipe(f, g, h)` instead of\n * deeply nesting calls. This is the method form used by many Effect data types\n * to compose transformations, validations, and effectful operations while\n * keeping the original value as the starting point of the pipeline.\n *\n * @since 2.0.0\n */\n/**\n * Applies a `pipe` method's variadic arguments to an initial value from left\n * to right.\n *\n * **When to use**\n *\n * Use to implement a custom `.pipe(...)` method from JavaScript's `arguments`\n * object.\n *\n * **Details**\n *\n * This helper is intended for implementing `Pipeable.pipe` methods that\n * receive JavaScript's `arguments` object. With no functions it returns the\n * original value; otherwise it feeds each result into the next function.\n *\n * **Example** (Implementing a pipe method)\n *\n * ```ts import.meta.vitest\n * import { Pipeable } from \"effect\"\n *\n * class NumberBox {\n * constructor(readonly value: number) {}\n *\n * pipe(..._fns: ReadonlyArray<(value: number) => number>): number {\n * return Pipeable.pipeArguments(this.value, arguments) as number\n * }\n * }\n *\n * const result = new NumberBox(5).pipe(\n * (n) => n + 2,\n * (n) => n * 3\n * )\n * result // => 21\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const pipeArguments = (self, args) => {\n switch (args.length) {\n case 0:\n return self;\n case 1:\n return args[0](self);\n case 2:\n return args[1](args[0](self));\n case 3:\n return args[2](args[1](args[0](self)));\n case 4:\n return args[3](args[2](args[1](args[0](self))));\n case 5:\n return args[4](args[3](args[2](args[1](args[0](self)))));\n case 6:\n return args[5](args[4](args[3](args[2](args[1](args[0](self))))));\n case 7:\n return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))));\n case 8:\n return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))));\n case 9:\n return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))));\n default:\n {\n let ret = self;\n for (let i = 0, len = args.length; i < len; i++) {\n ret = args[i](ret);\n }\n return ret;\n }\n }\n};\n/**\n * Reusable prototype that implements `Pipeable.pipe`.\n *\n * **When to use**\n *\n * Use when classes or object prototypes can reuse this value when they need the\n * standard pipe implementation backed by `pipeArguments`.\n *\n * @category prototypes\n * @since 3.15.0\n */\nexport const Prototype = {\n pipe() {\n return pipeArguments(this, arguments);\n }\n};\n/**\n * Provides a base constructor whose instances implement the standard `Pipeable.pipe`\n * method.\n *\n * **When to use**\n *\n * Use when you need to define a class that supports Effect-style method\n * chaining through `.pipe(...)`.\n *\n * @category constructors\n * @since 3.15.0\n */\nexport const Class = /*#__PURE__*/function () {\n function PipeableBase() {}\n PipeableBase.prototype = Prototype;\n return PipeableBase;\n}();\n/**\n * Returns a subclass of the provided class that adds the standard `pipe`\n * method.\n *\n * **When to use**\n *\n * Use to add pipe support to an existing class without extending a base class\n * or modifying its prototype.\n *\n * **Details**\n *\n * The original constructor and instance members are preserved, and the added\n * method delegates to `pipeArguments`.\n *\n * @see {@link Prototype} for a reusable prototype object\n * @see {@link Class} for a base constructor to extend\n * @category constructors\n * @since 4.0.0\n */\nexport const Mixin = klass => class extends klass {\n pipe() {\n return pipeArguments(this, arguments);\n }\n};\n//# sourceMappingURL=Pipeable.js.map","import { pipeArguments } from \"./Pipeable.js\";\n/**\n * Creates a function that can be called in data-first style or data-last\n * (`pipe`-friendly) style.\n *\n * **When to use**\n *\n * Use to expose one implementation through both direct and `pipe`-friendly\n * call styles.\n *\n * **Details**\n *\n * Pass either the arity of the uncurried function or a predicate that decides\n * whether the current call is data-first. Arity is the common case. Use a\n * predicate when optional arguments make arity ambiguous.\n *\n * **Example** (Selecting data-first or data-last style by arity)\n *\n * ```ts import.meta.vitest\n * import { Function, pipe } from \"effect\"\n *\n * const sum = Function.dual<\n * (that: number) => (self: number) => number,\n * (self: number, that: number) => number\n * >(2, (self, that) => self + that)\n *\n * sum(2, 3) // => 5\n * pipe(2, sum(3)) // => 5\n * ```\n *\n * **Example** (Defining overloads with call signatures)\n *\n * ```ts import.meta.vitest\n * import { Function, pipe } from \"effect\"\n *\n * const sum: {\n * (that: number): (self: number) => number\n * (self: number, that: number): number\n * } = Function.dual(2, (self: number, that: number): number => self + that)\n *\n * sum(2, 3) // => 5\n * pipe(2, sum(3)) // => 5\n * ```\n *\n * **Example** (Selecting data-first or data-last style with a predicate)\n *\n * ```ts import.meta.vitest\n * import { Function, pipe } from \"effect\"\n *\n * const sum = Function.dual<\n * (that: number) => (self: number) => number,\n * (self: number, that: number) => number\n * >(\n * (args) => args.length === 2,\n * (self, that) => self + that\n * )\n *\n * sum(2, 3) // => 5\n * pipe(2, sum(3)) // => 5\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const dual = function (arity, body) {\n if (typeof arity === \"function\") {\n return function () {\n return arity(arguments) ? body.apply(this, arguments) : self => body(self, ...arguments);\n };\n }\n switch (arity) {\n case 0:\n case 1:\n throw new RangeError(`Invalid arity ${arity}`);\n case 2:\n return function (a, b) {\n if (arguments.length >= 2) {\n return body(a, b);\n }\n return function (self) {\n return body(self, a);\n };\n };\n case 3:\n return function (a, b, c) {\n if (arguments.length >= 3) {\n return body(a, b, c);\n }\n return function (self) {\n return body(self, a, b);\n };\n };\n default:\n return function () {\n if (arguments.length >= arity) {\n // @ts-expect-error\n return body.apply(this, arguments);\n }\n const args = arguments;\n return function (self) {\n return body(self, ...args);\n };\n };\n }\n};\n/**\n * Applies a function to a given value.\n *\n * **When to use**\n *\n * Use to pass a fixed value into a unary function, especially when the function\n * is the value flowing through `pipe`.\n *\n * **Details**\n *\n * `apply(a)(f)` is equivalent to `f(a)`.\n *\n * **Example** (Applying an argument to a function)\n *\n * ```ts import.meta.vitest\n * import { Function, pipe, String } from \"effect\"\n *\n * pipe(String.length, Function.apply(\"hello\")) // => 5\n * ```\n *\n * @see {@link pipe} for building left-to-right pipelines\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const apply = a => self => self(a);\n/**\n * Returns its input argument unchanged.\n *\n * **When to use**\n *\n * Use to return a value unchanged where a function is required.\n *\n * **Example** (Returning the same value)\n *\n * ```ts import.meta.vitest\n * import { identity } from \"effect\"\n *\n * identity(5) // => 5\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const identity = a => a;\n/**\n * Ensures that the type of an expression matches some type,\n * without changing the resulting type of that expression.\n *\n * **When to use**\n *\n * Use to check assignability while preserving the expression's precise inferred\n * type.\n *\n * **Example** (Checking an expression against a type)\n *\n * ```ts import.meta.vitest\n * import { Function } from \"effect\"\n *\n * const test1 = Function.satisfies<number>()(5 as const) // => 5\n * // ^? const test: 5\n * // @ts-expect-error\n * const test2 = Function.satisfies<string>()(5)\n * // ^? Argument of type 'number' is not assignable to parameter of type 'string'\n * ```\n *\n * @see {@link cast} for changing only the static TypeScript type\n *\n * @category utility types\n * @since 2.0.0\n */\nexport const satisfies = () => b => b;\n/**\n * Returns the input value with a different static type.\n *\n * **When to use**\n *\n * Use when you need an explicit type-level cast and accept that the value is\n * returned unchanged at runtime.\n *\n * **Gotchas**\n *\n * This is a type-level cast only; it performs no runtime validation or\n * conversion.\n *\n * @see {@link satisfies} for checking assignability without changing the resulting type\n *\n * @category utility types\n * @since 4.0.0\n */\nexport const cast = identity;\n/**\n * Creates a zero-argument function that always returns the provided value.\n *\n * **When to use**\n *\n * Use when you need a thunk or callback that returns the same value on every\n * invocation.\n *\n * **Example** (Creating a constant thunk)\n *\n * ```ts import.meta.vitest\n * import { Function } from \"effect\"\n *\n * const constNull = Function.constant(null)\n *\n * constNull() // => null\n * constNull() // => null\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const constant = value => () => value;\n/**\n * Returns `true` when called.\n *\n * **When to use**\n *\n * Use when you need a thunk that returns `true` on every invocation.\n *\n * **Example** (Returning true from a thunk)\n *\n * ```ts import.meta.vitest\n * import { Function } from \"effect\"\n *\n * Function.constTrue() // => true\n * ```\n *\n * @category constants\n * @since 2.0.0\n */\nexport const constTrue = /*#__PURE__*/constant(true);\n/**\n * Returns `false` when called.\n *\n * **When to use**\n *\n * Use when you need a thunk that returns `false` on every invocation.\n *\n * **Example** (Returning false from a thunk)\n *\n * ```ts import.meta.vitest\n * import { Function } from \"effect\"\n *\n * Function.constFalse() // => false\n * ```\n *\n * @category constants\n * @since 2.0.0\n */\nexport const constFalse = /*#__PURE__*/constant(false);\n/**\n * Returns `null` when called.\n *\n * **When to use**\n *\n * Use when you need a thunk that returns `null` on every invocation.\n *\n * **Example** (Returning null from a thunk)\n *\n * ```ts import.meta.vitest\n * import { Function } from \"effect\"\n *\n * Function.constNull() // => null\n * ```\n *\n * @category constants\n * @since 2.0.0\n */\nexport const constNull = /*#__PURE__*/constant(null);\n/**\n * Returns `undefined` when called.\n *\n * **When to use**\n *\n * Use when you need a thunk that returns `undefined` on every invocation.\n *\n * **Example** (Returning undefined from a thunk)\n *\n * ```ts import.meta.vitest\n * import { Function } from \"effect\"\n *\n * Function.constUndefined() // => undefined\n * ```\n *\n * @category constants\n * @since 2.0.0\n */\nexport const constUndefined = /*#__PURE__*/constant(undefined);\n/**\n * Returns no meaningful value when called.\n *\n * **When to use**\n *\n * Use when you need a thunk that is called only for its effect and has no\n * meaningful return value.\n *\n * **Example** (Returning void from a thunk)\n *\n * ```ts import.meta.vitest\n * import { Function } from \"effect\"\n *\n * Function.constVoid() // => undefined\n * ```\n *\n * @category constants\n * @since 2.0.0\n */\nexport const constVoid = constUndefined;\n/**\n * Reverses the order of arguments for a curried function.\n *\n * **When to use**\n *\n * Use to adapt a curried function when its argument groups need to be supplied\n * in the opposite order.\n *\n * **Example** (Flipping curried arguments)\n *\n * ```ts import.meta.vitest\n * import { Function } from \"effect\"\n *\n * const f = (a: number) => (b: string) => a - b.length\n *\n * Function.flip(f)(\"aaa\")(2) // => -1\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const flip = f => (...b) => (...a) => f(...a)(...b);\n/**\n * Composes two functions, `ab` and `bc` into a single function that takes in an argument `a` of type `A` and returns a result of type `C`.\n * The result is obtained by first applying the `ab` function to `a` and then applying the `bc` function to the result of `ab`.\n *\n * **When to use**\n *\n * Use to compose exactly two unary functions into a reusable unary function.\n *\n * **Example** (Composing two functions)\n *\n * ```ts import.meta.vitest\n * import { Function } from \"effect\"\n *\n * const increment = (n: number) => n + 1\n * const square = (n: number) => n * n\n *\n * Function.compose(increment, square)(2) // => 9\n * ```\n *\n * @see {@link flow} for composing a left-to-right sequence of functions\n * @see {@link pipe} for applying a value through a left-to-right sequence immediately\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const compose = /*#__PURE__*/dual(2, (ab, bc) => a => bc(ab(a)));\n/**\n * Marks an impossible branch by accepting a `never` value and returning any\n * type.\n *\n * **When to use**\n *\n * Use when you need a return value in a branch that exhaustive checks prove\n * cannot be reached.\n *\n * **Gotchas**\n *\n * Calling `absurd` throws, because a value of type `never` should be\n * impossible at runtime.\n *\n * **Example** (Handling impossible values)\n *\n * ```ts import.meta.vitest\n * import { absurd } from \"effect\"\n *\n * const handleNever = (value: never) => {\n * return absurd(value) // This will throw an error if called\n * }\n * ```\n *\n * @category utility types\n * @since 2.0.0\n */\nexport const absurd = _ => {\n throw new Error(\"Called `absurd` function which should be uncallable\");\n};\n/**\n * Creates a tupled version of this function: instead of `n` arguments, it accepts a single tuple argument.\n *\n * **When to use**\n *\n * Use to adapt a multi-argument function so it accepts one tuple argument.\n *\n * **Example** (Converting arguments to a tuple)\n *\n * ```ts import.meta.vitest\n * import { Function } from \"effect\"\n *\n * const sumTupled = Function.tupled((x: number, y: number): number => x + y)\n *\n * sumTupled([1, 2]) // => 3\n * ```\n *\n * @see {@link untupled} for adapting a tuple-argument function back to multiple arguments\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const tupled = f => a => f(...a);\n/**\n * Converts a tupled function back to an uncurried function.\n *\n * **When to use**\n *\n * Use to adapt a tuple-argument function so it accepts multiple arguments.\n *\n * **Example** (Converting a tuple to arguments)\n *\n * ```ts import.meta.vitest\n * import { Function } from \"effect\"\n *\n * const getFirst = Function.untupled(<A, B>(tuple: [A, B]): A => tuple[0])\n *\n * getFirst(1, 2) // => 1\n * ```\n *\n * @see {@link tupled} for adapting a multi-argument function to one tuple argument\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const untupled = f => (...a) => f(a);\nexport function pipe(a, ...args) {\n return pipeArguments(a, args);\n}\nexport function flow(ab, bc, cd, de, ef, fg, gh, hi, ij) {\n switch (arguments.length) {\n case 1:\n return ab;\n case 2:\n return function () {\n return bc(ab.apply(this, arguments));\n };\n case 3:\n return function () {\n return cd(bc(ab.apply(this, arguments)));\n };\n case 4:\n return function () {\n return de(cd(bc(ab.apply(this, arguments))));\n };\n case 5:\n return function () {\n return ef(de(cd(bc(ab.apply(this, arguments)))));\n };\n case 6:\n return function () {\n return fg(ef(de(cd(bc(ab.apply(this, arguments))))));\n };\n case 7:\n return function () {\n return gh(fg(ef(de(cd(bc(ab.apply(this, arguments)))))));\n };\n case 8:\n return function () {\n return hi(gh(fg(ef(de(cd(bc(ab.apply(this, arguments))))))));\n };\n case 9:\n return function () {\n return ij(hi(gh(fg(ef(de(cd(bc(ab.apply(this, arguments)))))))));\n };\n }\n return;\n}\n/**\n * Creates a compile-time placeholder for a value of any type.\n *\n * **When to use**\n *\n * Use as a temporary typed placeholder while developing incomplete code.\n *\n * **Gotchas**\n *\n * `hole` is intended for temporary development use. If the placeholder is\n * evaluated at runtime, it throws.\n *\n * **Example** (Creating a development placeholder)\n *\n * ```ts import.meta.vitest\n * import { hole } from \"effect\"\n *\n * // Intentionally not called: `hole` throws if the placeholder is evaluated.\n * const buildUser = (id: number): { readonly id: number; readonly name: string } => ({\n * id,\n * name: hole<string>()\n * })\n *\n * ```\n *\n * @category utility types\n * @since 2.0.0\n */\nexport const hole = /*#__PURE__*/cast(absurd);\n/**\n * Returns the second argument and discards the first. The SK combinator is\n * a fundamental combinator in the lambda calculus and the SKI combinator\n * calculus.\n *\n * **When to use**\n *\n * Use to discard the first argument and return the second argument.\n *\n * **Example** (Discarding the first argument)\n *\n * ```ts import.meta.vitest\n * import { Function } from \"effect\"\n *\n * Function.SK(0, \"hello\") // => \"hello\"\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const SK = (_, b) => b;\n/**\n * Creates a memoized function whose input is an object, caching results by\n * object identity.\n *\n * **When to use**\n *\n * Use to reuse the result of a synchronous computation whose output is stable\n * for a given object reference.\n *\n * **Details**\n *\n * Each memoized wrapper owns a private `WeakMap` keyed by object identity.\n *\n * **Gotchas**\n *\n * `undefined` is reserved to represent a cache miss and is therefore not\n * supported as a return value.\n *\n * Structurally equal objects do not share cache entries. If the same object is\n * mutated after its first call, later calls still return the cached result for\n * that reference.\n *\n * @category caching\n * @since 4.0.0\n */\nexport function memoize(f) {\n const cache = new WeakMap();\n return a => {\n const cached = cache.get(a);\n if (cached !== undefined) return cached;\n const result = f(a);\n cache.set(a, result);\n return result;\n };\n}\n/**\n * Creates a memoized idempotent object transformation that caches both inputs\n * and their outputs by object identity.\n *\n * **When to use**\n *\n * Use when an object transformation is idempotent and its output can be safely\n * reused as a fixed point.\n *\n * **Details**\n *\n * After computing an input, the returned function caches both the input and\n * the output. Calling it with either reference returns the output without\n * invoking the supplied function again.\n *\n * **Gotchas**\n *\n * The returned function treats each computed output as a fixed point. If\n * applying the supplied function to an output would produce an observably\n * different value, this memoization changes that behavior.\n *\n * @see {@link memoize} for memoizing functions without an idempotence requirement\n * @category caching\n * @since 4.0.0\n */\nexport function memoizeIdempotent(f) {\n const cache = new WeakMap();\n return a => {\n const cached = cache.get(a);\n if (cached !== undefined) return cached;\n const result = f(a);\n cache.set(a, result);\n cache.set(result, result);\n return result;\n };\n}\n//# sourceMappingURL=Function.js.map","/** @internal */\nexport const getAllObjectKeys = obj => {\n const keys = new Set(Reflect.ownKeys(obj));\n if (obj.constructor === Object) return keys;\n if (obj instanceof Error) {\n keys.delete(\"stack\");\n }\n const proto = Object.getPrototypeOf(obj);\n let current = proto;\n while (current !== null && current !== Object.prototype) {\n const ownKeys = Reflect.ownKeys(current);\n for (let i = 0; i < ownKeys.length; i++) {\n keys.add(ownKeys[i]);\n }\n current = Object.getPrototypeOf(current);\n }\n if (keys.has(\"constructor\") && typeof obj.constructor === \"function\" && proto === obj.constructor.prototype) {\n keys.delete(\"constructor\");\n }\n return keys;\n};\n/** @internal */\nexport const byReferenceInstances = /*#__PURE__*/new WeakSet();\n//# sourceMappingURL=equal.js.map","/**\n * Defines runtime checks for values.\n *\n * A `Predicate<A>` returns `true` or `false` for an `A`. A\n * `Refinement<A, B>` is a predicate that also narrows the TypeScript type when\n * it succeeds. This module includes guards for common JavaScript values,\n * property and tag checks, tuple and struct checks, boolean combinators, and\n * helpers for composing predicates and refinements.\n *\n * @since 2.0.0\n */\nimport { dual } from \"./Function.js\";\n/**\n * Transforms the input of a predicate using a mapping function.\n *\n * **When to use**\n *\n * Use when you have a predicate on `A` and want to check `B` values by mapping\n * each `B` to an `A`, such as checking lengths or projections.\n *\n * **Details**\n *\n * Returns a new predicate that applies `f` before `self`. There is no\n * additional short-circuiting beyond what `self` does.\n *\n * **Example** (Checking string length)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const isLongerThan2 = Predicate.mapInput((s: string) => s.length)(\n * (n: number) => n > 2\n * )\n *\n * isLongerThan2(\"hello\") // => true\n * ```\n *\n * @see {@link Predicate}\n * @see {@link and}\n * @see {@link not}\n * @category combinators\n * @since 2.0.0\n */\nexport const mapInput = /*#__PURE__*/dual(2, (self, f) => b => self(f(b)));\n/**\n * Checks whether a readonly array has exactly `n` elements.\n *\n * **When to use**\n *\n * Use when you need a `Predicate` guard for exact tuple length that narrows\n * `ReadonlyArray<T>` to `TupleOf<N, T>`.\n *\n * **Details**\n *\n * This only checks length, not element types, and returns a refinement on the\n * array type.\n *\n * **Example** (Checking exact length)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const isPair = Predicate.isTupleOf(2)\n *\n * isPair([1, 2]) // => true\n * ```\n *\n * @see {@link isTupleOfAtLeast}\n * @see {@link Tuple}\n * @category guards\n * @since 3.3.0\n */\nexport const isTupleOf = /*#__PURE__*/dual(2, (self, n) => self.length === n);\n/**\n * Checks whether a readonly array has at least `n` elements.\n *\n * **When to use**\n *\n * Use when you need a `Predicate` guard for tuple-like minimum length that\n * narrows `ReadonlyArray<T>` to `TupleOfAtLeast<N, T>`.\n *\n * **Details**\n *\n * This only checks length, not element types, and returns a refinement on the\n * array type.\n *\n * **Example** (Checking minimum length)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const hasAtLeast2 = Predicate.isTupleOfAtLeast(2)\n *\n * hasAtLeast2([1, 2, 3]) // => true\n * ```\n *\n * @see {@link isTupleOf}\n * @see {@link Tuple}\n * @category guards\n * @since 3.3.0\n */\nexport const isTupleOfAtLeast = /*#__PURE__*/dual(2, (self, n) => self.length >= n);\n/**\n * Checks whether a value is truthy.\n *\n * **When to use**\n *\n * Use when you want a predicate that mirrors JavaScript truthiness and filters\n * out falsy values like `0`, `\"\"`, and `false`.\n *\n * **Details**\n *\n * This uses `!!input` and treats `0`, `\"\"`, `false`, `null`, and `undefined`\n * as false.\n *\n * **Example** (Filtering truthy values)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const values = [0, 1, \"\", \"ok\", false]\n * const truthy = values.filter(Predicate.isTruthy) // => [1, \"ok\"]\n * ```\n *\n * @see {@link isNullish}\n * @see {@link isNotNullish}\n * @category predicates\n * @since 2.0.0\n */\nexport function isTruthy(input) {\n return !!input;\n}\n/**\n * Checks whether a value is a `Set`.\n *\n * **When to use**\n *\n * Use when you need a `Predicate` runtime guard for `Set` values.\n *\n * **Details**\n *\n * Uses `instanceof Set`.\n *\n * **Example** (Guarding a Set)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const data: unknown = new Set([1, 2])\n *\n * if (Predicate.isSet(data)) {\n * data.size // => 2\n * }\n * ```\n *\n * @see {@link isMap}\n * @see {@link isIterable}\n * @category guards\n * @since 2.0.0\n */\nexport function isSet(input) {\n return input instanceof Set;\n}\n/**\n * Checks whether a value is a `Map`.\n *\n * **When to use**\n *\n * Use when you need a `Predicate` runtime guard for `Map` values.\n *\n * **Details**\n *\n * Uses `instanceof Map`.\n *\n * **Example** (Guarding a Map)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const data: unknown = new Map([[\"a\", 1]])\n *\n * if (Predicate.isMap(data)) {\n * data.size // => 1\n * }\n * ```\n *\n * @see {@link isSet}\n * @see {@link isIterable}\n * @category guards\n * @since 2.0.0\n */\nexport function isMap(input) {\n return input instanceof Map;\n}\n/**\n * Checks whether a value is a `string`.\n *\n * **When to use**\n *\n * Use when you need a `Predicate` guard to narrow an `unknown` value to a\n * string.\n *\n * **Details**\n *\n * Uses `typeof input === \"string\"`.\n *\n * **Example** (Guarding strings)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const data: unknown = \"hi\"\n *\n * if (Predicate.isString(data)) {\n * data.toUpperCase() // => \"HI\"\n * }\n * ```\n *\n * @see {@link isNumber}\n * @see {@link isBoolean}\n * @see {@link Refinement}\n * @category guards\n * @since 2.0.0\n */\nexport function isString(input) {\n return typeof input === \"string\";\n}\n/**\n * Checks whether a value is a `number`.\n *\n * **When to use**\n *\n * Use when you need a `Predicate` guard to narrow an `unknown` value to a\n * number.\n *\n * **Details**\n *\n * Uses `typeof input === \"number\"` and does not exclude `NaN` or `Infinity`.\n *\n * **Example** (Guarding numbers)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const data: unknown = 42\n *\n * if (Predicate.isNumber(data)) {\n * data + 1 // => 43\n * }\n * ```\n *\n * @see {@link isBigInt}\n * @see {@link isString}\n * @category guards\n * @since 2.0.0\n */\nexport function isNumber(input) {\n return typeof input === \"number\";\n}\n/**\n * Checks whether a value is a `boolean`.\n *\n * **When to use**\n *\n * Use when you need a `Predicate` guard to narrow an `unknown` value to a\n * boolean.\n *\n * **Details**\n *\n * Uses `typeof input === \"boolean\"`.\n *\n * **Example** (Guarding booleans)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const data: unknown = true\n *\n * if (Predicate.isBoolean(data)) {\n * data ? \"yes\" : \"no\" // => \"yes\"\n * }\n * ```\n *\n * @see {@link isString}\n * @see {@link isNumber}\n * @category guards\n * @since 2.0.0\n */\nexport function isBoolean(input) {\n return typeof input === \"boolean\";\n}\n/**\n * Checks whether a value is a `bigint`.\n *\n * **When to use**\n *\n * Use when you need a `Predicate` guard to narrow an `unknown` value to a\n * bigint.\n *\n * **Details**\n *\n * Uses `typeof input === \"bigint\"`.\n *\n * **Example** (Guarding bigints)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const data: unknown = 1n\n *\n * if (Predicate.isBigInt(data)) {\n * data + 2n // => 3n\n * }\n * ```\n *\n * @see {@link isNumber}\n * @category guards\n * @since 2.0.0\n */\nexport function isBigInt(input) {\n return typeof input === \"bigint\";\n}\n/**\n * Checks whether a value is a `symbol`.\n *\n * **When to use**\n *\n * Use when you need a `Predicate` guard to narrow an `unknown` value to a\n * symbol.\n *\n * **Details**\n *\n * Uses `typeof input === \"symbol\"`.\n *\n * **Example** (Guarding symbols)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const data: unknown = Symbol.for(\"id\")\n *\n * if (Predicate.isSymbol(data)) {\n * data.description // => \"id\"\n * }\n * ```\n *\n * @see {@link isPropertyKey}\n * @category guards\n * @since 2.0.0\n */\nexport function isSymbol(input) {\n return typeof input === \"symbol\";\n}\n/**\n * Checks whether a value is a valid `PropertyKey` (string, number, or symbol).\n *\n * **When to use**\n *\n * Use when you need a `Predicate` guard for unknown property keys before\n * indexing.\n *\n * **Details**\n *\n * Uses `isString`, `isNumber`, and `isSymbol`.\n *\n * **Example** (Guarding property keys)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const key: unknown = \"name\"\n * const obj: Record<PropertyKey, unknown> = { name: \"Ada\" }\n *\n * if (Predicate.isPropertyKey(key) && key in obj) {\n * obj[key] // => \"Ada\"\n * }\n * ```\n *\n * @see {@link isString}\n * @see {@link isNumber}\n * @see {@link isSymbol}\n * @category guards\n * @since 4.0.0\n */\nexport function isPropertyKey(u) {\n return isString(u) || isNumber(u) || isSymbol(u);\n}\n/**\n * Checks whether a value is a `function`.\n *\n * **When to use**\n *\n * Use when you need a `Predicate` guard to narrow an `unknown` value to a\n * callable function.\n *\n * **Details**\n *\n * Uses `typeof input === \"function\"`.\n *\n * **Example** (Guarding functions)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const data: unknown = () => 1\n *\n * if (Predicate.isFunction(data)) {\n * data() // => 1\n * }\n * ```\n *\n * @see {@link isObjectKeyword}\n * @category guards\n * @since 2.0.0\n */\nexport function isFunction(input) {\n return typeof input === \"function\";\n}\n/**\n * Checks whether a value is `undefined`.\n *\n * **When to use**\n *\n * Use when you need a `Predicate` guard for values that are exactly\n * `undefined`.\n *\n * **Details**\n *\n * Uses `input === undefined`.\n *\n * **Example** (Guarding undefined values)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const data: unknown = undefined\n *\n * Predicate.isUndefined(data) // => true\n * ```\n *\n * @see {@link isNotUndefined}\n * @see {@link isNullish}\n * @category guards\n * @since 2.0.0\n */\nexport function isUndefined(input) {\n return input === undefined;\n}\n/**\n * Checks whether a value is not `undefined`.\n *\n * **When to use**\n *\n * Use when you need a `Predicate` refinement that filters out `undefined`\n * while preserving other falsy values.\n *\n * **Details**\n *\n * Returns a refinement that excludes `undefined`.\n *\n * **Example** (Filtering undefined values)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const values = [1, undefined, 2]\n * const defined = values.filter(Predicate.isNotUndefined) // => [1, 2]\n * ```\n *\n * @see {@link isUndefined}\n * @see {@link isNotNullish}\n * @category guards\n * @since 2.0.0\n */\nexport function isNotUndefined(input) {\n return input !== undefined;\n}\n/**\n * Checks whether a value is `null`.\n *\n * **When to use**\n *\n * Use when you need a `Predicate` guard for nullable values.\n *\n * **Details**\n *\n * Uses `input === null`.\n *\n * **Example** (Guarding null values)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const data: unknown = null\n *\n * Predicate.isNull(data) // => true\n * ```\n *\n * @see {@link isNotNull}\n * @see {@link isNullish}\n * @category guards\n * @since 2.0.0\n */\nexport function isNull(input) {\n return input === null;\n}\n/**\n * Checks whether a value is not `null`.\n *\n * **When to use**\n *\n * Use when you need a `Predicate` refinement that filters out `null` while\n * preserving other falsy values.\n *\n * **Details**\n *\n * Returns a refinement that excludes `null`.\n *\n * **Example** (Filtering null values)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const values = [1, null, 2]\n * const nonNull = values.filter(Predicate.isNotNull) // => [1, 2]\n * ```\n *\n * @see {@link isNull}\n * @see {@link isNotNullish}\n * @category guards\n * @since 2.0.0\n */\nexport function isNotNull(input) {\n return input !== null;\n}\n/**\n * Checks whether a value is `null` or `undefined`.\n *\n * **When to use**\n *\n * Use when you need a `Predicate` guard for nullish values.\n *\n * **Details**\n *\n * Uses `input === null || input === undefined`.\n *\n * **Example** (Guarding nullish values)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const values = [0, null, \"\", undefined]\n * const nullish = values.filter(Predicate.isNullish) // => [null, undefined]\n * ```\n *\n * @see {@link isNotNullish}\n * @see {@link isUndefined}\n * @see {@link isNull}\n * @category guards\n * @since 4.0.0\n */\nexport function isNullish(input) {\n return input === null || input === undefined;\n}\n/**\n * Checks whether a value is not `null` and not `undefined`.\n *\n * **When to use**\n *\n * Use when you need a `Predicate` refinement that filters out nullish values\n * but keeps other falsy ones.\n *\n * **Details**\n *\n * Uses `input != null`.\n *\n * **Example** (Filtering non-nullish values)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const values = [0, null, \"\", undefined]\n * const present = values.filter(Predicate.isNotNullish) // => [0, \"\"]\n * ```\n *\n * @see {@link isNullish}\n * @see {@link isNotNull}\n * @see {@link isNotUndefined}\n * @category guards\n * @since 4.0.0\n */\nexport function isNotNullish(input) {\n return input != null;\n}\n/**\n * Type guard that always returns `false`.\n *\n * **When to use**\n *\n * Use when you need a `Predicate` that never accepts, e.g. in default branches.\n *\n * **Example** (Matching no values)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * Predicate.isNever(\"anything\") // => false\n * ```\n *\n * @see {@link isUnknown}\n * @category guards\n * @since 2.0.0\n */\nexport function isNever(_) {\n return false;\n}\n/**\n * Type guard that always returns `true`.\n *\n * **When to use**\n *\n * Use when you need a `Predicate` that always accepts, e.g. as a placeholder.\n *\n * **Example** (Matching every value)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * Predicate.isUnknown(123) // => true\n * ```\n *\n * @see {@link isNever}\n * @category guards\n * @since 2.0.0\n */\nexport function isUnknown(_) {\n return true;\n}\n/**\n * Checks whether a value is an object or an array (non-null object).\n *\n * **When to use**\n *\n * Use when you need a `Predicate` guard that accepts plain objects and arrays,\n * but not `null`.\n *\n * **Details**\n *\n * Uses `typeof input === \"object\" && input !== null` and includes arrays.\n *\n * **Example** (Checking objects or arrays)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * Predicate.isObjectOrArray([]) // => true\n * ```\n *\n * @see {@link isObject}\n * @see {@link isObjectKeyword}\n * @category guards\n * @since 4.0.0\n */\nexport function isObjectOrArray(input) {\n return typeof input === \"object\" && input !== null;\n}\n/**\n * Checks whether a value is a non-null object value that is not an array.\n *\n * **When to use**\n *\n * Use to narrow unknown input to a non-null, non-array object with a\n * `Predicate` guard.\n *\n * **Details**\n *\n * This is a structural runtime check using `typeof input === \"object\"`, so it\n * also accepts object instances such as `Date`, `Map`, class instances, and\n * typed arrays. It excludes `null` and arrays.\n *\n * **Example** (Guarding objects)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * Predicate.isObject({ a: 1 }) // => true\n * Predicate.isObject([1, 2]) // => false\n * ```\n *\n * @see {@link isObjectOrArray}\n * @see {@link isReadonlyObject}\n * @category guards\n * @since 2.0.0\n */\nexport function isObject(input) {\n return typeof input === \"object\" && input !== null && !Array.isArray(input);\n}\n/**\n * Checks whether a value is a non-null, non-array object and narrows it to a\n * readonly indexable object type.\n *\n * **When to use**\n *\n * Use to narrow unknown input to a readonly view of a non-null, non-array\n * object with a `Predicate` guard.\n *\n * **Details**\n *\n * Readonly-ness is a TypeScript type-level view; it is not observable at\n * runtime. This delegates to `isObject`, so class instances and built-in object\n * instances are accepted.\n *\n * **Example** (Checking readonly objects)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const data: unknown = { a: 1 }\n *\n * Predicate.isReadonlyObject(data) // => true\n * ```\n *\n * @see {@link isObject}\n * @category guards\n * @since 4.0.0\n */\nexport function isReadonlyObject(input) {\n return isObject(input);\n}\n/**\n * Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions).\n *\n * **When to use**\n *\n * Use when you need a `Predicate` guard that accepts arrays and functions as\n * well as objects.\n *\n * **Details**\n *\n * Returns `true` for arrays and functions, and `false` for `null`.\n *\n * **Example** (Checking object keywords)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * Predicate.isObjectKeyword(() => 1) // => true\n * Predicate.isObjectKeyword(null) // => false\n * ```\n *\n * @see {@link isObject}\n * @see {@link isObjectOrArray}\n * @category guards\n * @since 4.0.0\n */\nexport function isObjectKeyword(input) {\n return typeof input === \"object\" && input !== null || isFunction(input);\n}\n/**\n * Checks whether a value has a given property key.\n *\n * **When to use**\n *\n * Use when you need a `Predicate` guard for property access on `unknown`\n * values with a simple structural object check.\n *\n * **Details**\n *\n * Uses the `in` operator and `isObjectKeyword`. This does not check property\n * value types.\n *\n * **Example** (Guarding object properties)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const hasName = Predicate.hasProperty(\"name\")\n * const data: unknown = { name: \"Ada\" }\n *\n * if (hasName(data)) {\n * data.name // => \"Ada\"\n * }\n * ```\n *\n * @see {@link isTagged}\n * @see {@link isObjectKeyword}\n * @category guards\n * @since 2.0.0\n */\nexport const hasProperty = /*#__PURE__*/dual(2, (self, property) => isObjectKeyword(self) && property in self);\n/**\n * Checks whether a value has a `_tag` property equal to the given tag.\n *\n * **When to use**\n *\n * Use when you model tagged unions with a `_tag` field and want a quick\n * `Predicate` guard for tagged values.\n *\n * **Details**\n *\n * Uses `hasProperty` and strict equality on `_tag`.\n *\n * **Example** (Guarding tagged values)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const isOk = Predicate.isTagged(\"Ok\")\n *\n * isOk({ _tag: \"Ok\", value: 1 }) // => true\n * ```\n *\n * @see {@link hasProperty}\n * @category guards\n * @since 2.0.0\n */\nexport const isTagged = /*#__PURE__*/dual(2, (self, tag) => hasProperty(self, \"_tag\") && self[\"_tag\"] === tag);\n/**\n * Checks whether a value is an `Error`.\n *\n * **When to use**\n *\n * Use when you need a `Predicate` guard for errors caught from unknown sources.\n *\n * **Details**\n *\n * Uses `instanceof Error`.\n *\n * **Example** (Guarding errors)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const data: unknown = new Error(\"boom\")\n *\n * Predicate.isError(data) // => true\n * ```\n *\n * @see {@link isUnknown}\n * @category guards\n * @since 2.0.0\n */\nexport function isError(input) {\n return input instanceof Error;\n}\n/**\n * Checks whether a value is a `Uint8Array`.\n *\n * **When to use**\n *\n * Use when you need a `Predicate` runtime guard for binary data.\n *\n * **Details**\n *\n * Uses `instanceof Uint8Array`.\n *\n * **Example** (Guarding Uint8Array values)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const data: unknown = new Uint8Array([1, 2])\n *\n * Predicate.isUint8Array(data) // => true\n * ```\n *\n * @see {@link isIterable}\n * @see {@link isSet}\n * @category guards\n * @since 2.0.0\n */\nexport function isUint8Array(input) {\n return input instanceof Uint8Array;\n}\n/**\n * Checks whether a value is a `Date`.\n *\n * **When to use**\n *\n * Use when you need a `Predicate` runtime guard for dates.\n *\n * **Details**\n *\n * Uses `instanceof Date`.\n *\n * **Example** (Guarding Date values)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const data: unknown = new Date()\n *\n * Predicate.isDate(data) // => true\n * ```\n *\n * @see {@link isRegExp}\n * @category guards\n * @since 2.0.0\n */\nexport function isDate(input) {\n return input instanceof Date;\n}\n/**\n * Checks whether a value is iterable.\n *\n * **When to use**\n *\n * Use when you need a `Predicate` guard before iterating an unknown value.\n *\n * **Details**\n *\n * Accepts strings as iterable and uses `hasProperty` for `Symbol.iterator`.\n *\n * **Example** (Guarding iterables)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const data: unknown = [1, 2, 3]\n *\n * Predicate.isIterable(data) // => true\n * ```\n *\n * @see {@link isSet}\n * @see {@link isMap}\n * @category guards\n * @since 2.0.0\n */\nexport function isIterable(input) {\n return hasProperty(input, Symbol.iterator) || isString(input);\n}\n/**\n * Checks whether a value is a `Promise`-like object with `then` and `catch`.\n *\n * **When to use**\n *\n * Use when you need a `Predicate` guard for promise instances across realms.\n *\n * **Details**\n *\n * Performs a structural check for `then` and `catch` functions.\n *\n * **Example** (Guarding promises)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const data: unknown = Promise.resolve(1)\n *\n * Predicate.isPromise(data) // => true\n * ```\n *\n * @see {@link isPromiseLike}\n * @category guards\n * @since 2.0.0\n */\nexport function isPromise(input) {\n return hasProperty(input, \"then\") && \"catch\" in input && isFunction(input.then) && isFunction(input.catch);\n}\n/**\n * Checks whether a value is `PromiseLike` (has a `then` method).\n *\n * **When to use**\n *\n * Use when you need a `Predicate` guard for promise-like values with a\n * callable `then` method.\n *\n * **Details**\n *\n * Performs a structural check for a callable `then`.\n *\n * **Example** (Guarding promise-like values)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const data: unknown = { then: () => {} }\n *\n * Predicate.isPromiseLike(data) // => true\n * ```\n *\n * @see {@link isPromise}\n * @category guards\n * @since 2.0.0\n */\nexport function isPromiseLike(input) {\n return hasProperty(input, \"then\") && isFunction(input.then);\n}\n/**\n * Checks whether a value is a `RegExp`.\n *\n * **When to use**\n *\n * Use when you need a `Predicate` runtime guard for regular expressions.\n *\n * **Details**\n *\n * Uses `instanceof RegExp`.\n *\n * **Example** (Guarding RegExp values)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const data: unknown = /abc/\n *\n * Predicate.isRegExp(data) // => true\n * ```\n *\n * @see {@link isDate}\n * @category guards\n * @since 3.9.0\n */\nexport function isRegExp(input) {\n return input instanceof RegExp;\n}\n/**\n * Composes two predicates or refinements into one.\n *\n * **When to use**\n *\n * Use when you want to compose two `Predicate` checks in sequence, especially\n * when chaining refinements for progressive narrowing.\n *\n * **Details**\n *\n * For refinements, the output type is narrowed by both checks. Evaluation\n * short-circuits on the first `false`.\n *\n * **Example** (Composing refinements)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const isNumber: Predicate.Refinement<unknown, number> = (u): u is number => typeof u === \"number\"\n * const isInteger: Predicate.Refinement<number, number> = (n): n is number => Number.isInteger(n)\n *\n * const isIntegerNumber = Predicate.compose(isNumber, isInteger)\n *\n * isIntegerNumber(1) // => true\n * ```\n *\n * @see {@link and}\n * @see {@link Refinement}\n * @category combinators\n * @since 2.0.0\n */\nexport const compose = /*#__PURE__*/dual(2, (ab, bc) => a => ab(a) && bc(a));\n/**\n * Creates a predicate for tuples by applying predicates to each element.\n *\n * **When to use**\n *\n * Use when you want to validate tuple positions independently by lifting\n * element predicates into a tuple predicate.\n *\n * **Details**\n *\n * Returns a refinement if any element predicate is a refinement. Evaluation\n * stops at the first failing element.\n *\n * **Example** (Checking tuples)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const tupleCheck = Predicate.Tuple([(n: number) => n > 0, Predicate.isString])\n *\n * tupleCheck([1, \"ok\"]) // => true\n * ```\n *\n * @see {@link Struct}\n * @see {@link isTupleOf}\n * @category combinators\n * @since 4.0.0\n */\nexport function Tuple(elements) {\n return as => {\n for (let i = 0; i < elements.length; i++) {\n if (elements[i](as[i]) === false) {\n return false;\n }\n }\n return true;\n };\n}\n/**\n * Creates a predicate for objects by applying predicates to named properties.\n *\n * **When to use**\n *\n * Use when you want to validate a record shape at runtime by lifting property\n * predicates into an object predicate.\n *\n * **Details**\n *\n * Returns a refinement if any field predicate is a refinement. Only the\n * specified keys are checked, and extra keys are ignored.\n *\n * **Example** (Checking structs)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const userCheck = Predicate.Struct({\n * id: Predicate.isNumber,\n * name: Predicate.isString\n * })\n *\n * userCheck({ id: 1, name: \"Ada\" }) // => true\n * ```\n *\n * @see {@link Tuple}\n * @see {@link hasProperty}\n * @category combinators\n * @since 4.0.0\n */\nexport function Struct(fields) {\n const keys = Object.keys(fields);\n return a => {\n for (const key of keys) {\n if (!fields[key](a[key])) {\n return false;\n }\n }\n return true;\n };\n}\n/**\n * Negates a predicate.\n *\n * **When to use**\n *\n * Use when you want the inverse of an existing predicate.\n *\n * **Details**\n *\n * Returns a new predicate that flips the boolean result.\n *\n * **Example** (Negating a predicate)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const isNotString = Predicate.not(Predicate.isString)\n *\n * isNotString(1) // => true\n * ```\n *\n * @see {@link and}\n * @see {@link or}\n * @see {@link xor}\n * @category combinators\n * @since 2.0.0\n */\nexport function not(self) {\n return a => !self(a);\n}\n/**\n * Creates a predicate that returns `true` if either predicate is `true`.\n *\n * **When to use**\n *\n * Use when you want to combine `Predicate`s with OR, accepting values that\n * satisfy at least one condition, including refinements that narrow to a union.\n *\n * **Details**\n *\n * Evaluation short-circuits on the first `true`. For refinements, the output\n * type is a union.\n *\n * **Example** (Checking either condition)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const isStringOrNumber = Predicate.or(Predicate.isString, Predicate.isNumber)\n *\n * isStringOrNumber(\"a\") // => true\n * ```\n *\n * @see {@link and}\n * @see {@link xor}\n * @category combinators\n * @since 2.0.0\n */\nexport const or = /*#__PURE__*/dual(2, (self, that) => a => self(a) || that(a));\n/**\n * Creates a predicate that returns `true` only if both predicates are `true`.\n *\n * **When to use**\n *\n * Use when you want to combine `Predicate`s with AND, accepting values that\n * satisfy multiple conditions, including refinements that narrow to an\n * intersection.\n *\n * **Details**\n *\n * Evaluation short-circuits on the first `false`. For refinements, the output\n * type is an intersection.\n *\n * **Example** (Checking both conditions)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const hasAAndB = Predicate.and(\n * Predicate.hasProperty(\"a\"),\n * Predicate.hasProperty(\"b\")\n * )\n *\n * const input: unknown = JSON.parse(`{\"a\":1,\"b\":\"ok\"}`)\n * if (hasAAndB(input)) {\n * // input has both properties at this point\n * const a = input.a\n * const b = input.b\n *\n * const values = [a, b] // => [1, \"ok\"]\n * }\n * ```\n *\n * @see {@link or}\n * @see {@link not}\n * @category combinators\n * @since 2.0.0\n */\nexport const and = /*#__PURE__*/dual(2, (self, that) => a => self(a) && that(a));\n/**\n * Creates a predicate that returns `true` if exactly one predicate is `true`.\n *\n * **When to use**\n *\n * Use when you want to combine two `Predicate`s with exclusive-or semantics.\n *\n * **Details**\n *\n * Returns `true` when results differ.\n *\n * **Example** (Checking exclusive-or conditions)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const isEven = (n: number) => n % 2 === 0\n * const isPositive = (n: number) => n > 0\n * const either = Predicate.xor(isEven, isPositive)\n *\n * either(-2) // => true\n * ```\n *\n * @see {@link or}\n * @see {@link and}\n * @category combinators\n * @since 2.0.0\n */\nexport const xor = /*#__PURE__*/dual(2, (self, that) => a => self(a) !== that(a));\n/**\n * Creates a predicate that returns `true` when both predicates agree.\n *\n * **When to use**\n *\n * Use when you want to check equivalence of two `Predicate`s.\n *\n * **Details**\n *\n * Returns `true` when both results are equal.\n *\n * **Example** (Defining equivalence)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const isEven = (n: number) => n % 2 === 0\n * const same = Predicate.eqv(isEven, isEven)\n *\n * same(3) // => true\n * ```\n *\n * @see {@link xor}\n * @category combinators\n * @since 2.0.0\n */\nexport const eqv = /*#__PURE__*/dual(2, (self, that) => a => self(a) === that(a));\n/**\n * Creates a predicate representing logical implication: if `antecedent`, then `consequent`.\n *\n * **When to use**\n *\n * Use when you need to encode logical implication between `Predicate` rules,\n * where one rule only applies when a precondition holds.\n *\n * **Details**\n *\n * Models constraints like \"if A then B\" and returns `true` when the antecedent\n * is `false`.\n *\n * **Example** (Checking implication)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const isAdult = (age: number) => age >= 18\n * const canVote = (age: number) => age >= 18\n * const implies = Predicate.implies(isAdult, canVote)\n *\n * implies(16) // => true\n * ```\n *\n * @see {@link and}\n * @see {@link or}\n * @category combinators\n * @since 2.0.0\n */\nexport const implies = /*#__PURE__*/dual(2, (antecedent, consequent) => a => antecedent(a) ? consequent(a) : true);\n/**\n * Creates a predicate that returns `true` when neither predicate is `true`.\n *\n * **When to use**\n *\n * Use when you want to combine two `Predicate`s with logical NOR semantics.\n *\n * **Details**\n *\n * Returns the negation of `or`.\n *\n * **Example** (Checking NOR conditions)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const neither = Predicate.nor(Predicate.isString, Predicate.isNumber)\n *\n * neither(true) // => true\n * ```\n *\n * @see {@link or}\n * @see {@link not}\n * @category combinators\n * @since 2.0.0\n */\nexport const nor = /*#__PURE__*/dual(2, (self, that) => a => !(self(a) || that(a)));\n/**\n * Creates a predicate that returns `true` unless both predicates are `true`.\n *\n * **When to use**\n *\n * Use when you want to combine two `Predicate`s with logical NAND semantics.\n *\n * **Details**\n *\n * Returns the negation of `and`.\n *\n * **Example** (Checking NAND conditions)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const notBoth = Predicate.nand(Predicate.isString, Predicate.isNumber)\n *\n * notBoth(\"a\") // => true\n * ```\n *\n * @see {@link and}\n * @see {@link not}\n * @category combinators\n * @since 2.0.0\n */\nexport const nand = /*#__PURE__*/dual(2, (self, that) => a => !(self(a) && that(a)));\n/**\n * Creates a predicate that returns `true` if all predicates in the collection return `true`.\n *\n * **When to use**\n *\n * Use when you have a dynamic list of predicates to apply.\n *\n * **Details**\n *\n * Evaluation short-circuits on the first `false`. The collection is iterated\n * each time the predicate is called.\n *\n * **Example** (Checking all predicates)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const allChecks = Predicate.every([Predicate.isNumber, (n: number) => n > 0])\n *\n * allChecks(2) // => true\n * ```\n *\n * @see {@link some}\n * @see {@link and}\n * @category combining\n * @since 2.0.0\n */\nexport function every(collection) {\n return a => {\n for (const p of collection) {\n if (!p(a)) {\n return false;\n }\n }\n return true;\n };\n}\n/**\n * Creates a predicate that returns `true` if any predicate in the collection returns `true`.\n *\n * **When to use**\n *\n * Use when you have a dynamic list of predicates and only need one to pass.\n *\n * **Details**\n *\n * Evaluation short-circuits on the first `true`. The collection is iterated\n * each time the predicate is called.\n *\n * **Example** (Checking any predicate)\n *\n * ```ts import.meta.vitest\n * import { Predicate } from \"effect\"\n *\n * const anyCheck = Predicate.some([Predicate.isString, Predicate.isNumber])\n *\n * anyCheck(\"ok\") // => true\n * ```\n *\n * @see {@link every}\n * @see {@link or}\n * @category combining\n * @since 2.0.0\n */\nexport function some(collection) {\n return a => {\n for (const p of collection) {\n if (p(a)) {\n return true;\n }\n }\n return false;\n };\n}\n//# sourceMappingURL=Predicate.js.map","/**\n * Computes Effect hash values and defines the interface for objects that want\n * to provide their own hash implementation. Hashes are small numeric\n * fingerprints used by Effect data structures to bucket values quickly; they\n * are not cryptographic digests and they are not proof that two values are\n * equal. The module also includes helpers for primitive, structure, array, and\n * reference-based hashes, plus functions for combining and optimizing numeric\n * hash values.\n *\n * @since 2.0.0\n */\nimport { dual } from \"./Function.js\";\nimport { byReferenceInstances, getAllObjectKeys } from \"./internal/equal.js\";\nimport { hasProperty } from \"./Predicate.js\";\n/**\n * Defines the unique identifier used to identify objects that implement the Hash interface.\n *\n * **When to use**\n *\n * Use as the computed property key for the method that supplies a custom hash\n * value on a `Hash` implementor.\n *\n * @see {@link Hash} for the interface implemented with this symbol\n * @see {@link isHash} for checking whether a value implements `Hash`\n * @see {@link hash} for computing hash values\n *\n * @category symbols\n * @since 2.0.0\n */\nexport const symbol = \"~effect/Hash\";\n/**\n * Computes a hash value for any given value.\n *\n * **When to use**\n *\n * Use to compute an Effect hash for primitives, collections, and hashable\n * objects.\n *\n * **Details**\n *\n * This function can hash primitives (numbers, strings, booleans, etc.) as well as\n * objects, arrays, and other complex data structures. It automatically handles\n * different types and provides a consistent hash value for equivalent inputs.\n *\n * **Gotchas**\n *\n * Objects being hashed must be treated as immutable after their first hash\n * computation. Hash results are cached, so mutating an object after hashing will\n * lead to stale cached values and broken hash-based operations. For mutable\n * objects, implement a custom `Hash` interface that hashes the object reference\n * rather than its content.\n *\n * **Example** (Hashing different values)\n *\n * ```ts import.meta.vitest\n * import { Hash } from \"effect\"\n *\n * Hash.hash(42) === Hash.hash(42) // => true\n * Hash.hash(\"hello\") === Hash.hash(\"hello\") // => true\n * Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true\n * ```\n *\n * @category hashing\n * @since 2.0.0\n */\nexport const hash = self => {\n switch (typeof self) {\n case \"number\":\n return number(self);\n case \"bigint\":\n return string(self.toString(10));\n case \"string\":\n return string(self);\n case \"undefined\":\n return string(\"undefined\");\n case \"function\":\n case \"object\":\n {\n if (self === null) {\n return string(\"null\");\n } else if (self instanceof Date) {\n if (Number.isNaN(self.getTime())) {\n return string(\"Invalid Date\");\n }\n return string(self.toISOString());\n } else if (self instanceof RegExp) {\n return string(self.toString());\n } else {\n if (byReferenceInstances.has(self)) {\n return random(self);\n }\n if (hashCache.has(self)) {\n return hashCache.get(self);\n }\n const h = withVisitedTracking(self, () => {\n if (isHash(self)) {\n return self[symbol]();\n } else if (typeof self === \"function\") {\n return random(self);\n } else if (self instanceof DataView) {\n return array(new Uint8Array(self.buffer, self.byteOffset, self.byteLength));\n } else if (Array.isArray(self) || ArrayBuffer.isView(self)) {\n return array(self);\n } else if (self instanceof Map) {\n return hashMap(self);\n } else if (self instanceof Set) {\n return hashSet(self);\n }\n return structure(self);\n });\n hashCache.set(self, h);\n return h;\n }\n }\n default:\n // The remaining primitive types are boolean and symbol.\n return string(String(self));\n }\n};\n/**\n * Generates a random hash value for an object and caches it.\n *\n * **When to use**\n *\n * Use to hash an object by reference identity instead of structural content.\n *\n * **Details**\n *\n * This function creates a random hash value for objects that don't have their own\n * hash implementation. The hash value is cached using a WeakMap, so the same object\n * will always return the same hash value during its lifetime.\n *\n * **Example** (Hashing objects by reference)\n *\n * ```ts import.meta.vitest\n * import { Hash } from \"effect\"\n *\n * const obj1 = { a: 1 }\n * const obj2 = { a: 1 }\n *\n * Hash.random(obj1) === Hash.random(obj1) // => true\n *\n * typeof Hash.random(obj2) // => \"number\"\n * ```\n *\n * @category hashing\n * @since 2.0.0\n */\nexport const random = self => {\n if (!randomHashCache.has(self)) {\n randomHashCache.set(self, number(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)));\n }\n return randomHashCache.get(self);\n};\n/**\n * Combines two hash values into a single hash value.\n *\n * **When to use**\n *\n * Use to build a hash for a composite value by folding together hash values for\n * its parts.\n *\n * **Details**\n *\n * Supports both direct and pipeable usage. The implementation combines two\n * hash values with `(self * 53) ^ b`.\n *\n * **Example** (Combining hash values)\n *\n * ```ts import.meta.vitest\n * import { Hash, pipe } from \"effect\"\n *\n * const hash1 = Hash.hash(\"hello\")\n * const hash2 = Hash.hash(\"world\")\n *\n * const combined = Hash.combine(hash2)(hash1)\n * combined === pipe(hash1, Hash.combine(hash2)) // => true\n * ```\n *\n * @see {@link hash} for computing hash values from arbitrary inputs\n * @see {@link structureKeys} for hashing selected object fields without manual combination\n *\n * @category hashing\n * @since 2.0.0\n */\nexport const combine = /*#__PURE__*/dual(2, (self, b) => self * 53 ^ b);\n/**\n * Applies bit manipulation techniques to optimize a hash value.\n *\n * **When to use**\n *\n * Use to improve the bit distribution of a raw numeric hash value.\n *\n * **Details**\n *\n * This function takes a hash value and applies bitwise operations to improve\n * the distribution of hash values, reducing the likelihood of collisions.\n *\n * **Example** (Optimizing a hash value)\n *\n * ```ts import.meta.vitest\n * import { Hash } from \"effect\"\n *\n * Hash.optimize(1234567890) // => 160826066\n * ```\n *\n * @category hashing\n * @since 2.0.0\n */\nexport const optimize = n => n & 0xbfffffff | n >>> 1 & 0x40000000;\n/**\n * Checks whether a value implements the Hash interface.\n *\n * **When to use**\n *\n * Use to detect whether an unknown value provides a custom hash implementation.\n *\n * **Details**\n *\n * This function determines whether a given value has the Hash symbol property,\n * indicating that it can provide its own hash value implementation.\n *\n * **Example** (Checking for Hash support)\n *\n * ```ts import.meta.vitest\n * import { Hash } from \"effect\"\n *\n * class MyHashable implements Hash.Hash {\n * [Hash.symbol]() {\n * return 42\n * }\n * }\n *\n * Hash.isHash(new MyHashable()) // => true\n * Hash.isHash({}) // => false\n * Hash.isHash(\"string\") // => false\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isHash = u => hasProperty(u, symbol);\n/**\n * Computes a hash value for a number.\n *\n * **When to use**\n *\n * Use to hash a JavaScript number with Effect's numeric hash semantics.\n *\n * **Details**\n *\n * This function creates a hash value for numeric inputs, handling special cases\n * like NaN, Infinity, and -Infinity with distinct hash values. It uses bitwise operations to ensure good distribution\n * of hash values across different numeric inputs.\n *\n * **Example** (Hashing numbers)\n *\n * ```ts import.meta.vitest\n * import { Hash } from \"effect\"\n *\n * Number.isInteger(Hash.number(42)) // => true\n * Number.isInteger(Hash.number(3.14)) // => true\n * Hash.number(NaN) === Hash.number(NaN) // => true\n * Hash.number(Infinity) === Hash.number(Infinity) // => true\n * Hash.number(100) === Hash.number(100) // => true\n * ```\n *\n * @category hashing\n * @since 2.0.0\n */\nexport const number = n => {\n if (n !== n || n === Infinity || n === -Infinity) {\n return string(String(n));\n }\n let h = n | 0;\n if (h !== n) {\n h ^= n * 0xffffffff;\n }\n while (n > 0xffffffff) {\n h ^= n /= 0xffffffff;\n }\n return optimize(h);\n};\n/**\n * Computes a hash value for a string using the djb2 algorithm.\n *\n * **When to use**\n *\n * Use when you need a string field to contribute to a custom structural hash\n * implementation.\n *\n * **Details**\n *\n * This function implements a variation of the djb2 hash algorithm, which is\n * known for its good distribution properties and speed. It processes each\n * character of the string to produce a consistent hash value.\n *\n * **Example** (Hashing strings)\n *\n * ```ts import.meta.vitest\n * import { Hash } from \"effect\"\n *\n * Hash.string(\"hello\") // => 181380007\n * Hash.string(\"world\") // => 164394279\n * Hash.string(\"\") // => 5381\n * Hash.string(\"test\") === Hash.string(\"test\") // => true\n * ```\n *\n * @category hashing\n * @since 2.0.0\n */\nexport const string = str => {\n let h = 5381,\n i = str.length;\n while (i) {\n h = h * 33 ^ str.charCodeAt(--i);\n }\n return optimize(h);\n};\n/**\n * Computes a hash value for an object using only the specified keys.\n *\n * **When to use**\n *\n * Use to hash an object by a selected set of property keys.\n *\n * **Details**\n *\n * This function allows you to hash an object by considering only specific keys,\n * which is useful when you want to create a hash based on a subset of an object's\n * properties.\n *\n * **Example** (Hashing selected object keys)\n *\n * ```ts import.meta.vitest\n * import { Hash } from \"effect\"\n *\n * const person = { name: \"John\", age: 30, city: \"New York\" }\n *\n * const hash1 = Hash.structureKeys(person, [\"name\", \"age\"])\n * const hash2 = Hash.structureKeys(person, [\"name\", \"city\"])\n *\n * hash1 // => -590673747\n * hash2 // => 284850673\n *\n * const person2 = { name: \"John\", age: 30, city: \"Boston\" }\n * const hash3 = Hash.structureKeys(person2, [\"name\", \"age\"])\n * hash1 === hash3 // => true\n * ```\n *\n * @category hashing\n * @since 2.0.0\n */\nexport const structureKeys = (o, keys) => {\n let h = 12289;\n for (const key of keys) {\n h ^= combine(hash(key), hash(o[key]));\n }\n return optimize(h);\n};\n/**\n * Computes a structural hash for an object using Effect's object key collection.\n *\n * **When to use**\n *\n * Use to hash an object from all structural keys collected by Effect.\n *\n * **Details**\n *\n * The hash is based on the object's structural keys and their values, including\n * symbol keys and relevant prototype keys for non-plain objects.\n *\n * **Example** (Hashing object structures)\n *\n * ```ts import.meta.vitest\n * import { Hash } from \"effect\"\n *\n * const obj1 = { name: \"John\", age: 30 }\n * const obj2 = { name: \"Jane\", age: 25 }\n * const obj3 = { name: \"John\", age: 30 }\n *\n * Hash.structure(obj1) // => -590673747\n * Hash.structure(obj2) // => -590160631\n * Hash.structure(obj3) // => -590673747\n * Hash.structure(obj1) === Hash.structure(obj3) // => true\n * ```\n *\n * @category hashing\n * @since 2.0.0\n */\nexport const structure = o => structureKeys(o, getAllObjectKeys(o));\nconst iterableWith = (seed, f) => iter => {\n let h = seed;\n for (const element of iter) {\n h ^= f(element);\n }\n return optimize(h);\n};\n/**\n * Computes a hash value for an iterable by hashing all of its elements.\n *\n * **When to use**\n *\n * Use to hash the values yielded by an iterable with Effect hash semantics.\n *\n * **Details**\n *\n * The implementation folds element hashes from the seed `6151` with XOR and\n * then optimizes the final hash.\n *\n * **Gotchas**\n *\n * A hash is not an equality proof. Because this implementation uses XOR,\n * reordered inputs can produce the same hash.\n *\n * **Example** (Hashing arrays)\n *\n * ```ts import.meta.vitest\n * import { Hash } from \"effect\"\n *\n * const arr1 = [1, 2, 3]\n * const arr2 = [1, 2, 3]\n * const arr3 = [3, 2, 1]\n *\n * Hash.array(arr1) // => 6151\n * Hash.array(arr2) // => 6151\n * Hash.array(arr3) // => 6151\n * Hash.array(arr1) === Hash.array(arr2) // => true\n * Hash.array(arr1) === Hash.array(arr3) // => true\n * ```\n *\n * @see {@link hash} for the general-purpose hash dispatcher\n *\n * @category hashing\n * @since 2.0.0\n */\nexport const array = /*#__PURE__*/iterableWith(6151, hash);\nconst hashMap = /*#__PURE__*/iterableWith(/*#__PURE__*/string(\"Map\"), ([k, v]) => combine(hash(k), hash(v)));\nconst hashSet = /*#__PURE__*/iterableWith(/*#__PURE__*/string(\"Set\"), hash);\nconst randomHashCache = /*#__PURE__*/new WeakMap();\nconst hashCache = /*#__PURE__*/new WeakMap();\nconst visitedObjects = /*#__PURE__*/new WeakSet();\nfunction withVisitedTracking(obj, fn) {\n if (visitedObjects.has(obj)) {\n return string(\"[Circular]\");\n }\n visitedObjects.add(obj);\n const result = fn();\n visitedObjects.delete(obj);\n return result;\n}\n//# sourceMappingURL=Hash.js.map","import * as Hash from \"./Hash.js\";\nimport { byReferenceInstances, getAllObjectKeys } from \"./internal/equal.js\";\nimport { hasProperty } from \"./Predicate.js\";\n/**\n * Defines the unique string identifier for the `Equal` interface.\n *\n * **When to use**\n *\n * Use when you implement custom equality and need the computed property key for\n * the equality method.\n *\n * **Details**\n *\n * This is a pure constant with no allocation or side effects.\n *\n * **Example** (Implementing Equal on a class)\n *\n * ```ts import.meta.vitest\n * import { Equal, Hash } from \"effect\"\n *\n * class UserId implements Equal.Equal {\n * constructor(readonly id: string) {}\n *\n * [Equal.symbol](that: Equal.Equal): boolean {\n * return that instanceof UserId && this.id === that.id\n * }\n *\n * [Hash.symbol](): number {\n * return Hash.string(this.id)\n * }\n * }\n *\n * Equal.equals(new UserId(\"1\"), new UserId(\"1\")) // => true\n * Equal.equals(new UserId(\"1\"), new UserId(\"2\")) // => false\n * ```\n *\n * @see {@link Equal} — the interface that uses this symbol\n * @see {@link isEqual} — type guard for `Equal` implementors\n * @category symbols\n * @since 2.0.0\n */\nexport const symbol = \"~effect/Equal\";\nexport function equals() {\n if (arguments.length === 1) {\n return self => compareBoth(self, arguments[0]);\n }\n return compareBoth(arguments[0], arguments[1]);\n}\nfunction compareBoth(self, that) {\n if (self === that) return true;\n if (self == null || that == null) return false;\n const selfType = typeof self;\n if (selfType !== typeof that) {\n return false;\n }\n // Special case for NaN: NaN should be considered equal to NaN\n if (selfType === \"number\" && self !== self && that !== that) {\n return true;\n }\n if (selfType !== \"object\" && selfType !== \"function\") {\n return false;\n }\n if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) {\n return false;\n }\n // For objects and functions, use cached comparison\n return withCache(self, that, compareObjects);\n}\n/** Helper to run comparison with proper visited tracking */\nfunction withVisitedTracking(self, that, fn) {\n const hasLeft = visitedLeft.has(self);\n const hasRight = visitedRight.has(that);\n // Check for circular references before adding\n if (hasLeft && hasRight) {\n return true; // Both are circular at the same level\n }\n if (hasLeft || hasRight) {\n return false; // Only one is circular\n }\n visitedLeft.add(self);\n visitedRight.add(that);\n const result = fn();\n visitedLeft.delete(self);\n visitedRight.delete(that);\n return result;\n}\nconst visitedLeft = /*#__PURE__*/new WeakSet();\nconst visitedRight = /*#__PURE__*/new WeakSet();\n/** Helper to perform cached object comparison */\nfunction compareObjects(self, that) {\n if (Hash.hash(self) !== Hash.hash(that)) {\n return false;\n } else if (self instanceof Date) {\n if (!(that instanceof Date)) return false;\n const selfTime = self.getTime();\n const thatTime = that.getTime();\n return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime);\n } else if (self instanceof RegExp) {\n if (!(that instanceof RegExp)) return false;\n return self.toString() === that.toString();\n }\n const selfIsEqual = isEqual(self);\n const thatIsEqual = isEqual(that);\n if (selfIsEqual !== thatIsEqual) return false;\n const bothEquals = selfIsEqual && thatIsEqual;\n if (typeof self === \"function\" && !bothEquals) {\n return false;\n }\n return withVisitedTracking(self, that, () => {\n if (bothEquals) {\n return self[symbol](that);\n } else if (Array.isArray(self)) {\n if (!Array.isArray(that) || self.length !== that.length) {\n return false;\n }\n return compareArrays(self, that);\n } else if (ArrayBuffer.isView(self)) {\n const selfIsDataView = self instanceof DataView;\n if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) {\n return false;\n }\n if (selfIsDataView) {\n const thatDataView = that;\n return compareTypedArrays(new Uint8Array(self.buffer, self.byteOffset, self.byteLength), new Uint8Array(thatDataView.buffer, thatDataView.byteOffset, thatDataView.byteLength));\n }\n return compareTypedArrays(self, that);\n } else if (self instanceof Map) {\n if (!(that instanceof Map) || self.size !== that.size) {\n return false;\n }\n return compareMaps(self, that);\n } else if (self instanceof Set) {\n if (!(that instanceof Set) || self.size !== that.size) {\n return false;\n }\n return compareSets(self, that);\n }\n return compareRecords(self, that);\n });\n}\nfunction withCache(self, that, f) {\n // Check cache first\n let selfMap = equalityCache.get(self);\n if (!selfMap) {\n selfMap = new WeakMap();\n equalityCache.set(self, selfMap);\n } else if (selfMap.has(that)) {\n return selfMap.get(that);\n }\n // Perform the comparison\n const result = f(self, that);\n // Cache the result bidirectionally\n selfMap.set(that, result);\n let thatMap = equalityCache.get(that);\n if (!thatMap) {\n thatMap = new WeakMap();\n equalityCache.set(that, thatMap);\n }\n thatMap.set(self, result);\n return result;\n}\nconst equalityCache = /*#__PURE__*/new WeakMap();\nfunction compareArrays(self, that) {\n for (let i = 0; i < self.length; i++) {\n if (!compareBoth(self[i], that[i])) {\n return false;\n }\n }\n return true;\n}\nfunction compareTypedArrays(self, that) {\n if (self.length !== that.length) {\n return false;\n }\n for (let i = 0; i < self.length; i++) {\n if (self[i] !== that[i]) {\n return false;\n }\n }\n return true;\n}\nfunction compareRecords(self, that) {\n const selfKeys = getAllObjectKeys(self);\n const thatKeys = getAllObjectKeys(that);\n if (selfKeys.size !== thatKeys.size) {\n return false;\n }\n for (const key of selfKeys) {\n if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) {\n return false;\n }\n }\n return true;\n}\n/** @internal */\nexport function makeCompareMap(keyEquivalence, valueEquivalence) {\n return function compareMaps(self, that) {\n const thatEntries = Array.from(that);\n for (const [selfKey, selfValue] of self) {\n let found = false;\n for (let i = 0; i < thatEntries.length; i++) {\n const [thatKey, thatValue] = thatEntries[i];\n if (keyEquivalence(selfKey, thatKey) && valueEquivalence(selfValue, thatValue)) {\n thatEntries[i] = thatEntries[thatEntries.length - 1];\n thatEntries.pop();\n found = true;\n break;\n }\n }\n if (!found) {\n return false;\n }\n }\n return true;\n };\n}\nconst compareMaps = /*#__PURE__*/makeCompareMap(compareBoth, compareBoth);\n/** @internal */\nexport function makeCompareSet(equivalence) {\n return function compareSets(self, that) {\n const thatValues = Array.from(that);\n for (const selfValue of self) {\n let found = false;\n for (let i = 0; i < thatValues.length; i++) {\n const thatValue = thatValues[i];\n if (equivalence(selfValue, thatValue)) {\n thatValues[i] = thatValues[thatValues.length - 1];\n thatValues.pop();\n found = true;\n break;\n }\n }\n if (!found) {\n return false;\n }\n }\n return true;\n };\n}\nconst compareSets = /*#__PURE__*/makeCompareSet(compareBoth);\n/**\n * Checks whether a value implements the {@link Equal} interface.\n *\n * **When to use**\n *\n * Use when you need generic utility code to distinguish `Equal` implementors\n * from plain values before calling `[Equal.symbol]` directly.\n *\n * **Details**\n *\n * - Pure function, no side effects.\n * - Returns `true` if and only if `u` has a property keyed by\n * {@link symbol}.\n * - Acts as a TypeScript type guard, narrowing the input to {@link Equal}.\n *\n * **Example** (Checking Equal values)\n *\n * ```ts import.meta.vitest\n * import { Equal, Hash } from \"effect\"\n *\n * class Token implements Equal.Equal {\n * constructor(readonly value: string) {}\n * [Equal.symbol](that: Equal.Equal): boolean {\n * return that instanceof Token && this.value === that.value\n * }\n * [Hash.symbol](): number {\n * return Hash.string(this.value)\n * }\n * }\n *\n * Equal.isEqual(new Token(\"abc\")) // => true\n * Equal.isEqual({ x: 1 }) // => false\n * Equal.isEqual(42) // => false\n * ```\n *\n * @see {@link Equal} — the interface being checked\n * @see {@link symbol} — the property key that signals `Equal` support\n * @category guards\n * @since 2.0.0\n */\nexport const isEqual = u => hasProperty(u, symbol);\n/**\n * Wraps {@link equals} as an `Equivalence<A>`.\n *\n * **When to use**\n *\n * Use when you want to pass `Equal.equals` to APIs that require an\n * `Equivalence`.\n *\n * **Details**\n *\n * - Returns a function `(a: A, b: A) => boolean` that delegates to\n * {@link equals}.\n * - Pure; allocates a thin wrapper on each call.\n *\n * **Example** (Deduplicating with Equal semantics)\n *\n * ```ts import.meta.vitest\n * import { Array, Equal } from \"effect\"\n *\n * Array.dedupeWith([1, 2, 2, 3, 1], Equal.asEquivalence<number>()) // => [1, 2, 3]\n * ```\n *\n * @see {@link equals} — the underlying comparison function\n * @category instances\n * @since 4.0.0\n */\nexport const asEquivalence = () => equals;\n/**\n * Creates a proxy that uses reference equality instead of structural equality.\n *\n * **When to use**\n *\n * Use when you need to compare a plain object or array by identity without\n * mutating the original value.\n *\n * **Details**\n *\n * - Returns a `Proxy` wrapping `obj`. The proxy reads through to the\n * original, so property access is unchanged.\n * - The proxy is registered in an internal WeakSet; {@link equals} returns\n * `false` for any pair where at least one operand is in that set (unless\n * they are the same reference).\n * - Each call creates a **new** proxy, so `byReference(x) !== byReference(x)`.\n * - Does **not** mutate the original object (unlike {@link byReferenceUnsafe}).\n *\n * **Example** (Opting out of structural equality)\n *\n * ```ts import.meta.vitest\n * import { Equal } from \"effect\"\n *\n * const a = { x: 1 }\n * const b = { x: 1 }\n *\n * Equal.equals(a, b) // => true\n *\n * const aRef = Equal.byReference(a)\n * Equal.equals(aRef, b) // => false\n * Equal.equals(aRef, aRef) // => true\n * aRef.x // => 1\n * ```\n *\n * @see {@link byReferenceUnsafe} — same effect without a proxy (mutates the\n * original)\n * @see {@link equals} — the comparison function affected by this opt-out\n * @category equality\n * @since 4.0.0\n */\nexport const byReference = obj => byReferenceUnsafe(new Proxy(obj, {}));\n/**\n * Marks an object permanently to use reference equality, without creating a proxy.\n *\n * **When to use**\n *\n * Use when you need reference equality without proxy allocation and accept\n * permanently marking the original object for reference-only equality.\n *\n * **Details**\n *\n * - Adds `obj` to an internal WeakSet. From that point on, {@link equals}\n * treats it as reference-only.\n * - Returns the **same** object (not a copy or proxy), so\n * `byReferenceUnsafe(x) === x`.\n * - Does **not** affect the object's prototype, properties, or behavior\n * beyond equality checks.\n *\n * **Gotchas**\n *\n * The marking is irreversible for the lifetime of the object.\n *\n * **Example** (Marking an object for reference equality)\n *\n * ```ts import.meta.vitest\n * import { Equal } from \"effect\"\n *\n * const obj1 = { a: 1, b: 2 }\n * const obj2 = { a: 1, b: 2 }\n *\n * const marked = Equal.byReferenceUnsafe(obj1)\n *\n * Equal.equals(obj1, obj2) // => false\n * Equal.equals(obj1, obj1) // => true\n * marked === obj1 // => true\n * ```\n *\n * @see {@link byReference} — safer alternative that creates a proxy\n * @see {@link equals} — the comparison function affected by this opt-out\n * @category unsafe\n * @since 4.0.0\n */\nexport const byReferenceUnsafe = obj => {\n byReferenceInstances.add(obj);\n return obj;\n};\n//# sourceMappingURL=Equal.js.map","import { pipeArguments } from \"./Pipeable.js\";\nimport { hasProperty } from \"./Predicate.js\";\n/**\n * Defines the symbol used to identify objects that implement the {@link Redactable}\n * protocol.\n *\n * **When to use**\n *\n * Use as the property key when implementing the `Redactable` protocol.\n *\n * **Details**\n *\n * Add a method under this key to make an object redactable. The method receives\n * the current `Context` and must return the replacement value. The symbol is\n * registered globally via `Symbol.for(\"~effect/Redactable\")`, so it is\n * identical across multiple copies of the library at runtime.\n *\n * **Example** (Masking an API key)\n *\n * ```ts import.meta.vitest\n * import { Context, Redactable } from \"effect\"\n *\n * class ApiKey {\n * constructor(readonly raw: string) {}\n *\n * [Redactable.symbolRedactable](_ctx: Context.Context<never>) {\n * return this.raw.slice(0, 4) + \"...\"\n * }\n * }\n *\n * Redactable.redact(new ApiKey(\"secret-key\")) // => \"secr...\"\n * ```\n *\n * @see {@link Redactable} for the interface this symbol belongs to\n * @see {@link isRedactable} to check whether a value has this symbol\n * @category symbols\n * @since 3.10.0\n */\nexport const symbolRedactable = /*#__PURE__*/Symbol.for(\"~effect/Redactable\");\n/**\n * Type guard that checks whether a value implements the {@link Redactable}\n * interface.\n *\n * **When to use**\n *\n * Use to narrow an unknown value before calling redaction-specific helpers.\n *\n * @see {@link Redactable} for the interface being checked\n * @see {@link redact} to apply redaction if the value is redactable\n * @category guards\n * @since 3.10.0\n */\nexport const isRedactable = u => hasProperty(u, symbolRedactable);\n/**\n * Returns a redacted value if it implements {@link Redactable}, otherwise returns it\n * unchanged.\n *\n * **When to use**\n *\n * Use as the general-purpose entry point for redaction when the input may\n * or may not implement the redaction protocol.\n *\n * **Details**\n *\n * This function calls {@link isRedactable} and, when it returns `true`,\n * delegates to {@link getRedacted}.\n *\n * **Gotchas**\n *\n * Redaction is not recursive. Nested redactable values inside the returned\n * object are not automatically redacted.\n *\n * @see {@link isRedactable} to check before redacting\n * @see {@link getRedacted} for the lower-level variant for known redactables\n * @category destructors\n * @since 3.10.0\n */\nexport function redact(u) {\n if (isRedactable(u)) return getRedacted(u);\n return u;\n}\n/**\n * Returns the result of calling `[symbolRedactable]` on a value that is\n * already known to be {@link Redactable}.\n *\n * **When to use**\n *\n * Use when you need to read the redacted representation from a value already\n * verified as `Redactable`.\n *\n * **Details**\n *\n * This function reads the current fiber's `Context` from the global fiber\n * reference and passes it to the redaction method.\n *\n * **Gotchas**\n *\n * If no fiber is active, an empty `Context` is passed to the redaction method.\n *\n * @see {@link redact} for the higher-level variant that handles non-redactable values\n * @see {@link isRedactable} for the type guard to verify before calling this\n * @category destructors\n * @since 4.0.0\n */\nexport function getRedacted(redactable) {\n return redactable[symbolRedactable](globalThis[currentFiberTypeId]?.context ?? emptyContext);\n}\n/** @internal */\nexport const currentFiberTypeId = \"~effect/Fiber/currentFiber\";\nconst emptyMap = /*#__PURE__*/new Map();\nconst emptyContext = {\n \"~effect/Context\": {},\n base: emptyMap,\n depth: 0,\n mapUnsafe: emptyMap,\n pipe() {\n return pipeArguments(this, arguments);\n }\n};\n//# sourceMappingURL=Redactable.js.map","/**\n * Formats JavaScript values into readable strings.\n *\n * `format` is intended for logs, diagnostics, and error messages. It handles\n * primitives, objects, arrays, dates, regular expressions, maps, sets, class\n * instances, errors, circular references, and redactable values. `formatJson`\n * wraps JSON formatting with redaction and circular-reference handling, and the\n * module also includes helpers for property keys, paths, and dates.\n *\n * @since 4.0.0\n */\nimport * as Predicate from \"./Predicate.js\";\nimport { getRedacted, redact, symbolRedactable } from \"./Redactable.js\";\n/**\n * Converts any JavaScript value into a human-readable string.\n *\n * **When to use**\n *\n * Use when you need to format arbitrary JavaScript values for debugging,\n * logging, or error messages.\n *\n * **Details**\n *\n * - Output is **not** valid JSON; use {@link formatJson} when you need\n * parseable JSON.\n * - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class\n * instances that `JSON.stringify` cannot represent.\n * - Circular references are shown as `\"[Circular]\"` instead of throwing.\n * - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing.\n * - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`).\n * Strings are JSON-quoted.\n * - Objects with a custom `toString` (not `Object.prototype.toString`):\n * `toString()` is called unless `ignoreToString` is `true`.\n * - Errors with a `cause`: formatted as `\"<message> (cause: <cause>)\"`.\n * - Iterables (`Set`, `Map`, etc.): formatted as\n * `ClassName([...elements])`.\n * - Class instances: wrapped as `ClassName({...})`.\n * - `Redactable` values are automatically redacted.\n * - Arrays/objects with 0–1 entries are inline; larger ones are\n * pretty-printed when `space` is set.\n * - `space` — indentation unit (number of spaces, or a string like\n * `\"\\t\"`). Defaults to `0` (compact).\n * - `ignoreToString` — skip calling `toString()`. Defaults to `false`.\n *\n * **Example** (Formatting compact output)\n *\n * ```ts import.meta.vitest\n * import { Formatter } from \"effect\"\n *\n * Formatter.format({ a: 1, b: [2, 3] }) // => \"{\\\"a\\\":1,\\\"b\\\":[2,3]}\"\n * ```\n *\n * **Example** (Pretty-printed output)\n *\n * ```ts import.meta.vitest\n * import { Formatter } from \"effect\"\n *\n * const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 })\n * output // => \"{\\n \\\"a\\\": 1,\\n \\\"b\\\": [\\n 2,\\n 3\\n ]\\n}\"\n * ```\n *\n * **Example** (Handling circular references)\n *\n * ```ts import.meta.vitest\n * import { Formatter } from \"effect\"\n *\n * const obj: any = { name: \"loop\" }\n * obj.self = obj\n * Formatter.format(obj) // => \"{\\\"name\\\":\\\"loop\\\",\\\"self\\\":[Circular]}\"\n * ```\n *\n * @see {@link formatJson}\n * @see {@link Formatter}\n * @category formatting\n * @since 2.0.0\n */\nexport function format(input, options) {\n const space = options?.space ?? 0;\n const ancestors = new WeakSet();\n const gap = !space ? \"\" : typeof space === \"number\" ? \" \".repeat(space) : space;\n const ind = d => gap.repeat(d);\n const wrap = (v, body) => {\n const ctor = v?.constructor;\n return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body;\n };\n const ownKeys = o => {\n try {\n return Reflect.ownKeys(o);\n } catch {\n return [\"[ownKeys threw]\"];\n }\n };\n function recur(v, d = 0) {\n try {\n return recurUnsafe(v, d);\n } catch {\n if (typeof v === \"object\" && v !== null || typeof v === \"function\") ancestors.delete(v);\n return \"[inspection threw]\";\n }\n }\n function recurUnsafe(v, d = 0) {\n if (typeof v === \"string\") return JSON.stringify(v);\n if (typeof v === \"number\" || v == null || typeof v === \"boolean\" || typeof v === \"symbol\") return String(v);\n if (typeof v === \"bigint\") return String(v) + \"n\";\n if (typeof v === \"object\" || typeof v === \"function\") {\n if (ancestors.has(v)) return CIRCULAR;\n ancestors.add(v);\n let output;\n if (symbolRedactable in v) {\n output = recur(getRedacted(v), d);\n } else if (Array.isArray(v)) {\n output = !gap || v.length <= 1 ? `[${v.map(x => recur(x, d)).join(\",\")}]` : `[\\n${ind(d + 1)}${v.map(x => recur(x, d + 1)).join(\",\\n\" + ind(d + 1))}\\n${ind(d)}]`;\n } else if (v instanceof Date) {\n output = formatDate(v);\n } else if (!options?.ignoreToString && Predicate.hasProperty(v, \"toString\") && typeof v[\"toString\"] === \"function\" && v[\"toString\"] !== Object.prototype.toString && v[\"toString\"] !== Array.prototype.toString) {\n const s = safeToString(v);\n output = v instanceof Error && v.cause !== undefined ? `${s} (cause: ${recur(v.cause, d)})` : s;\n } else if (Symbol.iterator in v) {\n output = `${v.constructor.name}(${recur(Array.from(v), d)})`;\n } else {\n const keys = ownKeys(v);\n if (!gap || keys.length <= 1) {\n const body = `{${keys.map(k => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(\",\")}}`;\n output = wrap(v, body);\n } else {\n const body = `{\\n${keys.map(k => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(\",\\n\")}\\n${ind(d)}}`;\n output = wrap(v, body);\n }\n }\n ancestors.delete(v);\n return output;\n }\n return String(v);\n }\n return recur(input, 0);\n}\nconst CIRCULAR = \"[Circular]\";\n/**\n * @internal\n */\nexport function formatPropertyKey(name) {\n return typeof name === \"string\" ? JSON.stringify(name) : String(name);\n}\n/**\n * Formats an array of property keys as a bracket-notation path string.\n *\n * @internal\n */\nexport function formatPath(path) {\n return path.map(key => `[${formatPropertyKey(key)}]`).join(\"\");\n}\n/**\n * Formats a `Date` as an ISO 8601 string, returning `\"Invalid Date\"` for\n * invalid dates instead of throwing.\n *\n * @internal\n */\nexport function formatDate(date) {\n try {\n return date.toISOString();\n } catch {\n return \"Invalid Date\";\n }\n}\nfunction safeToString(input) {\n try {\n const s = input.toString();\n return typeof s === \"string\" ? s : String(s);\n } catch {\n return \"[toString threw]\";\n }\n}\nfunction safeGet(input, key) {\n try {\n return input[key];\n } catch {\n return \"[property access threw]\";\n }\n}\n/**\n * Stringifies a value to JSON safely, silently dropping circular references.\n *\n * **When to use**\n *\n * Use when you need valid JSON output, unlike `format`, and the input may\n * contain circular references that should be silently omitted rather than\n * throwing a `TypeError`.\n *\n * **Details**\n *\n * Uses `JSON.stringify` internally with a replacer that tracks the current\n * object ancestry. Circular references are replaced with `undefined`, which\n * omits them from object output. `Redactable` values are automatically redacted\n * before serialization. `BigInt` values are stringified with an `n` suffix.\n * Values not supported by JSON otherwise follow standard `JSON.stringify`\n * behavior. The `space` parameter controls indentation and defaults to `0`.\n *\n * **Gotchas**\n *\n * When the root input is `undefined`, a symbol, or a function, `formatJson`\n * returns `\"null\"` instead of the `undefined` returned by `JSON.stringify`.\n * Nested values retain standard `JSON.stringify` behavior.\n *\n * **Example** (Formatting compact JSON)\n *\n * ```ts import.meta.vitest\n * import { Formatter } from \"effect\"\n *\n * Formatter.formatJson({ name: \"Alice\", age: 30 }) // => \"{\\\"name\\\":\\\"Alice\\\",\\\"age\\\":30}\"\n * ```\n *\n * **Example** (Handling circular references)\n *\n * ```ts import.meta.vitest\n * import { Formatter } from \"effect\"\n *\n * const obj: any = { name: \"test\" }\n * obj.self = obj\n * Formatter.formatJson(obj) // => \"{\\\"name\\\":\\\"test\\\"}\"\n * ```\n *\n * **Example** (Pretty-printed JSON)\n *\n * ```ts import.meta.vitest\n * import { Formatter } from \"effect\"\n *\n * const output = Formatter.formatJson({ name: \"Alice\", age: 30 }, { space: 2 })\n * output // => \"{\\n \\\"name\\\": \\\"Alice\\\",\\n \\\"age\\\": 30\\n}\"\n * ```\n *\n * @see {@link format}\n * @see {@link Formatter}\n * @category serialization\n * @since 4.0.0\n */\nexport function formatJson(input, options) {\n const ancestors = [];\n return JSON.stringify(input, function (key, value) {\n const original = Object.getOwnPropertyDescriptor(this, key)?.value;\n const redacted = Predicate.hasProperty(original, symbolRedactable) ? redact(original) : redact(value);\n if (typeof redacted === \"bigint\") {\n return format(redacted);\n }\n if (typeof redacted !== \"object\" || redacted === null) {\n return redacted;\n }\n while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this) {\n ancestors.pop();\n }\n if (ancestors.includes(redacted)) {\n return undefined; // circular reference\n }\n ancestors.push(redacted);\n return redacted;\n }, options?.space) ?? \"null\";\n}\n//# sourceMappingURL=Formatter.js.map","/**\n * Controls how values appear in logs and debugging output.\n *\n * Effect data types use `Inspectable` to provide stable string, JSON, and\n * Node.js inspection output. This keeps custom values readable in logs, REPLs,\n * test failures, and diagnostics. This module defines the Node inspect symbol,\n * the `Inspectable` interface, safe conversion helpers, and shared prototype or\n * class implementations for custom values.\n *\n * @since 2.0.0\n */\nimport { format, formatJson } from \"./Formatter.js\";\nimport * as Predicate from \"./Predicate.js\";\nimport { redact } from \"./Redactable.js\";\n/**\n * Defines the symbol used by Node.js for custom object inspection.\n *\n * **When to use**\n *\n * Use to implement Node.js custom inspection for a value.\n *\n * **Details**\n *\n * This symbol is recognized by Node.js's `util.inspect()` function and the REPL\n * for custom object representation. When an object has a method with this symbol,\n * it will be called to determine how the object should be displayed.\n *\n * **Example** (Defining custom Node inspection)\n *\n * ```ts import.meta.vitest\n * import { Inspectable } from \"effect\"\n *\n * class CustomObject {\n * constructor(private value: string) {}\n *\n * [Inspectable.NodeInspectSymbol]() {\n * return `CustomObject(${this.value})`\n * }\n * }\n *\n * const obj = new CustomObject(\"hello\")\n * obj[Inspectable.NodeInspectSymbol]() // => \"CustomObject(hello)\"\n * ```\n *\n * @category symbols\n * @since 2.0.0\n */\nexport const NodeInspectSymbol = /*#__PURE__*/Symbol.for(\"nodejs.util.inspect.custom\");\n/**\n * Converts a value to its structured inspection representation.\n *\n * **When to use**\n *\n * Use when you need the structured representation of an inspectable value\n * without risking unhandled errors.\n *\n * **Details**\n *\n * This function applies redaction before extracting data from objects that\n * implement `toJSON`, recursively processes arrays, and handles errors\n * gracefully. Plain objects are returned unchanged, so the result is not\n * guaranteed to be accepted by `JSON.stringify`; it may still contain values\n * such as `BigInt`, functions, or circular references.\n *\n * @see {@link toStringUnknown} for converting unknown values to strings\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toJson = input => {\n try {\n input = redact(input);\n if (Predicate.hasProperty(input, \"toJSON\") && Predicate.isFunction(input[\"toJSON\"]) && input[\"toJSON\"].length === 0) {\n return input.toJSON();\n } else if (Array.isArray(input)) {\n return input.map(toJson);\n }\n return input;\n } catch {\n return \"[toJSON threw]\";\n }\n};\n/**\n * Converts an unknown value to a string for diagnostics.\n *\n * **When to use**\n *\n * Use to produce a diagnostic string from a value whose runtime type is unknown.\n *\n * **Details**\n *\n * Strings are returned unchanged. Objects are formatted as JSON using the\n * provided whitespace setting when possible, and values that cannot be\n * formatted are converted with `String`.\n *\n * @category converting\n * @since 2.0.0\n */\nexport const toStringUnknown = (u, whitespace = 2) => {\n if (typeof u === \"string\") {\n return u;\n }\n try {\n return typeof u === \"object\" ? formatJson(u, {\n space: whitespace\n }) : format(u, {\n space: whitespace\n });\n } catch {\n return String(u);\n }\n};\n/**\n * A base prototype object that implements the {@link Inspectable} interface.\n *\n * **When to use**\n *\n * Use as a prototype for plain objects that should share standard inspectable behavior.\n *\n * **Details**\n *\n * This object provides default implementations for the {@link Inspectable} methods.\n * It can be used as a prototype for objects that want to be inspectable,\n * or as a mixin to add inspection capabilities to existing objects.\n *\n * **Example** (Using the base inspectable prototype)\n *\n * ```ts import.meta.vitest\n * import { Inspectable } from \"effect\"\n *\n * // Use as prototype\n * const myObject = Object.create(Inspectable.BaseProto)\n * myObject.name = \"example\"\n * myObject.value = 42\n *\n * myObject.toString() // => \"\\\"[toJSON threw]\\\"\"\n *\n * // Or extend in a constructor\n * function MyClass(this: any, name: string) {\n * this.name = name\n * }\n * MyClass.prototype = Object.create(Inspectable.BaseProto)\n * MyClass.prototype.constructor = MyClass\n * ```\n *\n * @category prototypes\n * @since 2.0.0\n */\nexport const BaseProto = {\n toJSON() {\n return toJson(this);\n },\n [NodeInspectSymbol]() {\n return this.toJSON();\n },\n toString() {\n return format(this.toJSON());\n }\n};\n/**\n * Provides an abstract base class that implements the Inspectable interface.\n *\n * **When to use**\n *\n * Use as a base class for inspectable objects that define their own JSON representation.\n *\n * **Details**\n *\n * This class provides a convenient way to create inspectable objects by extending it.\n * Subclasses only need to implement the `toJSON()` method, and they automatically\n * get proper `toString()` and Node.js inspection support.\n *\n * **Example** (Extending the inspectable base class)\n *\n * ```ts import.meta.vitest\n * import { Inspectable } from \"effect\"\n *\n * class User extends Inspectable.Class {\n * constructor(\n * public readonly id: number,\n * public readonly name: string,\n * public readonly email: string\n * ) {\n * super()\n * }\n *\n * toJSON() {\n * return {\n * _tag: \"User\",\n * id: this.id,\n * name: this.name,\n * email: this.email\n * }\n * }\n * }\n *\n * const user = new User(1, \"Alice\", \"alice@example.com\")\n * user.toString() // => \"{\\\"_tag\\\":\\\"User\\\",\\\"id\\\":1,\\\"name\\\":\\\"Alice\\\",\\\"email\\\":\\\"alice@example.com\\\"}\"\n * user[Inspectable.NodeInspectSymbol]() // => { _tag: \"User\", id: 1, name: \"Alice\", email: \"alice@example.com\" }\n * ```\n *\n * @category models\n * @since 2.0.0\n */\nexport class Class {\n /**\n * Node.js custom inspection method.\n *\n * **When to use**\n *\n * Use to expose the class JSON representation to Node.js inspection.\n *\n * @since 2.0.0\n */\n [NodeInspectSymbol]() {\n return this.toJSON();\n }\n /**\n * Returns a formatted string representation of this object.\n *\n * **When to use**\n *\n * Use to format the class JSON representation as a string.\n *\n * @since 2.0.0\n */\n toString() {\n return format(this.toJSON());\n }\n}\n//# sourceMappingURL=Inspectable.js.map","/**\n * Check if `Error.stackTraceLimit` is writable.\n * Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible.\n *\n * @internal\n */\nexport const isStackTraceLimitWritable = () => {\n const desc = Object.getOwnPropertyDescriptor(Error, \"stackTraceLimit\");\n if (desc === undefined) {\n return Object.isExtensible(Error);\n }\n return Object.hasOwn(desc, \"writable\") ? desc.writable === true : desc.set !== undefined;\n};\n// Cache the check result since it won't change during runtime\nconst canWriteStackTraceLimit = /*#__PURE__*/isStackTraceLimitWritable();\n/**\n * Get the current `Error.stackTraceLimit` value.\n * Returns `undefined` if the property doesn't exist.\n *\n * @internal\n */\nexport const getStackTraceLimit = () => Error.stackTraceLimit;\n/**\n * Safely set `Error.stackTraceLimit` if possible, otherwise no-op.\n *\n * Accepts `undefined` so a value read via {@link getStackTraceLimit} can be\n * restored faithfully.\n *\n * @internal\n */\nexport const setStackTraceLimit = value => {\n if (canWriteStackTraceLimit) {\n ;\n Error.stackTraceLimit = value;\n }\n};\n//# sourceMappingURL=stackTraceLimit.js.map","import { getStackTraceLimit } from \"./internal/stackTraceLimit.js\";\n/**\n * Yields its wrapped value exactly once through an `IterableIterator`.\n *\n * **When to use**\n *\n * Use to implement `[Symbol.iterator]()` on Effect-like types so they can be\n * `yield*`-ed inside generator functions, such as `Effect.gen` and\n * `Option.gen`.\n *\n * **Details**\n *\n * The first call to `next()` returns `{ value: self, done: false }`. Every\n * subsequent call returns `{ value: a, done: true }` where `a` is the argument\n * passed to `next()`. `[Symbol.iterator]()` returns a **new** `SingleShotGen`\n * wrapping the same value, so the outer type can be iterated multiple times.\n *\n * **Example** (Yielding a wrapped value in a generator)\n *\n * ```ts import.meta.vitest\n * import { Utils } from \"effect\"\n *\n * const gen = new Utils.SingleShotGen<string, number>(\"hello\")\n *\n * gen.next(0) // => { value: \"hello\", done: false }\n *\n * gen.next(42) // => { value: 42, done: true }\n * ```\n *\n * @see {@link Gen} for the type-level signature that relies on `SingleShotGen`\n * @category constructors\n * @since 2.0.0\n */\nexport class SingleShotGen {\n called = false;\n self;\n constructor(self) {\n this.self = self;\n }\n /**\n * Yields the stored value once, then completes with the value sent back in.\n *\n * **When to use**\n *\n * Use to advance a `SingleShotGen` through its single yield and completion\n * step.\n *\n * @since 2.0.0\n */\n next(a) {\n return this.called ? {\n value: a,\n done: true\n } : (this.called = true, {\n value: this.self,\n done: false\n });\n }\n /**\n * Creates a fresh single-shot iterator over the stored value.\n *\n * **When to use**\n *\n * Use to iterate the wrapped value again without reusing the consumed\n * iterator state.\n *\n * @since 2.0.0\n */\n [Symbol.iterator]() {\n return new SingleShotGen(this.self);\n }\n}\n// the probe is wrapped in a single function call (rather than module-level\n// statements) so the whole selection is pure-annotated by the build and\n// tree-shakable when `internalCall` is unused.\nconst pickInternalCall = () => {\n const InternalTypeId = \"~effect/Utils/internal\";\n const standard = {\n [InternalTypeId]: body => {\n return body();\n }\n };\n const forced = {\n [InternalTypeId]: body => {\n try {\n return body();\n } finally {\n //\n }\n }\n };\n const isNotOptimizedAway = getStackTraceLimit() !== 0 && standard[InternalTypeId](() => new Error().stack)?.includes(InternalTypeId) === true;\n return isNotOptimizedAway ? standard[InternalTypeId] : forced[InternalTypeId];\n};\n/** @internal */\nexport const internalCall = /*#__PURE__*/pickInternalCall();\n//# sourceMappingURL=Utils.js.map","/** @internal */\nexport function assignProperty(self, key, value) {\n if (key === \"__proto__\") {\n Object.defineProperty(self, key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true\n });\n } else {\n ;\n self[key] = value;\n }\n}\n/** @internal */\nexport function assignProperties(self, source) {\n for (const key of Reflect.ownKeys(source)) {\n if (Object.prototype.propertyIsEnumerable.call(source, key)) {\n assignProperty(self, key, source[key]);\n }\n }\n}\n//# sourceMappingURL=record.js.map","import * as Equal from \"../Equal.js\";\nimport { format } from \"../Formatter.js\";\nimport { dual, identity } from \"../Function.js\";\nimport * as Hash from \"../Hash.js\";\nimport { NodeInspectSymbol } from \"../Inspectable.js\";\nimport { pipeArguments } from \"../Pipeable.js\";\nimport { hasProperty } from \"../Predicate.js\";\nimport { SingleShotGen } from \"../Utils.js\";\nimport * as InternalRecord from \"./record.js\";\n/** @internal */\nexport const EffectTypeId = `~effect/Effect`;\n/** @internal */\nexport const ExitTypeId = `~effect/Exit`;\nconst effectVariance = {\n _A: identity,\n _E: identity,\n _R: identity\n};\n/** @internal */\nexport const identifier = `${EffectTypeId}/identifier`;\n/** @internal */\nexport const args = `${EffectTypeId}/args`;\n/** @internal */\nexport const evaluate = `${EffectTypeId}/evaluate`;\n/** @internal */\nexport const contA = `${EffectTypeId}/successCont`;\n/** @internal */\nexport const contE = `${EffectTypeId}/failureCont`;\n/** @internal */\nexport const contAll = `${EffectTypeId}/ensureCont`;\n/** @internal */\nexport const Yield = /*#__PURE__*/Symbol.for(\"effect/Effect/Yield\");\n/** @internal */\nexport const PipeInspectableProto = {\n pipe() {\n return pipeArguments(this, arguments);\n },\n toJSON() {\n return {\n ...this\n };\n },\n toString() {\n return format(this.toJSON(), {\n ignoreToString: true,\n space: 2\n });\n },\n [NodeInspectSymbol]() {\n return this.toJSON();\n }\n};\n/** @internal */\nexport const StructuralProto = {\n [Hash.symbol]() {\n return Hash.structureKeys(this, Object.keys(this));\n },\n [Equal.symbol](that) {\n const selfKeys = Object.keys(this);\n const thatKeys = Object.keys(that);\n if (selfKeys.length !== thatKeys.length) return false;\n for (let i = 0; i < selfKeys.length; i++) {\n if (selfKeys[i] !== thatKeys[i] || !Equal.equals(this[selfKeys[i]], that[selfKeys[i]])) {\n return false;\n }\n }\n return true;\n }\n};\n/** @internal */\nexport const EffectProto = {\n [EffectTypeId]: effectVariance,\n ...PipeInspectableProto,\n [Symbol.iterator]() {\n return new SingleShotGen(this);\n },\n toJSON() {\n return {\n _id: \"Effect\",\n op: this[identifier],\n ...(args in this ? {\n args: this[args]\n } : undefined)\n };\n }\n};\n/** @internal */\nexport const isEffect = u => hasProperty(u, EffectTypeId);\n/** @internal */\nexport const isExit = u => hasProperty(u, ExitTypeId);\n// ----------------------------------------------------------------------------\n// Cause\n// ----------------------------------------------------------------------------\n/** @internal */\nexport const CauseTypeId = \"~effect/Cause\";\n/** @internal */\nexport const CauseReasonTypeId = \"~effect/Cause/Reason\";\n/** @internal */\nexport const isCause = self => hasProperty(self, CauseTypeId);\n/** @internal */\nexport const isCauseReason = self => hasProperty(self, CauseReasonTypeId);\n/** @internal */\nexport class CauseImpl {\n constructor(failures) {\n this[CauseTypeId] = CauseTypeId;\n this.reasons = failures;\n }\n pipe() {\n return pipeArguments(this, arguments);\n }\n toJSON() {\n return {\n _id: \"Cause\",\n failures: this.reasons.map(f => f.toJSON())\n };\n }\n toString() {\n return `Cause(${format(this.reasons)})`;\n }\n [NodeInspectSymbol]() {\n return this.toJSON();\n }\n [Equal.symbol](that) {\n return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => Equal.equals(e, that.reasons[i]));\n }\n [Hash.symbol]() {\n return Hash.array(this.reasons);\n }\n}\nconst annotationsMap = /*#__PURE__*/new WeakMap();\n/** @internal */\nexport class ReasonBase {\n [CauseReasonTypeId];\n annotations;\n _tag;\n constructor(_tag, annotations, originalError) {\n this[CauseReasonTypeId] = CauseReasonTypeId;\n this._tag = _tag;\n if (annotations !== constEmptyAnnotations && typeof originalError === \"object\" && originalError !== null && annotations.size > 0) {\n const prevAnnotations = annotationsMap.get(originalError);\n if (prevAnnotations) {\n annotations = new Map([...prevAnnotations, ...annotations]);\n }\n annotationsMap.set(originalError, annotations);\n }\n this.annotations = annotations;\n }\n annotate(annotations, options) {\n if (annotations.mapUnsafe.size === 0) return this;\n const newAnnotations = new Map(this.annotations);\n annotations.mapUnsafe.forEach((value, key) => {\n if (options?.overwrite !== true && newAnnotations.has(key)) return;\n newAnnotations.set(key, value);\n });\n const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this);\n self.annotations = newAnnotations;\n return self;\n }\n pipe() {\n return pipeArguments(this, arguments);\n }\n toString() {\n return format(this);\n }\n [NodeInspectSymbol]() {\n return this.toString();\n }\n}\n/** @internal */\nexport const constEmptyAnnotations = /*#__PURE__*/new Map();\n/** @internal */\nexport class Fail extends ReasonBase {\n constructor(error, annotations = constEmptyAnnotations) {\n super(\"Fail\", annotations, error);\n this.error = error;\n }\n toString() {\n return `Fail(${format(this.error)})`;\n }\n toJSON() {\n return {\n _tag: \"Fail\",\n error: this.error\n };\n }\n [Equal.symbol](that) {\n return isFailReason(that) && Equal.equals(this.error, that.error) && Equal.equals(this.annotations, that.annotations);\n }\n [Hash.symbol]() {\n return Hash.combine(Hash.string(this._tag))(Hash.combine(Hash.hash(this.error))(Hash.hash(this.annotations)));\n }\n}\n/** @internal */\nexport const causeFromReasons = reasons => new CauseImpl(reasons);\n/** @internal */\nexport const causeEmpty = /*#__PURE__*/new CauseImpl([]);\n/** @internal */\nexport const causeFail = error => new CauseImpl([new Fail(error)]);\n/** @internal */\nexport class Die extends ReasonBase {\n constructor(defect, annotations = constEmptyAnnotations) {\n super(\"Die\", annotations, defect);\n this.defect = defect;\n }\n toString() {\n return `Die(${format(this.defect)})`;\n }\n toJSON() {\n return {\n _tag: \"Die\",\n defect: this.defect\n };\n }\n [Equal.symbol](that) {\n return isDieReason(that) && Equal.equals(this.defect, that.defect) && Equal.equals(this.annotations, that.annotations);\n }\n [Hash.symbol]() {\n return Hash.combine(Hash.string(this._tag))(Hash.combine(Hash.hash(this.defect))(Hash.hash(this.annotations)));\n }\n}\n/** @internal */\nexport const causeDie = defect => new CauseImpl([new Die(defect)]);\n/** @internal */\nexport const causeAnnotate = /*#__PURE__*/dual(args => isCause(args[0]), (self, annotations, options) => {\n if (annotations.mapUnsafe.size === 0) return self;\n return new CauseImpl(self.reasons.map(f => f.annotate(annotations, options)));\n});\n/** @internal */\nexport const isFailReason = self => self._tag === \"Fail\";\n/** @internal */\nexport const isDieReason = self => self._tag === \"Die\";\n/** @internal */\nexport const isInterruptReason = self => self._tag === \"Interrupt\";\nfunction defaultEvaluate(_fiber) {\n return exitDie(`Effect.evaluate: Not implemented`);\n}\n/** @internal */\nexport const makePrimitiveProto = options => ({\n ...EffectProto,\n [identifier]: options.op,\n [evaluate]: options[evaluate] ?? defaultEvaluate,\n [contA]: options[contA],\n [contE]: options[contE],\n [contAll]: options[contAll]\n});\n/** @internal */\nexport const makePrimitive = options => {\n const Proto = makePrimitiveProto(options);\n const PrimitiveImpl = function (value) {\n this[args] = value;\n };\n PrimitiveImpl.prototype = Proto;\n return function (value) {\n return new PrimitiveImpl(value);\n };\n};\n/** @internal */\nexport const makeExit = options => {\n const Proto = {\n [ExitTypeId]: ExitTypeId,\n _tag: options.op,\n get [options.prop]() {\n return this[args];\n },\n ...makePrimitiveProto(options),\n toString() {\n return `${options.op}(${format(this[args])})`;\n },\n toJSON() {\n return {\n _id: \"Exit\",\n _tag: options.op,\n [options.prop]: this[args]\n };\n },\n [Equal.symbol](that) {\n return isExit(that) && that._tag === this._tag && Equal.equals(this[args], that[args]);\n },\n [Hash.symbol]() {\n return Hash.combine(Hash.string(options.op), Hash.hash(this[args]));\n }\n };\n const ExitPrimitive = function (value) {\n this[args] = value;\n };\n ExitPrimitive.prototype = Proto;\n return function (value) {\n return new ExitPrimitive(value);\n };\n};\n/** @internal */\nexport const exitSucceed = /*#__PURE__*/makeExit({\n op: \"Success\",\n prop: \"value\",\n [evaluate](fiber) {\n const cont = fiber.getCont(contA);\n return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this);\n }\n});\n/** @internal */\nexport const StackTraceKey = {\n key: \"effect/Cause/StackTrace\"\n};\n/** @internal */\nexport const InterruptorStackTrace = {\n key: \"effect/Cause/InterruptorStackTrace\"\n};\n/** @internal */\nexport const exitFailCause = /*#__PURE__*/makeExit({\n op: \"Failure\",\n prop: \"cause\",\n [evaluate](fiber) {\n let cause = this[args];\n let annotated = false;\n if (fiber.cache.stackFrame) {\n cause = causeAnnotate(cause, {\n mapUnsafe: new Map([[StackTraceKey.key, fiber.cache.stackFrame]])\n });\n annotated = true;\n }\n let cont = fiber.getCont(contE);\n while (fiber.interruptible && fiber._interruptedCause && cont) {\n cont = fiber.getCont(contE);\n }\n return cont ? cont[contE](cause, fiber, annotated ? undefined : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this);\n }\n});\n/** @internal */\nexport const exitFail = e => exitFailCause(causeFail(e));\n/** @internal */\nexport const exitDie = defect => exitFailCause(causeDie(defect));\n/** @internal */\nexport const withFiber = /*#__PURE__*/makePrimitive({\n op: \"WithFiber\",\n [evaluate](fiber) {\n return this[args](fiber);\n }\n});\n/**\n * Accesses the current fiber to compute a value without a separate `succeed`\n * operation.\n *\n * @internal\n */\nexport const withFiberSucceed = /*#__PURE__*/makePrimitive({\n op: \"WithFiberSucceed\",\n [evaluate](fiber) {\n const value = this[args](fiber);\n const cont = fiber.getCont(contA);\n return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value));\n }\n});\n/** @internal */\nexport const YieldableError = /*#__PURE__*/function () {\n class YieldableError extends globalThis.Error {}\n const proto = /*#__PURE__*/makePrimitiveProto({\n op: \"YieldableError\",\n [evaluate]() {\n return exitFail(this);\n }\n });\n delete proto.toString;\n Object.assign(YieldableError.prototype, proto);\n return YieldableError;\n}();\n/** @internal */\nexport const Error = /*#__PURE__*/function () {\n const plainArgsSymbol = /*#__PURE__*/Symbol.for(\"effect/Data/Error/plainArgs\");\n return class Base extends YieldableError {\n constructor(args) {\n super(args?.message, args?.cause ? {\n cause: args.cause\n } : undefined);\n if (args) {\n InternalRecord.assignProperties(this, args);\n // @effect-diagnostics-next-line floatingEffect:off\n Object.defineProperty(this, plainArgsSymbol, {\n value: args,\n enumerable: false\n });\n }\n }\n toJSON() {\n return {\n ...this[plainArgsSymbol],\n ...this\n };\n }\n };\n}();\n/** @internal */\nexport const TaggedError = tag => {\n class Base extends Error {\n _tag = tag;\n }\n ;\n Base.prototype.name = tag;\n return Base;\n};\n/** @internal */\nexport const NoSuchElementErrorTypeId = \"~effect/Cause/NoSuchElementError\";\n/** @internal */\nexport const isNoSuchElementError = u => hasProperty(u, NoSuchElementErrorTypeId);\n/** @internal */\nexport class NoSuchElementError extends /*#__PURE__*/TaggedError(\"NoSuchElementError\") {\n [NoSuchElementErrorTypeId] = NoSuchElementErrorTypeId;\n constructor(message) {\n super({\n message\n });\n }\n}\n/** @internal */\nexport const DoneTypeId = \"~effect/Cause/Done\";\n/** @internal */\nexport const isDone = u => hasProperty(u, DoneTypeId);\nconst DoneVoid = {\n [DoneTypeId]: DoneTypeId,\n _tag: \"Done\",\n value: undefined\n};\n/** @internal */\nexport const Done = value => {\n if (value === undefined) return DoneVoid;\n return {\n [DoneTypeId]: DoneTypeId,\n _tag: \"Done\",\n value\n };\n};\nconst doneVoid = /*#__PURE__*/exitFail(DoneVoid);\n/** @internal */\nexport const done = value => {\n if (value === undefined) return doneVoid;\n return exitFail(Done(value));\n};\n//# sourceMappingURL=core.js.map","import { evaluate, makePrimitiveProto } from \"./internal/core.js\";\n/**\n * Create a low-level `Effect` prototype.\n *\n * **When to use**\n *\n * Use when you need to create a custom Effect-like value without extending a\n * class, by providing a label and an evaluate function that receives the\n * current fiber.\n *\n * **Details**\n *\n * When the effect is evaluated, it calls `evaluate` with the current fiber.\n *\n * @see {@link Class} for a class-based approach to defining custom Effect values\n * @see {@link Mixin} for wrapping an existing class constructor\n *\n * @category prototypes\n * @since 4.0.0\n */\nexport const Prototype = options => makePrimitiveProto({\n op: options.label,\n [evaluate]: options.evaluate\n});\nconst proto = /*#__PURE__*/Prototype({\n label: \"Effectable\",\n evaluate(_) {\n return this.asEffect();\n }\n});\nconst Base = /*#__PURE__*/(() => {\n const Base = function () {};\n Base.prototype = proto;\n return Base;\n})();\n/**\n * Provides an abstract class that can be extended to create an `Effect`.\n *\n * **When to use**\n *\n * Use as an abstract base class to define custom classes whose instances behave\n * as `Effect` values.\n *\n * @see {@link Prototype} for a lower-level primitive approach to creating custom Effect-like values without a class\n * @see {@link Mixin} for wrapping an existing class constructor\n * @category constructors\n * @since 2.0.0\n */\nexport class Class extends Base {}\n/**\n * Returns a subclass of the provided class that inserts the Effect prototype\n * into the inheritance chain.\n *\n * **When to use**\n *\n * Use to make instances of an existing class behave as `Effect` values without\n * extending {@link Class} or modifying the original prototype.\n *\n * **Details**\n *\n * Pass the class to wrap, then implement `asEffect` on the final class. The\n * returned class is abstract, and the success, error, and service types are\n * inferred from the concrete `asEffect` return type. Concrete and abstract base\n * classes are supported. Constructor parameters and instance members are\n * preserved, except that Effect's prototype members shadow base prototype\n * members with the same name: `pipe`, `toString`, `toJSON`, `[Symbol.iterator]`,\n * and `[Symbol.for(\"nodejs.util.inspect.custom\")]`.\n *\n * **Example** (Evaluating a mixed-in class)\n *\n * ```ts import.meta.vitest\n * import { Effect, Effectable } from \"effect\"\n *\n * class Box {\n * constructor(readonly value: number) {}\n * }\n *\n * class EffectBox extends Effectable.Mixin(Box) {\n * asEffect() {\n * return Effect.succeed(this.value)\n * }\n * }\n *\n * const box = new EffectBox(2)\n * Effect.isEffect(box) // => true\n * await Effect.runPromise(box) // => 2\n * ```\n *\n * @see {@link Prototype} for a lower-level primitive approach to creating custom Effect-like values without a class\n * @see {@link Class} for a base constructor to extend\n * @category constructors\n * @since 4.0.0\n */\nexport const Mixin = klass => {\n class Mixed extends klass {}\n Object.defineProperties(Mixed.prototype, Object.getOwnPropertyDescriptors(proto));\n return Mixed;\n};\n//# sourceMappingURL=Effectable.js.map","/**\n * Defines reusable equality functions for values of the same type.\n *\n * An `Equivalence<A>` returns `true` when two `A` values should be treated as\n * the same for a particular purpose. This module includes strict equality\n * instances for primitive types, constructors for custom comparisons, and\n * helpers for tuples, arrays, structs, records, dates, and values compared\n * through a derived field.\n *\n * @since 2.0.0\n */\nimport { dual } from \"./Function.js\";\nimport * as Reducer from \"./Reducer.js\";\n/**\n * Creates a custom equivalence relation with an optimized reference equality check.\n *\n * **When to use**\n *\n * Use when you need an equality rule that the built-in instances and input\n * mapping helpers cannot express, and you can provide a law-abiding comparison.\n *\n * **Details**\n *\n * The returned equivalence first checks reference equality (`===`) for\n * performance. If the values are not the same reference, it falls back to the\n * provided equivalence function, which must satisfy reflexive, symmetric, and\n * transitive properties.\n *\n * **Example** (Case-insensitive string equivalence)\n *\n * ```ts import.meta.vitest\n * import { Equivalence } from \"effect\"\n *\n * const caseInsensitive = Equivalence.make<string>((a, b) =>\n * a.toLowerCase() === b.toLowerCase()\n * )\n *\n * caseInsensitive(\"Hello\", \"HELLO\") // => true\n * caseInsensitive(\"foo\", \"bar\") // => false\n *\n * // Same reference optimization\n * const str = \"test\"\n * caseInsensitive(str, str) // => true\n * ```\n *\n * **Example** (Comparing numbers with tolerance)\n *\n * ```ts import.meta.vitest\n * import { Equivalence } from \"effect\"\n *\n * const tolerance = Equivalence.make<number>((a, b) => Math.abs(a - b) < 0.0001)\n *\n * tolerance(1.0, 1.001) // => false\n * tolerance(1.0, 1.00001) // => true\n * ```\n *\n * @see {@link strictEqual}\n * @see {@link mapInput}\n * @category constructors\n * @since 2.0.0\n */\nexport const make = isEquivalent => (self, that) => self === that || isEquivalent(self, that);\nconst isStrictEquivalent = (x, y) => x === y;\n/**\n * Creates an equivalence relation that uses strict equality (`===`) to compare values.\n *\n * **When to use**\n *\n * Use when you need strict equality (`===`) as the comparison.\n *\n * **Details**\n *\n * Uses JavaScript's strict equality operator (`===`). Primitives compare by\n * value. Objects compare by reference, so only the same object instance is\n * equivalent. Use this as a building block for more complex equivalences via\n * `mapInput` or `combine`.\n *\n * **Gotchas**\n *\n * `NaN !== NaN`, so `NaN` values are never considered equivalent.\n *\n * **Example** (Comparing primitive types)\n *\n * ```ts import.meta.vitest\n * import { Equivalence } from \"effect\"\n *\n * const strictEq = Equivalence.strictEqual<number>()\n *\n * strictEq(1, 1) // => true\n * strictEq(1, 2) // => false\n * strictEq(NaN, NaN) // => false\n * ```\n *\n * **Example** (Comparing objects by reference)\n *\n * ```ts import.meta.vitest\n * import { Equivalence } from \"effect\"\n *\n * const obj = { value: 42 }\n * const strictObjEq = Equivalence.strictEqual<typeof obj>()\n *\n * strictObjEq(obj, obj) // => true\n * strictObjEq(obj, { value: 42 }) // => false\n * ```\n *\n * @see {@link make}\n * @see `Equal` for structural equality\n * @category constructors\n * @since 4.0.0\n */\nexport const strictEqual = () => isStrictEquivalent;\n/**\n * Equivalence instance for strings using strict equality (`===`).\n *\n * **When to use**\n *\n * Use when you need to supply case-sensitive string equality.\n *\n * **Example** (Comparing strings)\n *\n * ```ts import.meta.vitest\n * import { Equivalence } from \"effect\"\n *\n * Equivalence.String(\"hello\", \"hello\") // => true\n * Equivalence.String(\"hello\", \"world\") // => false\n * ```\n *\n * @category instances\n * @since 4.0.0\n */\nexport const String = isStrictEquivalent;\n/**\n * Equivalence instance for numbers.\n *\n * **When to use**\n *\n * Use when you need numeric equality that treats NaN as equal to itself.\n *\n * **Example** (Comparing numbers)\n *\n * ```ts import.meta.vitest\n * import { Equivalence } from \"effect\"\n *\n * Equivalence.Number(1, 1) // => true\n * Equivalence.Number(1, 2) // => false\n * Equivalence.Number(NaN, NaN) // => true\n * ```\n *\n * @category instances\n * @since 4.0.0\n */\nexport const Number = /*#__PURE__*/make((self, that) => globalThis.Number.isNaN(self) && globalThis.Number.isNaN(that));\n/**\n * Equivalence instance for booleans using strict equality (`===`).\n *\n * **When to use**\n *\n * Use when you need to supply boolean equality.\n *\n * **Example** (Comparing booleans)\n *\n * ```ts import.meta.vitest\n * import { Equivalence } from \"effect\"\n *\n * Equivalence.Boolean(true, true) // => true\n * Equivalence.Boolean(true, false) // => false\n * ```\n *\n * @category instances\n * @since 4.0.0\n */\nexport const Boolean = isStrictEquivalent;\n/**\n * Equivalence instance for bigints using strict equality (`===`).\n *\n * **When to use**\n *\n * Use when you need to supply bigint equality.\n *\n * **Example** (Comparing bigints)\n *\n * ```ts import.meta.vitest\n * import { Equivalence } from \"effect\"\n *\n * Equivalence.BigInt(1n, 1n) // => true\n * Equivalence.BigInt(1n, 2n) // => false\n * ```\n *\n * @category instances\n * @since 4.0.0\n */\nexport const BigInt = isStrictEquivalent;\n/**\n * Combines two equivalence relations using logical AND.\n *\n * **When to use**\n *\n * Use when you need to combine exactly two equivalences with AND semantics.\n *\n * **Details**\n *\n * Returns `true` only if both equivalences return `true`. The comparison\n * short-circuits when the first equivalence returns `false`. The result is also\n * an equivalence that satisfies reflexive, symmetric, and transitive\n * properties.\n *\n * **Example** (Combining name and age equivalences)\n *\n * ```ts import.meta.vitest\n * import { Equivalence } from \"effect\"\n *\n * interface Person {\n * name: string\n * age: number\n * }\n *\n * const nameEquivalence = Equivalence.mapInput(\n * Equivalence.strictEqual<string>(),\n * (p: Person) => p.name\n * )\n *\n * const ageEquivalence = Equivalence.mapInput(\n * Equivalence.strictEqual<number>(),\n * (p: Person) => p.age\n * )\n *\n * const personEquivalence = Equivalence.combine(nameEquivalence, ageEquivalence)\n *\n * const person1 = { name: \"Alice\", age: 30 }\n * const person2 = { name: \"Alice\", age: 30 }\n * const person3 = { name: \"Alice\", age: 31 }\n *\n * personEquivalence(person1, person2) // => true\n * personEquivalence(person1, person3) // => false\n * ```\n *\n * @see {@link combineAll}\n * @see {@link mapInput}\n * @category combining\n * @since 2.0.0\n */\nexport const combine = /*#__PURE__*/dual(2, (self, that) => make((x, y) => self(x, y) && that(x, y)));\n/**\n * Combines multiple equivalence relations into a single equivalence using logical AND.\n *\n * **When to use**\n *\n * Use when you need to combine many `Equivalence` instances from an iterable.\n *\n * **Details**\n *\n * Returns `true` only if all equivalences in the collection return `true`. The\n * comparison stops at the first equivalence that returns `false`. Empty\n * collections return an equivalence that always returns `true`. The result is\n * also an equivalence that satisfies reflexive, symmetric, and transitive\n * properties.\n *\n * **Example** (Combining multiple field equivalences)\n *\n * ```ts import.meta.vitest\n * import { Equivalence } from \"effect\"\n *\n * interface Point3D {\n * x: number\n * y: number\n * z: number\n * }\n *\n * const xEq = Equivalence.mapInput(\n * Equivalence.strictEqual<number>(),\n * (p: Point3D) => p.x\n * )\n * const yEq = Equivalence.mapInput(\n * Equivalence.strictEqual<number>(),\n * (p: Point3D) => p.y\n * )\n * const zEq = Equivalence.mapInput(\n * Equivalence.strictEqual<number>(),\n * (p: Point3D) => p.z\n * )\n *\n * const point3DEq = Equivalence.combineAll([xEq, yEq, zEq])\n *\n * const point1 = { x: 1, y: 2, z: 3 }\n * const point2 = { x: 1, y: 2, z: 3 }\n * const point3 = { x: 1, y: 2, z: 4 }\n *\n * point3DEq(point1, point2) // => true\n * point3DEq(point1, point3) // => false\n * ```\n *\n * **Example** (Handling empty collections)\n *\n * ```ts import.meta.vitest\n * import { Equivalence } from \"effect\"\n *\n * // Empty collection always returns true\n * const alwaysEq = Equivalence.combineAll([])\n * alwaysEq(\"anything\", \"else\") // => true\n * ```\n *\n * @see {@link combine}\n * @see {@link mapInput}\n * @category combining\n * @since 2.0.0\n */\nexport const combineAll = collection => make((x, y) => {\n for (const equivalence of collection) {\n if (!equivalence(x, y)) {\n return false;\n }\n }\n return true;\n});\n/**\n * Transforms an equivalence relation by mapping the input values before comparison.\n *\n * **When to use**\n *\n * Use when you need an equivalence for one type by comparing a derived value.\n *\n * **Details**\n *\n * - Applies the transformation function to both values before comparing\n * - The transformation function should be pure and have no side effects\n * - The resulting equivalence compares the transformed values using the provided equivalence\n * - The result is also an equivalence that satisfies reflexive, symmetric, and transitive properties\n * - Useful for comparing by one property or normalizing values before\n * comparison, such as case-insensitive strings\n *\n * **Example** (Deriving equivalence from an object property)\n *\n * ```ts import.meta.vitest\n * import { Equivalence } from \"effect\"\n *\n * interface User {\n * id: number\n * name: string\n * email: string\n * }\n *\n * // Create equivalence based on user ID only\n * const userByIdEq = Equivalence.mapInput(\n * Equivalence.strictEqual<number>(),\n * (user: User) => user.id\n * )\n *\n * const user1 = { id: 1, name: \"Alice\", email: \"alice@example.com\" }\n * const user2 = { id: 1, name: \"Alice Smith\", email: \"alice.smith@example.com\" }\n * const user3 = { id: 2, name: \"Bob\", email: \"bob@example.com\" }\n *\n * userByIdEq(user1, user2) // => true\n * userByIdEq(user1, user3) // => false\n * ```\n *\n * **Example** (Case-insensitive string equivalence)\n *\n * ```ts import.meta.vitest\n * import { Equivalence } from \"effect\"\n *\n * const caseInsensitiveEq = Equivalence.mapInput(\n * Equivalence.strictEqual<string>(),\n * (s: string) => s.toLowerCase()\n * )\n *\n * caseInsensitiveEq(\"Hello\", \"HELLO\") // => true\n * caseInsensitiveEq(\"Hello\", \"World\") // => false\n * ```\n *\n * @see {@link combine}\n * @see {@link Struct}\n * @category mapping\n * @since 2.0.0\n */\nexport const mapInput = /*#__PURE__*/dual(2, (self, f) => make((x, y) => self(f(x), f(y))));\n/**\n * Creates an equivalence for tuples with heterogeneous element types.\n *\n * **When to use**\n *\n * Use when you need an `Equivalence` for fixed-length tuples with per-position\n * equivalences.\n *\n * **Details**\n *\n * Tuples must have the same length; different lengths are never equivalent.\n * Each equivalence is applied to the corresponding element position. The result\n * returns `true` only if all elements are equivalent according to their\n * respective equivalences, and it also satisfies reflexive, symmetric, and\n * transitive properties.\n *\n * **Example** (Comparing homogeneous tuples)\n *\n * ```ts import.meta.vitest\n * import { Equivalence } from \"effect\"\n *\n * const stringTupleEq = Equivalence.Tuple([\n * Equivalence.strictEqual<string>(),\n * Equivalence.strictEqual<string>(),\n * Equivalence.strictEqual<string>()\n * ])\n *\n * const tuple1 = [\"hello\", \"world\", \"test\"] as const\n * const tuple2 = [\"hello\", \"world\", \"test\"] as const\n * const tuple3 = [\"hello\", \"world\", \"different\"] as const\n *\n * stringTupleEq(tuple1, tuple2) // => true\n * stringTupleEq(tuple1, tuple3) // => false\n * ```\n *\n * **Example** (Comparing tuples with custom equivalences)\n *\n * ```ts import.meta.vitest\n * import { Equivalence } from \"effect\"\n *\n * const caseInsensitive = Equivalence.mapInput(\n * Equivalence.strictEqual<string>(),\n * (s: string) => s.toLowerCase()\n * )\n *\n * const customTupleEq = Equivalence.Tuple([\n * caseInsensitive,\n * caseInsensitive,\n * caseInsensitive\n * ])\n *\n * customTupleEq([\"Hello\", \"World\", \"Test\"], [\"HELLO\", \"WORLD\", \"TEST\"]) // => true\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport function Tuple(elements) {\n return make((self, that) => {\n if (self.length !== that.length) {\n return false;\n }\n for (let i = 0; i < self.length; i++) {\n if (!elements[i](self[i], that[i])) {\n return false;\n }\n }\n return true;\n });\n}\n/**\n * @since 4.0.0\n */\nfunction Array_(item) {\n return make((self, that) => {\n if (self.length !== that.length) return false;\n for (let i = 0; i < self.length; i++) {\n if (!item(self[i], that[i])) return false;\n }\n return true;\n });\n}\nexport {\n/**\n * Creates an equivalence for arrays where all elements are compared using the same equivalence.\n *\n * **When to use**\n *\n * Use when you need to compare arrays with one equivalence for every element.\n *\n * **Details**\n *\n * - Requires arrays to have the same length; different lengths are never equivalent\n * - Compares elements positionally, such as index `0` with index `0`\n * - Returns `true` only if all corresponding elements are equivalent\n * - Empty arrays are considered equivalent\n * - The result is also an equivalence that satisfies reflexive, symmetric, and transitive properties\n *\n * **Example** (Comparing number arrays)\n *\n * ```ts import.meta.vitest\n * import { Equivalence } from \"effect\"\n *\n * const numberArrayEq = Equivalence.Array(Equivalence.strictEqual<number>())\n *\n * numberArrayEq([1, 2, 3], [1, 2, 3]) // => true\n * numberArrayEq([1, 2, 3], [1, 2, 4]) // => false\n * numberArrayEq([1, 2], [1, 2, 3]) // => false\n * ```\n *\n * **Example** (Case-insensitive string array)\n *\n * ```ts import.meta.vitest\n * import { Equivalence } from \"effect\"\n *\n * const caseInsensitive = Equivalence.mapInput(\n * Equivalence.strictEqual<string>(),\n * (s: string) => s.toLowerCase()\n * )\n * const stringArrayEq = Equivalence.Array(caseInsensitive)\n *\n * stringArrayEq([\"Hello\", \"World\"], [\"HELLO\", \"WORLD\"]) // => true\n * stringArrayEq([\"Hello\"], [\"Hi\"]) // => false\n * stringArrayEq([], []) // => true\n * ```\n *\n * @see {@link Tuple}\n * @see {@link Record}\n * @category combinators\n * @since 4.0.0\n */\nArray_ as Array };\n/**\n * Creates an equivalence for objects by comparing their properties using provided equivalences.\n *\n * **When to use**\n *\n * Use when you need an `Equivalence` for objects with known, fixed property\n * names.\n *\n * **Details**\n *\n * Compares only the properties specified in the struct definition; other\n * properties are ignored. String and symbol keys are supported via\n * `Reflect.ownKeys`. The result returns `true` only if all specified properties\n * are equivalent according to their equivalences, and it also satisfies\n * reflexive, symmetric, and transitive properties.\n *\n * **Example** (Comparing structs with different equivalences per field)\n *\n * ```ts import.meta.vitest\n * import { Equivalence } from \"effect\"\n *\n * interface Person {\n * name: string\n * age: number\n * email: string\n * }\n *\n * const caseInsensitive = Equivalence.mapInput(\n * Equivalence.strictEqual<string>(),\n * (s: string) => s.toLowerCase()\n * )\n *\n * const personEq = Equivalence.Struct({\n * name: caseInsensitive,\n * age: Equivalence.strictEqual<number>(),\n * email: caseInsensitive\n * })\n *\n * const person1 = { name: \"Alice\", age: 30, email: \"alice@example.com\" }\n * const person2 = { name: \"ALICE\", age: 30, email: \"ALICE@EXAMPLE.COM\" }\n * const person3 = { name: \"Alice\", age: 31, email: \"alice@example.com\" }\n *\n * personEq(person1, person2) // => true\n * personEq(person1, person3) // => false\n * ```\n *\n * **Example** (Comparing specific fields)\n *\n * ```ts import.meta.vitest\n * import { Equivalence } from \"effect\"\n *\n * const nameAgeEq = Equivalence.Struct({\n * name: Equivalence.strictEqual<string>(),\n * age: Equivalence.strictEqual<number>()\n * })\n *\n * // Only compares name and age, ignores other properties\n * const obj1 = { name: \"Alice\", age: 30, extra: \"ignored\" }\n * const obj2 = { name: \"Alice\", age: 30, extra: \"different\" }\n * nameAgeEq(obj1, obj2) // => true\n * ```\n *\n * @see {@link Record}\n * @see {@link mapInput}\n * @see {@link combine}\n * @category combinators\n * @since 4.0.0\n */\nexport function Struct(fields) {\n const keys = Reflect.ownKeys(fields);\n return make((self, that) => {\n for (const key of keys) {\n if (!fields[key](self[key], that[key])) return false;\n }\n return true;\n });\n}\n/**\n * Creates an equivalence for objects by comparing all properties using the same equivalence.\n *\n * **When to use**\n *\n * Use when you need to compare records with the same equivalence for every\n * property value.\n *\n * **Details**\n *\n * - Compares all properties present in both objects\n * - Requires both objects to have the same set of keys; different keys result in `false`\n * - All property values must be equivalent according to the provided equivalence\n * - Supports both string and symbol keys via `Reflect.ownKeys`\n * - Empty objects are considered equivalent\n * - The result is also an equivalence that satisfies reflexive, symmetric, and transitive properties\n *\n * **Example** (Defining records with string values)\n *\n * ```ts import.meta.vitest\n * import { Equivalence } from \"effect\"\n *\n * const stringRecordEq = Equivalence.Record(Equivalence.strictEqual<string>())\n *\n * const record1 = { a: \"hello\", b: \"world\" }\n * const record2 = { a: \"hello\", b: \"world\" }\n * const record3 = { a: \"hello\", b: \"different\" }\n * const record4 = { a: \"hello\" } // missing key 'b'\n *\n * stringRecordEq(record1, record2) // => true\n * stringRecordEq(record1, record3) // => false\n * stringRecordEq(record1, record4) // => false\n * ```\n *\n * **Example** (Defining records with number values)\n *\n * ```ts import.meta.vitest\n * import { Equivalence } from \"effect\"\n *\n * const numberRecordEq = Equivalence.Record(Equivalence.strictEqual<number>())\n *\n * const scores1 = { alice: 100, bob: 85 }\n * const scores2 = { alice: 100, bob: 85 }\n * const scores3 = { alice: 100, bob: 90 }\n *\n * numberRecordEq(scores1, scores2) // => true\n * numberRecordEq(scores1, scores3) // => false\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport function Record(value) {\n return make((self, that) => {\n const selfKeys = Reflect.ownKeys(self);\n const thatKeys = Reflect.ownKeys(that);\n if (selfKeys.length !== thatKeys.length) return false;\n for (const key of selfKeys) {\n if (!Object.hasOwn(that, key) || !value(self[key], that[key])) {\n return false;\n }\n }\n return true;\n });\n}\n/**\n * Creates a `Reducer` for combining `Equivalence` instances, useful for aggregating equivalences in collections.\n *\n * **When to use**\n *\n * Use when you need a reducer that combines equivalences.\n *\n * **Details**\n *\n * Returns a reducer that combines equivalences using `combine`. The identity\n * element for empty collections is an equivalence that always returns `true`.\n * The reducer uses `combineAll` for collections of equivalences and can be used\n * with fold operations.\n *\n * **Example** (Creating a Reducer)\n *\n * ```ts import.meta.vitest\n * import { Equivalence } from \"effect\"\n *\n * const reducer = Equivalence.makeReducer<number>()\n * const equivalences = [\n * Equivalence.strictEqual<number>(),\n * Equivalence.make<number>((a, b) => Math.abs(a - b) < 1)\n * ]\n *\n * const combined = reducer.combineAll(equivalences)\n * // Combined equivalence requires both conditions to be true\n * combined(1, 1) // => true\n * combined(1, 1.5) // => false\n * ```\n *\n * @see {@link combine} Combine two equivalences\n * @see {@link combineAll} Combine multiple equivalences\n * @see {@link Reducer} Reducer type for collection operations\n * @category constructors\n * @since 4.0.0\n */\nexport function makeReducer() {\n return Reducer.make(combine, () => true, combineAll);\n}\n/**\n * Equivalence instance for `Date` objects that compares their `getTime()` values using `Equivalence.Number`.\n *\n * **When to use**\n *\n * Use when you need an `Equivalence` for JavaScript date objects by their\n * millisecond timestamp.\n *\n * **Details**\n *\n * Different `Date` instances that represent the same millisecond timestamp are equivalent. Because `Equivalence.Number`\n * treats `NaN` as equal to `NaN`, two invalid `Date` values are also considered equivalent.\n *\n * **Example** (Comparing Date values)\n *\n * ```ts import.meta.vitest\n * import { Equivalence } from \"effect\"\n *\n * const d1 = new Date(\"2020-01-01T00:00:00.000Z\")\n * const d2 = new Date(\"2020-01-01T00:00:00.000Z\")\n * const d3 = new Date(\"2021-01-01T00:00:00.000Z\")\n * const invalidDate1 = new Date(\"foo\")\n * const invalidDate2 = new Date(\"bar\")\n *\n * Equivalence.Date(d1, d2) // => true\n * Equivalence.Date(d1, d3) // => false\n * Equivalence.Date(invalidDate1, invalidDate2) // => true\n * Equivalence.Date(invalidDate1, d1) // => false\n * ```\n *\n * **Example** (Comparing reference and value equality)\n *\n * ```ts import.meta.vitest\n * import { Equivalence } from \"effect\"\n *\n * const d1 = new Date(0)\n * const d2 = new Date(0)\n *\n * d1 === d2 // => false\n * Equivalence.Date(d1, d2) // => true\n * ```\n *\n * @see {@link Number} for the numeric equivalence applied to each `Date#getTime()` result\n * @see {@link mapInput} for deriving an equivalence by mapping inputs before comparison\n * @see {@link strictEqual} for reference equality when two values must be the same object\n * @category instances\n * @since 2.0.0\n */\nexport const Date = /*#__PURE__*/mapInput(Number, d => d.getTime());\n//# sourceMappingURL=Equivalence.js.map","/**\n * @since 2.0.0\n */\nimport * as Equal from \"../Equal.js\";\nimport { format } from \"../Formatter.js\";\nimport * as Hash from \"../Hash.js\";\nimport { toJson } from \"../Inspectable.js\";\nimport { hasProperty } from \"../Predicate.js\";\nimport { SingleShotGen } from \"../Utils.js\";\nimport { PipeInspectableProto } from \"./core.js\";\nconst TypeId = \"~effect/Option\";\nconst CommonProto = {\n [TypeId]: {\n _A: _ => _\n },\n ...PipeInspectableProto,\n [Symbol.iterator]() {\n return new SingleShotGen(this);\n }\n};\n// `valueOrUndefined` is folded into the initializer (rather than a separate\n// `Object.defineProperty(SomeProto, ...)` statement) so the whole definition\n// is pure-annotated by the build and tree-shakable.\nconst SomeProto = /*#__PURE__*/Object.defineProperty(/*#__PURE__*/Object.assign(/*#__PURE__*/Object.create(CommonProto), {\n _tag: \"Some\",\n _op: \"Some\",\n [Equal.symbol](that) {\n return isOption(that) && isSome(that) && Equal.equals(this.value, that.value);\n },\n [Hash.symbol]() {\n return Hash.combine(Hash.hash(this._tag))(Hash.hash(this.value));\n },\n toString() {\n return `some(${format(this.value)})`;\n },\n toJSON() {\n return {\n _id: \"Option\",\n _tag: this._tag,\n value: toJson(this.value)\n };\n }\n}), \"valueOrUndefined\", {\n get() {\n return this.value;\n }\n});\nconst NoneHash = /*#__PURE__*/Hash.hash(\"None\");\nconst NoneProto = /*#__PURE__*/Object.assign(/*#__PURE__*/Object.create(CommonProto), {\n _tag: \"None\",\n _op: \"None\",\n valueOrUndefined: undefined,\n [Equal.symbol](that) {\n return isOption(that) && isNone(that);\n },\n [Hash.symbol]() {\n return NoneHash;\n },\n toString() {\n return `none()`;\n },\n toJSON() {\n return {\n _id: \"Option\",\n _tag: this._tag\n };\n }\n});\n/** @internal */\nexport const isOption = input => hasProperty(input, TypeId);\n/** @internal */\nexport const isNone = fa => fa._tag === \"None\";\n/** @internal */\nexport const isSome = fa => fa._tag === \"Some\";\n/** @internal */\nexport const none = /*#__PURE__*/Object.create(NoneProto);\n/** @internal */\nconst SomeImpl = function (value) {\n this.value = value;\n};\nSomeImpl.prototype = SomeProto;\n/** @internal */\nexport const some = value => new SomeImpl(value);\n//# sourceMappingURL=option.js.map","import * as Equal from \"../Equal.js\";\nimport { format } from \"../Formatter.js\";\nimport { dual } from \"../Function.js\";\nimport * as Hash from \"../Hash.js\";\nimport { toJson } from \"../Inspectable.js\";\nimport { hasProperty } from \"../Predicate.js\";\nimport { SingleShotGen } from \"../Utils.js\";\nimport { PipeInspectableProto } from \"./core.js\";\nimport * as option from \"./option.js\";\nconst TypeId = \"~effect/Result\";\nconst CommonProto = {\n [TypeId]: {\n /* v8 ignore next 2 */\n _A: _ => _,\n _E: _ => _\n },\n ...PipeInspectableProto,\n [Symbol.iterator]() {\n return new SingleShotGen(this);\n }\n};\nconst SuccessProto = /*#__PURE__*/Object.assign(/*#__PURE__*/Object.create(CommonProto), {\n _tag: \"Success\",\n _op: \"Success\",\n [Equal.symbol](that) {\n return isResult(that) && isSuccess(that) && Equal.equals(this.success, that.success);\n },\n [Hash.symbol]() {\n return Hash.combine(Hash.hash(this._tag))(Hash.hash(this.success));\n },\n toString() {\n return `success(${format(this.success)})`;\n },\n toJSON() {\n return {\n _id: \"Result\",\n _tag: this._tag,\n value: toJson(this.success)\n };\n }\n});\nconst FailureProto = /*#__PURE__*/Object.assign(/*#__PURE__*/Object.create(CommonProto), {\n _tag: \"Failure\",\n _op: \"Failure\",\n [Equal.symbol](that) {\n return isResult(that) && isFailure(that) && Equal.equals(this.failure, that.failure);\n },\n [Hash.symbol]() {\n return Hash.combine(Hash.hash(this._tag))(Hash.hash(this.failure));\n },\n toString() {\n return `failure(${format(this.failure)})`;\n },\n toJSON() {\n return {\n _id: \"Result\",\n _tag: this._tag,\n failure: toJson(this.failure)\n };\n }\n});\n/** @internal */\nexport const isResult = input => hasProperty(input, TypeId);\n/** @internal */\nexport const isFailure = result => result._tag === \"Failure\";\n/** @internal */\nexport const isSuccess = result => result._tag === \"Success\";\n/** @internal */\nconst FailureImpl = function (failure) {\n this.failure = failure;\n};\nFailureImpl.prototype = FailureProto;\n/** @internal */\nexport const fail = failure => new FailureImpl(failure);\n/** @internal */\nconst SuccessImpl = function (success) {\n this.success = success;\n};\nSuccessImpl.prototype = SuccessProto;\n/** @internal */\nexport const succeed = success => new SuccessImpl(success);\n/** @internal */\nexport const getFailure = self => isSuccess(self) ? option.none : option.some(self.failure);\n/** @internal */\nexport const getSuccess = self => isFailure(self) ? option.none : option.some(self.success);\n/** @internal */\nexport const fromOption = /*#__PURE__*/dual(2, (self, onNone) => option.isNone(self) ? fail(onNone()) : succeed(self.value));\n//# sourceMappingURL=result.js.map","/**\n * Defines comparison functions for ordered values.\n *\n * An `Order<A>` compares two `A` values and returns whether the first is less\n * than, equal to, or greater than the second. Orders are used for sorting,\n * choosing minimum or maximum values, checking ranges, and building ordered data\n * structures. This module includes built-in orders, constructors for custom\n * orders, tools for reversing and combining comparisons, tuple and struct\n * helpers, comparison predicates, clamping, and reducer support.\n *\n * @since 2.0.0\n */\nimport { dual } from \"./Function.js\";\nimport * as Reducer from \"./Reducer.js\";\n/**\n * Creates a new `Order` instance from a comparison function.\n *\n * **When to use**\n *\n * Use when you need a sorting rule not covered by the built-in orders or input\n * mapping helpers, and you can provide a total comparison.\n *\n * **Details**\n *\n * Uses reference equality (`===`) as a shortcut: if `self === that`, it returns\n * `0` without calling the comparison function. The comparison function should\n * return `-1`, `0`, or `1`, and the returned order satisfies total ordering\n * laws when the comparison function does.\n *\n * **Example** (Creating an Order)\n *\n * ```ts import.meta.vitest\n * import { Order } from \"effect\"\n *\n * const byAge = Order.make<{ name: string; age: number }>((self, that) => {\n * if (self.age < that.age) return -1\n * if (self.age > that.age) return 1\n * return 0\n * })\n *\n * byAge({ name: \"Alice\", age: 30 }, { name: \"Bob\", age: 25 }) // => 1\n * byAge({ name: \"Alice\", age: 25 }, { name: \"Bob\", age: 30 }) // => -1\n * ```\n *\n * @see {@link mapInput} to transform an order by mapping the input type\n * @see {@link combine} to combine multiple orders\n * @category constructors\n * @since 2.0.0\n */\nexport function make(compare) {\n return (self, that) => self === that ? 0 : compare(self, that);\n}\n/**\n * Order instance for strings that compares them lexicographically using JavaScript's `<` operator.\n *\n * **When to use**\n *\n * Use when you need lexicographic string ordering.\n *\n * **Details**\n *\n * Uses lexicographic dictionary ordering. The empty string is less than any\n * non-empty string, and comparisons are case-sensitive.\n *\n * **Example** (Ordering strings)\n *\n * ```ts import.meta.vitest\n * import { Order } from \"effect\"\n *\n * Order.String(\"apple\", \"banana\") // => -1\n * Order.String(\"banana\", \"apple\") // => 1\n * Order.String(\"apple\", \"apple\") // => 0\n * ```\n *\n * @see {@link mapInput} to compare objects by a string property\n * @see {@link Struct} to combine with other orders for struct comparison\n * @category instances\n * @since 4.0.0\n */\nexport const String = /*#__PURE__*/make((self, that) => self < that ? -1 : 1);\n/**\n * Order instance for numbers that compares them numerically.\n *\n * **When to use**\n *\n * Use when you need numeric ordering for numbers.\n *\n * **Details**\n *\n * `0` is considered equal to `-0`. All `NaN` values are considered equal to\n * each other, and any `NaN` is considered less than any non-`NaN` number. All\n * other values use standard numeric comparison.\n *\n * **Example** (Ordering numbers)\n *\n * ```ts import.meta.vitest\n * import { Order } from \"effect\"\n *\n * Order.Number(1, 1) // => 0\n * Order.Number(1, 2) // => -1\n * Order.Number(2, 1) // => 1\n *\n * Order.Number(0, -0) // => 0\n * Order.Number(NaN, 1) // => -1\n * ```\n *\n * @see {@link mapInput} to compare objects by a number property\n * @see {@link BigInt} for bigint comparisons\n * @category instances\n * @since 4.0.0\n */\nexport const Number = /*#__PURE__*/make((self, that) => {\n if (globalThis.Number.isNaN(self) && globalThis.Number.isNaN(that)) return 0;\n if (globalThis.Number.isNaN(self)) return -1; // NaN < any number\n if (globalThis.Number.isNaN(that)) return 1; // any number > NaN\n return self < that ? -1 : 1;\n});\n/**\n * Order instance for booleans where `false` is considered less than `true`.\n *\n * **When to use**\n *\n * Use when you need boolean ordering where `false` comes before `true`.\n *\n * **Details**\n *\n * `false` is less than `true`, and equal values return `0`.\n *\n * **Example** (Ordering booleans)\n *\n * ```ts import.meta.vitest\n * import { Order } from \"effect\"\n *\n * Order.Boolean(false, true) // => -1\n * Order.Boolean(true, false) // => 1\n * Order.Boolean(true, true) // => 0\n * ```\n *\n * @see {@link mapInput} to compare objects by a boolean property\n * @category instances\n * @since 4.0.0\n */\nexport const Boolean = /*#__PURE__*/make((self, that) => self < that ? -1 : 1);\n/**\n * Order instance for bigints that compares them numerically.\n *\n * **When to use**\n *\n * Use when you need numeric ordering for `bigint` values.\n *\n * **Details**\n *\n * Uses standard numeric comparison for bigint values and handles arbitrarily\n * large integers.\n *\n * **Example** (Ordering BigInts)\n *\n * ```ts import.meta.vitest\n * import { Order } from \"effect\"\n *\n * Order.BigInt(1n, 2n) // => -1\n * Order.BigInt(2n, 1n) // => 1\n * Order.BigInt(1n, 1n) // => 0\n * ```\n *\n * @see {@link Number} for regular number comparisons\n * @see {@link mapInput} to compare objects by a bigint property\n * @category instances\n * @since 4.0.0\n */\nexport const BigInt = /*#__PURE__*/make((self, that) => self < that ? -1 : 1);\n/**\n * Creates a new `Order` that reverses the comparison order of the input `Order`.\n *\n * **When to use**\n *\n * Use when you need the reverse of an existing order.\n *\n * **Details**\n *\n * Returns a new order that swaps the arguments before comparison. If the\n * original order returns `-1`, the flipped order returns `1`, and vice versa.\n * Equal comparisons remain `0`.\n *\n * **Example** (Reversing an Order)\n *\n * ```ts import.meta.vitest\n * import { Order } from \"effect\"\n *\n * const flip = Order.flip(Order.Number)\n *\n * flip(1, 2) // => 1\n * flip(2, 1) // => -1\n * flip(1, 1) // => 0\n * ```\n *\n * @see {@link combine} to combine orders for multi-criteria comparison\n * @category combinators\n * @since 4.0.0\n */\nexport function flip(O) {\n return make((self, that) => O(that, self));\n}\n/**\n * Combines two `Order` instances to create a new `Order` that first compares using the first `Order`,\n * and if the values are equal, then compares using the second `Order`.\n *\n * **When to use**\n *\n * Use when you need tie-breaking with exactly two orders.\n *\n * **Details**\n *\n * First applies the first order. If the result is non-zero, that result is\n * returned; otherwise, the second order is applied. The result is the first\n * non-zero comparison result, or `0` if both orders return `0`.\n *\n * **Example** (Combining two Orders)\n *\n * ```ts import.meta.vitest\n * import { Order } from \"effect\"\n *\n * const byAge = Order.mapInput(\n * Order.Number,\n * (person: { name: string; age: number }) => person.age\n * )\n * const byName = Order.mapInput(\n * Order.String,\n * (person: { name: string; age: number }) => person.name\n * )\n * const byAgeAndName = Order.combine(byAge, byName)\n *\n * const person1 = { name: \"Alice\", age: 30 }\n * const person2 = { name: \"Bob\", age: 30 }\n * const person3 = { name: \"Charlie\", age: 25 }\n *\n * byAgeAndName(person1, person2) // => -1\n * byAgeAndName(person1, person3) // => 1\n * ```\n *\n * @see {@link combineAll} to combine multiple orders from a collection\n * @see {@link mapInput} to transform orders to work with different types\n * @category combining\n * @since 2.0.0\n */\nexport const combine = /*#__PURE__*/dual(2, (self, that) => make((a1, a2) => {\n const out = self(a1, a2);\n if (out !== 0) {\n return out;\n }\n return that(a1, a2);\n}));\n/**\n * Creates an `Order` that considers all values as equal.\n *\n * **When to use**\n *\n * Use when you need an order that treats all values as equal.\n *\n * **Details**\n *\n * Always returns `0` regardless of input values, making it useful as a neutral\n * element in order composition.\n *\n * **Example** (Ordering with an always-equal Order)\n *\n * ```ts import.meta.vitest\n * import { Order } from \"effect\"\n *\n * const alwaysEqualOrder = Order.alwaysEqual<number>()\n *\n * alwaysEqualOrder(1, 2) // => 0\n * alwaysEqualOrder(2, 1) // => 0\n * alwaysEqualOrder(1, 1) // => 0\n * ```\n *\n * @see {@link combine} to combine with other orders\n * @category constructors\n * @since 4.0.0\n */\nexport function alwaysEqual() {\n return make(() => 0);\n}\n/**\n * Combines all `Order` instances in the provided collection into a single `Order`.\n * The resulting `Order` compares using each `Order` in sequence until a non-zero result is found.\n *\n * **When to use**\n *\n * Use when you need tie-breaking across a variable number of orders.\n *\n * **Details**\n *\n * Applies orders in iteration order and short-circuits on the first non-zero\n * result. It returns `0` only if all orders return `0`.\n * The collection is materialized when the order is created, so it must be finite.\n *\n * **Example** (Combining multiple Orders)\n *\n * ```ts import.meta.vitest\n * import { Order } from \"effect\"\n *\n * const byAge = Order.mapInput(\n * Order.Number,\n * (person: { name: string; age: number }) => person.age\n * )\n * const byName = Order.mapInput(\n * Order.String,\n * (person: { name: string; age: number }) => person.name\n * )\n *\n * const combinedOrder = Order.combineAll([byAge, byName])\n *\n * const person1 = { name: \"Alice\", age: 30 }\n * const person2 = { name: \"Bob\", age: 30 }\n *\n * combinedOrder(person1, person2) // => -1\n * ```\n *\n * @see {@link combine} to combine two orders\n * @see {@link makeReducer} to create a reducer for combining orders\n * @category combining\n * @since 2.0.0\n */\nexport function combineAll(collection) {\n const orders = Array.from(collection);\n return make((a1, a2) => {\n let out = 0;\n for (const O of orders) {\n out = O(a1, a2);\n if (out !== 0) {\n return out;\n }\n }\n return out;\n });\n}\n/**\n * Transforms an `Order` on type `A` into an `Order` on type `B` by providing a function that\n * maps values of type `B` to values of type `A`.\n *\n * **When to use**\n *\n * Use when you need to adapt an `Order` to compare a larger value by one\n * derived property.\n *\n * **Details**\n *\n * Applies the mapping function to both values before comparison. The mapping\n * function should be pure and not have side effects so the ordering properties\n * of the original order are preserved.\n *\n * **Example** (Mapping Input)\n *\n * ```ts import.meta.vitest\n * import { Order } from \"effect\"\n *\n * const byLength = Order.mapInput(Order.Number, (s: string) => s.length)\n *\n * byLength(\"a\", \"bb\") // => -1\n * byLength(\"bb\", \"a\") // => 1\n * byLength(\"aa\", \"bb\") // => 0\n * ```\n *\n * @see {@link combine} to combine mapped orders for multi-criteria comparison\n * @see {@link Struct} to create orders for structs with multiple fields\n * @category mapping\n * @since 2.0.0\n */\nexport const mapInput = /*#__PURE__*/dual(2, (self, f) => make((b1, b2) => self(f(b1), f(b2))));\n/**\n * Order instance for `Date` objects that compares them chronologically by their timestamp.\n *\n * **When to use**\n *\n * Use when you need chronological ordering for JavaScript date values.\n *\n * **Details**\n *\n * Compares dates by their underlying timestamp in milliseconds since the epoch.\n * Earlier dates are less than later dates. Invalid dates are compared through\n * their `getTime()` result.\n *\n * **Example** (Ordering Dates)\n *\n * ```ts import.meta.vitest\n * import { Order } from \"effect\"\n *\n * const date1 = new Date(\"2023-01-01\")\n * const date2 = new Date(\"2023-01-02\")\n *\n * Order.Date(date1, date2) // => -1\n * Order.Date(date2, date1) // => 1\n * Order.Date(date1, date1) // => 0\n * ```\n *\n * @see {@link mapInput} to compare objects by a date property\n * @category instances\n * @since 2.0.0\n */\nexport const Date = /*#__PURE__*/mapInput(Number, date => date.getTime());\n/**\n * Creates an `Order` for a tuple type based on orders for each element.\n *\n * **When to use**\n *\n * Use when you need fixed-length tuple ordering with per-position orders.\n *\n * **Details**\n *\n * Compares tuples element-by-element using the corresponding order and stops at\n * the first non-zero comparison result. Tuples must have the same length as the\n * order collection, and the result is `0` only if all elements are equal.\n *\n * **Example** (Ordering tuples)\n *\n * ```ts import.meta.vitest\n * import { Order } from \"effect\"\n *\n * const tupleOrder = Order.Tuple([Order.Number, Order.String])\n *\n * tupleOrder([1, \"a\"], [2, \"b\"]) // => -1\n * tupleOrder([1, \"b\"], [1, \"a\"]) // => 1\n * tupleOrder([1, \"a\"], [1, \"a\"]) // => 0\n * ```\n *\n * @see {@link Array} to compare arrays with length consideration\n * @category combinators\n * @since 4.0.0\n */\nexport function Tuple(elements) {\n return make((self, that) => {\n const len = elements.length;\n for (let i = 0; i < len; i++) {\n const o = elements[i](self[i], that[i]);\n if (o !== 0) {\n return o;\n }\n }\n return 0;\n });\n}\n/**\n * @since 4.0.0\n */\nfunction Array_(O) {\n return make((self, that) => {\n const aLen = self.length;\n const bLen = that.length;\n const len = Math.min(aLen, bLen);\n for (let i = 0; i < len; i++) {\n const o = O(self[i], that[i]);\n if (o !== 0) {\n return o;\n }\n }\n return Number(aLen, bLen);\n });\n}\nexport {\n/**\n * Creates an `Order` for arrays by applying the given `Order` to each element, then comparing by length if all elements are equal.\n *\n * **When to use**\n *\n * Use when you need lexicographic ordering for arrays of one element type.\n *\n * **Details**\n *\n * Compares arrays element-by-element using the provided order and stops at the\n * first non-zero comparison result. If all elements are equal, shorter arrays\n * are less than longer arrays. The result is `0` only if arrays have the same\n * length and all elements are equal.\n *\n * **Example** (Ordering array elements)\n *\n * ```ts import.meta.vitest\n * import { Order } from \"effect\"\n *\n * const arrayOrder = Order.Array(Order.Number)\n *\n * arrayOrder([1, 2], [1, 3]) // => -1\n * arrayOrder([1, 2], [1, 2, 3]) // => -1\n * arrayOrder([1, 2, 3], [1, 2]) // => 1\n * arrayOrder([1, 2], [1, 2]) // => 0\n * ```\n *\n * @see {@link Tuple} for type-safe tuple ordering\n * @category combinators\n * @since 4.0.0\n */\nArray_ as Array };\n/**\n * Creates an `Order` for structs by applying the given `Order`s to each property in sequence.\n *\n * **When to use**\n *\n * Use when you need multi-field ordering for objects with known properties.\n *\n * **Details**\n *\n * Compares structs field-by-field in the key order of the fields object and\n * stops at the first non-zero comparison result. Field order matters: earlier\n * fields take precedence. The result is `0` only if all fields are equal.\n *\n * **Example** (Ordering structs)\n *\n * ```ts import.meta.vitest\n * import { Order } from \"effect\"\n *\n * const personOrder = Order.Struct({\n * name: Order.String,\n * age: Order.Number\n * })\n *\n * const person1 = { name: \"Alice\", age: 30 }\n * const person2 = { name: \"Bob\", age: 25 }\n * const person3 = { name: \"Alice\", age: 25 }\n *\n * personOrder(person1, person2) // => -1\n * personOrder(person1, person3) // => 1\n * personOrder(person1, person1) // => 0\n * ```\n *\n * @see {@link combine} to combine orders manually\n * @see {@link mapInput} to extract and compare by a single property\n * @category combinators\n * @since 4.0.0\n */\nexport function Struct(fields) {\n const keys = Object.keys(fields);\n return make((self, that) => {\n for (const key of keys) {\n const o = fields[key](self[key], that[key]);\n if (o !== 0) {\n return o;\n }\n }\n return 0;\n });\n}\n/**\n * Checks whether one value is strictly less than another according to the given order.\n *\n * **When to use**\n *\n * Use when you need a boolean less-than predicate using an `Order`.\n *\n * **Details**\n *\n * Returns `true` if the order returns `-1`, meaning the first value is less\n * than the second. Equal or greater values return `false`.\n *\n * **Example** (Checking less-than comparisons)\n *\n * ```ts import.meta.vitest\n * import { Order } from \"effect\"\n *\n * const isLessThanNumber = Order.isLessThan(Order.Number)\n *\n * isLessThanNumber(1, 2) // => true\n * isLessThanNumber(2, 1) // => false\n * isLessThanNumber(1, 1) // => false\n * ```\n *\n * @see {@link isLessThanOrEqualTo} for non-strict less than or equal\n * @see {@link isGreaterThan} for strict greater than\n * @category predicates\n * @since 4.0.0\n */\nexport const isLessThan = O => dual(2, (self, that) => O(self, that) === -1);\n/**\n * Checks whether one value is strictly greater than another according to the given order.\n *\n * **When to use**\n *\n * Use when you need a boolean greater-than predicate using an `Order`.\n *\n * **Details**\n *\n * Returns `true` if the order returns `1`, meaning the first value is greater\n * than the second. Equal or lesser values return `false`.\n *\n * **Example** (Checking greater-than comparisons)\n *\n * ```ts import.meta.vitest\n * import { Order } from \"effect\"\n *\n * const isGreaterThanNumber = Order.isGreaterThan(Order.Number)\n *\n * isGreaterThanNumber(2, 1) // => true\n * isGreaterThanNumber(1, 2) // => false\n * isGreaterThanNumber(1, 1) // => false\n * ```\n *\n * @see {@link isGreaterThanOrEqualTo} for non-strict greater than or equal\n * @see {@link isLessThan} for strict less than\n * @category predicates\n * @since 4.0.0\n */\nexport const isGreaterThan = O => dual(2, (self, that) => O(self, that) === 1);\n/**\n * Checks whether one value is less than or equal to another according to the given order.\n *\n * **When to use**\n *\n * Use when you need a boolean less-than-or-equal predicate using an `Order`.\n *\n * **Details**\n *\n * Returns `true` if the order returns `-1` or `0`, and returns `false` only if\n * the order returns `1`.\n *\n * **Example** (Checking less-than-or-equal comparisons)\n *\n * ```ts import.meta.vitest\n * import { Order } from \"effect\"\n *\n * const isLessThanOrEqualToNumber = Order.isLessThanOrEqualTo(Order.Number)\n *\n * isLessThanOrEqualToNumber(1, 2) // => true\n * isLessThanOrEqualToNumber(1, 1) // => true\n * isLessThanOrEqualToNumber(2, 1) // => false\n * ```\n *\n * @see {@link isLessThan} for strict less than\n * @see {@link isGreaterThan} for strict greater than\n * @category predicates\n * @since 4.0.0\n */\nexport const isLessThanOrEqualTo = O => dual(2, (self, that) => O(self, that) !== 1);\n/**\n * Checks whether one value is greater than or equal to another according to the given order.\n *\n * **When to use**\n *\n * Use when you need a boolean greater-than-or-equal predicate using an\n * `Order`.\n *\n * **Details**\n *\n * Returns `true` if the order returns `1` or `0`, and returns `false` only if\n * the order returns `-1`.\n *\n * **Example** (Checking greater-than-or-equal comparisons)\n *\n * ```ts import.meta.vitest\n * import { Order } from \"effect\"\n *\n * const isGreaterThanOrEqualToNumber = Order.isGreaterThanOrEqualTo(Order.Number)\n *\n * isGreaterThanOrEqualToNumber(2, 1) // => true\n * isGreaterThanOrEqualToNumber(1, 1) // => true\n * isGreaterThanOrEqualToNumber(1, 2) // => false\n * ```\n *\n * @see {@link isGreaterThan} for strict greater than\n * @see {@link isLessThanOrEqualTo} for less than or equal\n * @category predicates\n * @since 4.0.0\n */\nexport const isGreaterThanOrEqualTo = O => dual(2, (self, that) => O(self, that) !== -1);\n/**\n * Returns the minimum of two values according to the given order. If they are equal, returns the first argument.\n *\n * **When to use**\n *\n * Use when you need to select the smaller of two values according to an\n * `Order`.\n *\n * **Details**\n *\n * Returns the value that compares as less than or equal to the other value. If\n * values are equal, the first argument is returned.\n *\n * **Example** (Selecting the minimum value)\n *\n * ```ts import.meta.vitest\n * import { Order } from \"effect\"\n *\n * const minNumber = Order.min(Order.Number)\n *\n * minNumber(1, 2) // => 1\n * minNumber(2, 1) // => 1\n * minNumber(1, 1) // => 1\n * ```\n *\n * @see {@link max} for the maximum of two values\n * @see {@link clamp} to clamp a value between min and max\n * @category comparisons\n * @since 2.0.0\n */\nexport const min = O => dual(2, (self, that) => self === that || O(self, that) < 1 ? self : that);\n/**\n * Returns the maximum of two values according to the given order. If they are equal, returns the first argument.\n *\n * **When to use**\n *\n * Use when you need to select the larger of two values according to an\n * `Order`.\n *\n * **Details**\n *\n * Returns the value that compares as greater than or equal to the other value.\n * If values are equal, the first argument is returned.\n *\n * **Example** (Selecting the maximum value)\n *\n * ```ts import.meta.vitest\n * import { Order } from \"effect\"\n *\n * const maxNumber = Order.max(Order.Number)\n *\n * maxNumber(1, 2) // => 2\n * maxNumber(2, 1) // => 2\n * maxNumber(1, 1) // => 1\n * ```\n *\n * @see {@link min} for the minimum of two values\n * @see {@link clamp} to clamp a value between min and max\n * @category comparisons\n * @since 2.0.0\n */\nexport const max = O => dual(2, (self, that) => self === that || O(self, that) > -1 ? self : that);\n/**\n * Restricts a value between a minimum and a maximum according to the given order.\n *\n * **When to use**\n *\n * Use when you need to clamp a value to an inclusive range according to an\n * `Order`.\n *\n * **Details**\n *\n * Returns the value itself when it is between minimum and maximum, inclusive.\n * Values below the range return minimum, and values above the range return\n * maximum. The minimum must be less than or equal to the maximum according to\n * the order.\n *\n * **Example** (Clamping values)\n *\n * ```ts import.meta.vitest\n * import { Order } from \"effect\"\n *\n * const clamp = Order.clamp(Order.Number)({ minimum: 1, maximum: 5 })\n *\n * clamp(3) // => 3\n * clamp(0) // => 1\n * clamp(6) // => 5\n * ```\n *\n * @see {@link min} for the minimum of two values\n * @see {@link max} for the maximum of two values\n * @see {@link isBetween} to check if a value is within a range\n * @category comparisons\n * @since 2.0.0\n */\nexport const clamp = O => dual(2, (self, options) => min(O)(options.maximum, max(O)(options.minimum, self)));\n/**\n * Checks whether a value is between a minimum and a maximum (inclusive) according to the given order.\n *\n * **When to use**\n *\n * Use when you need range checks that respect domain-specific ordering, such as\n * dates, versions, or custom priorities, instead of JavaScript numeric\n * comparison.\n *\n * **Details**\n *\n * Returns `true` when the value is greater than or equal to minimum and less\n * than or equal to maximum. Values outside the range return `false`. Both\n * bounds are inclusive.\n *\n * **Example** (Checking ranges)\n *\n * ```ts import.meta.vitest\n * import { Order } from \"effect\"\n *\n * const betweenNumber = Order.isBetween(Order.Number)\n *\n * betweenNumber(5, { minimum: 1, maximum: 10 }) // => true\n * betweenNumber(1, { minimum: 1, maximum: 10 }) // => true\n * betweenNumber(10, { minimum: 1, maximum: 10 }) // => true\n * betweenNumber(0, { minimum: 1, maximum: 10 }) // => false\n * betweenNumber(11, { minimum: 1, maximum: 10 }) // => false\n * ```\n *\n * @see {@link clamp} to clamp a value to a range\n * @see {@link isLessThanOrEqualTo} for less than or equal check\n * @see {@link isGreaterThanOrEqualTo} for greater than or equal check\n * @category predicates\n * @since 4.0.0\n */\nexport const isBetween = O => dual(2, (self, options) => !isLessThan(O)(self, options.minimum) && !isGreaterThan(O)(self, options.maximum));\n/**\n * Creates a `Reducer` for combining `Order` instances, useful for aggregating orders in collections.\n *\n * **When to use**\n *\n * Use when you need a reducer that combines orders.\n *\n * **Details**\n *\n * Returns a reducer that combines orders using `combine`, uses `alwaysEqual` as\n * the identity element for empty collections, and uses `combineAll` for\n * combining collections of orders. The reducer can be used with fold operations\n * on collections.\n *\n * **Example** (Creating a Reducer)\n *\n * ```ts import.meta.vitest\n * import { Order } from \"effect\"\n *\n * const reducer = Order.makeReducer<number>()\n * const orders = [Order.Number, Order.flip(Order.Number)]\n *\n * const combined = reducer.combineAll(orders)\n * combined(1, 2) // => -1\n * ```\n *\n * @see {@link combine} to combine two orders\n * @see {@link combineAll} to combine multiple orders\n * @see {@link Reducer} for reducing orders as a collection operation\n * @category constructors\n * @since 4.0.0\n */\nexport function makeReducer() {\n return Reducer.make(combine, () => 0, combineAll);\n}\n//# sourceMappingURL=Order.js.map","/**\n * Models a value that may be present or absent.\n *\n * An `Option<A>` is `Some<A>` when a value is available and `None` when it is\n * not. This lets code handle missing values explicitly instead of relying on\n * `null` or `undefined`. The module includes helpers for creating, checking,\n * transforming, combining, and extracting optional values, plus conversions to\n * and from common nullable or result-like shapes. It also includes `Option.gen`\n * for writing small generator-based computations that stop at the first `None`.\n *\n * @since 2.0.0\n */\nimport * as Combiner from \"./Combiner.js\";\nimport * as Equal from \"./Equal.js\";\nimport * as Equivalence from \"./Equivalence.js\";\nimport { constNull, constUndefined, dual, identity } from \"./Function.js\";\nimport * as doNotation from \"./internal/doNotation.js\";\nimport * as option from \"./internal/option.js\";\nimport * as InternalRecord from \"./internal/record.js\";\nimport * as result from \"./internal/result.js\";\nimport * as order from \"./Order.js\";\nimport { isFunction } from \"./Predicate.js\";\nimport * as Reducer from \"./Reducer.js\";\nconst TypeId = \"~effect/Option\";\n/**\n * Creates an `Option` representing the absence of a value.\n *\n * **When to use**\n *\n * Use to represent a missing or uninitialized value, such as returning \"no\n * result\" from a function.\n *\n * **Details**\n *\n * - Returns `Option<never>`, which is a subtype of `Option<A>` for any `A`\n * - Always returns the same singleton instance\n *\n * **Example** (Creating an empty Option)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * // ┌─── Option<never>\n * // ▼\n * const noValue = Option.none() // => Option.none()\n * ```\n *\n * @see {@link some} for the opposite operation.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const none = () => option.none;\n/**\n * Wraps the given value into an `Option` to represent its presence.\n *\n * **When to use**\n *\n * Use to wrap a known present value as `Option`\n * - Returning a successful result from a partial function\n *\n * **Details**\n *\n * - Always returns `Some<A>`\n * - Does not filter `null` or `undefined`; use {@link fromNullishOr} for that\n *\n * **Example** (Wrapping a value)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * // ┌─── Option<number>\n * // ▼\n * const value = Option.some(1) // => Option.some(1)\n * ```\n *\n * @see {@link none} for the opposite operation.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const some = option.some;\n/**\n * Determines whether the given value is an `Option`.\n *\n * **When to use**\n *\n * Use to validate unknown values at runtime boundaries, such as type-narrowing\n * in union types.\n *\n * **Details**\n *\n * - Returns `true` for both `Some` and `None` instances\n * - Acts as a type guard, narrowing the input to `Option<unknown>`\n *\n * **Example** (Checking if a value is an Option)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * Option.isOption(Option.some(1)) // => true\n * Option.isOption(Option.none()) // => true\n * Option.isOption({}) // => false\n * ```\n *\n * @see {@link isNone} to check for `None` specifically\n * @see {@link isSome} to check for `Some` specifically\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isOption = option.isOption;\n/**\n * Checks whether an `Option` is `None` (absent).\n *\n * **When to use**\n *\n * Use when you need to branch on an absent `Option` before accessing `.value`.\n *\n * **Details**\n *\n * - Acts as a type guard, narrowing to `None<A>`\n *\n * **Example** (Checking for None)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * Option.isNone(Option.some(1)) // => false\n * Option.isNone(Option.none()) // => true\n * ```\n *\n * @see {@link isSome} for the opposite check.\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isNone = option.isNone;\n/**\n * Checks whether an `Option` contains a value (`Some`).\n *\n * **When to use**\n *\n * Use when you need to branch on a present `Option` before accessing `.value`.\n *\n * **Details**\n *\n * - Acts as a type guard, narrowing to `Some<A>`\n *\n * **Example** (Checking for Some)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * Option.isSome(Option.some(1)) // => true\n * Option.isSome(Option.none()) // => false\n * ```\n *\n * @see {@link isNone} for the opposite check.\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isSome = option.isSome;\n/**\n * Pattern-matches on an `Option`, handling both `None` and `Some` cases.\n *\n * **When to use**\n *\n * Use when you need to handle both `Some` and `None` in one expression and\n * transform an `Option` into a plain value.\n *\n * **Details**\n *\n * - If `None`, calls `onNone` and returns its result\n * - If `Some`, calls `onSome` with the value and returns its result\n * - Supports the `dual` API (data-last and data-first)\n *\n * **Example** (Matching on an Option)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * Option.match(Option.some(1), {\n * onNone: () => \"Option is empty\",\n * onSome: (value) => `Option has a value: ${value}`\n * }) // => \"Option has a value: 1\"\n * ```\n *\n * @see {@link getOrElse} for unwrapping with a default\n *\n * @category pattern matching\n * @since 2.0.0\n */\nexport const match = /*#__PURE__*/dual(2, (self, {\n onNone,\n onSome\n}) => isNone(self) ? onNone() : onSome(self.value));\n/**\n * Converts an `Option`-returning function into a type guard (refinement).\n *\n * **When to use**\n *\n * Use when you need to turn an `Option`-returning parser into a type-narrowing\n * predicate, such as for `Array.prototype.filter`.\n *\n * **Details**\n *\n * - Returns `true` when the original function returns `Some`\n * - Returns `false` when the original function returns `None`\n * - Narrows the input type to `B` on success\n *\n * **Example** (Converting a parser to a type guard)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * type MyData = string | number\n *\n * const parseString = (data: MyData): Option.Option<string> =>\n * typeof data === \"string\" ? Option.some(data) : Option.none()\n *\n * // ┌─── (a: MyData) => a is string\n * // ▼\n * const isString = Option.toRefinement(parseString)\n *\n * isString(\"a\") // => true\n * isString(1) // => false\n * ```\n *\n * @see {@link liftPredicate} for the reverse direction\n *\n * @category converting\n * @since 2.0.0\n */\nexport const toRefinement = f => a => isSome(f(a));\n/**\n * Wraps the first element of an `Iterable` in a `Some`, or returns `None` if\n * the iterable is empty.\n *\n * **When to use**\n *\n * Use when you need to safely extract the head of a collection, including\n * generators or lazy iterables.\n *\n * **Details**\n *\n * - Only consumes the first element; does not iterate the rest\n * - Returns `None` for empty iterables\n *\n * **Example** (Getting the first element)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * Option.fromIterable([1, 2, 3]) // => Option.some(1)\n * Option.fromIterable([]) // => Option.none()\n * ```\n *\n * @see {@link toArray} for the inverse direction\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromIterable = collection => {\n for (const a of collection) {\n return some(a);\n }\n return none();\n};\n/**\n * Converts a `Result` into an `Option`, keeping only the success value.\n *\n * **When to use**\n *\n * Use when you need to discard a `Result` failure and keep only the success\n * value as an `Option`.\n *\n * **Details**\n *\n * - `Success` becomes `Some` with the success value\n * - `Failure` becomes `None` and the failure value is discarded\n *\n * **Example** (Extracting the success side)\n *\n * ```ts import.meta.vitest\n * import { Option, Result } from \"effect\"\n *\n * Option.getSuccess(Result.succeed(\"ok\")) // => Option.some(\"ok\")\n * Option.getSuccess(Result.fail(\"err\")) // => Option.none()\n * ```\n *\n * @see {@link getFailure} for the opposite operation.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const getSuccess = result.getSuccess;\n/**\n * Converts a `Result` into an `Option`, keeping only the failure value.\n *\n * **When to use**\n *\n * Use when you need to discard a `Result` success and keep only the failure\n * value as an `Option`.\n *\n * **Details**\n *\n * - `Failure` becomes `Some` with the failure value\n * - `Success` becomes `None` and the success value is discarded\n *\n * **Example** (Extracting the failure side)\n *\n * ```ts import.meta.vitest\n * import { Option, Result } from \"effect\"\n *\n * Option.getFailure(Result.succeed(\"ok\")) // => Option.none()\n * Option.getFailure(Result.fail(\"err\")) // => Option.some(\"err\")\n * ```\n *\n * @see {@link getSuccess} for the opposite operation.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const getFailure = result.getFailure;\n/**\n * Extracts the value from a `Some`, or evaluates a fallback thunk on `None`.\n *\n * **When to use**\n *\n * Use when providing a default value for an absent `Option`\n * - Unwrapping with lazy evaluation of the fallback\n *\n * **Details**\n *\n * - `Some` → returns the inner value\n * - `None` → calls `onNone()` and returns its result\n * - `onNone` is only called when needed (lazy)\n *\n * **Example** (Unwrapping with a fallback)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * Option.some(1).pipe(Option.getOrElse(() => 0)) // => 1\n * Option.none().pipe(Option.getOrElse(() => 0)) // => 0\n * ```\n *\n * @see {@link getOrNull} to fall back to `null`\n * @see {@link getOrUndefined} to fall back to `undefined`\n * @see {@link getOrThrow} to throw on `None`\n *\n * @category getters\n * @since 2.0.0\n */\nexport const getOrElse = /*#__PURE__*/dual(2, (self, onNone) => isNone(self) ? onNone() : self.value);\n/**\n * Returns the fallback `Option` if `self` is `None`; otherwise returns `self`.\n *\n * **When to use**\n *\n * Use when you need a lazy fallback `Option`, such as when building priority\n * chains of optional values.\n *\n * **Details**\n *\n * - `Some` → returns `self` unchanged\n * - `None` → evaluates and returns `that()`\n * - `that` is lazily evaluated\n *\n * **Example** (Providing a fallback Option)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * Option.none().pipe(Option.orElse(() => Option.some(\"b\"))) // => Option.some(\"b\")\n * Option.some(\"a\").pipe(Option.orElse(() => Option.some(\"b\"))) // => Option.some(\"a\")\n * ```\n *\n * @see {@link orElseSome} to wrap the fallback value in `Some` automatically\n * @see {@link firstSomeOf} to pick the first `Some` from a collection\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const orElse = /*#__PURE__*/dual(2, (self, that) => isNone(self) ? that() : self);\n/**\n * Returns `Some` of the fallback value if `self` is `None`; otherwise returns\n * `self`.\n *\n * **When to use**\n *\n * Use when providing a default plain value (not an `Option`) as fallback\n *\n * **Details**\n *\n * - `Some` → returns `self` unchanged\n * - `None` → calls `onNone()`, wraps result in `Some`, and returns it\n *\n * **Example** (Providing a fallback value)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * Option.none().pipe(Option.orElseSome(() => \"b\")) // => Option.some(\"b\")\n * Option.some(\"a\").pipe(Option.orElseSome(() => \"b\")) // => Option.some(\"a\")\n * ```\n *\n * @see {@link orElse} when the fallback is itself an `Option`\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const orElseSome = /*#__PURE__*/dual(2, (self, onNone) => isNone(self) ? some(onNone()) : self);\n/**\n * Returns the first available value and marks whether it came from the fallback.\n *\n * **When to use**\n *\n * Use when you need to know whether a present value came from the primary or\n * fallback `Option`.\n *\n * **Details**\n *\n * - `self` is `Some` → `Some(Result.fail(value))` (value from primary)\n * - `self` is `None`, `that()` is `Some` → `Some(Result.succeed(value))` (value from fallback)\n * - Both `None` → `None`\n *\n * **Example** (Tracking value source)\n *\n * ```ts import.meta.vitest\n * import { Option, Result } from \"effect\"\n *\n * const fallback = () => Option.some(\"fallback\")\n *\n * Option.orElseResult(Option.some(\"primary\"), fallback) // => Option.some(Result.fail(\"primary\"))\n * Option.orElseResult(Option.none(), fallback) // => Option.some(Result.succeed(\"fallback\"))\n * ```\n *\n * @see {@link orElse} for the simpler variant without source tracking\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const orElseResult = /*#__PURE__*/dual(2, (self, that) => isNone(self) ? map(that(), result.succeed) : map(self, result.fail));\n/**\n * Returns the first `Some` found in an iterable of `Option`s, or `None` if\n * all are `None`.\n *\n * **When to use**\n *\n * Use when you need the first available `Some` value from a priority list.\n *\n * **Details**\n *\n * - Short-circuits on the first `Some`\n * - Returns `None` only when every element is `None`\n *\n * **Example** (Finding the first Some)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * Option.firstSomeOf([\n * Option.none(),\n * Option.some(1),\n * Option.some(2)\n * ]) // => Option.some(1)\n * ```\n *\n * @see {@link orElse} for a two-option fallback\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const firstSomeOf = collection => {\n let out = none();\n for (out of collection) {\n if (isSome(out)) {\n return out;\n }\n }\n return out;\n};\n/**\n * Converts a nullable value (`null` or `undefined`) into an `Option`.\n *\n * **When to use**\n *\n * Use when you need JavaScript nullish values to become absence at an API\n * boundary while all other values, including falsy ones, remain present.\n *\n * **Details**\n *\n * - `null` or `undefined` → `None`\n * - Any other value → `Some` (typed as `NonNullable<A>`)\n *\n * **Example** (Converting nullable values to an Option)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * Option.fromNullishOr(undefined) // => Option.none()\n * Option.fromNullishOr(null) // => Option.none()\n * Option.fromNullishOr(1) // => Option.some(1)\n * ```\n *\n * @see {@link fromNullOr} to only treat `null` as absent\n * @see {@link fromUndefinedOr} to only treat `undefined` as absent\n * @see {@link liftNullishOr} to lift a nullable-returning function\n *\n * @category converting\n * @since 4.0.0\n */\nexport const fromNullishOr = a => a == null ? none() : some(a);\n/**\n * Converts a possibly `undefined` value into an `Option`, leaving `null`\n * as a valid `Some`.\n *\n * **When to use**\n *\n * Use when you want to treat only `undefined` as absent while preserving `null`\n * as a meaningful value.\n *\n * **Details**\n *\n * - `undefined` → `None`\n * - Any other value (including `null`) → `Some`\n *\n * **Example** (Converting possibly undefined values to an Option)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * Option.fromUndefinedOr(undefined) // => Option.none()\n * Option.fromUndefinedOr(null) // => Option.some(null)\n * Option.fromUndefinedOr(42) // => Option.some(42)\n * ```\n *\n * @see {@link fromNullishOr} to treat both `null` and `undefined` as absent\n * @see {@link fromNullOr} to only treat `null` as absent\n *\n * @category converting\n * @since 4.0.0\n */\nexport const fromUndefinedOr = a => a === undefined ? none() : some(a);\n/**\n * Converts a possibly `null` value into an `Option`, leaving `undefined`\n * as a valid `Some`.\n *\n * **When to use**\n *\n * Use when you want to treat only `null` as absent while preserving\n * `undefined` as a meaningful value.\n *\n * **Details**\n *\n * - `null` → `None`\n * - Any other value (including `undefined`) → `Some`\n *\n * **Example** (Converting possibly null values to an Option)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * Option.fromNullOr(null) // => Option.none()\n * Option.fromNullOr(undefined) // => Option.some(undefined)\n * Option.fromNullOr(42) // => Option.some(42)\n * ```\n *\n * @see {@link fromNullishOr} to treat both `null` and `undefined` as absent\n * @see {@link fromUndefinedOr} to only treat `undefined` as absent\n *\n * @category converting\n * @since 4.0.0\n */\nexport const fromNullOr = a => a === null ? none() : some(a);\n/**\n * Lifts a function that may return `null` or `undefined` into one that returns\n * an `Option`.\n *\n * **When to use**\n *\n * Use to wrap existing nullable-returning functions for use in `Option` pipelines\n *\n * **Details**\n *\n * - Calls the original function with the given arguments\n * - Wraps the result via {@link fromNullishOr}\n *\n * **Example** (Lifting a parser)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * const parse = (s: string): number | undefined => {\n * const n = parseFloat(s)\n * return isNaN(n) ? undefined : n\n * }\n *\n * const parseOption = Option.liftNullishOr(parse)\n *\n * parseOption(\"1\") // => Option.some(1)\n * parseOption(\"not a number\") // => Option.none()\n * ```\n *\n * @see {@link fromNullishOr} for converting a single value\n * @see {@link liftThrowable} for functions that throw instead\n *\n * @category converting\n * @since 4.0.0\n */\nexport const liftNullishOr = f => (...a) => fromNullishOr(f(...a));\n/**\n * Extracts the value from a `Some`, or returns `null` for `None`.\n *\n * **When to use**\n *\n * Use when you need to pass absent `Option` values to APIs that expect `null`.\n *\n * **Details**\n *\n * - `Some` → the inner value\n * - `None` → `null`\n *\n * **Example** (Unwrapping to null)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * Option.getOrNull(Option.some(1)) // => 1\n * Option.getOrNull(Option.none()) // => null\n * ```\n *\n * @see {@link getOrUndefined} to return `undefined` instead\n * @see {@link getOrElse} for a custom fallback\n *\n * @category getters\n * @since 2.0.0\n */\nexport const getOrNull = /*#__PURE__*/getOrElse(constNull);\n/**\n * Extracts the value from a `Some`, or returns `undefined` for `None`.\n *\n * **When to use**\n *\n * Use when you need to pass absent `Option` values to APIs that expect\n * `undefined`.\n *\n * **Details**\n *\n * - `Some` → the inner value\n * - `None` → `undefined`\n *\n * **Example** (Unwrapping to undefined)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * Option.getOrUndefined(Option.some(1)) // => 1\n * Option.getOrUndefined(Option.none()) // => undefined\n * ```\n *\n * @see {@link getOrNull} to return `null` instead\n * @see {@link getOrElse} for a custom fallback\n *\n * @category getters\n * @since 2.0.0\n */\nexport const getOrUndefined = /*#__PURE__*/getOrElse(constUndefined);\n/**\n * Lifts a function that may throw into one that returns an `Option`.\n *\n * **When to use**\n *\n * Use to wrap exception-throwing APIs (e.g. `JSON.parse`) for safe usage\n *\n * **Details**\n *\n * - If the function returns normally → `Some` with the result\n * - If the function throws → `None` (exception is swallowed)\n *\n * **Example** (Lifting JSON.parse)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * const parse = Option.liftThrowable(JSON.parse)\n *\n * parse(\"1\") // => Option.some(1)\n * parse(\"\") // => Option.none()\n * ```\n *\n * @see {@link liftNullishOr} for nullable-returning functions\n *\n * @category converting\n * @since 2.0.0\n */\nexport const liftThrowable = f => (...a) => {\n try {\n return some(f(...a));\n } catch {\n return none();\n }\n};\n/**\n * Extracts the value from a `Some`, or throws a custom error for `None`.\n *\n * **When to use**\n *\n * Use when you need fail-fast unwrapping of an `Option` for unexpected absence\n * and want to provide a descriptive debugging error.\n *\n * **Details**\n *\n * - `Some` → returns the inner value\n * - `None` → throws the value returned by `onNone()`\n *\n * **Example** (Throwing a custom error)\n *\n * ```ts import.meta.vitest\n * import { Option, Result } from \"effect\"\n *\n * Option.getOrThrowWith(Option.some(1), () => new Error(\"missing\")) // => 1\n *\n * const failure = Result.try({\n * try: () => Option.getOrThrowWith(Option.none(), () => new Error(\"missing\")),\n * catch: (error) => (error as Error).message\n * })\n * Result.getFailure(failure).pipe(Option.getOrElse(() => \"no error\")) // => \"missing\"\n * ```\n *\n * @see {@link getOrThrow} for a version with a default error\n * @see {@link getOrElse} for a non-throwing alternative\n *\n * @category converting\n * @since 2.0.0\n */\nexport const getOrThrowWith = /*#__PURE__*/dual(2, (self, onNone) => {\n if (isSome(self)) {\n return self.value;\n }\n throw onNone();\n});\n/**\n * Extracts the value from a `Some`, or throws a default `Error` for `None`.\n *\n * **When to use**\n *\n * Use when you need quick fail-fast unwrapping of an `Option` and a generic\n * error is acceptable.\n *\n * **Details**\n *\n * - `Some` → returns the inner value\n * - `None` → throws `new Error(\"getOrThrow called on a None\")`\n *\n * **Example** (Throwing a default error)\n *\n * ```ts import.meta.vitest\n * import { Option, Result } from \"effect\"\n *\n * Option.getOrThrow(Option.some(1)) // => 1\n *\n * const failure = Result.try({\n * try: () => Option.getOrThrow(Option.none()),\n * catch: (error) => (error as Error).message\n * })\n * Result.getFailure(failure).pipe(Option.getOrElse(() => \"no error\")) // => \"getOrThrow called on a None\"\n * ```\n *\n * @see {@link getOrThrowWith} for a custom error\n * @see {@link getOrElse} for a non-throwing alternative\n *\n * @category converting\n * @since 2.0.0\n */\nexport const getOrThrow = /*#__PURE__*/getOrThrowWith(() => new Error(\"getOrThrow called on a None\"));\n/**\n * Transforms the value inside a `Some` using the provided function, leaving\n * `None` unchanged.\n *\n * **When to use**\n *\n * Use to apply a pure transformation to an `Option`'s present value, especially\n * when chaining transformations in a pipeline.\n *\n * **Details**\n *\n * - `Some` → applies `f` and wraps the result in a new `Some`\n * - `None` → returns `None` unchanged\n *\n * **Example** (Mapping over an Option)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * Option.map(Option.some(2), (n) => n * 2) // => Option.some(4)\n * Option.map(Option.none(), (n: number) => n * 2) // => Option.none()\n * ```\n *\n * @see {@link flatMap} when `f` returns an `Option`\n * @see {@link as} to replace the value with a constant\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => isNone(self) ? none() : some(f(self.value)));\n/**\n * Replaces the value inside a `Some` with a constant, leaving `None` unchanged.\n *\n * **When to use**\n *\n * Use when you need to replace a present `Option` value while preserving\n * whether it was `Some` or `None`.\n *\n * **Example** (Replacing a value)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * Option.as(Option.some(42), \"new value\") // => Option.some(\"new value\")\n * Option.as(Option.none(), \"new value\") // => Option.none()\n * ```\n *\n * @see {@link asVoid} to replace with `undefined`\n * @see {@link map} for a general transformation\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const as = /*#__PURE__*/dual(2, (self, b) => map(self, () => b));\n/**\n * Replaces the value inside a `Some` with `void` (`undefined`), leaving `None`\n * unchanged.\n *\n * **When to use**\n *\n * Use when you need to discard a present `Option` value while preserving\n * whether it was `Some` or `None`.\n *\n * **Example** (Voiding the value)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * Option.asVoid(Option.some(42)) // => Option.some(undefined)\n * Option.asVoid(Option.none()) // => Option.none()\n * ```\n *\n * @see {@link as} to replace with a specific constant\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const asVoid = /*#__PURE__*/as(undefined);\nconst void_ = /*#__PURE__*/some(undefined);\nexport {\n/**\n * Provides a pre-built `Some(undefined)` constant.\n *\n * **When to use**\n *\n * Use to return a \"success with no meaningful value\" from an `Option`-returning function\n *\n * **Example** (Referencing Option.void)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * Option.void // => Option.some(undefined)\n * ```\n *\n * @see {@link asVoid} to convert an existing `Option` to `Option<void>`\n *\n * @category constructors\n * @since 2.0.0\n */\nvoid_ as void };\n/**\n * Applies a function that returns an `Option` to the value of a `Some`,\n * flattening the result. Returns `None` if the input is `None`.\n *\n * **When to use**\n *\n * Use when you need to chain dependent `Option` computations where each step\n * may return `None`.\n *\n * **Details**\n *\n * - `Some` → applies `f` to the value and returns its `Option` result\n * - `None` → returns `None` without calling `f`\n * - Equivalent to `map` followed by {@link flatten}\n *\n * **Example** (Chaining optional lookups)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * interface User {\n * readonly name: string\n * readonly address: Option.Option<{ readonly street: Option.Option<string> }>\n * }\n *\n * const user: User = {\n * name: \"John\",\n * address: Option.some({ street: Option.some(\"123 Main St\") })\n * }\n *\n * user.address.pipe(\n * Option.flatMap((addr) => addr.street)\n * ) // => Option.some(\"123 Main St\")\n * ```\n *\n * @see {@link map} when `f` returns a plain value\n * @see {@link andThen} for a more flexible variant\n * @see {@link flatten} to unwrap a nested `Option<Option<A>>`\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const flatMap = /*#__PURE__*/dual(2, (self, f) => isNone(self) ? none() : f(self.value));\n/**\n * Chains a second computation onto an `Option`. The second value can be a\n * plain value, an `Option`, or a function returning either.\n *\n * **When to use**\n *\n * Use when you need to chain an `Option` with a next step that may be another\n * `Option`, a plain value, or a function.\n *\n * **Details**\n *\n * - If `self` is `None`, returns `None` immediately\n * - If `f` is a function, calls it with the `Some` value\n * - If `f` returns an `Option`, returns it as-is; if a plain value, wraps in `Some`\n * - If `f` is not a function, uses it directly (same wrapping rules)\n *\n * **Example** (Chaining with andThen)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * // Chain with a function returning Option\n * Option.andThen(Option.some(5), (x) => Option.some(x * 2)) // => Option.some(10)\n *\n * // Chain with a static value\n * Option.andThen(Option.some(5), \"hello\") // => Option.some(\"hello\")\n *\n * // Chain with None - skips\n * Option.andThen(Option.none(), (x) => Option.some(x * 2)) // => Option.none()\n * ```\n *\n * @see {@link flatMap} for the standard monadic bind\n * @see {@link map} when you always return a plain value\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const andThen = /*#__PURE__*/dual(2, (self, f) => flatMap(self, a => {\n const b = isFunction(f) ? f(a) : f;\n return isOption(b) ? b : some(b);\n}));\n/**\n * Combines {@link flatMap} with {@link fromNullishOr}: applies a function that\n * may return `null`/`undefined` to the value of a `Some`.\n *\n * **When to use**\n *\n * Use when you need to chain optional computations that use `null` or\n * `undefined` instead of `Option`, such as nested property access.\n *\n * **Details**\n *\n * - `None` → `None`\n * - `Some` → applies `f`, then wraps via {@link fromNullishOr}\n *\n * **Example** (Navigating optional properties)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * interface Employee {\n * company?: { address?: { street?: { name?: string } } }\n * }\n *\n * const emp: Employee = {\n * company: { address: { street: { name: \"high street\" } } }\n * }\n *\n * Option.some(emp).pipe(\n * Option.flatMapNullishOr((e) => e.company?.address?.street?.name)\n * ) // => Option.some(\"high street\")\n * ```\n *\n * @see {@link flatMap} when the function already returns `Option`\n * @see {@link fromNullishOr} for single-value conversion\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const flatMapNullishOr = /*#__PURE__*/dual(2, (self, f) => isNone(self) ? none() : fromNullishOr(f(self.value)));\n/**\n * Flattens a nested `Option<Option<A>>` into `Option<A>`.\n *\n * **When to use**\n *\n * Use when you need to remove one layer of nested `Option`.\n *\n * **Details**\n *\n * - `Some(Some(value))` → `Some(value)`\n * - `Some(None)` → `None`\n * - `None` → `None`\n *\n * **Example** (Flattening nested Options)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * Option.flatten(Option.some(Option.some(\"value\"))) // => Option.some(\"value\")\n * Option.flatten(Option.some(Option.none())) // => Option.none()\n * ```\n *\n * @see {@link flatMap} which is `map` + `flatten`\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const flatten = /*#__PURE__*/flatMap(identity);\n/**\n * Sequences two `Option`s, keeping the value from the second if both are `Some`.\n *\n * **When to use**\n *\n * Use when you need two `Option` values to both be `Some`, then keep only the\n * second value.\n *\n * **Details**\n *\n * - Both `Some` → returns `that`\n * - Either `None` → returns `None`\n *\n * **Example** (Keeping the second value)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * Option.zipRight(Option.some(1), Option.some(\"hello\")) // => Option.some(\"hello\")\n * Option.zipRight(Option.none(), Option.some(\"hello\")) // => Option.none()\n * ```\n *\n * @see {@link zipLeft} to keep the first value instead\n * @see {@link zipWith} to combine both values\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipRight = /*#__PURE__*/dual(2, (self, that) => flatMap(self, () => that));\n/**\n * Sequences two `Option`s, keeping the value from the first if both are `Some`.\n *\n * **When to use**\n *\n * Use when you need two `Option` values to both be `Some`, then keep only the\n * first value.\n *\n * **Details**\n *\n * - Both `Some` → returns `self`\n * - Either `None` → returns `None`\n *\n * **Example** (Keeping the first value)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * Option.zipLeft(Option.some(\"hello\"), Option.some(1)) // => Option.some(\"hello\")\n * Option.zipLeft(Option.some(\"hello\"), Option.none()) // => Option.none()\n * ```\n *\n * @see {@link zipRight} to keep the second value instead\n * @see {@link zipWith} to combine both values\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipLeft = /*#__PURE__*/dual(2, (self, that) => tap(self, () => that));\n/**\n * Composes two `Option`-returning functions into a single function that chains\n * them together.\n *\n * **When to use**\n *\n * Use when you need to compose two functions that each return an `Option`, so\n * `None` short-circuits without calling the next function.\n *\n * **Details**\n *\n * - Calls `afb(a)`, then if `Some`, calls `bfc` with its value\n * - Short-circuits to `None` if either function returns `None`\n *\n * **Example** (Composing parsers)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * const parse = (s: string): Option.Option<number> =>\n * isNaN(Number(s)) ? Option.none() : Option.some(Number(s))\n *\n * const double = (n: number): Option.Option<number> =>\n * n > 0 ? Option.some(n * 2) : Option.none()\n *\n * const parseAndDouble = Option.composeK(parse, double)\n *\n * parseAndDouble(\"42\") // => Option.some(84)\n * parseAndDouble(\"not a number\") // => Option.none()\n * ```\n *\n * @see {@link flatMap} for single-step chaining\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const composeK = /*#__PURE__*/dual(2, (afb, bfc) => a => flatMap(afb(a), bfc));\n/**\n * Runs a side-effecting `Option`-returning function on the value of a `Some`,\n * returning the original `Option` if the function returns `Some`, or `None`\n * if it returns `None`.\n *\n * **When to use**\n *\n * Use to validate an `Option`'s present value without transforming it, such as\n * adding a side-condition check in a pipeline.\n *\n * **Details**\n *\n * - `None` → `None`\n * - `Some` → calls `f(value)`; if result is `Some`, returns original `self`; if `None`, returns `None`\n *\n * **Example** (Validating without transforming)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * const getInteger = (n: number) =>\n * Number.isInteger(n) ? Option.some(n) : Option.none()\n *\n * Option.tap(Option.some(1), getInteger) // => Option.some(1)\n * Option.tap(Option.some(1.14), getInteger) // => Option.none()\n * ```\n *\n * @see {@link flatMap} when you want to transform the value\n * @see {@link filter} for predicate-based filtering\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const tap = /*#__PURE__*/dual(2, (self, f) => flatMap(self, a => map(f(a), () => a)));\n/**\n * Combines two `Option`s into a `Some` containing a tuple `[A, B]` if both\n * are `Some`.\n *\n * **When to use**\n *\n * Use when you need to require two `Option` values to both be `Some` and keep\n * both values as a tuple.\n *\n * **Details**\n *\n * - Both `Some` → `Some([a, b])`\n * - Either `None` → `None`\n *\n * **Example** (Pairing two Options)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * Option.product(Option.some(\"hello\"), Option.some(42)) // => Option.some([\"hello\", 42])\n * Option.product(Option.none(), Option.some(42)) // => Option.none()\n * ```\n *\n * @see {@link zipWith} to combine with a function instead of a tuple\n * @see {@link all} to combine many `Option`s\n *\n * @category combining\n * @since 2.0.0\n */\nexport const product = (self, that) => isSome(self) && isSome(that) ? some([self.value, that.value]) : none();\n/**\n * Combines a primary `Option` with an iterable of `Option`s into a tuple if\n * all are `Some`.\n *\n * **When to use**\n *\n * Use when you need several `Option` values of the same type to all be `Some`\n * and return them as a non-empty tuple.\n *\n * **Details**\n *\n * - All `Some` → `Some([self.value, ...rest])`\n * - Any `None` → `None`\n *\n * **Example** (Combining many Options)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * const first = Option.some(1)\n * const rest = [Option.some(2), Option.some(3)]\n *\n * Option.productMany(first, rest) // => Option.some([1, 2, 3])\n * Option.productMany(first, [Option.some(2), Option.none()]) // => Option.none()\n * ```\n *\n * @see {@link product} for combining exactly two\n * @see {@link all} for tuples, structs, and iterables\n *\n * @category combining\n * @since 2.0.0\n */\nexport const productMany = (self, collection) => {\n if (isNone(self)) {\n return none();\n }\n const out = [self.value];\n for (const o of collection) {\n if (isNone(o)) {\n return none();\n }\n out.push(o.value);\n }\n return some(out);\n};\n/**\n * Combines a structure of `Option`s (tuple, struct, or iterable) into a single\n * `Option` containing the unwrapped structure.\n *\n * **When to use**\n *\n * Use when you need to combine multiple `Option` values into one while\n * preserving the input shape, with any `None` making the result `None`.\n *\n * **Details**\n *\n * - Tuple input → `Option` of a tuple with the same length\n * - Struct input → `Option` of a struct with the same keys\n * - Iterable input → `Option` of an `Array`\n * - Any `None` in the input → entire result is `None`\n *\n * **Example** (Combining a tuple and a struct)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * const maybeName: Option.Option<string> = Option.some(\"John\")\n * const maybeAge: Option.Option<number> = Option.some(25)\n *\n * // ┌─── Option<[string, number]>\n * // ▼\n * const tuple = Option.all([maybeName, maybeAge]) // => Option.some([\"John\", 25])\n *\n * // ┌─── Option<{ name: string; age: number; }>\n * // ▼\n * const struct = Option.all({ name: maybeName, age: maybeAge }) // => Option.some({ name: \"John\", age: 25 })\n * ```\n *\n * @see {@link product} for combining exactly two\n * @see {@link productMany} for a homogeneous collection\n *\n * @category combining\n * @since 2.0.0\n */\n// @ts-expect-error\nexport const all = input => {\n if (Symbol.iterator in input) {\n const out = [];\n for (const o of input) {\n if (isNone(o)) {\n return none();\n }\n out.push(o.value);\n }\n return some(out);\n }\n const out = {};\n for (const key of Object.keys(input)) {\n const o = input[key];\n if (isNone(o)) {\n return none();\n }\n InternalRecord.assignProperty(out, key, o.value);\n }\n return some(out);\n};\n/**\n * Combines two `Option`s using a provided function.\n *\n * **When to use**\n *\n * Use when you need to combine two present `Option` values into a computed\n * result.\n *\n * **Details**\n *\n * - Both `Some` → applies `f(a, b)` and wraps in `Some`\n * - Either `None` → `None`\n *\n * **Example** (Combining with a function)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * Option.zipWith(\n * Option.some(\"John\"),\n * Option.some(25),\n * (name, age) => ({ name: name.toUpperCase(), age })\n * ) // => Option.some({ name: \"JOHN\", age: 25 })\n * ```\n *\n * @see {@link product} to combine into a tuple instead\n * @see {@link lift2} to lift a binary function\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipWith = /*#__PURE__*/dual(3, (self, that, f) => map(product(self, that), ([a, b]) => f(a, b)));\n/**\n * Reduces an iterable of `Option`s to a single value, skipping `None` entries.\n *\n * **When to use**\n *\n * Use when you need to aggregate values from a collection where some may be\n * absent.\n *\n * **Details**\n *\n * - Iterates through the collection, applying `f` only to `Some` values\n * - `None` values are skipped entirely\n * - Returns the accumulated result\n *\n * **Example** (Summing present values)\n *\n * ```ts import.meta.vitest\n * import { Option, pipe } from \"effect\"\n *\n * const items = [Option.some(1), Option.none(), Option.some(2), Option.none()]\n *\n * pipe(items, Option.reduceCompact(0, (b, a) => b + a)) // => 3\n * ```\n *\n * @category folding\n * @since 2.0.0\n */\nexport const reduceCompact = /*#__PURE__*/dual(3, (self, b, f) => {\n let out = b;\n for (const oa of self) {\n if (isSome(oa)) {\n out = f(out, oa.value);\n }\n }\n return out;\n});\n/**\n * Converts an `Option` into an `Array`.\n *\n * **When to use**\n *\n * Use when you need to pass an `Option` to array-based APIs or spread optional\n * values into collections.\n *\n * **Details**\n *\n * - `Some` → single-element array `[value]`\n * - `None` → empty array `[]`\n *\n * **Example** (Converting to an array)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * Option.toArray(Option.some(1)) // => [1]\n * Option.toArray(Option.none()) // => []\n * ```\n *\n * @see {@link fromIterable} for the inverse direction\n *\n * @category converting\n * @since 2.0.0\n */\nexport const toArray = self => isNone(self) ? [] : [self.value];\n/**\n * Splits an `Option` into two `Option`s using a function that returns a `Result`.\n *\n * **When to use**\n *\n * Use when you need to split an optional value into \"left\" and \"right\"\n * channels using a `Result`-returning function.\n *\n * **Details**\n *\n * - `None` → `[None, None]`\n * - `Some` where `f` returns `Err` → `[Some(error), None]`\n * - `Some` where `f` returns `Ok` → `[None, Some(value)]`\n *\n * **Example** (Partitioning by Result)\n *\n * ```ts import.meta.vitest\n * import { Option, Result } from \"effect\"\n *\n * const parseNumber = (s: string): Result.Result<number, string> => {\n * const n = Number(s)\n * return isNaN(n) ? Result.fail(\"Not a number\") : Result.succeed(n)\n * }\n *\n * Option.partitionMap(Option.some(\"42\"), parseNumber) // => [Option.none(), Option.some(42)]\n * Option.partitionMap(Option.some(\"abc\"), parseNumber) // => [Option.some(\"Not a number\"), Option.none()]\n * Option.partitionMap(Option.none(), parseNumber) // => [Option.none(), Option.none()]\n * ```\n *\n * @see {@link filter} for simple predicate-based filtering\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const partitionMap = /*#__PURE__*/dual(2, (self, f) => {\n if (isNone(self)) {\n return [none(), none()];\n }\n const e = f(self.value);\n return result.isFailure(e) ? [some(e.failure), none()] : [none(), some(e.success)];\n});\n/**\n * Transforms and filters an `Option` using a `Filter` callback.\n *\n * **When to use**\n *\n * Use to transform an `Option`'s present value and discard it when the `Filter`\n * fails.\n *\n * **Details**\n *\n * The callback returns a `Result`: `Result.succeed` keeps and transforms the\n * value, while `Result.fail` discards it.\n *\n * **Example** (Filtering and transforming)\n *\n * ```ts import.meta.vitest\n * import { Option, Result } from \"effect\"\n *\n * Option.filterMap(\n * Option.some(2),\n * (n) => (n % 2 === 0 ? Result.succeed(`Even: ${n}`) : Result.failVoid)\n * ) // => Option.some(\"Even: 2\")\n * ```\n *\n * @see {@link filter} for predicate-based filtering\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const filterMap = /*#__PURE__*/dual(2, (self, f) => {\n if (isNone(self)) {\n return none();\n }\n const next = f(self.value);\n return result.isSuccess(next) ? some(next.success) : none();\n});\n/**\n * Filters an `Option` using a predicate. Returns `None` if the predicate is\n * not satisfied or the input is `None`.\n *\n * **When to use**\n *\n * Use when you need to discard an `Option`'s present value when it does not\n * meet a condition, while narrowing the type via a refinement predicate.\n *\n * **Details**\n *\n * - `None` → `None`\n * - `Some` where `predicate(value)` is `true` → `Some(value)`\n * - `Some` where `predicate(value)` is `false` → `None`\n * - Supports refinements for type narrowing\n *\n * **Example** (Filtering with a predicate)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * const removeEmpty = (input: Option.Option<string>) =>\n * Option.filter(input, (value) => value !== \"\")\n *\n * removeEmpty(Option.some(\"hello\")) // => Option.some(\"hello\")\n * removeEmpty(Option.some(\"\")) // => Option.none()\n * removeEmpty(Option.none()) // => Option.none()\n * ```\n *\n * @see {@link filterMap} to transform and filter simultaneously\n * @see {@link exists} to test without filtering\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const filter = /*#__PURE__*/dual(2, (self, predicate) => isNone(self) ? none() : predicate(self.value) ? some(self.value) : none());\n/**\n * Creates an `Equivalence` for `Option<A>` from an `Equivalence` for `A`.\n *\n * **When to use**\n *\n * Use when you need equality to treat two `None` values as equal and compare\n * two `Some` values with a supplied equality rule.\n *\n * **Details**\n *\n * - `None` vs `None` → `true`\n * - `Some` vs `None` (or vice versa) → `false`\n * - `Some(a)` vs `Some(b)` → delegates to the provided `Equivalence`\n *\n * **Example** (Comparing Options)\n *\n * ```ts import.meta.vitest\n * import { Equivalence, Option } from \"effect\"\n *\n * const eq = Option.makeEquivalence(Equivalence.strictEqual<number>())\n *\n * eq(Option.some(1), Option.some(1)) // => true\n * eq(Option.some(1), Option.some(2)) // => false\n * eq(Option.none(), Option.none()) // => true\n * ```\n *\n * @category instances\n * @since 4.0.0\n */\nexport const makeEquivalence = isEquivalent => Equivalence.make((x, y) => isNone(x) ? isNone(y) : isNone(y) ? false : isEquivalent(x.value, y.value));\n/**\n * Creates an `Order` for `Option<A>` from an `Order` for `A`.\n *\n * **When to use**\n *\n * Use when you need to sort `Some` and `None` values, with `None` ordered\n * before present values and present values compared by a supplied ordering\n * rule.\n *\n * **Details**\n *\n * - `None` is considered less than any `Some`\n * - Two `Some` values are compared using the provided `Order`\n * - Two `None` values are equal (returns `0`)\n *\n * **Example** (Ordering Options)\n *\n * ```ts import.meta.vitest\n * import { Number as N, Option } from \"effect\"\n *\n * const ord = Option.makeOrder(N.Order)\n *\n * ord(Option.none(), Option.some(1)) // => -1\n * ord(Option.some(1), Option.none()) // => 1\n * ord(Option.some(1), Option.some(2)) // => -1\n * ```\n *\n * @category sorting\n * @since 4.0.0\n */\nexport const makeOrder = O => order.make((self, that) => isSome(self) ? isSome(that) ? O(self.value, that.value) : 1 : -1);\n/**\n * Lifts a binary function to operate on two `Option` values.\n *\n * **When to use**\n *\n * Use when you need to reuse an existing binary function with two `Option`\n * values.\n *\n * **Details**\n *\n * - Both `Some` → applies `f` and wraps in `Some`\n * - Either `None` → `None`\n *\n * **Example** (Lifting addition)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * const addOptions = Option.lift2((a: number, b: number) => a + b)\n *\n * addOptions(Option.some(2), Option.some(3)) // => Option.some(5)\n * addOptions(Option.some(2), Option.none()) // => Option.none()\n * ```\n *\n * @see {@link zipWith} for a non-lifted variant\n *\n * @category lifting\n * @since 2.0.0\n */\nexport const lift2 = f => dual(2, (self, that) => zipWith(self, that, f));\n/**\n * Lifts a `Predicate` or `Refinement` into the `Option` context: returns\n * `Some(value)` when the predicate holds, `None` otherwise.\n *\n * **When to use**\n *\n * Use to convert a boolean check into an `Option`-returning function\n * - Validating input and wrapping it in `Option`\n *\n * **Details**\n *\n * - `predicate(value)` is `true` → `Some(value)`\n * - `predicate(value)` is `false` → `None`\n * - Supports refinements for type narrowing\n *\n * **Example** (Validating positive numbers)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * const parsePositive = Option.liftPredicate((n: number) => n > 0)\n *\n * parsePositive(1) // => Option.some(1)\n * parsePositive(-1) // => Option.none()\n * ```\n *\n * @see {@link filter} to apply a predicate to an existing `Option`\n * @see {@link toRefinement} for the inverse direction\n *\n * @category lifting\n * @since 2.0.0\n */\nexport const liftPredicate = /*#__PURE__*/dual(2, (b, predicate) => predicate(b) ? some(b) : none());\n/**\n * Checks whether an `Option` contains a value equivalent to the given one, using a\n * custom `Equivalence`.\n *\n * **When to use**\n *\n * Use when you need to test whether an `Option` contains a value using a\n * custom equality check.\n *\n * **Details**\n *\n * - `Some` where `isEquivalent(value, a)` is `true` → `true`\n * - `Some` where not equivalent, or `None` → `false`\n *\n * **Example** (Checking with custom equivalence)\n *\n * ```ts import.meta.vitest\n * import { Equivalence, Option } from \"effect\"\n *\n * const check = Option.containsWith(Equivalence.strictEqual<number>())\n *\n * Option.some(2).pipe(check(2)) // => true\n * Option.some(1).pipe(check(2)) // => false\n * Option.none().pipe(check(2)) // => false\n * ```\n *\n * @see {@link contains} for a version using default equality\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const containsWith = isEquivalent => dual(2, (self, a) => isNone(self) ? false : isEquivalent(self.value, a));\n/**\n * Checks whether an `Option` contains a value equal to the given one, using default\n * structural equality.\n *\n * **When to use**\n *\n * Use when you need a quick membership test for an `Option` value using\n * standard equality.\n *\n * **Details**\n *\n * - `Some` where `Equal.equals(value, a)` is `true` → `true`\n * - `Some` where not equal, or `None` → `false`\n *\n * **Example** (Checking containment)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * Option.some(2).pipe(Option.contains(2)) // => true\n * Option.some(1).pipe(Option.contains(2)) // => false\n * Option.none().pipe(Option.contains(2)) // => false\n * ```\n *\n * @see {@link containsWith} for custom equality\n * @see {@link exists} to test with a predicate\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const contains = /*#__PURE__*/containsWith(/*#__PURE__*/Equal.asEquivalence());\n/**\n * Checks whether the value in a `Some` satisfies a predicate or refinement.\n *\n * **When to use**\n *\n * Use to check a condition on an optional value without unwrapping\n *\n * **Details**\n *\n * - `None` → `false`\n * - `Some` where `predicate(value)` is `true` → `true`\n * - `Some` where `predicate(value)` is `false` → `false`\n * - With a refinement, narrows the `Option` type on `true`\n *\n * **Example** (Testing a condition)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * const isEven = (n: number) => n % 2 === 0\n *\n * Option.some(2).pipe(Option.exists(isEven)) // => true\n * Option.some(1).pipe(Option.exists(isEven)) // => false\n * Option.none().pipe(Option.exists(isEven)) // => false\n * ```\n *\n * @see {@link filter} to keep or discard based on a predicate\n * @see {@link contains} to test for a specific value\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const exists = /*#__PURE__*/dual(2, (self, refinement) => isNone(self) ? false : refinement(self.value));\n// -------------------------------------------------------------------------------------\n// do notation\n// -------------------------------------------------------------------------------------\n/**\n * Gives a name to the value of an `Option`, creating a single-key record\n * inside `Some`. Starting point for the do notation pipeline.\n *\n * **When to use**\n *\n * Use when you need to start an `Option` do notation chain by naming the first\n * value.\n *\n * **Example** (Starting do notation)\n *\n * ```ts import.meta.vitest\n * import { Option, pipe } from \"effect\"\n *\n * pipe(\n * Option.some(2),\n * Option.bindTo(\"x\"),\n * Option.bind(\"y\", () => Option.some(3)),\n * Option.let(\"sum\", ({ x, y }) => x + y)\n * ) // => Option.some({ x: 2, y: 3, sum: 5 })\n * ```\n *\n * @see {@link Do} for starting with an empty record\n * @see {@link bind} to add `Option` values\n * @see {@link let_ let} to add plain values\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const bindTo = /*#__PURE__*/doNotation.bindTo(map);\nconst let_ = /*#__PURE__*/doNotation.let_(map);\nexport {\n/**\n * Adds a computed plain value to the do notation record.\n *\n * **When to use**\n *\n * Use when you need to bind a derived non-`Option` value in an `Option` do\n * notation pipeline.\n *\n * **Example** (Adding a computed value)\n *\n * ```ts import.meta.vitest\n * import { Option, pipe } from \"effect\"\n *\n * pipe(\n * Option.Do,\n * Option.bind(\"x\", () => Option.some(2)),\n * Option.bind(\"y\", () => Option.some(3)),\n * Option.let(\"sum\", ({ x, y }) => x + y)\n * ) // => Option.some({ x: 2, y: 3, sum: 5 })\n * ```\n *\n * @see {@link Do} for starting the chain\n * @see {@link bind} to add `Option` values\n * @see {@link bindTo} to start by naming an existing `Option`\n *\n * @category mapping\n * @since 2.0.0\n */\nlet_ as let };\n/**\n * Adds an `Option` value to the do notation record under a given name. If the\n * `Option` is `None`, the whole pipeline short-circuits to `None`.\n *\n * **When to use**\n *\n * Use when you need to sequence `Option` computations in do notation.\n *\n * **Example** (Binding Option values)\n *\n * ```ts import.meta.vitest\n * import { Option, pipe } from \"effect\"\n *\n * pipe(\n * Option.Do,\n * Option.bind(\"x\", () => Option.some(2)),\n * Option.bind(\"y\", () => Option.some(3)),\n * Option.let(\"sum\", ({ x, y }) => x + y),\n * Option.filter(({ x, y }) => x * y > 5)\n * ) // => Option.some({ x: 2, y: 3, sum: 5 })\n * ```\n *\n * @see {@link Do} for starting the chain\n * @see {@link let_ let} to add plain values\n * @see {@link bindTo} to start by naming an existing `Option`\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const bind = /*#__PURE__*/doNotation.bind(map, flatMap);\n/**\n * Provides an `Option` containing an empty record `{}`, used as the starting point for\n * do notation chains.\n *\n * **When to use**\n *\n * Use when you need to start an `Option` do notation pipeline before adding\n * bindings.\n *\n * **Example** (Building Option pipelines with do notation)\n *\n * ```ts import.meta.vitest\n * import { Option, pipe } from \"effect\"\n *\n * pipe(\n * Option.Do,\n * Option.bind(\"x\", () => Option.some(2)),\n * Option.bind(\"y\", () => Option.some(3)),\n * Option.let(\"sum\", ({ x, y }) => x + y),\n * Option.filter(({ x, y }) => x * y > 5)\n * ) // => Option.some({ x: 2, y: 3, sum: 5 })\n * ```\n *\n * @see {@link bind} to add `Option` values\n * @see {@link let_ let} to add plain values\n * @see {@link bindTo} to start by naming an existing `Option`\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const Do = /*#__PURE__*/some({});\n/**\n * Provides generator-based syntax for `Option`, similar to `async`/`await` but for\n * optional values. Yielding a `None` short-circuits the generator to `None`.\n *\n * **When to use**\n *\n * Use when you need generator syntax for a sequence of `Option` steps that\n * should short-circuit on `None`.\n *\n * **Details**\n *\n * - Each `yield*` unwraps a `Some` value or short-circuits to `None`\n * - The return value is wrapped in `Some`\n * - No `Effect` runtime is needed\n *\n * **Example** (Sequencing Option computations with generator syntax)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n *\n * const maybeName: Option.Option<string> = Option.some(\"John\")\n * const maybeAge: Option.Option<number> = Option.some(25)\n *\n * Option.gen(function*() {\n * const name = (yield* maybeName).toUpperCase()\n * const age = yield* maybeAge\n * return { name, age }\n * }) // => Option.some({ name: \"JOHN\", age: 25 })\n * ```\n *\n * @see {@link Do} / {@link bind} for the do notation alternative\n *\n * @category generators\n * @since 2.0.0\n */\nexport const gen = (...args) => {\n const f = args.length === 1 ? args[0] : args[1].bind(args[0]);\n const iterator = f();\n let state = iterator.next();\n while (!state.done) {\n const current = state.value;\n if (isNone(current)) {\n return current;\n }\n state = iterator.next(current.value);\n }\n return some(state.value);\n};\n/**\n * Creates a `Reducer` for `Option<A>` that prioritizes the first non-`None`\n * value and combines values when both are `Some`.\n *\n * **When to use**\n *\n * Use to build an `Option` reducer that falls back to the first available value\n * when either side may be absent.\n *\n * **Details**\n *\n * - `None` + `None` → `None`\n * - `Some(a)` + `None` → `Some(a)`\n * - `None` + `Some(b)` → `Some(b)`\n * - `Some(a)` + `Some(b)` → `Some(combine(a, b))`\n * - Initial value is `None`\n *\n * **Example** (Reducing with first-wins semantics)\n *\n * ```ts import.meta.vitest\n * import { Number, Option } from \"effect\"\n *\n * const reducer = Option.makeReducer(Number.ReducerSum)\n * reducer.combineAll([Option.some(1), Option.none(), Option.some(2)]) // => Option.some(3)\n * ```\n *\n * @see {@link makeReducerFailFast} for fail-fast semantics\n *\n * @category constructors\n * @since 4.0.0\n */\nexport function makeReducer(combiner) {\n return Reducer.make((self, that) => {\n if (isNone(self)) return that;\n if (isNone(that)) return self;\n return some(combiner.combine(self.value, that.value));\n }, none());\n}\n/**\n * Creates a `Combiner` for `Option<A>` with fail-fast semantics: returns `None`\n * if either operand is `None`.\n *\n * **When to use**\n *\n * Use when you need an `Option` combiner that returns `None` unless both\n * operands are `Some`.\n *\n * **Details**\n *\n * - `None` + anything → `None`\n * - anything + `None` → `None`\n * - `Some(a)` + `Some(b)` → `Some(combine(a, b))`\n *\n * **Example** (Fail-fast combining)\n *\n * ```ts import.meta.vitest\n * import { Number, Option } from \"effect\"\n *\n * const combiner = Option.makeCombinerFailFast(Number.ReducerSum)\n * combiner.combine(Option.some(1), Option.some(2)) // => Option.some(3)\n * combiner.combine(Option.some(1), Option.none()) // => Option.none()\n * ```\n *\n * @see {@link makeReducerFailFast} to get a full `Reducer`\n *\n * @category constructors\n * @since 4.0.0\n */\nexport function makeCombinerFailFast(combiner) {\n return Combiner.make((self, that) => {\n if (isNone(self) || isNone(that)) return none();\n return some(combiner.combine(self.value, that.value));\n });\n}\n/**\n * Creates a `Reducer` for `Option<A>` by lifting an existing `Reducer` with\n * fail-fast semantics.\n *\n * **When to use**\n *\n * Use when you need to reduce `Option` values with fail-fast semantics, where\n * any `None` aborts the entire result instead of being skipped.\n *\n * **Details**\n *\n * - Initial value is `Some(reducer.initialValue)`\n * - Combines only when both operands are `Some`\n * - Any `None` causes the result to become `None` immediately\n *\n * **Example** (Fail-fast reducing)\n *\n * ```ts import.meta.vitest\n * import { Number, Option } from \"effect\"\n *\n * const reducer = Option.makeReducerFailFast(Number.ReducerSum)\n * reducer.combineAll([Option.some(1), Option.some(2)]) // => Option.some(3)\n * reducer.combineAll([Option.some(1), Option.none()]) // => Option.none()\n * ```\n *\n * @see {@link makeCombinerFailFast} for just the combiner\n * @see {@link makeReducer} for non-fail-fast semantics\n *\n * @category constructors\n * @since 4.0.0\n */\nexport function makeReducerFailFast(reducer) {\n const combine = makeCombinerFailFast(reducer).combine;\n const initialValue = some(reducer.initialValue);\n return Reducer.make(combine, initialValue, collection => {\n let out = initialValue;\n for (const value of collection) {\n out = combine(out, value);\n if (isNone(out)) return out;\n }\n return out;\n });\n}\n//# sourceMappingURL=Option.js.map","import * as Effectable from \"./Effectable.js\";\nimport * as Equal from \"./Equal.js\";\nimport { dual } from \"./Function.js\";\nimport * as Hash from \"./Hash.js\";\nimport { exitSucceed, PipeInspectableProto, withFiber } from \"./internal/core.js\";\nimport * as Option from \"./Option.js\";\nimport { hasProperty } from \"./Predicate.js\";\n/**\n * Runtime type identifier attached to `Context` service keys and used by\n * `isKey` to recognize them.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const ServiceTypeId = \"~effect/Context/Service\";\n/**\n * Creates a `Context` service key.\n *\n * **When to use**\n *\n * Use when you need to define a context service key for a dependency that must\n * be provided by the surrounding context.\n *\n * **Details**\n *\n * Call `Context.Service(\"Key\")` for a function-style key, or use the two-stage\n * form `Context.Service<Self, Shape>()(\"Key\")` for class-style service\n * declarations. The returned key can be yielded as an Effect and passed to\n * `Context.make`, `Context.add`, and the Context getter functions.\n *\n * **Gotchas**\n *\n * The string key is the runtime identity of the service. Reusing the same key\n * string for unrelated services makes them occupy the same slot in a\n * `Context`.\n *\n * **Example** (Creating service keys)\n *\n * ```ts import.meta.vitest\n * import { Context } from \"effect\"\n *\n * // Create a simple service\n * const Database = Context.Service<{\n * query: (sql: string) => string\n * }>(\"Database\")\n *\n * // Create a service class\n * class Config extends Context.Service<Config, {\n * port: number\n * }>()(\"Config\") {}\n *\n * // Use the services to create contexts\n * const db = Context.make(Database, {\n * query: (sql) => `Result: ${sql}`\n * })\n * const config = Context.make(Config, { port: 8080 })\n * Context.get(db, Database).query(\"SELECT 1\") // => \"Result: SELECT 1\"\n * Context.get(config, Config).port // => 8080\n * ```\n *\n * @see {@link Reference} for service keys with default values\n *\n * @category services\n * @since 4.0.0\n */\nexport const Service = function () {\n function KeyClass() {}\n const self = KeyClass;\n Object.setPrototypeOf(self, ServiceProto);\n const init = (key, options) => {\n self.key = key;\n if (options?.defaultValue) {\n self[ReferenceTypeId] = ReferenceTypeId;\n self.defaultValue = options.defaultValue;\n }\n if (options?.make) {\n ;\n self.make = options.make;\n }\n if (options?.fiberCached) {\n cacheKeys.add(key);\n }\n return self;\n };\n return arguments.length > 0 ? init(arguments[0], arguments[1]) : init;\n};\nconst ServiceProto = {\n [ServiceTypeId]: ServiceTypeId,\n ... /*#__PURE__*/Effectable.Prototype({\n label: \"Service\",\n evaluate(fiber) {\n return exitSucceed(get(fiber.context, this));\n }\n }),\n toJSON() {\n return {\n _id: \"Service\",\n key: this.key\n };\n },\n of(self) {\n return self;\n },\n context(self) {\n return make(this, self);\n },\n use(f) {\n return withFiber(fiber => f(get(fiber.context, this)));\n },\n useSync(f) {\n return withFiber(fiber => exitSucceed(f(get(fiber.context, this))));\n }\n};\nconst cacheKeys = /*#__PURE__*/new Set();\nconst ReferenceTypeId = \"~effect/Context/Reference\";\nconst TypeId = \"~effect/Context\";\nconst MaxDepth = 8;\nconst FlattenAfterBaseHits = 8;\nconst makeImpl = (cacheRoot, base, overlay, depth) => {\n const self = Object.create(Proto);\n self.cacheRoot = cacheRoot ?? self;\n self.base = base;\n self.overlay = overlay;\n self.depth = depth;\n self._flat = undefined;\n self.baseHits = 0;\n return self;\n};\nconst applyOverlays = (map, overlay) => {\n if (!overlay) return;\n applyOverlays(map, overlay.parent);\n map.set(overlay.key, overlay.value);\n};\nconst flatten = self => {\n if (self._flat) return self._flat;\n if (!self.overlay) return self._flat = self.base;\n const map = new Map(self.base);\n applyOverlays(map, self.overlay);\n return self._flat = map;\n};\nconst withFlat = (self, f) => {\n const map = new Map(self.mapUnsafe);\n f(map);\n return makeUnsafe(map);\n};\n// A private symbol so user code cannot forge a value that reads as absent\nconst notFound = /*#__PURE__*/Symbol();\nconst lookup = (self, key) => {\n const impl = self;\n for (let overlay = impl.overlay; overlay; overlay = overlay.parent) {\n if (overlay.key === key) return overlay.value;\n }\n const value = impl.base.get(key);\n // Misses must not advance the counter: reference-default lookups miss the\n // base on every fiber cache refresh, which would flatten every short-lived\n // request context and reintroduce the O(services) per-request cost\n if (value === undefined && !impl.base.has(key)) return notFound;\n if (impl.overlay && ++impl.baseHits >= FlattenAfterBaseHits) {\n impl.base = flatten(impl);\n impl.overlay = undefined;\n impl.depth = 0;\n }\n return value;\n};\n/**\n * Creates a `Context` from an existing service map.\n *\n * **When to use**\n *\n * Use when constructing a low-level `Context` from a trusted map whose lifecycle\n * you control.\n *\n * **Gotchas**\n *\n * The provided map is retained without copying and must not be mutated after\n * construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context\n * construction.\n *\n * **Example** (Creating a context from a map)\n *\n * ```ts import.meta.vitest\n * import { Context } from \"effect\"\n *\n * // Create a context from a Map (unsafe)\n * const map = new Map([\n * [\"Logger\", { log: (_msg: string) => {} }]\n * ])\n *\n * const context = Context.makeUnsafe(map)\n * context.mapUnsafe.size // => 1\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeUnsafe = mapUnsafe => makeImpl(undefined, mapUnsafe, undefined, 0);\nconst Proto = {\n get mapUnsafe() {\n return flatten(this);\n },\n ...PipeInspectableProto,\n [TypeId]: {\n _Services: _ => _\n },\n toJSON() {\n return {\n _id: \"Context\",\n services: Array.from(this.mapUnsafe).map(([key, value]) => ({\n key,\n value\n }))\n };\n },\n [Equal.symbol](that) {\n if (!isContext(that)) return false;\n const self = this.mapUnsafe;\n const other = that.mapUnsafe;\n if (self.size !== other.size) return false;\n for (const [key, value] of self) {\n if (!other.has(key) || !Equal.equals(value, other.get(key))) return false;\n }\n return true;\n },\n [Hash.symbol]() {\n return Hash.number(this.mapUnsafe.size);\n }\n};\n/** @internal */\nexport const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot;\n/**\n * Checks whether the provided argument is a `Context`.\n *\n * **When to use**\n *\n * Use to narrow an unknown value before passing it to APIs that require a\n * `Context`.\n *\n * **Details**\n *\n * This checks the runtime `Context` marker and does not inspect which services\n * the context contains.\n *\n * **Gotchas**\n *\n * This guard only proves that the value is a `Context`; it does not prove that\n * any specific service is present.\n *\n * **Example** (Checking for contexts)\n *\n * ```ts import.meta.vitest\n * import { Context } from \"effect\"\n * Context.isContext(Context.empty()) // => true\n * ```\n *\n * @see {@link isKey} for checking service keys\n * @see {@link isReference} for checking references with defaults\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isContext = u => hasProperty(u, TypeId);\n/**\n * Checks whether the provided argument is a `Key`.\n *\n * **Example** (Checking for keys)\n *\n * ```ts import.meta.vitest\n * import { Context } from \"effect\"\n * Context.isKey(Context.Service(\"Service\")) // => true\n * ```\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isKey = u => hasProperty(u, ServiceTypeId);\n/**\n * Checks whether the provided argument is a `Reference`.\n *\n * **Example** (Checking for references)\n *\n * ```ts import.meta.vitest\n * import { Context } from \"effect\"\n *\n * const LoggerRef = Context.Reference(\"Logger\", {\n * defaultValue: () => ({ log: (_msg: string) => {} })\n * })\n *\n * Context.isReference(LoggerRef) // => true\n * Context.isReference(Context.Service(\"Key\")) // => false\n * ```\n *\n * @category guards\n * @since 3.11.0\n */\nexport const isReference = u => !!u[ReferenceTypeId];\n/**\n * Returns an empty `Context`.\n *\n * **Example** (Creating an empty context)\n *\n * ```ts import.meta.vitest\n * import { Context } from \"effect\"\n * Context.empty().mapUnsafe.size // => 0\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const empty = () => emptyContext;\nconst emptyContext = /*#__PURE__*/makeUnsafe(/*#__PURE__*/new Map());\n/**\n * Creates a new `Context` with a single service associated to the key.\n *\n * **Example** (Creating a context with one service)\n *\n * ```ts import.meta.vitest\n * import { Context } from \"effect\"\n *\n * const Port = Context.Service<{ PORT: number }>(\"Port\")\n *\n * const context = Context.make(Port, { PORT: 8080 })\n *\n * Context.get(context, Port).PORT // => 8080\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const make = (key, service) => makeUnsafe(new Map([[key.key, service]]));\n/**\n * Adds a service to a given `Context`.\n *\n * **When to use**\n *\n * Use when you need to store a known service value in a `Context`.\n *\n * **Details**\n *\n * If the context already contains the same service key, the new service\n * replaces the previous one.\n *\n * **Example** (Adding a service to a context)\n *\n * ```ts import.meta.vitest\n * import { Context, pipe } from \"effect\"\n *\n * const Port = Context.Service<{ PORT: number }>(\"Port\")\n * const Timeout = Context.Service<{ TIMEOUT: number }>(\"Timeout\")\n *\n * const someContext = Context.make(Port, { PORT: 8080 })\n *\n * const context = pipe(\n * someContext,\n * Context.add(Timeout, { TIMEOUT: 5000 })\n * )\n *\n * const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT]\n * values // => [8080, 5000]\n * ```\n *\n * @see {@link addOrOmit} for adding or removing a service from an `Option`\n *\n * @category combining\n * @since 2.0.0\n */\nexport const add = /*#__PURE__*/dual(3, (self, key, service) => addUnsafe(self, key.key, service));\n/**\n * Adds a service by key to a given `Context` using a string key.\n *\n * @category combining\n * @since 4.0.0\n */\nexport const addUnsafe = (self, key, service) => {\n const impl = self;\n const cacheRoot = cacheKeys.has(key) ? undefined : impl.cacheRoot;\n if (impl.depth >= MaxDepth) {\n // Rebase the overlay chain into a flat map, keeping the cacheRoot so a\n // rebase on an ordinary key does not invalidate fiber caches\n const map = new Map(impl.mapUnsafe);\n map.set(key, service);\n return makeImpl(cacheRoot, map, undefined, 0);\n }\n return makeImpl(cacheRoot, impl.base, {\n key,\n value: service,\n parent: impl.overlay\n }, impl.depth + 1);\n};\n/**\n * Adds or removes a service depending on an `Option`.\n *\n * **When to use**\n *\n * Use when you need to add or omit a `Context` service based on an `Option`.\n *\n * **Details**\n *\n * When `service` is `Option.some`, the value is stored for the key. When it is\n * `Option.none`, the key is removed from the returned `Context`.\n *\n * **Example** (Adding optional services)\n *\n * ```ts import.meta.vitest\n * import { Context, Option } from \"effect\"\n *\n * const Port = Context.Service<{ PORT: number }>(\"Port\")\n *\n * const withPort = Context.empty().pipe(\n * Context.addOrOmit(Port, Option.some({ PORT: 8080 }))\n * )\n *\n * const withoutPort = withPort.pipe(\n * Context.addOrOmit(Port, Option.none())\n * )\n * Context.getOption(withPort, Port) // => Option.some({ PORT: 8080 })\n * Context.getOption(withoutPort, Port) // => Option.none()\n * ```\n *\n * @see {@link add} for always storing a service value\n *\n * @category combining\n * @since 4.0.0\n */\nexport const addOrOmit = /*#__PURE__*/dual(3, (self, key, service) => service._tag === \"None\" ? omit(key)(self) : add(self, key, service.value));\n/**\n * Gets the service for a key, or evaluates the fallback when a non-reference\n * key is absent.\n *\n * **When to use**\n *\n * Use when you need a fallback for a missing `Context.Service` key while still\n * resolving `Context.Reference` defaults.\n *\n * **Details**\n *\n * If the key is a `Context.Reference` and no override is stored in the\n * context, its cached default value is returned instead of the fallback.\n *\n * **Gotchas**\n *\n * The fallback is not evaluated for missing `Context.Reference` keys because\n * references resolve to their default value.\n *\n * **Example** (Falling back for missing services)\n *\n * ```ts import.meta.vitest\n * import { Context } from \"effect\"\n *\n * const Logger = Context.Service<{ log: (msg: string) => void }>(\"Logger\")\n * const Database = Context.Service<{ query: (sql: string) => string }>(\n * \"Database\"\n * )\n *\n * const context = Context.make(Logger, { log: (_msg: string) => {} })\n *\n * const logger = Context.getOrElse(context, Logger, () => ({ log: () => {} }))\n * const database = Context.getOrElse(\n * context,\n * Database,\n * () => ({ query: () => \"fallback\" })\n * )\n *\n * logger === Context.get(context, Logger) // => true\n * database.query(\"SELECT 1\") // => \"fallback\"\n * ```\n *\n * @see {@link getOption} for returning `Option.none` when a non-reference key is missing\n *\n * @category getters\n * @since 3.7.0\n */\nexport const getOrElse = /*#__PURE__*/dual(3, (self, key, orElse) => {\n const value = lookup(self, key.key);\n if (value !== notFound) return value;\n return isReference(key) ? getDefaultValue(key) : orElse();\n});\n/**\n * Returns the service currently stored for a key, or `undefined` when the key\n * is absent.\n *\n * **When to use**\n *\n * Use when you need to read the service stored for a key without resolving\n * `Context.Reference` defaults.\n *\n * **Gotchas**\n *\n * This is a raw lookup and does not resolve default values for\n * `Context.Reference` keys.\n *\n * @see {@link getOption} for a reference-aware optional lookup\n *\n * @category getters\n * @since 4.0.0\n */\nexport const getOrUndefined = /*#__PURE__*/dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key));\n/** @internal */\nexport const getOrUndefinedUnsafe = (self, key) => {\n const value = lookup(self, key);\n return value === notFound ? undefined : value;\n};\n/**\n * Gets the service for a key, throwing if an absent non-reference key cannot be\n * resolved.\n *\n * **When to use**\n *\n * Use when you need to read a service from a context whose type does not prove\n * the service is present.\n *\n * **Details**\n *\n * If the key is a `Context.Reference` and no override is stored in the\n * context, its cached default value is returned. For absent non-reference keys,\n * this function throws a runtime error.\n *\n * **Example** (Getting services unsafely)\n *\n * ```ts import.meta.vitest\n * import { Context, Option } from \"effect\"\n *\n * const Port = Context.Service<{ PORT: number }>(\"Port\")\n * const Timeout = Context.Service<{ TIMEOUT: number }>(\"Timeout\")\n *\n * const context = Context.make(Port, { PORT: 8080 })\n *\n * Context.getUnsafe(context, Port).PORT // => 8080\n * Context.getOption(context, Timeout) // => Option.none()\n * ```\n *\n * @see {@link get} for type-checked service access\n * @see {@link getOption} for optional service access\n *\n * @category unsafe\n * @since 4.0.0\n */\nexport const getUnsafe = /*#__PURE__*/dual(2, (self, service) => {\n const value = lookup(self, service.key);\n if (value === notFound) {\n if (isReference(service)) return getDefaultValue(service);\n throw serviceNotFoundError(service);\n }\n return value;\n});\n/**\n * Gets a service from the context that corresponds to the given key.\n *\n * **When to use**\n *\n * Use when you need type-checked access to a service already included in the\n * context type.\n *\n * **Example** (Getting a service from a context)\n *\n * ```ts import.meta.vitest\n * import { Context, pipe } from \"effect\"\n *\n * const Port = Context.Service<{ PORT: number }>(\"Port\")\n * const Timeout = Context.Service<{ TIMEOUT: number }>(\"Timeout\")\n *\n * const context = pipe(\n * Context.make(Port, { PORT: 8080 }),\n * Context.add(Timeout, { TIMEOUT: 5000 })\n * )\n *\n * Context.get(context, Timeout).TIMEOUT // => 5000\n * ```\n *\n * @see {@link getOption} for optional service access\n * @see {@link getOrElse} for fallback values\n *\n * @category getters\n * @since 2.0.0\n */\nexport const get = getUnsafe;\nconst defaultValueCacheKey = \"~effect/Context/defaultValue\";\nconst getDefaultValue = ref => {\n if (defaultValueCacheKey in ref) {\n return ref[defaultValueCacheKey];\n }\n return ref[defaultValueCacheKey] = ref.defaultValue();\n};\nconst serviceNotFoundError = service => {\n const error = new Error(`Service not found${service.key ? `: ${String(service.key)}` : \"\"}`);\n if (error.stack) {\n const lines = error.stack.split(\"\\n\");\n lines.splice(1, 3);\n error.stack = lines.join(\"\\n\");\n }\n return error;\n};\n/**\n * Gets the service for a key safely wrapped in an `Option`.\n *\n * **When to use**\n *\n * Use when you need to read a `Context` service as an `Option` so absence is\n * represented as data.\n *\n * **Details**\n *\n * Returns `Option.some` when the service is stored in the context. If the key\n * is a `Context.Reference` and no override is stored, returns `Option.some` of\n * the cached default value. Missing non-reference keys return `Option.none`.\n *\n * **Example** (Getting optional services)\n *\n * ```ts import.meta.vitest\n * import { Context, Option } from \"effect\"\n *\n * const Port = Context.Service<{ PORT: number }>(\"Port\")\n * const Timeout = Context.Service<{ TIMEOUT: number }>(\"Timeout\")\n *\n * const context = Context.make(Port, { PORT: 8080 })\n *\n * Context.getOption(context, Port) // => Option.some({ PORT: 8080 })\n * Context.getOption(context, Timeout) // => Option.none()\n * ```\n *\n * @see {@link getOrElse} for returning a fallback value directly\n *\n * @category getters\n * @since 2.0.0\n */\nexport const getOption = /*#__PURE__*/dual(2, (self, service) => {\n const value = lookup(self, service.key);\n if (value !== notFound) return Option.some(value);\n return isReference(service) ? Option.some(getDefaultValue(service)) : Option.none();\n});\n/**\n * Merges two `Context`s into one.\n *\n * **When to use**\n *\n * Use when you need to combine two contexts.\n *\n * **Details**\n *\n * When both contexts contain the same service key, the service from `that`\n * overrides the service from `self`.\n *\n * **Example** (Merging two contexts)\n *\n * ```ts import.meta.vitest\n * import { Context } from \"effect\"\n *\n * const Port = Context.Service<{ PORT: number }>(\"Port\")\n * const Timeout = Context.Service<{ TIMEOUT: number }>(\"Timeout\")\n *\n * const firstContext = Context.make(Port, { PORT: 8080 })\n * const secondContext = Context.make(Timeout, { TIMEOUT: 5000 })\n *\n * const context = Context.merge(firstContext, secondContext)\n *\n * const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT]\n * values // => [8080, 5000]\n * ```\n *\n * @see {@link mergeAll} for merging more than two contexts at once\n *\n * @category combining\n * @since 2.0.0\n */\nexport const merge = /*#__PURE__*/dual(2, (self, that) => {\n if (self.mapUnsafe.size === 0) return that;\n if (that.mapUnsafe.size === 0) return self;\n return withFlat(self, map => that.mapUnsafe.forEach((value, key) => map.set(key, value)));\n});\n/**\n * Merges any number of `Context`s into one.\n *\n * **When to use**\n *\n * Use when you need to combine a variadic list of contexts.\n *\n * **Details**\n *\n * When multiple contexts contain the same service key, the service from the\n * last context with that key is kept.\n *\n * **Example** (Merging multiple contexts)\n *\n * ```ts import.meta.vitest\n * import { Context } from \"effect\"\n *\n * const Port = Context.Service<{ PORT: number }>(\"Port\")\n * const Timeout = Context.Service<{ TIMEOUT: number }>(\"Timeout\")\n * const Host = Context.Service<{ HOST: string }>(\"Host\")\n *\n * const firstContext = Context.make(Port, { PORT: 8080 })\n * const secondContext = Context.make(Timeout, { TIMEOUT: 5000 })\n * const thirdContext = Context.make(Host, { HOST: \"localhost\" })\n *\n * const context = Context.mergeAll(\n * firstContext,\n * secondContext,\n * thirdContext\n * )\n *\n * context.mapUnsafe.size // => 3\n * ```\n *\n * @see {@link merge} for merging two contexts\n *\n * @category combining\n * @since 3.12.0\n */\nexport const mergeAll = (...ctxs) => {\n const map = new Map();\n for (let i = 0; i < ctxs.length; i++) {\n ctxs[i].mapUnsafe.forEach((value, key) => {\n map.set(key, value);\n });\n }\n return makeUnsafe(map);\n};\n/**\n * Returns a new `Context` that contains only the specified services.\n *\n * **When to use**\n *\n * Use when you want to keep an allowlist of services in a `Context`.\n *\n * **Example** (Picking services from a context)\n *\n * ```ts import.meta.vitest\n * import { Context, Option, pipe } from \"effect\"\n *\n * const Port = Context.Service<{ PORT: number }>(\"Port\")\n * const Timeout = Context.Service<{ TIMEOUT: number }>(\"Timeout\")\n *\n * const someContext = pipe(\n * Context.make(Port, { PORT: 8080 }),\n * Context.add(Timeout, { TIMEOUT: 5000 })\n * )\n *\n * const context = pipe(someContext, Context.pick(Port))\n *\n * Context.getOption(context, Port) // => Option.some({ PORT: 8080 })\n * Context.getOption(context, Timeout) // => Option.none()\n * ```\n *\n * @see {@link omit} for removing selected services\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const pick = (...services) => self => {\n const keep = new Set(services.map(key => key.key));\n return withFlat(self, map => map.forEach((_, key) => {\n if (!keep.has(key)) map.delete(key);\n }));\n};\n/**\n * Returns a new `Context` with the specified service keys removed.\n *\n * **When to use**\n *\n * Use when you want to remove a denylist of services from a `Context`.\n *\n * **Example** (Omitting services from a context)\n *\n * ```ts import.meta.vitest\n * import { Context, Option, pipe } from \"effect\"\n *\n * const Port = Context.Service<{ PORT: number }>(\"Port\")\n * const Timeout = Context.Service<{ TIMEOUT: number }>(\"Timeout\")\n *\n * const someContext = pipe(\n * Context.make(Port, { PORT: 8080 }),\n * Context.add(Timeout, { TIMEOUT: 5000 })\n * )\n *\n * const context = pipe(someContext, Context.omit(Timeout))\n *\n * Context.getOption(context, Port) // => Option.some({ PORT: 8080 })\n * Context.getOption(context, Timeout) // => Option.none()\n * ```\n *\n * @see {@link pick} for keeping selected services\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const omit = (...keys) => self => withFlat(self, map => {\n for (let i = 0; i < keys.length; i++) {\n map.delete(keys[i].key);\n }\n});\n/**\n * Creates a context key with a default value.\n *\n * **When to use**\n *\n * Use when you need to define a context key with a lazily computed default\n * value.\n *\n * **Details**\n *\n * `Context.Reference` allows you to create a key that can hold a value. You\n * can provide a default value for the service, which will automatically be used\n * when the context is accessed, or override it with a custom implementation\n * when needed. The default value is computed lazily and cached on the\n * reference.\n *\n * **Example** (Creating references with default values)\n *\n * ```ts import.meta.vitest\n * import { Context } from \"effect\"\n *\n * // Create a reference with a default value\n * const messages: Array<string> = []\n * const LoggerRef = Context.Reference(\"Logger\", {\n * defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) })\n * })\n *\n * // The reference provides the default value when accessed from an empty context\n * const context = Context.empty()\n * const logger = Context.get(context, LoggerRef)\n *\n * // You can also override the default value\n * const customContext = Context.make(LoggerRef, {\n * log: (msg: string) => messages.push(`Custom: ${msg}`)\n * })\n * const customLogger = Context.get(customContext, LoggerRef)\n * logger.log(\"default\")\n * customLogger.log(\"message\")\n * messages // => [\"Default: default\", \"Custom: message\"]\n * ```\n *\n * @see {@link Service} for required services without default values\n *\n * @category services\n * @since 3.11.0\n */\nexport const Reference = Service;\n//# sourceMappingURL=Context.js.map","/**\n * Represents immutable spans of time.\n *\n * A `Duration` can be finite, positive infinity, or negative infinity. It is\n * the standard representation for delays, timeouts, intervals, and\n * time-to-live values across Effect APIs. This module includes constructors\n * from common input shapes, unit conversions, comparisons, arithmetic,\n * formatting, and reusable reducer or combiner helpers.\n *\n * @since 2.0.0\n */\nimport * as Combiner from \"./Combiner.js\";\nimport * as Equal from \"./Equal.js\";\nimport { dual, identity } from \"./Function.js\";\nimport * as Hash from \"./Hash.js\";\nimport { NodeInspectSymbol } from \"./Inspectable.js\";\nimport * as Option from \"./Option.js\";\nimport * as order from \"./Order.js\";\nimport { pipeArguments } from \"./Pipeable.js\";\nimport { hasProperty, isNumber } from \"./Predicate.js\";\nimport * as Reducer from \"./Reducer.js\";\nconst TypeId = \"~effect/Duration\";\nconst bigint0 = /*#__PURE__*/BigInt(0);\nconst bigint1 = /*#__PURE__*/BigInt(1);\nconst bigint2 = /*#__PURE__*/BigInt(2);\nconst bigint10 = /*#__PURE__*/BigInt(10);\nconst bigint24 = /*#__PURE__*/BigInt(24);\nconst bigint60 = /*#__PURE__*/BigInt(60);\nconst bigint1e3 = /*#__PURE__*/BigInt(1_000);\nconst bigint1e6 = /*#__PURE__*/BigInt(1_000_000);\nconst bigint1e9 = /*#__PURE__*/BigInt(1_000_000_000);\nconst roundTiesAwayFromZero = input => BigInt(input < 0 ? Math.ceil(input - 0.5) : Math.floor(input + 0.5));\nconst roundMillisToNanos = millis => roundTiesAwayFromZero(millis * 1_000_000);\nconst parseNanos = (input, scale) => {\n const decimalIndex = input.indexOf(\".\");\n if (decimalIndex === -1) return BigInt(input) * scale;\n const isNegative = input[0] === \"-\";\n const fractional = input.slice(decimalIndex + 1);\n const fractionalScale = bigint10 ** BigInt(fractional.length);\n const scaled = (BigInt(input.slice(isNegative ? 1 : 0, decimalIndex)) * fractionalScale + BigInt(fractional)) * scale;\n const rounded = scaled / fractionalScale + (scaled % fractionalScale * bigint2 >= fractionalScale ? bigint1 : bigint0);\n return isNegative ? -rounded : rounded;\n};\nconst nanosToHrTime = nanos => {\n const sign = nanos < bigint0 ? -bigint1 : bigint1;\n const absolute = nanos < bigint0 ? -nanos : nanos;\n return [Number(sign * (absolute / bigint1e9)), Number(sign * (absolute % bigint1e9))];\n};\nconst DURATION_REGEXP = /^(-?\\d+(?:\\.\\d+)?)\\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/;\n/**\n * Decodes a `Duration.Input` into a `Duration`.\n *\n * **When to use**\n *\n * Use when the input has already been validated or comes from a trusted source\n * and throwing is acceptable for invalid duration syntax.\n *\n * **Gotchas**\n *\n * If the input is not a valid `Duration.Input`, it throws an error.\n *\n * **Example** (Decoding duration inputs)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.fromInputUnsafe(1000) // => Duration.millis(1000)\n * Duration.fromInputUnsafe(\"5 seconds\") // => Duration.seconds(5)\n * Duration.fromInputUnsafe(\"Infinity\") // => Duration.infinity\n * Duration.fromInputUnsafe([2, 500_000_000]) // => Duration.nanos(2_500_000_000n)\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromInputUnsafe = input => {\n switch (typeof input) {\n case \"number\":\n return millis(input);\n case \"bigint\":\n return nanos(input);\n case \"string\":\n {\n if (input === \"Infinity\") {\n return infinity;\n }\n if (input === \"-Infinity\") {\n return negativeInfinity;\n }\n const match = DURATION_REGEXP.exec(input);\n if (!match) break;\n const [_, valueStr, unit] = match;\n if (unit === \"nano\" || unit === \"nanos\") {\n return nanos(parseNanos(valueStr, bigint1));\n }\n if (unit === \"micro\" || unit === \"micros\") {\n return nanos(parseNanos(valueStr, bigint1e3));\n }\n const value = Number(valueStr);\n switch (unit) {\n case \"milli\":\n case \"millis\":\n return millis(value);\n case \"second\":\n case \"seconds\":\n return seconds(value);\n case \"minute\":\n case \"minutes\":\n return minutes(value);\n case \"hour\":\n case \"hours\":\n return hours(value);\n case \"day\":\n case \"days\":\n return days(value);\n case \"week\":\n case \"weeks\":\n return weeks(value);\n }\n break;\n }\n case \"object\":\n {\n if (input === null) break;\n if (TypeId in input) return input;\n if (Array.isArray(input)) {\n if (input.length !== 2 || !input.every(isNumber)) {\n return invalid(input);\n }\n if (Number.isNaN(input[0]) || Number.isNaN(input[1])) {\n return zero;\n }\n if (input[0] === -Infinity || input[1] === -Infinity) {\n return negativeInfinity;\n }\n if (input[0] === Infinity || input[1] === Infinity) {\n return infinity;\n }\n return make(roundTiesAwayFromZero(input[0] * 1_000_000_000 + input[1]));\n }\n const obj = input;\n let millis = 0;\n // we can use truthy checks here, because 0 can be ignored\n if (obj.weeks) millis += obj.weeks * 604_800_000;\n if (obj.days) millis += obj.days * 86_400_000;\n if (obj.hours) millis += obj.hours * 3_600_000;\n if (obj.minutes) millis += obj.minutes * 60_000;\n if (obj.seconds) millis += obj.seconds * 1_000;\n if (obj.milliseconds) millis += obj.milliseconds;\n if (!obj.microseconds && !obj.nanoseconds) return make(millis);\n return make(roundTiesAwayFromZero(millis * 1_000_000 + (obj.microseconds ?? 0) * 1_000 + (obj.nanoseconds ?? 0)));\n }\n }\n return invalid(input);\n};\nconst invalid = input => {\n throw new Error(`Invalid Input: ${input}`);\n};\n/**\n * Decodes a `Input` value into a `Duration` safely, returning\n * `Option.none()` if decoding fails.\n *\n * **Example** (Safely decoding duration inputs)\n *\n * ```ts import.meta.vitest\n * import { Duration, Option } from \"effect\"\n *\n * Duration.fromInput(1000) // => Option.some(Duration.seconds(1))\n * Duration.fromInput(\"invalid\" as any) // => Option.none()\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromInput = /*#__PURE__*/Option.liftThrowable(fromInputUnsafe);\nconst zeroDurationValue = {\n _tag: \"Millis\",\n millis: 0\n};\nconst infinityDurationValue = {\n _tag: \"Infinity\"\n};\nconst negativeInfinityDurationValue = {\n _tag: \"NegativeInfinity\"\n};\nconst DurationProto = {\n [TypeId]: TypeId,\n [Hash.symbol]() {\n // Hash equal finite durations using the same canonical nanoseconds\n // representation used by `equals`.\n switch (this.value._tag) {\n case \"Millis\":\n {\n const nanos = this.value.millis * 1_000_000;\n return Number.isFinite(nanos) ? Hash.hash(roundTiesAwayFromZero(nanos)) : Hash.number(this.value.millis);\n }\n case \"Nanos\":\n return Hash.hash(this.value.nanos);\n default:\n return Hash.structure(this.value);\n }\n },\n [Equal.symbol](that) {\n return isDuration(that) && equals(this, that);\n },\n toString() {\n switch (this.value._tag) {\n case \"Infinity\":\n return \"Infinity\";\n case \"NegativeInfinity\":\n return \"-Infinity\";\n case \"Nanos\":\n return `${this.value.nanos} nanos`;\n case \"Millis\":\n return `${this.value.millis} millis`;\n }\n },\n toJSON() {\n switch (this.value._tag) {\n case \"Millis\":\n return {\n _id: \"Duration\",\n _tag: \"Millis\",\n millis: this.value.millis\n };\n case \"Nanos\":\n return {\n _id: \"Duration\",\n _tag: \"Nanos\",\n nanos: String(this.value.nanos)\n };\n case \"Infinity\":\n return {\n _id: \"Duration\",\n _tag: \"Infinity\"\n };\n case \"NegativeInfinity\":\n return {\n _id: \"Duration\",\n _tag: \"NegativeInfinity\"\n };\n }\n },\n [NodeInspectSymbol]() {\n return this.toJSON();\n },\n pipe() {\n return pipeArguments(this, arguments);\n }\n};\nconst make = input => {\n const duration = Object.create(DurationProto);\n if (typeof input === \"number\") {\n if (isNaN(input) || input === 0 || Object.is(input, -0)) {\n duration.value = zeroDurationValue;\n } else if (!Number.isFinite(input)) {\n duration.value = input > 0 ? infinityDurationValue : negativeInfinityDurationValue;\n } else if (!Number.isInteger(input)) {\n duration.value = {\n _tag: \"Nanos\",\n nanos: roundMillisToNanos(input)\n };\n } else {\n duration.value = {\n _tag: \"Millis\",\n millis: input\n };\n }\n } else if (input === bigint0) {\n duration.value = zeroDurationValue;\n } else {\n duration.value = {\n _tag: \"Nanos\",\n nanos: input\n };\n }\n return duration;\n};\n/**\n * Checks whether a value is a Duration.\n *\n * **Example** (Checking for durations)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.isDuration(Duration.seconds(1)) // => true\n * Duration.isDuration(1000) // => false\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isDuration = u => hasProperty(u, TypeId);\n/**\n * Checks whether a Duration is finite (not infinite).\n *\n * **Example** (Checking finite durations)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.isFinite(Duration.seconds(5)) // => true\n * Duration.isFinite(Duration.infinity) // => false\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const isFinite = self => self.value._tag !== \"Infinity\" && self.value._tag !== \"NegativeInfinity\";\n/**\n * Checks whether a Duration is zero.\n *\n * **Example** (Checking for zero durations)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.isZero(Duration.zero) // => true\n * Duration.isZero(Duration.seconds(1)) // => false\n * ```\n *\n * @category predicates\n * @since 3.5.0\n */\nexport const isZero = self => {\n switch (self.value._tag) {\n case \"Millis\":\n return self.value.millis === 0;\n case \"Nanos\":\n return self.value.nanos === bigint0;\n case \"Infinity\":\n case \"NegativeInfinity\":\n return false;\n }\n};\n/**\n * Returns `true` if the duration is negative (strictly less than zero).\n *\n * **Example** (Checking for negative durations)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.isNegative(Duration.seconds(-5)) // => true\n * Duration.isNegative(Duration.zero) // => false\n * Duration.isNegative(Duration.negativeInfinity) // => true\n * ```\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isNegative = self => {\n switch (self.value._tag) {\n case \"Millis\":\n return self.value.millis < 0;\n case \"Nanos\":\n return self.value.nanos < bigint0;\n case \"NegativeInfinity\":\n return true;\n case \"Infinity\":\n return false;\n }\n};\n/**\n * Returns `true` if the duration is positive (strictly greater than zero).\n *\n * **Example** (Checking for positive durations)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.isPositive(Duration.seconds(5)) // => true\n * Duration.isPositive(Duration.zero) // => false\n * Duration.isPositive(Duration.infinity) // => true\n * ```\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isPositive = self => {\n switch (self.value._tag) {\n case \"Millis\":\n return self.value.millis > 0;\n case \"Nanos\":\n return self.value.nanos > bigint0;\n case \"Infinity\":\n return true;\n case \"NegativeInfinity\":\n return false;\n }\n};\n/**\n * Returns the absolute value of the duration.\n *\n * **Example** (Taking absolute duration values)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.abs(Duration.seconds(-5)) // => Duration.seconds(5)\n * Duration.abs(Duration.negativeInfinity) // => Duration.infinity\n * ```\n *\n * @category math\n * @since 4.0.0\n */\nexport const abs = self => {\n switch (self.value._tag) {\n case \"Infinity\":\n case \"NegativeInfinity\":\n return infinity;\n case \"Millis\":\n return self.value.millis < 0 ? make(-self.value.millis) : self;\n case \"Nanos\":\n return self.value.nanos < bigint0 ? make(-self.value.nanos) : self;\n }\n};\n/**\n * Returns the negated duration.\n *\n * **Example** (Negating durations)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.negate(Duration.seconds(5)) // => Duration.seconds(-5)\n * Duration.negate(Duration.infinity) // => Duration.negativeInfinity\n * ```\n *\n * @category math\n * @since 4.0.0\n */\nexport const negate = self => {\n switch (self.value._tag) {\n case \"Infinity\":\n return negativeInfinity;\n case \"NegativeInfinity\":\n return infinity;\n case \"Millis\":\n return self.value.millis === 0 ? self : make(-self.value.millis);\n case \"Nanos\":\n return self.value.nanos === bigint0 ? self : make(-self.value.nanos);\n }\n};\n/**\n * A Duration representing zero time.\n *\n * **Example** (Referencing the zero duration)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.toMillis(Duration.zero) // => 0\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const zero = /*#__PURE__*/make(0);\n/**\n * A Duration representing infinite time.\n *\n * **Example** (Referencing infinite duration)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.toMillis(Duration.infinity) // => Infinity\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const infinity = /*#__PURE__*/make(Infinity);\n/**\n * A Duration representing negative infinite time.\n *\n * **Example** (Referencing negative infinite duration)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.toMillis(Duration.negativeInfinity) // => -Infinity\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const negativeInfinity = /*#__PURE__*/make(-Infinity);\n/**\n * Creates a Duration from nanoseconds.\n *\n * **Example** (Creating durations from nanoseconds)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.nanos(500_000_000n) // => Duration.nanos(500_000_000n)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const nanos = nanos => make(nanos);\n/**\n * Creates a Duration from microseconds.\n *\n * **Example** (Creating durations from microseconds)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.micros(500_000n) // => Duration.nanos(500_000_000n)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const micros = micros => make(micros * bigint1e3);\n/**\n * Creates a Duration from milliseconds.\n *\n * **Example** (Creating durations from milliseconds)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.toMillis(Duration.millis(1000)) // => 1000\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const millis = millis => make(millis);\n/**\n * Creates a Duration from seconds.\n *\n * **Example** (Creating durations from seconds)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.toMillis(Duration.seconds(30)) // => 30_000\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const seconds = seconds => make(seconds * 1000);\n/**\n * Creates a Duration from minutes.\n *\n * **Example** (Creating durations from minutes)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.toMillis(Duration.minutes(5)) // => 300_000\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const minutes = minutes => make(minutes * 60_000);\n/**\n * Creates a Duration from hours.\n *\n * **Example** (Creating durations from hours)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.toMillis(Duration.hours(2)) // => 7_200_000\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const hours = hours => make(hours * 3_600_000);\n/**\n * Creates a Duration from days.\n *\n * **Example** (Creating durations from days)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.toMillis(Duration.days(1)) // => 86_400_000\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const days = days => make(days * 86_400_000);\n/**\n * Creates a Duration from weeks.\n *\n * **Example** (Creating durations from weeks)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.toMillis(Duration.weeks(1)) // => 604_800_000\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const weeks = weeks => make(weeks * 604_800_000);\n/**\n * Converts a Duration to milliseconds.\n *\n * **Example** (Converting durations to milliseconds)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.toMillis(Duration.seconds(5)) // => 5000\n * Duration.toMillis(Duration.minutes(2)) // => 120_000\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const toMillis = self => match(fromInputUnsafe(self), {\n onMillis: identity,\n onNanos: nanos => Number(nanos) / 1_000_000,\n onInfinity: () => Infinity,\n onNegativeInfinity: () => -Infinity\n});\n/**\n * Converts a Duration to seconds.\n *\n * **Example** (Converting durations to seconds)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.toSeconds(Duration.millis(5000)) // => 5\n * Duration.toSeconds(Duration.minutes(2)) // => 120\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const toSeconds = self => match(fromInputUnsafe(self), {\n onMillis: millis => millis / 1_000,\n onNanos: nanos => Number(nanos) / 1_000_000_000,\n onInfinity: () => Infinity,\n onNegativeInfinity: () => -Infinity\n});\n/**\n * Converts a Duration to minutes.\n *\n * **Example** (Converting durations to minutes)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.toMinutes(Duration.seconds(120)) // => 2\n * Duration.toMinutes(Duration.hours(1)) // => 60\n * ```\n *\n * @category getters\n * @since 3.8.0\n */\nexport const toMinutes = self => match(fromInputUnsafe(self), {\n onMillis: millis => millis / 60_000,\n onNanos: nanos => Number(nanos) / 60_000_000_000,\n onInfinity: () => Infinity,\n onNegativeInfinity: () => -Infinity\n});\n/**\n * Converts a Duration to hours.\n *\n * **Example** (Converting durations to hours)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.toHours(Duration.minutes(120)) // => 2\n * Duration.toHours(Duration.days(1)) // => 24\n * ```\n *\n * @category getters\n * @since 3.8.0\n */\nexport const toHours = self => match(fromInputUnsafe(self), {\n onMillis: millis => millis / 3_600_000,\n onNanos: nanos => Number(nanos) / 3_600_000_000_000,\n onInfinity: () => Infinity,\n onNegativeInfinity: () => -Infinity\n});\n/**\n * Converts a Duration to days.\n *\n * **Example** (Converting durations to days)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.toDays(Duration.hours(48)) // => 2\n * Duration.toDays(Duration.weeks(1)) // => 7\n * ```\n *\n * @category getters\n * @since 3.8.0\n */\nexport const toDays = self => match(fromInputUnsafe(self), {\n onMillis: millis => millis / 86_400_000,\n onNanos: nanos => Number(nanos) / 86_400_000_000_000,\n onInfinity: () => Infinity,\n onNegativeInfinity: () => -Infinity\n});\n/**\n * Converts a Duration to weeks.\n *\n * **Example** (Converting durations to weeks)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.toWeeks(Duration.days(14)) // => 2\n * Duration.toWeeks(Duration.days(7)) // => 1\n * ```\n *\n * @category getters\n * @since 3.8.0\n */\nexport const toWeeks = self => match(fromInputUnsafe(self), {\n onMillis: millis => millis / 604_800_000,\n onNanos: nanos => Number(nanos) / 604_800_000_000_000,\n onInfinity: () => Infinity,\n onNegativeInfinity: () => -Infinity\n});\n/**\n * Gets the duration in nanoseconds as a bigint.\n *\n * **When to use**\n *\n * Use when the duration is known to be finite and you need the nanosecond value\n * as a `bigint`.\n *\n * **Details**\n *\n * Millisecond-backed fractional durations are rounded to the nearest\n * nanosecond, with ties away from zero.\n *\n * **Gotchas**\n *\n * If the duration is infinite, it throws an error.\n *\n * **Example** (Reading nanoseconds unsafely)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.toNanosUnsafe(Duration.seconds(2)) // => 2_000_000_000n\n *\n * // Duration.toNanosUnsafe(Duration.infinity)\n * // throws Error: \"Cannot convert infinite duration to nanos\"\n * ```\n *\n * @category getters\n * @since 4.0.0\n */\nexport const toNanosUnsafe = input => {\n const self = fromInputUnsafe(input);\n switch (self.value._tag) {\n case \"Infinity\":\n case \"NegativeInfinity\":\n throw new Error(\"Cannot convert infinite duration to nanos\");\n case \"Nanos\":\n return self.value.nanos;\n case \"Millis\":\n return roundMillisToNanos(self.value.millis);\n }\n};\n/**\n * Gets the duration in nanoseconds safely as an `Option<bigint>`.\n *\n * **Details**\n *\n * If the duration is infinite, returns `Option.none()`.\n *\n * **Example** (Safely reading nanoseconds)\n *\n * ```ts import.meta.vitest\n * import { Duration, Option } from \"effect\"\n *\n * Duration.toNanos(Duration.seconds(1)) // => Option.some(1_000_000_000n)\n * Duration.toNanos(Duration.infinity) // => Option.none()\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const toNanos = /*#__PURE__*/Option.liftThrowable(toNanosUnsafe);\n/**\n * Converts a Duration to high-resolution time format [seconds, nanoseconds].\n *\n * **Example** (Converting durations to high-resolution time)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.toHrTime(Duration.millis(1500)) // => [1, 500_000_000]\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const toHrTime = input => {\n const self = fromInputUnsafe(input);\n switch (self.value._tag) {\n case \"Infinity\":\n return [Infinity, 0];\n case \"NegativeInfinity\":\n return [-Infinity, 0];\n case \"Nanos\":\n return nanosToHrTime(self.value.nanos);\n case \"Millis\":\n return nanosToHrTime(roundMillisToNanos(self.value.millis));\n }\n};\n/**\n * Pattern matches on the representation of a `Duration`.\n *\n * **Details**\n *\n * Provide handlers for millisecond-backed values, nanosecond-backed values,\n * and positive infinity. Use `onNegativeInfinity` to handle negative infinity\n * separately; otherwise negative infinity is handled by `onInfinity`.\n *\n * **Example** (Pattern matching on duration representations)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.match(Duration.seconds(5), {\n * onMillis: (millis) => `${millis} milliseconds`,\n * onNanos: (nanos) => `${nanos} nanoseconds`,\n * onInfinity: () => \"infinite\"\n * }) // => \"5000 milliseconds\"\n * ```\n *\n * @category pattern matching\n * @since 2.0.0\n */\nexport const match = /*#__PURE__*/dual(2, (self, options) => {\n switch (self.value._tag) {\n case \"Millis\":\n return options.onMillis(self.value.millis);\n case \"Nanos\":\n return options.onNanos(self.value.nanos);\n case \"Infinity\":\n return options.onInfinity();\n case \"NegativeInfinity\":\n return (options.onNegativeInfinity ?? options.onInfinity)();\n }\n});\n/**\n * Pattern matches on two `Duration`s, providing handlers that receive both values.\n *\n * **Example** (Pattern matching on duration pairs)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.matchPair(Duration.seconds(3), Duration.seconds(2), {\n * onMillis: (a, b) => a + b,\n * onNanos: (a, b) => Number(a + b),\n * onInfinity: () => Infinity\n * }) // => 5000\n * ```\n *\n * @category pattern matching\n * @since 4.0.0\n */\nexport const matchPair = /*#__PURE__*/dual(3, (self, that, options) => {\n if (self.value._tag === \"Infinity\" || self.value._tag === \"NegativeInfinity\" || that.value._tag === \"Infinity\" || that.value._tag === \"NegativeInfinity\") return options.onInfinity(self, that);\n if (self.value._tag === \"Millis\") {\n return that.value._tag === \"Millis\" ? options.onMillis(self.value.millis, that.value.millis) : options.onNanos(toNanosUnsafe(self), that.value.nanos);\n } else {\n return options.onNanos(self.value.nanos, toNanosUnsafe(that));\n }\n});\n/**\n * Provides an `Order` instance for comparing `Duration` values.\n *\n * **Details**\n *\n * `NegativeInfinity` < any finite value < `Infinity`.\n *\n * **Example** (Sorting durations)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * const durations = [\n * Duration.seconds(3),\n * Duration.seconds(1),\n * Duration.seconds(2)\n * ]\n * durations.sort((a, b) => Duration.Order(a, b)).map(Duration.toSeconds) // => [1, 2, 3]\n * ```\n *\n * @category instances\n * @since 2.0.0\n */\nexport const Order = /*#__PURE__*/order.make((self, that) => matchPair(self, that, {\n onMillis: (self, that) => self < that ? -1 : self > that ? 1 : 0,\n onNanos: (self, that) => self < that ? -1 : self > that ? 1 : 0,\n onInfinity: (self, that) => {\n if (self.value._tag === that.value._tag) return 0;\n if (self.value._tag === \"Infinity\") return 1;\n if (self.value._tag === \"NegativeInfinity\") return -1;\n // self is finite\n if (that.value._tag === \"Infinity\") return -1;\n // that is NegativeInfinity\n return 1;\n }\n}));\n/**\n * Returns `true` if a `Duration` is greater than or equal to `minimum` and\n * less than or equal to `maximum`, according to `Duration.Order`.\n *\n * **When to use**\n *\n * Use to test whether a duration is inside an inclusive range.\n *\n * **Details**\n *\n * Both bounds are inclusive and compared with `Duration.Order`.\n *\n * **Gotchas**\n *\n * The bounds are not normalized. If `minimum` is greater than `maximum`, the\n * predicate returns `false` for every duration.\n *\n * **Example** (Checking duration ranges)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.between(Duration.seconds(3), {\n * minimum: Duration.seconds(2),\n * maximum: Duration.seconds(5)\n * }) // => true\n * ```\n *\n * @see {@link clamp} for constraining a duration to a range\n * @see {@link isGreaterThanOrEqualTo} for checking only the lower bound\n * @see {@link isLessThanOrEqualTo} for checking only the upper bound\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const between = /*#__PURE__*/order.isBetween(Order);\n/**\n * Provides an `Equivalence` instance for comparing `Duration` values.\n *\n * **Example** (Comparing durations for equivalence)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.Equivalence(Duration.seconds(5), Duration.millis(5000)) // => true\n * ```\n *\n * @category instances\n * @since 2.0.0\n */\nexport const Equivalence = (self, that) => matchPair(self, that, {\n onMillis: (self, that) => self === that,\n onNanos: (self, that) => self === that,\n onInfinity: (self, that) => self.value._tag === that.value._tag\n});\n/**\n * Returns the smaller of two Durations.\n *\n * **Example** (Selecting the shorter duration)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.min(Duration.seconds(5), Duration.seconds(3)) // => Duration.seconds(3)\n * ```\n *\n * @category ordering\n * @since 2.0.0\n */\nexport const min = /*#__PURE__*/order.min(Order);\n/**\n * Returns the larger of two Durations.\n *\n * **Example** (Selecting the longer duration)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.max(Duration.seconds(5), Duration.seconds(3)) // => Duration.seconds(5)\n * ```\n *\n * @category ordering\n * @since 2.0.0\n */\nexport const max = /*#__PURE__*/order.max(Order);\n/**\n * Returns a `Duration` constrained between a minimum and maximum value.\n *\n * **Example** (Clamping durations to a range)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.clamp(Duration.seconds(10), {\n * minimum: Duration.seconds(2),\n * maximum: Duration.seconds(5)\n * }) // => Duration.seconds(5)\n * ```\n *\n * @category ordering\n * @since 2.0.0\n */\nexport const clamp = /*#__PURE__*/order.clamp(Order);\n/**\n * Divides a `Duration` by a finite, non-zero number safely.\n *\n * **Details**\n *\n * Returns `Option.none()` for zero, negative zero, or non-finite divisors. For\n * nanosecond-backed durations, also returns `Option.none()` when the divisor\n * cannot be converted to a `bigint`, such as a fractional divisor.\n *\n * **Example** (Safely dividing durations)\n *\n * ```ts import.meta.vitest\n * import { Duration, Option } from \"effect\"\n *\n * Duration.divide(Duration.seconds(10), 2) // => Option.some(Duration.seconds(5))\n * Duration.divide(Duration.seconds(10), 0) // => Option.none()\n * ```\n *\n * @category math\n * @since 2.4.19\n */\nexport const divide = /*#__PURE__*/dual(2, (self, by) => {\n if (!Number.isFinite(by)) return Option.none();\n if (by === 0 || Object.is(by, -0)) return Option.none();\n return match(self, {\n onMillis: millis => Option.some(make(millis / by)),\n onNanos: nanos => {\n try {\n return Option.some(make(nanos / BigInt(by)));\n } catch {\n return Option.none();\n }\n },\n onInfinity: () => Option.some(by > 0 ? infinity : negativeInfinity),\n onNegativeInfinity: () => Option.some(by > 0 ? negativeInfinity : infinity)\n });\n});\n/**\n * Divides a `Duration` by a number using fallback rules instead of returning\n * an `Option`.\n *\n * **When to use**\n *\n * Use when dividing a `Duration` should return `Duration.zero` or signed\n * infinity for invalid cases instead of forcing callers to handle `Option.none`.\n *\n * **Details**\n *\n * Non-finite divisors return `Duration.zero`. Division by positive or negative\n * zero can produce signed infinity for non-zero finite durations, while zero\n * or infinite durations divided by zero produce `Duration.zero`.\n * Nanosecond-backed durations return `Duration.zero` when the divisor cannot\n * be converted to a `bigint`.\n *\n * **Example** (Dividing durations unsafely)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.divideUnsafe(Duration.seconds(10), 2) // => Duration.seconds(5)\n * Duration.divideUnsafe(Duration.seconds(10), 0) // => Duration.infinity\n * ```\n *\n * @category math\n * @since 4.0.0\n */\nexport const divideUnsafe = /*#__PURE__*/dual(2, (self, by) => {\n if (!Number.isFinite(by)) return zero;\n return match(self, {\n onMillis: millis => make(millis / by),\n onNanos: nanos => {\n if (Object.is(by, 0) || Object.is(by, -0)) {\n if (nanos === bigint0) return zero;\n // match IEEE 754: same sign → +infinity, different sign → -infinity\n const positiveNanos = nanos > bigint0;\n const positiveZero = Object.is(by, 0);\n return positiveNanos === positiveZero ? infinity : negativeInfinity;\n }\n try {\n return make(nanos / BigInt(by));\n } catch {\n return zero;\n }\n },\n onInfinity: () => by > 0 ? infinity : by < 0 ? negativeInfinity : zero,\n onNegativeInfinity: () => by > 0 ? negativeInfinity : by < 0 ? infinity : zero\n });\n});\n/**\n * Returns a `Duration` multiplied by a number.\n *\n * **Details**\n *\n * For nanosecond-backed durations, the multiplier must be convertible to a\n * `bigint`; fractional or non-finite multipliers can throw. Infinite\n * durations return positive infinity, negative infinity, or zero depending on\n * the multiplier sign.\n *\n * **Example** (Multiplying durations)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.times(Duration.seconds(5), 2) // => Duration.seconds(10)\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const times = /*#__PURE__*/dual(2, (self, times) => match(self, {\n onMillis: millis => make(millis * times),\n onNanos: nanos => make(nanos * BigInt(times)),\n onInfinity: () => times > 0 ? infinity : times < 0 ? negativeInfinity : zero,\n onNegativeInfinity: () => times > 0 ? negativeInfinity : times < 0 ? infinity : zero\n}));\n/**\n * Subtracts one Duration from another. The result can be negative.\n *\n * **Details**\n *\n * Infinity subtraction follows signed-infinity arithmetic. Subtracting the\n * same infinity from itself returns zero. Positive infinity minus negative\n * infinity or any finite duration remains positive infinity. Negative infinity\n * minus positive infinity or any finite duration remains negative infinity.\n * Finite durations minus positive infinity produce negative infinity, and\n * finite durations minus negative infinity produce positive infinity.\n *\n * **Example** (Subtracting durations)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.subtract(Duration.seconds(10), Duration.seconds(3)) // => Duration.seconds(7)\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const subtract = /*#__PURE__*/dual(2, (self, that) => matchPair(self, that, {\n onMillis: (self, that) => make(self - that),\n onNanos: (self, that) => make(self - that),\n onInfinity: (self, that) => {\n const s = self.value._tag;\n const t = that.value._tag;\n if (s === \"Infinity\") return t === \"Infinity\" ? zero : infinity;\n if (s === \"NegativeInfinity\") return t === \"NegativeInfinity\" ? zero : negativeInfinity;\n return t === \"Infinity\" ? negativeInfinity : infinity;\n }\n}));\n/**\n * Adds two Durations together.\n *\n * **Details**\n *\n * Infinity addition follows these rules:\n *\n * - infinity + infinity = infinity\n * - infinity + negativeInfinity = zero\n * - infinity + finite = infinity\n * - negativeInfinity + negativeInfinity = negativeInfinity\n * - negativeInfinity + finite = negativeInfinity\n *\n * **Example** (Adding durations)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.sum(Duration.seconds(5), Duration.seconds(3)) // => Duration.seconds(8)\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const sum = /*#__PURE__*/dual(2, (self, that) => matchPair(self, that, {\n onMillis: (self, that) => make(self + that),\n onNanos: (self, that) => make(self + that),\n onInfinity: (self, that) => {\n const s = self.value._tag;\n const t = that.value._tag;\n if (s === \"Infinity\" && t === \"NegativeInfinity\") return zero;\n if (s === \"NegativeInfinity\" && t === \"Infinity\") return zero;\n if (s === \"Infinity\" || t === \"Infinity\") return infinity;\n if (s === \"NegativeInfinity\" || t === \"NegativeInfinity\") return negativeInfinity;\n // unreachable, but satisfy TS\n return zero;\n }\n}));\n/**\n * Checks whether the first Duration is less than the second.\n *\n * **Example** (Comparing durations with less than)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.isLessThan(Duration.seconds(3), Duration.seconds(5)) // => true\n * ```\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isLessThan = /*#__PURE__*/order.isLessThan(Order);\n/**\n * Checks whether the first Duration is less than or equal to the second.\n *\n * **Example** (Comparing durations with less than or equal)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.isLessThanOrEqualTo(\n * Duration.seconds(5),\n * Duration.seconds(5)\n * ) // => true\n * ```\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isLessThanOrEqualTo = /*#__PURE__*/order.isLessThanOrEqualTo(Order);\n/**\n * Checks whether the first Duration is greater than the second.\n *\n * **Example** (Comparing durations with greater than)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.isGreaterThan(Duration.seconds(5), Duration.seconds(3)) // => true\n * ```\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isGreaterThan = /*#__PURE__*/order.isGreaterThan(Order);\n/**\n * Checks whether the first Duration is greater than or equal to the second.\n *\n * **Example** (Comparing durations with greater than or equal)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.isGreaterThanOrEqualTo(\n * Duration.seconds(5),\n * Duration.seconds(5)\n * ) // => true\n * ```\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isGreaterThanOrEqualTo = /*#__PURE__*/order.isGreaterThanOrEqualTo(Order);\n/**\n * Checks whether two Durations are equal.\n *\n * **Example** (Checking duration equality)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.equals(Duration.seconds(5), Duration.millis(5000)) // => true\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const equals = /*#__PURE__*/dual(2, (self, that) => Equivalence(self, that));\n/**\n * Decomposes a `Duration` into normalized signed components.\n *\n * **Details**\n *\n * Finite durations are returned as `{ days, hours, minutes, seconds, millis,\n * nanos }`. Infinite durations return every component as `Infinity` or\n * `-Infinity`.\n *\n * **Example** (Decomposing durations into parts)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * // Create a complex duration by adding multiple parts\n * const duration = Duration.sum(\n * Duration.sum(\n * Duration.sum(Duration.days(1), Duration.hours(2)),\n * Duration.sum(Duration.minutes(30), Duration.seconds(45))\n * ),\n * Duration.millis(123)\n * )\n * Duration.parts(duration) // => ({ days: 1, hours: 2, minutes: 30, seconds: 45, millis: 123, nanos: 0 })\n *\n * const complex = Duration.sum(Duration.hours(25), Duration.minutes(90))\n * Duration.parts(complex) // => ({ days: 1, hours: 2, minutes: 30, seconds: 0, millis: 0, nanos: 0 })\n * ```\n *\n * @category converting\n * @since 3.8.0\n */\nexport const parts = self => {\n if (self.value._tag === \"Infinity\") {\n return {\n days: Infinity,\n hours: Infinity,\n minutes: Infinity,\n seconds: Infinity,\n millis: Infinity,\n nanos: Infinity\n };\n }\n if (self.value._tag === \"NegativeInfinity\") {\n return {\n days: -Infinity,\n hours: -Infinity,\n minutes: -Infinity,\n seconds: -Infinity,\n millis: -Infinity,\n nanos: -Infinity\n };\n }\n const n = toNanosUnsafe(self);\n const neg = n < bigint0;\n const a = neg ? -n : n;\n const ms = a / bigint1e6;\n const sec = ms / bigint1e3;\n const min = sec / bigint60;\n const hr = min / bigint60;\n const d = hr / bigint24;\n const sign = neg ? -1 : 1;\n return {\n days: sign * Number(d),\n hours: sign * Number(hr % bigint24),\n minutes: sign * Number(min % bigint60),\n seconds: sign * Number(sec % bigint60),\n millis: sign * Number(ms % bigint1e3),\n nanos: sign * Number(a % bigint1e6)\n };\n};\n/**\n * Converts a `Duration` to a human readable string.\n *\n * **Example** (Formatting durations)\n *\n * ```ts import.meta.vitest\n * import { Duration } from \"effect\"\n *\n * Duration.format(Duration.millis(1000)) // => \"1s\"\n * Duration.format(Duration.millis(1001)) // => \"1s 1ms\"\n * ```\n *\n * @category converting\n * @since 2.0.0\n */\nexport const format = self => {\n if (self.value._tag === \"Infinity\") {\n return \"Infinity\";\n }\n if (self.value._tag === \"NegativeInfinity\") {\n return \"-Infinity\";\n }\n if (isZero(self)) {\n return \"0\";\n }\n if (isNegative(self)) {\n return \"-\" + format(abs(self));\n }\n const fragments = parts(self);\n const pieces = [];\n if (fragments.days !== 0) {\n pieces.push(`${fragments.days}d`);\n }\n if (fragments.hours !== 0) {\n pieces.push(`${fragments.hours}h`);\n }\n if (fragments.minutes !== 0) {\n pieces.push(`${fragments.minutes}m`);\n }\n if (fragments.seconds !== 0) {\n pieces.push(`${fragments.seconds}s`);\n }\n if (fragments.millis !== 0) {\n pieces.push(`${fragments.millis}ms`);\n }\n if (fragments.nanos !== 0) {\n pieces.push(`${fragments.nanos}ns`);\n }\n return pieces.join(\" \");\n};\n/**\n * Reducer for summing `Duration`s.\n *\n * **When to use**\n *\n * Use to sum many `Duration` values through APIs that consume a `Reducer`.\n *\n * **Details**\n *\n * `ReducerSum` uses `sum` and starts from `zero`, so `combineAll([])` returns\n * `zero`.\n *\n * @see {@link sum} for adding two duration values directly\n * @see {@link CombinerMax} for keeping the longest duration instead of summing\n * @see {@link CombinerMin} for keeping the shortest duration instead of summing\n *\n * @category math\n * @since 4.0.0\n */\nexport const ReducerSum = /*#__PURE__*/Reducer.make(sum, zero);\n/**\n * Combiner that returns the maximum `Duration`.\n *\n * **When to use**\n *\n * Use to keep the longest `Duration` when an API consumes a `Combiner`.\n *\n * @see {@link CombinerMin} for keeping the shortest `Duration`\n * @see {@link max} for comparing two `Duration` values directly\n *\n * @category math\n * @since 4.0.0\n */\nexport const CombinerMax = /*#__PURE__*/Combiner.max(Order);\n/**\n * Combiner that returns the minimum `Duration`.\n *\n * **When to use**\n *\n * Use to keep the shortest `Duration` through APIs that consume a `Combiner`.\n *\n * @see {@link CombinerMax} for keeping the longest `Duration`\n * @see {@link min} for comparing two `Duration` values directly\n *\n * @category math\n * @since 4.0.0\n */\nexport const CombinerMin = /*#__PURE__*/Combiner.min(Order);\n//# sourceMappingURL=Duration.js.map","/**\n * @since 2.0.0\n */\n/** @internal */\nexport const isArrayNonEmpty = self => self.length > 0;\n//# sourceMappingURL=array.js.map","/**\n * Models a value that has already succeeded or failed.\n *\n * A `Result<A, E>` is `Success<A, E>` when a value is available and\n * `Failure<A, E>` when an error is available. It is plain data, so inspecting\n * or transforming it does not run side effects. This module includes helpers\n * for creating, checking, mapping, combining, and extracting results, plus\n * conversions to and from `Option` and nullable values.\n *\n * @since 4.0.0\n */\nimport * as Equivalence from \"./Equivalence.js\";\nimport { constNull, constUndefined, dual, identity } from \"./Function.js\";\nimport * as doNotation from \"./internal/doNotation.js\";\nimport * as option_ from \"./internal/option.js\";\nimport * as InternalRecord from \"./internal/record.js\";\nimport * as result from \"./internal/result.js\";\nimport { isFunction } from \"./Predicate.js\";\nconst TypeId = \"~effect/Result\";\n/**\n * Creates a `Result` holding a `Success` value.\n *\n * **Details**\n *\n * - Use when you have a value and want to lift it into the `Result` type\n * - The error type `E` defaults to `never`\n *\n * **Example** (Wrapping a value)\n *\n * ```ts import.meta.vitest\n * import { Result } from \"effect\"\n *\n * Result.succeed(42) // => Result.succeed(42)\n * ```\n *\n * @see {@link fail} to create a Failure\n * @see {@link void_ void} for a pre-built `Success<void>`\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const succeed = result.succeed;\n/**\n * Creates a `Result` holding a `Failure` value.\n *\n * **When to use**\n *\n * Use to represent a failed `Result` with a typed failure value.\n *\n * **Details**\n *\n * - The success type `A` defaults to `never`\n *\n * **Example** (Creating a failure)\n *\n * ```ts import.meta.vitest\n * import { Result } from \"effect\"\n *\n * Result.fail(\"Something went wrong\") // => Result.fail(\"Something went wrong\")\n * ```\n *\n * @see {@link succeed} to create a Success\n * @see {@link mapError} to transform the error\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fail = result.fail;\nconst void_ = /*#__PURE__*/succeed(void 0);\nexport {\n/**\n * Provides a pre-built successful `Result` that carries `undefined`.\n *\n * **When to use**\n *\n * Use when you need a successful `Result` value that signals completion\n * without carrying meaningful data.\n *\n * **Details**\n *\n * This is equivalent to `Result.succeed(undefined)`, but reuses a shared\n * `Success` wrapper instead of allocating one each time.\n *\n * **Example** (Referencing void results)\n *\n * ```ts import.meta.vitest\n * import { Result } from \"effect\"\n *\n * const result: Result.Result<void> = Result.void // => Result.succeed(undefined)\n * ```\n *\n * @see {@link succeed} to create a Success with a specific value\n *\n * @category constructors\n * @since 3.13.0\n */\nvoid_ as void };\n/**\n * Provides a pre-built failed `Result` whose failure value is `undefined`.\n *\n * **When to use**\n *\n * Use when you need a failed `Result` value that acts only as a control signal\n * without failure data.\n *\n * **Details**\n *\n * This is equivalent to `Result.fail(undefined)` with type\n * `Result<never, void>`, but reuses a shared `Failure` wrapper instead of\n * allocating one each time.\n *\n * **Example** (Failing without a payload)\n *\n * ```ts import.meta.vitest\n * import { Result } from \"effect\"\n *\n * Result.failVoid // => Result.fail(undefined)\n * ```\n *\n * @see {@link fail} to create a Failure with a specific value\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const failVoid = /*#__PURE__*/fail(void 0);\n/**\n * Converts a possibly `null` or `undefined` value into a `Result`.\n *\n * **When to use**\n *\n * Use when you need `null` or `undefined` input to become a `Failure` while\n * present values remain available as `Success`.\n *\n * **Details**\n *\n * - Non-nullish values become `Success<NonNullable<A>>`\n * - `null` or `undefined` becomes `Failure<E>` using the provided function\n * - Supports both data-first and data-last (piped) usage\n * - The `onNullish` callback receives the original value\n *\n * **Example** (Handling nullable values)\n *\n * ```ts import.meta.vitest\n * import { Result } from \"effect\"\n *\n * Result.fromNullishOr(1, () => \"fallback\") // => Result.succeed(1)\n *\n * Result.fromNullishOr(null, () => \"fallback\") // => Result.fail(\"fallback\")\n * ```\n *\n * @see {@link fromOption} to convert from an Option\n * @see {@link succeed} / {@link fail} for direct construction\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromNullishOr = /*#__PURE__*/dual(2, (self, onNullish) => self == null ? fail(onNullish(self)) : succeed(self));\n/**\n * Converts an `Option<A>` into a `Result<A, E>`.\n *\n * **When to use**\n *\n * Use when an existing `Option` should become a `Result`, preserving `Some` as\n * success and turning `None` into a caller-provided failure.\n *\n * **Details**\n *\n * - `Some<A>` becomes `Success<A>`\n * - `None` becomes `Failure<E>` using the provided function\n * - Supports both data-first and data-last (piped) usage\n *\n * **Example** (Converting an Option to a Result)\n *\n * ```ts import.meta.vitest\n * import { Option, Result } from \"effect\"\n *\n * Result.fromOption(Option.some(1), () => \"missing\") // => Result.succeed(1)\n *\n * Result.fromOption(Option.none(), () => \"missing\") // => Result.fail(\"missing\")\n * ```\n *\n * @see {@link getSuccess} to extract the success value as an Option\n * @see {@link getFailure} to extract the failure value as an Option\n * @see {@link fromNullishOr} to build a Result from nullable values\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromOption = result.fromOption;\nconst try_ = evaluate => {\n if (isFunction(evaluate)) {\n try {\n return succeed(evaluate());\n } catch (e) {\n return fail(e);\n }\n } else {\n try {\n return succeed(evaluate.try());\n } catch (e) {\n return fail(evaluate.catch(e));\n }\n }\n};\nexport {\n/**\n * Wraps a synchronous computation that may throw into a `Result` safely.\n *\n * **Details**\n *\n * - If the function returns normally, the result is `Success<A>`\n * - If the function throws, the exception is caught and becomes `Failure<E>`\n * - With a single function argument, the error type is `unknown`\n * - With `{ try, catch }` options, the `catch` function maps the thrown value to `E`\n *\n * **Example** (Catching JSON parse errors)\n *\n * ```ts import.meta.vitest\n * import { Result } from \"effect\"\n *\n * Result.try(() => JSON.parse('{\"name\": \"Alice\"}')) // => Result.succeed({ name: \"Alice\" })\n *\n * const err = Result.try({\n * try: () => JSON.parse(\"not json\"),\n * catch: (e) => `Parse failed: ${e}`\n * })\n * Result.isFailure(err) // => true\n * ```\n *\n * @see {@link succeed} / {@link fail} for direct construction\n * @see {@link fromNullishOr} for nullable values\n *\n * @category constructors\n * @since 2.0.0\n */\ntry_ as try };\n/**\n * Checks whether a value is a `Result` (either `Success` or `Failure`).\n *\n * **When to use**\n *\n * Use to validate unknown input before operating on it as a `Result`.\n *\n * **Details**\n *\n * - Returns `true` for both `Success` and `Failure` variants\n * - Acts as a TypeScript type guard, narrowing to `Result<unknown, unknown>`\n *\n * **Example** (Checking if a value is a Result)\n *\n * ```ts import.meta.vitest\n * import { Result } from \"effect\"\n *\n * Result.isResult(Result.succeed(1)) // => true\n *\n * Result.isResult({ value: 1 }) // => false\n * ```\n *\n * @see {@link isSuccess} / {@link isFailure} to narrow to a specific variant\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isResult = result.isResult;\n/**\n * Checks whether a `Result` is a `Failure`.\n *\n * **When to use**\n *\n * Use to narrow a known `Result` to the `Failure` variant.\n *\n * **Details**\n *\n * - Acts as a TypeScript type guard, narrowing to `Failure<A, E>`\n * - After narrowing, you can access `.failure` to read the error value\n *\n * **Example** (Narrowing to failure)\n *\n * ```ts import.meta.vitest\n * import { Result } from \"effect\"\n *\n * const result = Result.fail(\"oops\")\n *\n * if (Result.isFailure(result)) {\n * result.failure // => \"oops\"\n * }\n * ```\n *\n * @see {@link isSuccess} for the opposite check\n * @see {@link isResult} to check if a value is any Result\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isFailure = result.isFailure;\n/**\n * Checks whether a `Result` is a `Success`.\n *\n * **When to use**\n *\n * Use to narrow a known `Result` to the `Success` variant.\n *\n * **Details**\n *\n * - Acts as a TypeScript type guard, narrowing to `Success<A, E>`\n * - After narrowing, you can access `.success` to read the value\n *\n * **Example** (Narrowing to success)\n *\n * ```ts import.meta.vitest\n * import { Result } from \"effect\"\n *\n * const result = Result.succeed(42)\n *\n * if (Result.isSuccess(result)) {\n * result.success // => 42\n * }\n * ```\n *\n * @see {@link isFailure} for the opposite check\n * @see {@link isResult} to check if a value is any Result\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isSuccess = result.isSuccess;\n/**\n * Extracts the success value as an `Option`, discarding the failure.\n *\n * **When to use**\n *\n * Use when you need to extract the success value from a `Result` as an\n * `Option` and discard failure information.\n *\n * **Details**\n *\n * - `Success<A>` becomes `Some<A>`\n * - `Failure<E>` becomes `None`\n *\n * **Example** (Extracting the success as an Option)\n *\n * ```ts import.meta.vitest\n * import { Option, Result } from \"effect\"\n *\n * Result.getSuccess(Result.succeed(\"ok\")) // => Option.some(\"ok\")\n *\n * Result.getSuccess(Result.fail(\"err\")) // => Option.none()\n * ```\n *\n * @see {@link getFailure} to extract the error instead\n * @see {@link fromOption} for the reverse conversion\n *\n * @category getters\n * @since 4.0.0\n */\nexport const getSuccess = result.getSuccess;\n/**\n * Extracts the failure value as an `Option`, discarding the success.\n *\n * **When to use**\n *\n * Use when you need to extract the failure value from a `Result` as an\n * `Option` and discard successful values.\n *\n * **Details**\n *\n * - `Failure<E>` becomes `Some<E>`\n * - `Success<A>` becomes `None`\n *\n * **Example** (Extracting the failure as an Option)\n *\n * ```ts import.meta.vitest\n * import { Option, Result } from \"effect\"\n *\n * Result.getFailure(Result.succeed(\"ok\")) // => Option.none()\n *\n * Result.getFailure(Result.fail(\"err\")) // => Option.some(\"err\")\n * ```\n *\n * @see {@link getSuccess} to extract the success instead\n * @see {@link fromOption} for the reverse conversion\n *\n * @category getters\n * @since 4.0.0\n */\nexport const getFailure = result.getFailure;\n/**\n * Creates an `Equivalence` for comparing two `Result` values.\n *\n * **Details**\n *\n * - Two `Success` values are equal when the `success` equivalence says so\n * - Two `Failure` values are equal when the `failure` equivalence says so\n * - A `Success` and a `Failure` are never equal\n *\n * **Example** (Comparing Results for equality)\n *\n * ```ts import.meta.vitest\n * import { Equivalence, Result } from \"effect\"\n *\n * const eq = Result.makeEquivalence(\n * Equivalence.strictEqual<number>(),\n * Equivalence.strictEqual<string>()\n * )\n *\n * eq(Result.succeed(1), Result.succeed(1)) // => true\n *\n * eq(Result.succeed(1), Result.fail(\"x\")) // => false\n * ```\n *\n * @category instances\n * @since 4.0.0\n */\nexport const makeEquivalence = (success, failure) => Equivalence.make((x, y) => isFailure(x) ? isFailure(y) && failure(x.failure, y.failure) : isSuccess(y) && success(x.success, y.success));\n/**\n * Transforms both the success and failure channels of a `Result`.\n *\n * **When to use**\n *\n * Use to transform both success and failure values without changing whether the\n * result succeeds or fails.\n *\n * **Details**\n *\n * - Applies `onSuccess` if the result is a `Success`\n * - Applies `onFailure` if the result is a `Failure`\n *\n * **Example** (Mapping both channels)\n *\n * ```ts import.meta.vitest\n * import { pipe, Result } from \"effect\"\n *\n * pipe(\n * Result.succeed(1),\n * Result.mapBoth({\n * onSuccess: (n) => n + 1,\n * onFailure: (e) => `Error: ${e}`\n * })\n * ) // => Result.succeed(2)\n * ```\n *\n * @see {@link map} to transform only the success value\n * @see {@link mapError} to transform only the error value\n * @see {@link match} to fold into a single value\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const mapBoth = /*#__PURE__*/dual(2, (self, {\n onFailure,\n onSuccess\n}) => isFailure(self) ? fail(onFailure(self.failure)) : succeed(onSuccess(self.success)));\n/**\n * Transforms the failure channel of a `Result`, leaving the success channel unchanged.\n *\n * **When to use**\n *\n * Use to transform only the failure channel while preserving success values.\n *\n * **Details**\n *\n * - If the result is a `Failure`, applies `f` to the error and returns a new `Failure`\n * - If the result is a `Success`, returns it as-is\n *\n * **Example** (Adding context to an error)\n *\n * ```ts import.meta.vitest\n * import { pipe, Result } from \"effect\"\n *\n * pipe(\n * Result.fail(\"not found\"),\n * Result.mapError((e) => `Error: ${e}`)\n * ) // => Result.fail(\"Error: not found\")\n * ```\n *\n * @see {@link map} to transform only the success value\n * @see {@link mapBoth} to transform both channels\n *\n * @category mapping\n * @since 4.0.0\n */\nexport const mapError = /*#__PURE__*/dual(2, (self, f) => isFailure(self) ? fail(f(self.failure)) : self);\n/**\n * Transforms the success channel of a `Result`, leaving the failure channel unchanged.\n *\n * **When to use**\n *\n * Use to apply a transformation to the success value of a `Result` while\n * preserving any existing failure.\n *\n * **Details**\n *\n * - If the result is a `Success`, applies `f` to the value and returns a new `Success`\n * - If the result is a `Failure`, returns it as-is\n * - Use {@link flatMap} if `f` returns a `Result` (to avoid nested Results)\n *\n * **Example** (Doubling the success value)\n *\n * ```ts import.meta.vitest\n * import { pipe, Result } from \"effect\"\n *\n * pipe(\n * Result.succeed(3),\n * Result.map((n) => n * 2)\n * ) // => Result.succeed(6)\n * ```\n *\n * @see {@link mapError} to transform only the error value\n * @see {@link mapBoth} to transform both channels\n * @see {@link flatMap} when `f` returns a `Result`\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => isSuccess(self) ? succeed(f(self.success)) : self);\n/**\n * Folds a `Result` into a single value by applying one of two functions.\n *\n * **When to use**\n *\n * Use when a `Result`'s success and failure branches should be collapsed into\n * one plain output type.\n *\n * **Details**\n *\n * - Applies `onSuccess` if the result is a `Success`\n * - Applies `onFailure` if the result is a `Failure`\n * - Both branches must return the same type (or a common supertype)\n *\n * **Example** (Folding to a string)\n *\n * ```ts import.meta.vitest\n * import { pipe, Result } from \"effect\"\n *\n * const format = Result.match({\n * onSuccess: (n: number) => `Got ${n}`,\n * onFailure: (e: string) => `Err: ${e}`\n * })\n *\n * format(Result.succeed(42)) // => \"Got 42\"\n *\n * format(Result.fail(\"timeout\")) // => \"Err: timeout\"\n * ```\n *\n * @see {@link merge} to extract `A | E` without mapping\n * @see {@link getOrElse} to unwrap only the success with a fallback\n *\n * @category pattern matching\n * @since 2.0.0\n */\nexport const match = /*#__PURE__*/dual(2, (self, {\n onFailure,\n onSuccess\n}) => isFailure(self) ? onFailure(self.failure) : onSuccess(self.success));\n/**\n * Lifts a value into a `Result` based on a predicate or refinement.\n *\n * **When to use**\n *\n * Use to construct a `Result` from a raw value guarded by a predicate or\n * refinement.\n *\n * **Details**\n *\n * - If the predicate returns `true`, the value becomes `Success<A>`\n * - If the predicate returns `false`, `orFailWith` produces the error for `Failure<E>`\n * - Also accepts a `Refinement` to narrow the success type\n * - Supports both data-first and data-last (piped) usage\n *\n * **Example** (Validating a number)\n *\n * ```ts import.meta.vitest\n * import { pipe, Result } from \"effect\"\n *\n * pipe(\n * 5,\n * Result.liftPredicate(\n * (n: number) => n > 0,\n * (n) => `${n} is not positive`\n * )\n * ) // => Result.succeed(5)\n * ```\n *\n * @see {@link filterOrFail} to validate a value that is already in a `Result`\n * @see {@link fromNullishOr} for nullable-based construction\n *\n * @category constructors\n * @since 3.4.0\n */\nexport const liftPredicate = /*#__PURE__*/dual(3, (a, predicate, orFailWith) => predicate(a) ? succeed(a) : fail(orFailWith(a)));\n/**\n * Validates the success value of a `Result` using a predicate, failing with a\n * custom error if the predicate returns `false`.\n *\n * **When to use**\n *\n * Use to validate an already-successful `Result` value with a predicate or\n * refinement.\n *\n * **Details**\n *\n * - If the result is already a `Failure`, it is returned as-is\n * - If the predicate passes, the `Success` is returned unchanged\n * - If the predicate fails, `orFailWith` produces the error for a new `Failure`\n * - Also accepts a `Refinement` to narrow the success type\n * - The error type of the output is the union of both error types\n *\n * **Example** (Filtering a success value)\n *\n * ```ts import.meta.vitest\n * import { pipe, Result } from \"effect\"\n *\n * pipe(\n * Result.succeed(0),\n * Result.filterOrFail(\n * (n) => n > 0,\n * (n) => `${n} is not positive`\n * )\n * ) // => Result.fail(\"0 is not positive\")\n * ```\n *\n * @see {@link liftPredicate} to create a `Result` from a raw value with a predicate\n * @see {@link flatMap} for general conditional chaining\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterOrFail = /*#__PURE__*/dual(3, (self, predicate, orFailWith) => flatMap(self, a => predicate(a) ? succeed(a) : fail(orFailWith(a))));\n/**\n * Unwraps a `Result` into `A | E` by returning the inner value regardless\n * of whether it is a success or failure.\n *\n * **Details**\n *\n * - `Success<A>` returns `A`\n * - `Failure<E>` returns `E`\n * - Useful when both channels share a compatible type\n *\n * **Example** (Extracting the inner value)\n *\n * ```ts import.meta.vitest\n * import { Result } from \"effect\"\n *\n * Result.merge(Result.succeed(42)) // => 42\n *\n * Result.merge(Result.fail(\"error\")) // => \"error\"\n * ```\n *\n * @see {@link match} to map each branch to a common type\n * @see {@link getOrElse} to provide a fallback for failures\n *\n * @category getters\n * @since 2.0.0\n */\nexport const merge = /*#__PURE__*/match({\n onFailure: identity,\n onSuccess: identity\n});\n/**\n * Extracts the success value, or computes a fallback from the error.\n *\n * **When to use**\n *\n * Use when you need the success value from a `Result`, with a fallback computed\n * from the failure value.\n *\n * **Details**\n *\n * - `Success<A>` returns the inner value\n * - `Failure<E>` applies `onFailure` to the error and returns the result\n * - The return type is `A | A2` (union of both branches)\n *\n * **Example** (Providing a fallback)\n *\n * ```ts import.meta.vitest\n * import { Result } from \"effect\"\n *\n * Result.getOrElse(Result.succeed(1), () => 0) // => 1\n *\n * Result.getOrElse(Result.fail(\"err\"), () => 0) // => 0\n * ```\n *\n * @see {@link getOrNull} / {@link getOrUndefined} for simpler fallbacks\n * @see {@link getOrThrow} to throw on failure\n * @see {@link match} to map both branches\n * @see {@link orElse} to recover with another Result instead of unwrapping\n *\n * @category getters\n * @since 2.0.0\n */\nexport const getOrElse = /*#__PURE__*/dual(2, (self, onFailure) => isFailure(self) ? onFailure(self.failure) : self.success);\n/**\n * Extracts the success value, or returns `null` on failure.\n *\n * **When to use**\n *\n * Use when you need to pass failed `Result` values to APIs that represent\n * absence as `null`.\n *\n * **Details**\n *\n * - `Success<A>` returns `A`\n * - `Failure<E>` returns `null`\n *\n * **Example** (Unwrapping to nullable)\n *\n * ```ts import.meta.vitest\n * import { Result } from \"effect\"\n *\n * Result.getOrNull(Result.succeed(1)) // => 1\n *\n * Result.getOrNull(Result.fail(\"err\")) // => null\n * ```\n *\n * @see {@link getOrUndefined} to return `undefined` instead\n * @see {@link getOrElse} for a custom fallback\n *\n * @category getters\n * @since 2.0.0\n */\nexport const getOrNull = /*#__PURE__*/getOrElse(constNull);\n/**\n * Extracts the success value, or returns `undefined` on failure.\n *\n * **When to use**\n *\n * Use when you need to pass failed `Result` values to APIs that represent\n * absence as `undefined`.\n *\n * **Details**\n *\n * - `Success<A>` returns `A`\n * - `Failure<E>` returns `undefined`\n *\n * **Example** (Unwrapping to optional)\n *\n * ```ts import.meta.vitest\n * import { Result } from \"effect\"\n *\n * Result.getOrUndefined(Result.succeed(1)) // => 1\n *\n * Result.getOrUndefined(Result.fail(\"err\")) // => undefined\n * ```\n *\n * @see {@link getOrNull} to return `null` instead\n * @see {@link getOrElse} for a custom fallback\n *\n * @category getters\n * @since 2.0.0\n */\nexport const getOrUndefined = /*#__PURE__*/getOrElse(constUndefined);\n/**\n * Extracts the success value or throws a custom error derived from the failure.\n *\n * **When to use**\n *\n * Use when converting a `Result` into a thrown exception with a custom error\n * message or error type.\n *\n * **Details**\n *\n * - `Success<A>` returns `A`\n * - `Failure<E>` throws the value returned by `onFailure(e)`\n *\n * **Example** (Throwing a custom error)\n *\n * ```ts import.meta.vitest\n * import { Result } from \"effect\"\n *\n * Result.getOrThrowWith(Result.succeed(1), () => new Error(\"fail\")) // => 1\n *\n * const failure = Result.try({\n * try: () => Result.getOrThrowWith(\n * Result.fail(\"oops\"),\n * (error) => new Error(`Unexpected: ${error}`)\n * ),\n * catch: (error) => (error as Error).message\n * })\n * Result.merge(failure) // => \"Unexpected: oops\"\n * ```\n *\n * @see {@link getOrThrow} to throw the raw failure value\n * @see {@link getOrElse} for a non-throwing alternative\n *\n * @category getters\n * @since 2.0.0\n */\nexport const getOrThrowWith = /*#__PURE__*/dual(2, (self, onFailure) => {\n if (isSuccess(self)) {\n return self.success;\n }\n throw onFailure(self.failure);\n});\n/**\n * Extracts the success value or throws the raw failure value `E`.\n *\n * **When to use**\n *\n * Use when unchecked boundaries should turn failures into thrown exceptions.\n *\n * **Details**\n *\n * - `Success<A>` returns `A`\n * - `Failure<E>` throws `E` directly\n * - Use {@link getOrThrowWith} for a custom error object\n *\n * **Example** (Unwrapping or throwing)\n *\n * ```ts import.meta.vitest\n * import { Result } from \"effect\"\n *\n * Result.getOrThrow(Result.succeed(1)) // => 1\n *\n * const failure = Result.try(() => Result.getOrThrow(Result.fail(\"error\")))\n * Result.merge(failure) // => \"error\"\n * ```\n *\n * @see {@link getOrThrowWith} for custom error mapping\n * @see {@link getOrElse} for a non-throwing alternative\n *\n * @category getters\n * @since 2.0.0\n */\nexport const getOrThrow = /*#__PURE__*/getOrThrowWith(identity);\n/**\n * Returns the original `Result` if it is a `Success`, otherwise applies\n * `that` to the error and returns the resulting `Result`.\n *\n * **When to use**\n *\n * Use when a failure should recover into another `Result` while keeping\n * successes unchanged.\n *\n * **Details**\n *\n * - `Success<A>` is returned unchanged\n * - `Failure<E>` calls `that(e)` to produce a new `Result`\n *\n * **Example** (Recovering from a failure)\n *\n * ```ts import.meta.vitest\n * import { pipe, Result } from \"effect\"\n *\n * pipe(\n * Result.fail(\"primary failed\"),\n * Result.orElse(() => Result.succeed(99))\n * ) // => Result.succeed(99)\n * ```\n *\n * @see {@link getOrElse} to unwrap with a fallback value (not a Result)\n * @see {@link mapError} to transform the error without recovering\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const orElse = /*#__PURE__*/dual(2, (self, that) => isFailure(self) ? that(self.failure) : succeed(self.success));\n/**\n * Chains a function that returns a `Result` onto a successful value.\n *\n * **When to use**\n *\n * Use to sequence `Result`-returning computations that should short-circuit on\n * failure.\n *\n * **Details**\n *\n * - If `self` is a `Success`, applies `f` to the value and returns the resulting `Result`\n * - If `self` is a `Failure`, short-circuits and returns it unchanged\n * - The error types are merged into a union (`E | E2`)\n * - This is the monadic `bind` / `>>=` for `Result`\n *\n * **Example** (Validating sequentially)\n *\n * ```ts import.meta.vitest\n * import { pipe, Result } from \"effect\"\n *\n * pipe(\n * Result.succeed(5),\n * Result.flatMap((n) =>\n * n > 0 ? Result.succeed(n * 2) : Result.fail(\"not positive\")\n * )\n * ) // => Result.succeed(10)\n * ```\n *\n * @see {@link andThen} for a more flexible variant that also accepts plain values\n * @see {@link map} when `f` does not return a `Result`\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const flatMap = /*#__PURE__*/dual(2, (self, f) => isFailure(self) ? fail(self.failure) : f(self.success));\n/**\n * Provides a flexible variant of {@link flatMap} that accepts multiple input shapes.\n *\n * **When to use**\n *\n * Use to sequence a next step that may be a `Result`, a function, or a plain\n * value.\n *\n * **Details**\n *\n * The second argument can be:\n * - A function `(a: A) => Result<A2, E2>` (same as `flatMap`)\n * - A function `(a: A) => A2` (auto-wrapped in `succeed`)\n * - A `Result<A2, E2>` value (ignores the success of `self`)\n * - A plain value `A2` (auto-wrapped in `succeed`, ignores `self`)\n *\n * If `self` is a `Failure`, the second argument is never evaluated.\n *\n * **Example** (Chaining Result values with different argument types)\n *\n * ```ts import.meta.vitest\n * import { pipe, Result } from \"effect\"\n *\n * // With a function returning a Result\n * const a = pipe(\n * Result.succeed(1),\n * Result.andThen((n) => Result.succeed(n + 1))\n * ) // => Result.succeed(2)\n *\n * // With a plain mapping function\n * const b = pipe(\n * Result.succeed(1),\n * Result.andThen((n) => n + 1)\n * ) // => Result.succeed(2)\n *\n * // With a constant value\n * const c = pipe(Result.succeed(1), Result.andThen(\"done\")) // => Result.succeed(\"done\")\n * ```\n *\n * @see {@link flatMap} for the stricter variant (function returning Result only)\n * @see {@link map} when you always return a plain value\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const andThen = /*#__PURE__*/dual(2, (self, f) => flatMap(self, a => {\n const out = isFunction(f) ? f(a) : f;\n return isResult(out) ? out : succeed(out);\n}));\n/**\n * Collects a structure of `Result`s into a single `Result` of collected values.\n *\n * **When to use**\n *\n * Use to collect independent `Result` values into one `Result` while preserving\n * the original structure.\n *\n * **Details**\n *\n * Accepts:\n * - A tuple/array: returns `Result` with a tuple/array of success values\n * - A struct (record): returns `Result` with a struct of success values\n * - An iterable: returns `Result` with an array of success values\n *\n * Short-circuits on the first `Failure` encountered; later elements are not inspected.\n *\n * **Example** (Collecting a tuple and a struct)\n *\n * ```ts import.meta.vitest\n * import { Result } from \"effect\"\n *\n * // Tuple\n * Result.all([Result.succeed(1), Result.succeed(\"two\")]) // => Result.succeed([1, \"two\"])\n *\n * // Struct\n * Result.all({ x: Result.succeed(1), y: Result.fail(\"err\") }) // => Result.fail(\"err\")\n * ```\n *\n * @see {@link flatMap} for chaining two Results sequentially\n * @see {@link gen} for generator-based composition of multiple Results\n *\n * @category sequencing\n * @since 2.0.0\n */\n// @ts-expect-error\nexport const all = input => {\n if (Symbol.iterator in input) {\n const out = [];\n for (const e of input) {\n if (isFailure(e)) {\n return e;\n }\n out.push(e.success);\n }\n return succeed(out);\n }\n const out = {};\n for (const key of Object.keys(input)) {\n const e = input[key];\n if (isFailure(e)) {\n return e;\n }\n InternalRecord.assignProperty(out, key, e.success);\n }\n return succeed(out);\n};\n/**\n * Swaps the success and failure channels of a `Result`.\n *\n * **When to use**\n *\n * Use to swap channels when failure-focused operations are easier through\n * success-oriented combinators.\n *\n * **Details**\n *\n * - `Success<A>` becomes `Failure<A>` (i.e., `Result<E, A>`)\n * - `Failure<E>` becomes `Success<E>` (i.e., `Result<E, A>`)\n * - Useful when you want to apply success-oriented operations (like `map`)\n * to the error channel, then flip back\n *\n * **Example** (Swapping channels)\n *\n * ```ts import.meta.vitest\n * import { Result } from \"effect\"\n *\n * Result.flip(Result.succeed(42)) // => Result.fail(42)\n *\n * Result.flip(Result.fail(\"error\")) // => Result.succeed(\"error\")\n * ```\n *\n * @see {@link mapError} to transform the error without swapping\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const flip = self => isFailure(self) ? succeed(self.failure) : fail(self.success);\n/**\n * Provides generator-based syntax for composing `Result` values sequentially.\n *\n * **When to use**\n *\n * Use when you need generator syntax to compose sequential `Result`\n * computations instead of nested `flatMap` calls.\n *\n * **Details**\n *\n * - Use `yield*` to unwrap a `Result` inside the generator; if any yielded\n * `Result` is a `Failure`, the generator short-circuits and returns that failure\n * - The return value of the generator is wrapped in `Success`\n * - Evaluated eagerly and synchronously (unlike `Effect.gen`)\n *\n * **Example** (Composing multiple Results)\n *\n * ```ts import.meta.vitest\n * import { Result } from \"effect\"\n *\n * Result.gen(function*() {\n * const a = yield* Result.succeed(1)\n * const b = yield* Result.succeed(2)\n * return a + b\n * }) // => Result.succeed(3)\n * ```\n *\n * @see {@link flatMap} for point-free sequential composition\n * @see {@link all} to collect multiple independent Results\n *\n * @category generators\n * @since 2.0.0\n */\nexport const gen = (...args) => {\n const f = args.length === 1 ? args[0] : args[1].bind(args[0]);\n const iterator = f();\n let state = iterator.next();\n while (!state.done) {\n const current = state.value;\n if (isFailure(current)) {\n return current;\n }\n state = iterator.next(current.success);\n }\n return succeed(state.value);\n};\n// -------------------------------------------------------------------------------------\n// do notation\n// -------------------------------------------------------------------------------------\n/**\n * Provides the starting point for the \"do notation\" simulation with `Result`.\n *\n * **When to use**\n *\n * Use to start a `Result` do-notation pipeline from an empty successful record\n * before adding named fields from `Result`-producing computations and pure\n * computed values.\n *\n * **Details**\n *\n * Creates a `Result<{}>` (success with an empty object). Use with\n * {@link bind} to add `Result`-producing fields and {@link let_ let}\n * to add pure computed fields.\n *\n * **Example** (Building an object step by step)\n *\n * ```ts import.meta.vitest\n * import { pipe, Result } from \"effect\"\n *\n * pipe(\n * Result.Do,\n * Result.bind(\"x\", () => Result.succeed(2)),\n * Result.bind(\"y\", () => Result.succeed(3)),\n * Result.let(\"sum\", ({ x, y }) => x + y)\n * ) // => Result.succeed({ x: 2, y: 3, sum: 5 })\n * ```\n *\n * @see {@link bind} to add Result-producing fields\n * @see {@link let_ let} to add pure computed fields\n * @see {@link gen} for an alternative generator-based syntax\n * @see {@link bindTo} for starting a do-notation chain from an existing Result\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const Do = /*#__PURE__*/succeed({});\n/**\n * Adds a named field to the do-notation accumulator by running a `Result`-producing\n * function that receives the current accumulated object.\n *\n * **When to use**\n *\n * Use when you need to add a `Result`-producing step to a `Result`\n * do-notation pipeline and store its successful value under a named field in\n * the accumulated object.\n *\n * **Details**\n *\n * - Short-circuits on the first `Failure`\n * - The field name must not collide with existing keys\n * - Use {@link let_ let} for pure (non-Result) computed fields\n *\n * **Example** (Binding Result values)\n *\n * ```ts import.meta.vitest\n * import { pipe, Result } from \"effect\"\n *\n * pipe(\n * Result.Do,\n * Result.bind(\"x\", () => Result.succeed(2)),\n * Result.bind(\"y\", ({ x }) => Result.succeed(x + 3))\n * ) // => Result.succeed({ x: 2, y: 5 })\n * ```\n *\n * @see {@link Do} to start the do-notation chain\n * @see {@link let_ let} for pure computed fields\n * @see {@link bindTo} to wrap an initial Result into a named field\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const bind = /*#__PURE__*/doNotation.bind(map, flatMap);\n/**\n * Wraps the success value of a `Result` into a named field, producing a\n * `Result<Record<N, A>>`.\n *\n * **When to use**\n *\n * Use to name the success value of an existing `Result` before continuing a\n * do-notation pipeline.\n *\n * **Details**\n *\n * This is typically used to start a do-notation chain from an existing\n * `Result`.\n *\n * **Example** (Wrapping a value into a named field)\n *\n * ```ts import.meta.vitest\n * import { pipe, Result } from \"effect\"\n *\n * pipe(\n * Result.succeed(42),\n * Result.bindTo(\"answer\")\n * ) // => Result.succeed({ answer: 42 })\n * ```\n *\n * @see {@link Do} to start from an empty object\n * @see {@link bind} to add more fields\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const bindTo = /*#__PURE__*/doNotation.bindTo(map);\nconst let_ = /*#__PURE__*/doNotation.let_(map);\nexport {\n/**\n * Adds a named field to the do-notation accumulator by computing a pure\n * (non-Result) value from the current accumulated object.\n *\n * **When to use**\n *\n * Use when you need to add a derived field that cannot fail inside a\n * do-notation pipeline.\n *\n * **Details**\n *\n * - Use {@link bind} when the computation returns a `Result`\n * - The field name must not collide with existing keys\n *\n * **Example** (Adding a computed field)\n *\n * ```ts import.meta.vitest\n * import { pipe, Result } from \"effect\"\n *\n * pipe(\n * Result.Do,\n * Result.bind(\"x\", () => Result.succeed(2)),\n * Result.bind(\"y\", () => Result.succeed(3)),\n * Result.let(\"sum\", ({ x, y }) => x + y)\n * ) // => Result.succeed({ x: 2, y: 3, sum: 5 })\n * ```\n *\n * @see {@link Do} to start the do-notation chain\n * @see {@link bind} for Result-producing fields\n *\n * @category mapping\n * @since 2.0.0\n */\nlet_ as let };\n/**\n * Transforms `Option<Result<A, E>>` into `Result<Option<A>, E>`.\n *\n * **When to use**\n *\n * Use when optional absence should be treated as a successful `None`, while an\n * inner `Result` failure should still fail the whole result.\n *\n * **Details**\n *\n * - `None` becomes `Success(None)`\n * - `Some(Success(a))` becomes `Success(Some(a))`\n * - `Some(Failure(e))` becomes `Failure(e)`\n *\n * **Example** (Transposing an Option of a Result)\n *\n * ```ts import.meta.vitest\n * import { Option, Result } from \"effect\"\n *\n * Result.transposeOption(Option.some(Result.succeed(42))) // => Result.succeed(Option.some(42))\n *\n * Result.transposeOption(Option.none<Result.Result<number, string>>()) // => Result.succeed(Option.none())\n * ```\n *\n * @see {@link transposeMapOption} to map and transpose in one step\n *\n * @category transposing\n * @since 3.14.0\n */\nexport const transposeOption = self => {\n return option_.isNone(self) ? succeedNone : map(self.value, option_.some);\n};\n/**\n * Maps an `Option` value with a `Result`-producing function, then transposes\n * the structure from `Option<Result<B, E>>` to `Result<Option<B>, E>`.\n *\n * **When to use**\n *\n * Use when an optional value should be validated only when present, preserving\n * absence as a successful `None`.\n *\n * **Details**\n *\n * - `None` becomes `Success(None)` (the function is never called)\n * - `Some(a)` where `f(a)` is `Success(b)` becomes `Success(Some(b))`\n * - `Some(a)` where `f(a)` is `Failure(e)` becomes `Failure(e)`\n *\n * **Example** (Mapping and transposing in one step)\n *\n * ```ts import.meta.vitest\n * import { Option, Result } from \"effect\"\n *\n * const parse = (s: string) =>\n * isNaN(Number(s))\n * ? Result.fail(\"not a number\" as const)\n * : Result.succeed(Number(s))\n *\n * Result.transposeMapOption(Option.some(\"42\"), parse) // => Result.succeed(Option.some(42))\n *\n * Result.transposeMapOption(Option.none(), parse) // => Result.succeed(Option.none())\n * ```\n *\n * @see {@link transposeOption} when the Option already contains a Result\n *\n * @category transposing\n * @since 3.15.0\n */\nexport const transposeMapOption = /*#__PURE__*/dual(2, (self, f) => option_.isNone(self) ? succeedNone : map(f(self.value), option_.some));\n/**\n * Provides a pre-built `Result<Option<never>>` that succeeds with `None`.\n *\n * **When to use**\n *\n * Use when an optional success should be absent, such as the `None` branch of\n * `transposeOption` or `transposeMapOption`.\n *\n * **Details**\n *\n * This is equivalent to `Result.succeed(Option.none())`, but reuses a shared\n * `Success` wrapper instead of allocating one each time.\n *\n * **Example** (Succeeding with None)\n *\n * ```ts import.meta.vitest\n * import { Option, Result } from \"effect\"\n *\n * Result.succeedNone // => Result.succeed(Option.none())\n * ```\n *\n * @see {@link succeedSome} for the `Some` counterpart\n * @see {@link transposeOption} to transpose an Option that already contains a Result\n * @see {@link transposeMapOption} to map and transpose an Option in one step\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const succeedNone = /*#__PURE__*/succeed(option_.none);\n/**\n * Creates a `Result<Option<A>>` that succeeds with `Some(a)`.\n *\n * **Details**\n *\n * - Equivalent to `Result.succeed(Option.some(a))`\n * - Useful with {@link transposeOption} patterns\n *\n * **Example** (Wrapping a value in Some inside a Result)\n *\n * ```ts import.meta.vitest\n * import { Option, Result } from \"effect\"\n *\n * Result.succeedSome(42) // => Result.succeed(Option.some(42))\n * ```\n *\n * @see {@link succeedNone} for the `None` counterpart\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const succeedSome = a => succeed(option_.some(a));\n/**\n * Runs a side-effect on the success value without altering the `Result`.\n *\n * **Details**\n *\n * - If the result is a `Success`, calls `f` with the value (return value is ignored)\n * - If the result is a `Failure`, `f` is not called\n * - Returns the original `Result` unchanged (same reference)\n * - Useful for logging, debugging, or performing mutations outside the Result chain\n *\n * **Example** (Logging a success value)\n *\n * ```ts import.meta.vitest\n * import { pipe, Result } from \"effect\"\n *\n * const values: Array<number> = []\n * const result = pipe(\n * Result.succeed(42),\n * Result.tap((n) => values.push(n))\n * )\n *\n * values // => [42]\n * result // => Result.succeed(42)\n * ```\n *\n * @see {@link map} to transform the success value\n *\n * @category mapping\n * @since 4.0.0\n */\nexport const tap = /*#__PURE__*/dual(2, (self, f) => {\n if (isSuccess(self)) {\n f(self.success);\n }\n return self;\n});\n//# sourceMappingURL=Result.js.map","/**\n * Works with JavaScript values that implement `[Symbol.iterator]`.\n *\n * Iterables include arrays, strings, generators, sets, and custom lazy\n * sequences. The helpers in this module let code transform, search, group, and\n * fold iterable values while preserving the input as an iterable instead of\n * forcing an array first.\n *\n * @since 2.0.0\n */\nimport * as Equal from \"./Equal.js\";\nimport { dual } from \"./Function.js\";\nimport * as Count from \"./internal/count.js\";\nimport * as InternalRecord from \"./internal/record.js\";\nimport * as O from \"./Option.js\";\nimport { isBoolean } from \"./Predicate.js\";\nimport * as R from \"./Result.js\";\nimport * as Tuple from \"./Tuple.js\";\n/**\n * Creates an iterable by applying a function to consecutive integers.\n *\n * **Details**\n *\n * The function is called with each index starting from `0`. If a length is\n * provided, it is rounded down and normalized to at least `1`, with `NaN`\n * treated as `1`. If no length is specified, the iterable is infinite.\n *\n * **Example** (Generating values by index)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Generate first 5 even numbers\n * const evens = Iterable.makeBy((n) => n * 2, { length: 5 })\n * Array.from(evens) // => [0, 2, 4, 6, 8]\n *\n * // Generate squares\n * const squares = Iterable.makeBy((n) => n * n, { length: 4 })\n * Array.from(squares) // => [0, 1, 4, 9]\n *\n * // Infinite sequence (be careful when consuming!)\n * const naturals = Iterable.makeBy((n) => n)\n * const first10 = Iterable.take(naturals, 10)\n * Array.from(first10) // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const makeBy = (f, options) => {\n const max = options?.length !== undefined ? Count.normalizeNonEmpty(options.length) : Infinity;\n return {\n [Symbol.iterator]() {\n let i = 0;\n return {\n next() {\n if (i < max) {\n return {\n value: f(i++),\n done: false\n };\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n };\n};\n/**\n * Returns an iterable of integers starting at `start` and increasing by `1`.\n *\n * **Details**\n *\n * When `end` is provided and `start <= end`, both endpoints are included. When\n * `end` is omitted, the iterable is unbounded. When `start > end`, the\n * iterable contains only `start`.\n *\n * **Example** (Creating a range)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * Array.from(Iterable.range(1, 3)) // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const range = (start, end) => {\n if (end === undefined) {\n return makeBy(i => start + i);\n }\n return makeBy(i => start + i, {\n length: start <= end ? end - start + 1 : 1\n });\n};\n/**\n * Returns a `Iterable` containing a value repeated the specified number of times.\n *\n * **Details**\n *\n * `n` is rounded down and normalized to an integer greater than or equal to\n * `1`. `NaN` is treated as `1`.\n *\n * **Example** (Repeating a value)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * Array.from(Iterable.replicate(\"a\", 3)) // => [\"a\", \"a\", \"a\"]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const replicate = /*#__PURE__*/dual(2, (a, n) => makeBy(() => a, {\n length: n\n}));\n/**\n * Repeats an iterable `n` times, yielding the full contents of `self` for each\n * repetition.\n *\n * **When to use**\n *\n * Use to repeat an iterable's contents a specific number of times.\n *\n * **Details**\n *\n * The result is lazy. `n` is rounded down and normalized to at least `1`, with\n * `NaN` treated as `1`. Each repetition obtains a new iterator from `self`.\n *\n * @see {@link forever} for repeating without an upper bound\n * @see {@link replicate} for repeating a single value\n * @category constructors\n * @since 4.0.0\n */\nexport const repeat = /*#__PURE__*/dual(2, (self, n) => flatten(makeBy(() => self, {\n length: n\n})));\n/**\n * Repeats an iterable without an upper bound.\n *\n * **When to use**\n *\n * Use to cycle a reusable iterable without an upper bound when a downstream\n * consumer controls how many values are taken.\n *\n * **Gotchas**\n *\n * The returned iterable is lazy and should usually be bounded with `take` or\n * another terminating consumer before materializing it.\n *\n * @see {@link repeat} for repeating an iterable a specific number of times\n * @see {@link take} for bounding the unbounded result before materializing it\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const forever = self => repeat(self, Infinity);\n/**\n * Takes a record and returns an Iterable of tuples containing its keys and values.\n *\n * **Example** (Converting a record to entries)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const x = { a: 1, b: 2, c: 3 }\n * Array.from(Iterable.fromRecord(x)) // => [[\"a\", 1], [\"b\", 2], [\"c\", 3]]\n * ```\n *\n * @category converting\n * @since 2.0.0\n */\nexport const fromRecord = self => ({\n *[Symbol.iterator]() {\n for (const key in self) {\n if (Object.hasOwn(self, key)) {\n yield [key, self[key]];\n }\n }\n }\n});\n/**\n * Prepends an element to the front of an `Iterable`, creating a new `Iterable`.\n *\n * **Example** (Prepending an element)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [2, 3, 4]\n * const withOne = Iterable.prepend(numbers, 1)\n * Array.from(withOne) // => [1, 2, 3, 4]\n *\n * // Works with any iterable\n * const letters = \"abc\"\n * const withZ = Iterable.prepend(letters, \"z\")\n * Array.from(withZ) // => [\"z\", \"a\", \"b\", \"c\"]\n * ```\n *\n * @category combining\n * @since 2.0.0\n */\nexport const prepend = /*#__PURE__*/dual(2, (self, head) => prependAll(self, [head]));\n/**\n * Prepends the specified prefix iterable to the beginning of the specified iterable.\n *\n * **Example** (Prepending another iterable)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * Array.from(Iterable.prependAll([1, 2], [\"a\", \"b\"])) // => [\"a\", \"b\", 1, 2]\n * ```\n *\n * @category combining\n * @since 2.0.0\n */\nexport const prependAll = /*#__PURE__*/dual(2, (self, that) => appendAll(that, self));\n/**\n * Appends an element to the end of an `Iterable`, creating a new `Iterable`.\n *\n * **When to use**\n *\n * Use to add one element after all elements of an iterable while keeping the\n * result as a lazy `Iterable`.\n *\n * **Details**\n *\n * The result yields every element from `self` first, then yields `last` after\n * `self` is exhausted.\n *\n * **Gotchas**\n *\n * If `self` is infinite or never completes, the appended element is never\n * reached.\n *\n * **Example** (Appending an element)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 2, 3]\n * Array.from(Iterable.append(numbers, 4)) // => [1, 2, 3, 4]\n * ```\n *\n * @see {@link prepend} for adding one element before the existing elements\n * @see {@link appendAll} for appending all elements from another iterable\n *\n * @category combining\n * @since 2.0.0\n */\nexport const append = /*#__PURE__*/dual(2, (self, last) => appendAll(self, [last]));\n/**\n * Concatenates two iterables, combining their elements.\n *\n * **When to use**\n *\n * Use to lazily concatenate two iterables while preserving order, yielding all\n * elements from `self` before `that`.\n *\n * **Details**\n *\n * The result is lazy. The iterator for `that` is not created or read until\n * `self` is exhausted.\n *\n * **Gotchas**\n *\n * If `self` is infinite or never completes, `that` is never reached.\n *\n * **Example** (Concatenating iterables)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * Array.from(Iterable.appendAll([1, 2, 3], [4, 5, 6])) // => [1, 2, 3, 4, 5, 6]\n *\n * // Works with different iterable types\n * const numbers = [1, 2]\n * const letters = \"abc\"\n * const mixed = Iterable.appendAll(numbers, letters)\n * Array.from(mixed) // => [1, 2, \"a\", \"b\", \"c\"]\n *\n * // Lazy evaluation - only consumes what's needed\n * const infinite = Iterable.range(1)\n * const finite = [0, -1, -2]\n * Array.from(Iterable.take(Iterable.appendAll(finite, infinite), 5)) // => [0, -1, -2, 1, 2]\n * ```\n *\n * @see {@link append} for appending one value instead of another iterable\n * @see {@link prependAll} for yielding another iterable before `self`\n *\n * @category combining\n * @since 2.0.0\n */\nexport const appendAll = /*#__PURE__*/dual(2, (self, that) => ({\n [Symbol.iterator]() {\n const iterA = self[Symbol.iterator]();\n let doneA = false;\n let iterB;\n return {\n next() {\n if (!doneA) {\n const r = iterA.next();\n if (r.done) {\n doneA = true;\n iterB = that[Symbol.iterator]();\n return iterB.next();\n }\n return r;\n }\n return iterB.next();\n }\n };\n }\n}));\n/**\n * Reduces an `Iterable` from the left, keeping all intermediate results instead of only the final result.\n *\n * **Example** (Tracking running results)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Running sum of numbers\n * const numbers = [1, 2, 3, 4, 5]\n * const runningSum = Iterable.scan(numbers, 0, (acc, n) => acc + n)\n * Array.from(runningSum) // => [0, 1, 3, 6, 10, 15]\n *\n * // Build strings progressively\n * const letters = [\"a\", \"b\", \"c\"]\n * const progressive = Iterable.scan(letters, \"\", (acc, letter) => acc + letter)\n * Array.from(progressive) // => [\"\", \"a\", \"ab\", \"abc\"]\n *\n * // Track maximum values seen so far\n * const values = [3, 1, 4, 1, 5, 9, 2]\n * const runningMax = Iterable.scan(values, -Infinity, Math.max)\n * Array.from(runningMax) // => [-Infinity, 3, 3, 4, 4, 5, 9, 9]\n * ```\n *\n * @category folding\n * @since 2.0.0\n */\nexport const scan = /*#__PURE__*/dual(3, (self, b, f) => ({\n [Symbol.iterator]() {\n let acc = b;\n let iterator;\n function next() {\n if (iterator === undefined) {\n iterator = self[Symbol.iterator]();\n return {\n done: false,\n value: acc\n };\n }\n const result = iterator.next();\n if (result.done) {\n return result;\n }\n acc = f(acc, result.value);\n return {\n done: false,\n value: acc\n };\n }\n return {\n next\n };\n }\n}));\n/**\n * Checks whether an `Iterable` is empty.\n *\n * **Example** (Checking for emptiness)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * Iterable.isEmpty([]) // => true\n * Iterable.isEmpty([1, 2, 3]) // => false\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isEmpty = self => {\n const iterator = self[Symbol.iterator]();\n return iterator.next().done === true;\n};\n/**\n * Returns the number of elements in a `Iterable`.\n *\n * **Example** (Counting iterable elements)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4, 5]\n * Iterable.size(numbers) // => 5\n *\n * const empty = Iterable.empty<number>()\n * Iterable.size(empty) // => 0\n *\n * // Works with any iterable\n * const letters = \"hello\"\n * Iterable.size(letters) // => 5\n *\n * // Note: This consumes the entire iterable\n * const range = Iterable.range(1, 100)\n * Iterable.size(range) // => 100\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const size = self => {\n const iterator = self[Symbol.iterator]();\n let count = 0;\n while (!iterator.next().done) {\n count++;\n }\n return count;\n};\n/**\n * Gets the first element of a `Iterable` safely, or `None` if the `Iterable` is empty.\n *\n * **Example** (Getting the first element)\n *\n * ```ts import.meta.vitest\n * import { Iterable, Option } from \"effect\"\n *\n * const numbers = [1, 2, 3]\n * Iterable.head(numbers) // => Option.some(1)\n *\n * const empty = Iterable.empty<number>()\n * Iterable.head(empty) // => Option.none()\n *\n * // Safe way to get first element\n * const firstEven = Iterable.head(\n * Iterable.filter([1, 3, 4, 5], (x) => x % 2 === 0)\n * )\n * firstEven // => Option.some(4)\n *\n * // Use with Option methods\n * const doubled = Option.map(Iterable.head([5, 10, 15]), (x) => x * 2)\n * doubled // => Option.some(10)\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const head = self => {\n const iterator = self[Symbol.iterator]();\n const result = iterator.next();\n return result.done ? O.none() : O.some(result.value);\n};\n/**\n * Gets the first element of an `Iterable` without returning an `Option`.\n *\n * **When to use**\n *\n * Use when the `Iterable` is known to be non-empty and direct access to the\n * first element is preferred over handling `Option.none`.\n *\n * **Gotchas**\n *\n * Throws if the `Iterable` is empty.\n *\n * **Example** (Getting the first element unsafely)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 2, 3]\n * Iterable.headUnsafe(numbers) // => 1\n *\n * const letters = \"hello\"\n * Iterable.headUnsafe(letters) // => \"h\"\n *\n * // Iterable.headUnsafe(Iterable.empty<number>())\n * // throws Error: \"headUnsafe: empty iterable\"\n *\n * // Use only when you're certain the iterable is non-empty\n * const nonEmpty = Iterable.range(1, 10)\n * Iterable.headUnsafe(nonEmpty) // => 1\n * ```\n *\n * @category getters\n * @since 4.0.0\n */\nexport const headUnsafe = self => {\n const iterator = self[Symbol.iterator]();\n const result = iterator.next();\n if (result.done) throw new Error(\"headUnsafe: empty iterable\");\n return result.value;\n};\n/**\n * Keeps only a max number of elements from the start of an `Iterable`, creating a new `Iterable`.\n *\n * **Details**\n *\n * `n` is rounded down and normalized to a non-negative integer. `NaN` is\n * treated as `0`.\n *\n * **Example** (Taking from the start)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4, 5]\n * const firstThree = Iterable.take(numbers, 3)\n * Array.from(firstThree) // => [1, 2, 3]\n *\n * // Taking more than available returns all elements\n * const firstTen = Iterable.take(numbers, 10)\n * Array.from(firstTen) // => [1, 2, 3, 4, 5]\n *\n * // Taking 0 or negative returns empty\n * const none = Iterable.take(numbers, 0)\n * Array.from(none) // => []\n *\n * // Useful with infinite iterables\n * const naturals = Iterable.range(1)\n * const firstFive = Iterable.take(naturals, 5)\n * Array.from(firstFive) // => [1, 2, 3, 4, 5]\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const take = /*#__PURE__*/dual(2, (self, n) => {\n const count = Count.normalize(n);\n return {\n [Symbol.iterator]() {\n let i = 0;\n const iterator = self[Symbol.iterator]();\n return {\n next() {\n if (i < count) {\n i++;\n return iterator.next();\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n };\n});\n/**\n * Takes the longest initial `Iterable` prefix for which all elements satisfy the\n * specified predicate.\n *\n * **Example** (Taking while a predicate holds)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [2, 4, 6, 8, 3, 10, 12]\n * const evenPrefix = Iterable.takeWhile(numbers, (x) => x % 2 === 0)\n * Array.from(evenPrefix) // => [2, 4, 6, 8]\n *\n * // With index\n * const letters = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n * const firstThreeByIndex = Iterable.takeWhile(letters, (_, i) => i < 3)\n * Array.from(firstThreeByIndex) // => [\"a\", \"b\", \"c\"]\n *\n * // Stops at first non-matching element\n * const mixed = [1, 3, 5, 4, 7, 9]\n * const oddPrefix = Iterable.takeWhile(mixed, (x) => x % 2 === 1)\n * Array.from(oddPrefix) // => [1, 3, 5]\n *\n * // Type refinement\n * const values: Array<string | number> = [\"a\", \"b\", \"c\", 1, \"d\"]\n * const stringPrefix = Iterable.takeWhile(\n * values,\n * (x): x is string => typeof x === \"string\"\n * )\n * Array.from(stringPrefix) // => [\"a\", \"b\", \"c\"]\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const takeWhile = /*#__PURE__*/dual(2, (self, predicate) => ({\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n let i = 0;\n return {\n next() {\n const result = iterator.next();\n if (result.done || !predicate(result.value, i++)) {\n return {\n done: true,\n value: undefined\n };\n }\n return result;\n }\n };\n }\n}));\n/**\n * Drops a max number of elements from the start of an `Iterable`\n *\n * **Details**\n *\n * `n` is rounded down and normalized to a non-negative integer. `NaN` is\n * treated as `0`.\n *\n * **Example** (Dropping from the start)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4, 5]\n * const withoutFirstTwo = Iterable.drop(numbers, 2)\n * Array.from(withoutFirstTwo) // => [3, 4, 5]\n *\n * // Dropping more than available returns empty\n * const withoutFirstTen = Iterable.drop(numbers, 10)\n * Array.from(withoutFirstTen) // => []\n *\n * // Dropping 0 or negative returns all elements\n * const all = Iterable.drop(numbers, 0)\n * Array.from(all) // => [1, 2, 3, 4, 5]\n *\n * // Combine with take for slicing\n * const slice = Iterable.take(Iterable.drop(numbers, 1), 3)\n * Array.from(slice) // => [2, 3, 4]\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const drop = /*#__PURE__*/dual(2, (self, n) => {\n const count = Count.normalize(n);\n return {\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n let i = 0;\n return {\n next() {\n while (i < count) {\n const result = iterator.next();\n if (result.done) {\n return {\n done: true,\n value: undefined\n };\n }\n i++;\n }\n return iterator.next();\n }\n };\n }\n };\n});\n/**\n * Returns the first element that satisfies the specified\n * predicate, or `None` if no such element exists.\n *\n * **Example** (Finding the first match)\n *\n * ```ts import.meta.vitest\n * import { Iterable, Option } from \"effect\"\n *\n * const numbers = [1, 3, 4, 6, 8]\n * const firstEven = Iterable.findFirst(numbers, (x) => x % 2 === 0)\n * firstEven // => Option.some(4)\n *\n * const firstGreaterThan10 = Iterable.findFirst(numbers, (x) => x > 10)\n * firstGreaterThan10 // => Option.none()\n *\n * // With index\n * const letters = [\"a\", \"b\", \"c\", \"d\"]\n * const atEvenIndex = Iterable.findFirst(letters, (_, i) => i % 2 === 0)\n * atEvenIndex // => Option.some(\"a\")\n *\n * // Type refinement\n * const mixed: Array<string | number> = [1, \"hello\", 2, \"world\"]\n * const firstString = Iterable.findFirst(\n * mixed,\n * (x): x is string => typeof x === \"string\"\n * )\n * firstString // => Option.some(\"hello\")\n *\n * // Transform during search\n * const findSquareRoot = Iterable.findFirst([1, 4, 9, 16], (x) => {\n * const sqrt = Math.sqrt(x)\n * return Number.isInteger(sqrt) ? Option.some(sqrt) : Option.none()\n * })\n * findSquareRoot // => Option.some(1)\n * ```\n *\n * @category searching\n * @since 2.0.0\n */\nexport const findFirst = /*#__PURE__*/dual(2, (self, f) => {\n let i = 0;\n for (const a of self) {\n const o = f(a, i);\n if (isBoolean(o)) {\n if (o) {\n return O.some(a);\n }\n } else {\n if (O.isSome(o)) {\n return o;\n }\n }\n i++;\n }\n return O.none();\n});\n/**\n * Finds the last element for which a predicate holds.\n *\n * **Example** (Finding the last match)\n *\n * ```ts import.meta.vitest\n * import { Iterable, Option } from \"effect\"\n *\n * const numbers = [1, 3, 4, 6, 8, 2]\n * const lastEven = Iterable.findLast(numbers, (x) => x % 2 === 0)\n * lastEven // => Option.some(2)\n *\n * const lastGreaterThan10 = Iterable.findLast(numbers, (x) => x > 10)\n * lastGreaterThan10 // => Option.none()\n *\n * // With index\n * const letters = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n * const lastAtEvenIndex = Iterable.findLast(letters, (_, i) => i % 2 === 0)\n * lastAtEvenIndex // => Option.some(\"e\")\n *\n * // Type refinement\n * const mixed: Array<string | number> = [1, \"hello\", 2, \"world\", 3]\n * const lastString = Iterable.findLast(\n * mixed,\n * (x): x is string => typeof x === \"string\"\n * )\n * lastString // => Option.some(\"world\")\n * ```\n *\n * @category searching\n * @since 2.0.0\n */\nexport const findLast = /*#__PURE__*/dual(2, (self, f) => {\n let i = 0;\n let last = O.none();\n for (const a of self) {\n const o = f(a, i);\n if (isBoolean(o)) {\n if (o) {\n last = O.some(a);\n }\n } else {\n if (O.isSome(o)) {\n last = o;\n }\n }\n i++;\n }\n return last;\n});\n/**\n * Takes two `Iterable`s and returns an `Iterable` of corresponding pairs.\n *\n * **Example** (Zipping iterables)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 2, 3]\n * const letters = [\"a\", \"b\", \"c\"]\n * const zipped = Iterable.zip(numbers, letters)\n * Array.from(zipped) // => [[1, \"a\"], [2, \"b\"], [3, \"c\"]]\n *\n * // Different lengths - shorter one determines result length\n * const short = [1, 2]\n * const long = [\"a\", \"b\", \"c\", \"d\"]\n * const partial = Iterable.zip(short, long)\n * Array.from(partial) // => [[1, \"a\"], [2, \"b\"]]\n *\n * // Works with any iterables\n * const range = Iterable.range(1, 3)\n * const word = \"abc\"\n * const mixed = Iterable.zip(range, word)\n * Array.from(mixed) // => [[1, \"a\"], [2, \"b\"], [3, \"c\"]]\n *\n * // Create indexed pairs\n * const values = [\"apple\", \"banana\", \"cherry\"]\n * const indices = Iterable.range(0, 2)\n * const indexed = Iterable.zip(indices, values)\n * Array.from(indexed) // => [[0, \"apple\"], [1, \"banana\"], [2, \"cherry\"]]\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zip = /*#__PURE__*/dual(2, (self, that) => zipWith(self, that, Tuple.make));\n/**\n * Applies a function to pairs of elements at the same index in two `Iterable`s, collecting the results. If one\n * input `Iterable` is short, excess elements of the longer `Iterable` are discarded.\n *\n * **Example** (Zipping with a combining function)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Add corresponding elements\n * const a = [1, 2, 3, 4]\n * const b = [10, 20, 30, 40]\n * const sums = Iterable.zipWith(a, b, (x, y) => x + y)\n * Array.from(sums) // => [11, 22, 33, 44]\n *\n * // Combine strings\n * const firstNames = [\"John\", \"Jane\", \"Bob\"]\n * const lastNames = [\"Doe\", \"Smith\", \"Johnson\"]\n * const fullNames = Iterable.zipWith(\n * firstNames,\n * lastNames,\n * (first, last) => `${first} ${last}`\n * )\n * Array.from(fullNames) // => [\"John Doe\", \"Jane Smith\", \"Bob Johnson\"]\n *\n * // Different lengths - stops at shorter\n * const short = [1, 2]\n * const long = [\"a\", \"b\", \"c\", \"d\"]\n * const combined = Iterable.zipWith(\n * short,\n * long,\n * (num, letter) => `${num}${letter}`\n * )\n * Array.from(combined) // => [\"1a\", \"2b\"]\n *\n * // Complex transformations\n * const prices = [10.99, 25.50, 5.00]\n * const quantities = [2, 1, 3]\n * const totals = Iterable.zipWith(prices, quantities, (price, qty) => {\n * return Math.round(price * qty * 100) / 100 // round to 2 decimal places\n * })\n * Array.from(totals) // => [21.98, 25.5, 15]\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipWith = /*#__PURE__*/dual(3, (self, that, f) => ({\n [Symbol.iterator]() {\n const selfIterator = self[Symbol.iterator]();\n const thatIterator = that[Symbol.iterator]();\n return {\n next() {\n const selfResult = selfIterator.next();\n const thatResult = thatIterator.next();\n if (selfResult.done || thatResult.done) {\n return {\n done: true,\n value: undefined\n };\n }\n return {\n done: false,\n value: f(selfResult.value, thatResult.value)\n };\n }\n };\n }\n}));\n/**\n * Places a separator between members of an `Iterable`.\n *\n * **When to use**\n *\n * Use to lazily insert a separator between adjacent values.\n *\n * **Details**\n *\n * If the input is a non-empty array, the result is also a non-empty array.\n *\n * **Example** (Interspersing separators)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Join numbers with separator\n * const numbers = [1, 2, 3, 4]\n * const withCommas = Iterable.intersperse(numbers, \",\")\n * Array.from(withCommas) // => [1, \",\", 2, \",\", 3, \",\", 4]\n *\n * // Join words with spaces\n * const words = [\"hello\", \"world\", \"from\", \"effect\"]\n * const sentence = Iterable.intersperse(words, \" \")\n * Array.from(sentence).join(\"\") // => \"hello world from effect\"\n *\n * // Empty iterable remains empty\n * const empty = Iterable.empty<string>()\n * const stillEmpty = Iterable.intersperse(empty, \"-\")\n * Array.from(stillEmpty) // => []\n *\n * // Single element has no separators added\n * const single = [42]\n * const noSeparator = Iterable.intersperse(single, \"|\")\n * Array.from(noSeparator) // => [42]\n *\n * // Build CSS-like strings\n * const styles = [\"color: red\", \"font-size: 14px\", \"margin: 10px\"]\n * const css = Iterable.intersperse(styles, \"; \")\n * Array.from(css).join(\"\") // => \"color: red; font-size: 14px; margin: 10px\"\n * ```\n *\n * @category combining\n * @since 2.0.0\n */\nexport const intersperse = /*#__PURE__*/dual(2, (self, middle) => ({\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n let next = iterator.next();\n let emitted = false;\n return {\n next() {\n if (next.done) {\n return next;\n } else if (emitted) {\n emitted = false;\n return {\n done: false,\n value: middle\n };\n }\n emitted = true;\n const result = next;\n next = iterator.next();\n return result;\n }\n };\n }\n}));\n/**\n * Returns a function that checks if an `Iterable` contains a given value using a provided `isEquivalent` function.\n *\n * **Example** (Checking membership with custom equivalence)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Custom equivalence for objects\n * const byId = (a: { id: number }, b: { id: number }) => a.id === b.id\n * const containsById = Iterable.containsWith(byId)\n *\n * const users = [{ id: 1 }, { id: 2 }]\n * const hasUser1 = containsById(users, { id: 1 })\n * hasUser1 // => true\n *\n * // Case-insensitive string comparison\n * const caseInsensitive = (a: string, b: string) =>\n * a.toLowerCase() === b.toLowerCase()\n * const containsCaseInsensitive = Iterable.containsWith(caseInsensitive)\n *\n * const words = [\"Hello\", \"World\"]\n * const hasHello = containsCaseInsensitive(words, \"hello\")\n * hasHello // => true\n *\n * // Approximate number comparison\n * const approxEqual = (a: number, b: number) => Math.abs(a - b) < 0.1\n * const containsApprox = Iterable.containsWith(approxEqual)\n *\n * const values = [1.0, 2.0, 3.0]\n * const hasAlmostTwo = containsApprox(values, 2.05)\n * hasAlmostTwo // => true\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const containsWith = isEquivalent => dual(2, (self, a) => {\n for (const i of self) {\n if (isEquivalent(a, i)) {\n return true;\n }\n }\n return false;\n});\n/**\n * Checks whether an iterable contains a value using Effect's default `Equal`\n * equivalence.\n *\n * **Details**\n *\n * Can be called as `contains(self, value)` or curried as\n * `contains(value)(self)`.\n *\n * **Example** (Checking membership)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4, 5]\n * Iterable.contains(numbers, 3) // => true\n * Iterable.contains(numbers, 6) // => false\n *\n * const letters = \"hello\"\n * Iterable.contains(letters, \"l\") // => true\n * Iterable.contains(letters, \"x\") // => false\n *\n * // Works with any iterable\n * const range = Iterable.range(1, 100)\n * Iterable.contains(range, 50) // => true\n * Iterable.contains(range, 150) // => false\n *\n * // Curried version\n * const containsThree = Iterable.contains(3)\n * containsThree([1, 2, 3]) // => true\n * containsThree([4, 5, 6]) // => false\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const contains = /*#__PURE__*/containsWith(/*#__PURE__*/Equal.asEquivalence());\n/**\n * Splits an `Iterable` into length-`n` pieces. The last piece will be shorter if `n` does not evenly divide the length of\n * the `Iterable`.\n * `n` is rounded down and normalized to at least `1`; `NaN` and non-positive\n * values therefore produce singleton pieces.\n *\n * **Example** (Chunking an iterable)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n * const chunks = Iterable.chunksOf(numbers, 3)\n * Array.from(chunks) // => [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n *\n * // Last chunk can be shorter\n * const uneven = [1, 2, 3, 4, 5, 6, 7]\n * const chunks2 = Iterable.chunksOf(uneven, 3)\n * Array.from(chunks2) // => [[1, 2, 3], [4, 5, 6], [7]]\n *\n * // Chunk size larger than iterable\n * const small = [1, 2]\n * const chunks3 = Iterable.chunksOf(small, 5)\n * Array.from(chunks3) // => [[1, 2]]\n *\n * // Process data in batches\n * const data = Iterable.range(1, 100)\n * const batches = Iterable.chunksOf(data, 10)\n * const batchSums = Iterable.map(\n * batches,\n * (batch) => Iterable.reduce(batch, 0, (sum, n) => sum + n)\n * )\n * Array.from(Iterable.take(batchSums, 3)) // => [55, 155, 255]\n * ```\n *\n * @category splitting\n * @since 2.0.0\n */\nexport const chunksOf = /*#__PURE__*/dual(2, (self, n) => {\n const safeN = Count.normalizeNonEmpty(n);\n return {\n [Symbol.iterator]() {\n let iterator = self[Symbol.iterator]();\n return {\n next() {\n if (iterator === undefined) {\n return {\n done: true,\n value: undefined\n };\n }\n const chunk = [];\n for (let i = 0; i < safeN; i++) {\n const result = iterator.next();\n if (result.done) {\n iterator = undefined;\n return chunk.length === 0 ? {\n done: true,\n value: undefined\n } : {\n done: false,\n value: chunk\n };\n }\n chunk.push(result.value);\n }\n return {\n done: false,\n value: chunk\n };\n }\n };\n }\n };\n});\n/**\n * Groups equal, consecutive elements of an `Iterable` into `NonEmptyArray`s using the provided `isEquivalent` function.\n *\n * **Example** (Grouping consecutive elements with custom equivalence)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Group consecutive equal numbers\n * const numbers = [1, 1, 2, 2, 2, 3, 1, 1]\n * const grouped = Iterable.groupWith(numbers, (a, b) => a === b)\n * Array.from(grouped) // => [[1, 1], [2, 2, 2], [3], [1, 1]]\n *\n * // Case-insensitive grouping of strings\n * const words = [\"Apple\", \"APPLE\", \"banana\", \"Banana\", \"cherry\"]\n * const caseInsensitive = (a: string, b: string) =>\n * a.toLowerCase() === b.toLowerCase()\n * const groupedWords = Iterable.groupWith(words, caseInsensitive)\n * Array.from(groupedWords) // => [[\"Apple\", \"APPLE\"], [\"banana\", \"Banana\"], [\"cherry\"]]\n *\n * // Group by approximate equality\n * const floats = [1.1, 1.12, 1.9, 2.01, 2.05, 3.5]\n * const approxEqual = (a: number, b: number) => Math.abs(a - b) < 0.2\n * const groupedFloats = Iterable.groupWith(floats, approxEqual)\n * Array.from(groupedFloats) // => [[1.1, 1.12], [1.9, 2.01, 2.05], [3.5]]\n *\n * // Only groups consecutive elements\n * const scattered = [1, 2, 1, 2, 1]\n * const scatteredGroups = Iterable.groupWith(scattered, (a, b) => a === b)\n * Array.from(scatteredGroups) // => [[1], [2], [1], [2], [1]]\n * ```\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const groupWith = /*#__PURE__*/dual(2, (self, isEquivalent) => ({\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n let nextResult;\n return {\n next() {\n let result;\n if (nextResult !== undefined) {\n if (nextResult.done) {\n return {\n done: true,\n value: undefined\n };\n }\n result = nextResult;\n nextResult = undefined;\n } else {\n result = iterator.next();\n if (result.done) {\n return {\n done: true,\n value: undefined\n };\n }\n }\n const chunk = [result.value];\n while (true) {\n const next = iterator.next();\n if (next.done || !isEquivalent(result.value, next.value)) {\n nextResult = next;\n return {\n done: false,\n value: chunk\n };\n }\n chunk.push(next.value);\n }\n }\n };\n }\n}));\n/**\n * Groups equal, consecutive elements of an `Iterable` into `NonEmptyArray`s.\n *\n * **Example** (Grouping consecutive elements)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 1, 2, 2, 2, 3, 1, 1]\n * const grouped = Iterable.group(numbers)\n * Array.from(grouped) // => [[1, 1], [2, 2, 2], [3], [1, 1]]\n *\n * const letters = \"aabbccaa\"\n * const groupedLetters = Iterable.group(letters)\n * Array.from(groupedLetters) // => [[\"a\", \"a\"], [\"b\", \"b\"], [\"c\", \"c\"], [\"a\", \"a\"]]\n *\n * // Works with objects using deep equality\n * const objects = [\n * { type: \"A\", value: 1 },\n * { type: \"A\", value: 1 },\n * { type: \"B\", value: 2 },\n * { type: \"A\", value: 1 }\n * ]\n * const groupedObjects = Iterable.group(objects)\n * Array.from(groupedObjects).length // => 3\n * // Note: Only consecutive equal objects are grouped together\n * ```\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const group = /*#__PURE__*/groupWith(/*#__PURE__*/Equal.asEquivalence());\n/**\n * Groups all elements by the string or symbol key returned by `f`.\n *\n * **Details**\n *\n * Each property in the returned record contains a non-empty array of elements\n * that produced that key. Unlike `group`, matching elements do not need to be\n * consecutive.\n *\n * **Gotchas**\n *\n * When the key function returns a finite union of string literals or unique\n * symbols, the result preserves those keys as optional properties because the\n * input may not produce every key. Open `string` and `symbol` key types retain\n * their record index signatures.\n *\n * **Example** (Grouping by a key)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Group by string length\n * const words = [\"a\", \"bb\", \"ccc\", \"dd\", \"eee\", \"f\"]\n * const byLength = Iterable.groupBy(words, (word) => word.length.toString())\n * byLength // => { \"1\": [\"a\", \"f\"], \"2\": [\"bb\", \"dd\"], \"3\": [\"ccc\", \"eee\"] }\n *\n * // Group by first letter\n * const names = [\"Alice\", \"Bob\", \"Charlie\", \"David\", \"Anna\", \"Betty\"]\n * const byFirstLetter = Iterable.groupBy(names, (name) => name[0])\n * byFirstLetter // => { A: [\"Alice\", \"Anna\"], B: [\"Bob\", \"Betty\"], C: [\"Charlie\"], D: [\"David\"] }\n *\n * // Group by category\n * const items = [\n * { name: \"apple\", category: \"fruit\" },\n * { name: \"carrot\", category: \"vegetable\" },\n * { name: \"banana\", category: \"fruit\" },\n * { name: \"broccoli\", category: \"vegetable\" }\n * ]\n * const byCategory = Iterable.groupBy(items, (item) => item.category)\n * Object.keys(byCategory) // => [\"fruit\", \"vegetable\"]\n *\n * // Group numbers by even/odd\n * const numbers = [1, 2, 3, 4, 5, 6]\n * const evenOdd = Iterable.groupBy(numbers, (n) => n % 2 === 0 ? \"even\" : \"odd\")\n * evenOdd // => { odd: [1, 3, 5], even: [2, 4, 6] }\n * ```\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const groupBy = /*#__PURE__*/dual(2, (self, f) => {\n const out = {};\n for (const a of self) {\n const k = f(a);\n if (Object.hasOwn(out, k)) {\n out[k].push(a);\n } else {\n InternalRecord.assignProperty(out, k, [a]);\n }\n }\n return out;\n});\nconst constEmpty = {\n [Symbol.iterator]() {\n return constEmptyIterator;\n }\n};\nconst constEmptyIterator = {\n next() {\n return {\n done: true,\n value: undefined\n };\n }\n};\n/**\n * Creates an empty iterable that yields no elements.\n *\n * **When to use**\n *\n * Use when you need an empty iterable as a typed \"no data\" value or a base\n * case for iterable operations.\n *\n * **Example** (Creating an empty iterable)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * Array.from(Iterable.empty<string>()) // => []\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const empty = () => constEmpty;\n/**\n * Creates an iterable containing a single element.\n *\n * **When to use**\n *\n * Use to wrap a single value in an iterable context so it can be combined\n * with other iterable operations.\n *\n * **Example** (Wrapping a single value)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const single = Iterable.of(42)\n * Array.from(single) // => [42]\n *\n * // Useful for creating homogeneous sequences\n * const sequences = [\n * Iterable.of(\"hello\"),\n * Iterable.range(1, 3),\n * Iterable.empty<string>()\n * ]\n *\n * // Can be used with flatMap for conditional inclusion\n * const numbers = [1, 2, 3, 4, 5]\n * const evensOnly = Iterable.flatMap(\n * numbers,\n * (n) => n % 2 === 0 ? Iterable.of(n) : Iterable.empty()\n * )\n * Array.from(evensOnly) // => [2, 4]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const of = a => [a];\n/**\n * Transforms each element of an iterable using a function.\n *\n * **Details**\n *\n * This is one of the most fundamental operations for working with iterables.\n * It applies a transformation function to each element, creating a new iterable\n * with the transformed values. The operation is lazy, so elements are only\n * transformed when the iterable is consumed.\n *\n * **Example** (Mapping elements)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Transform numbers to their squares\n * const numbers = [1, 2, 3, 4, 5]\n * const squares = Iterable.map(numbers, (x) => x * x)\n * Array.from(squares) // => [1, 4, 9, 16, 25]\n *\n * // Use index in transformation\n * const indexed = Iterable.map([\"a\", \"b\", \"c\"], (char, i) => `${i}: ${char}`)\n * Array.from(indexed) // => [\"0: a\", \"1: b\", \"2: c\"]\n *\n * Array.from(Iterable.map(\n * Iterable.map([1, 2, 3], (x) => x * 2),\n * (x) => x + 1\n * )) // => [3, 5, 7]\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => ({\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n let i = 0;\n return {\n next() {\n const result = iterator.next();\n if (result.done) {\n return {\n done: true,\n value: undefined\n };\n }\n return {\n done: false,\n value: f(result.value, i++)\n };\n }\n };\n }\n}));\n/**\n * Applies a function to each element in an Iterable and returns a new Iterable containing the concatenated mapped elements.\n *\n * **Example** (Flat mapping iterables)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Expand each number to a range\n * const numbers = [1, 2, 3]\n * const expanded = Iterable.flatMap(numbers, (n) => Iterable.range(1, n))\n * Array.from(expanded) // => [1, 1, 2, 1, 2, 3]\n *\n * // Split strings into characters\n * const words = [\"hi\", \"bye\"]\n * const chars = Iterable.flatMap(words, (word) => word)\n * Array.from(chars) // => [\"h\", \"i\", \"b\", \"y\", \"e\"]\n *\n * // Conditional expansion with empty iterables\n * const values = [1, 2, 3, 4, 5]\n * const evenMultiples = Iterable.flatMap(\n * values,\n * (n) => n % 2 === 0 ? [n, n * 2, n * 3] : []\n * )\n * Array.from(evenMultiples) // => [2, 4, 6, 4, 8, 12]\n *\n * // Use index in transformation\n * const letters = [\"a\", \"b\", \"c\"]\n * const indexed = Iterable.flatMap(\n * letters,\n * (letter, i) => Iterable.replicate(letter, i + 1)\n * )\n * Array.from(indexed) // => [\"a\", \"b\", \"b\", \"c\", \"c\", \"c\"]\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const flatMap = /*#__PURE__*/dual(2, (self, f) => flatten(map(self, f)));\n/**\n * Flattens an Iterable of Iterables into a single Iterable\n *\n * **Example** (Flattening nested iterables)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Flatten nested arrays\n * const nested = [[1, 2], [3, 4], [5, 6]]\n * const flat = Iterable.flatten(nested)\n * Array.from(flat) // => [1, 2, 3, 4, 5, 6]\n *\n * // Flatten different iterable types\n * const mixed: Array<Iterable<string>> = [\"ab\", \"cd\"]\n * const flatMixed = Iterable.flatten(mixed)\n * Array.from(flatMixed) // => [\"a\", \"b\", \"c\", \"d\"]\n *\n * // Flatten deeply nested (only one level)\n * const deepNested = [[[1, 2]], [[3, 4]]]\n * const oneLevelFlat = Iterable.flatten(deepNested)\n * Array.from(oneLevelFlat) // => [[1, 2], [3, 4]]\n * // [[1, 2], [3, 4]] (still contains arrays)\n *\n * // Empty iterables are handled correctly\n * const withEmpty = [[1, 2], [], [3, 4], []]\n * const flatWithEmpty = Iterable.flatten(withEmpty)\n * Array.from(flatWithEmpty) // => [1, 2, 3, 4]\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const flatten = self => ({\n [Symbol.iterator]() {\n const outerIterator = self[Symbol.iterator]();\n let innerIterator;\n function next() {\n while (true) {\n if (innerIterator === undefined) {\n const next = outerIterator.next();\n if (next.done) {\n return next;\n }\n innerIterator = next.value[Symbol.iterator]();\n }\n const result = innerIterator.next();\n if (!result.done) {\n return result;\n }\n innerIterator = undefined;\n }\n }\n return {\n next\n };\n }\n});\n/**\n * Transforms elements of an iterable using a function that returns a `Result`, keeping only successful values.\n *\n * **Details**\n *\n * This combines mapping and filtering in a single operation. The function is\n * applied to each element, and only elements that result in `Result.succeed`\n * are included in the result.\n *\n * **Example** (Filtering and transforming Result values)\n *\n * ```ts import.meta.vitest\n * import { Iterable, Result } from \"effect\"\n *\n * // Parse strings to numbers, keeping only valid ones\n * const strings = [\"1\", \"2\", \"invalid\", \"4\", \"not-a-number\"]\n * const numbers = Iterable.filterMap(strings, (s) => {\n * const num = parseInt(s)\n * return isNaN(num) ? Result.failVoid : Result.succeed(num)\n * })\n * Array.from(numbers) // => [1, 2, 4]\n *\n * // Extract specific properties from objects\n * const users = [\n * { name: \"Alice\", age: 25, email: \"alice@example.com\" },\n * { name: \"Bob\", age: 17, email: undefined },\n * { name: \"Charlie\", age: 30, email: \"charlie@example.com\" },\n * { name: \"David\", age: 16, email: undefined }\n * ]\n * const adultEmails = Iterable.filterMap(\n * users,\n * (user) =>\n * user.age >= 18 && user.email ? Result.succeed(user.email) : Result.failVoid\n * )\n * Array.from(adultEmails) // => [\"alice@example.com\", \"charlie@example.com\"]\n *\n * // Use index in transformation\n * const items = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n * const evenIndexItems = Iterable.filterMap(\n * items,\n * (item, i) => i % 2 === 0 ? Result.succeed(`${i}: ${item}`) : Result.failVoid\n * )\n * Array.from(evenIndexItems) // => [\"0: a\", \"2: c\", \"4: e\"]\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const filterMap = /*#__PURE__*/dual(2, (self, f) => ({\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n let i = 0;\n return {\n next() {\n let result = iterator.next();\n while (!result.done) {\n const next = f(result.value, i++);\n if (R.isSuccess(next)) {\n return {\n done: false,\n value: next.success\n };\n }\n result = iterator.next();\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n}));\n/**\n * Transforms all elements of the `Iterable` for as long as the specified function succeeds.\n *\n * **Example** (Filtering and transforming until failure)\n *\n * ```ts import.meta.vitest\n * import { Iterable, Result } from \"effect\"\n *\n * // Parse numbers until we hit an invalid one\n * const strings = [\"1\", \"2\", \"3\", \"invalid\", \"4\", \"5\"]\n * const numbers = Iterable.filterMapWhile(strings, (s) => {\n * const num = parseInt(s)\n * return isNaN(num) ? Result.failVoid : Result.succeed(num)\n * })\n * Array.from(numbers) // => [1, 2, 3]\n *\n * // Take elements while they meet a condition and transform them\n * const values = [2, 4, 6, 7, 8, 10]\n * const doubledEvens = Iterable.filterMapWhile(\n * values,\n * (n) => n % 2 === 0 ? Result.succeed(n * 2) : Result.failVoid\n * )\n * Array.from(doubledEvens) // => [4, 8, 12]\n *\n * // Process with index until condition fails\n * const letters = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n * const indexedUntilC = Iterable.filterMapWhile(\n * letters,\n * (letter, i) => letter !== \"c\" ? Result.succeed(`${i}: ${letter}`) : Result.failVoid\n * )\n * Array.from(indexedUntilC) // => [\"0: a\", \"1: b\"]\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const filterMapWhile = /*#__PURE__*/dual(2, (self, f) => ({\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n let i = 0;\n return {\n next() {\n const result = iterator.next();\n if (result.done) {\n return {\n done: true,\n value: undefined\n };\n }\n const next = f(result.value, i++);\n if (R.isSuccess(next)) {\n return {\n done: false,\n value: next.success\n };\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n}));\n/**\n * Retrieves the `Some` values from an `Iterable` of `Option`s.\n *\n * **Example** (Extracting Some values)\n *\n * ```ts import.meta.vitest\n * import { Iterable, Option } from \"effect\"\n *\n * Array.from(Iterable.getSomes([Option.some(1), Option.none(), Option.some(2)])) // => [1, 2]\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const getSomes = self => {\n return {\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n return {\n next() {\n let result = iterator.next();\n while (!result.done) {\n if (O.isSome(result.value)) {\n return {\n done: false,\n value: result.value.value\n };\n }\n result = iterator.next();\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n };\n};\n/**\n * Returns a lazy iterable containing the failure values from an iterable of\n * `Result`s, skipping successful results.\n *\n * **Example** (Extracting failures)\n *\n * ```ts import.meta.vitest\n * import { Iterable, Result } from \"effect\"\n *\n * Array.from(Iterable.getFailures([\n * Result.succeed(1),\n * Result.fail(\"err\"),\n * Result.succeed(2)\n * ])) // => [\"err\"]\n * ```\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const getFailures = self => {\n return {\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n return {\n next() {\n let result = iterator.next();\n while (!result.done) {\n if (R.isFailure(result.value)) {\n return {\n done: false,\n value: result.value.failure\n };\n }\n result = iterator.next();\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n };\n};\n/**\n * Returns a lazy iterable containing the success values from an iterable of\n * `Result`s, skipping failed results.\n *\n * **Example** (Extracting successes)\n *\n * ```ts import.meta.vitest\n * import { Iterable, Result } from \"effect\"\n *\n * Array.from(Iterable.getSuccesses([\n * Result.succeed(1),\n * Result.fail(\"err\"),\n * Result.succeed(2)\n * ])) // => [1, 2]\n * ```\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const getSuccesses = self => {\n return {\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n return {\n next() {\n let result = iterator.next();\n while (!result.done) {\n if (R.isSuccess(result.value)) {\n return {\n done: false,\n value: result.value.success\n };\n }\n result = iterator.next();\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n };\n};\n/**\n * Filters an iterable to only include elements that match a predicate.\n *\n * **Details**\n *\n * This function creates a new iterable containing only the elements for which\n * the predicate function returns true. Like map, this operation is lazy and\n * elements are only tested when the iterable is consumed.\n *\n * **Example** (Filtering elements)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Filter even numbers\n * const numbers = [1, 2, 3, 4, 5, 6]\n * const evens = Iterable.filter(numbers, (x) => x % 2 === 0)\n * Array.from(evens) // => [2, 4, 6]\n *\n * // Filter with index\n * const items = [\"a\", \"b\", \"c\", \"d\"]\n * const oddPositions = Iterable.filter(items, (_, i) => i % 2 === 1)\n * Array.from(oddPositions) // => [\"b\", \"d\"]\n *\n * // Type refinement\n * const mixed: Array<string | number> = [\"hello\", 42, \"world\", 100]\n * const onlyStrings = Iterable.filter(\n * mixed,\n * (x): x is string => typeof x === \"string\"\n * )\n * Array.from(onlyStrings) // => [\"hello\", \"world\"]\n *\n * // Combine with map\n * const processed = Iterable.map(\n * Iterable.filter([1, 2, 3, 4, 5], (x) => x > 2),\n * (x) => x * 10\n * )\n * Array.from(processed) // => [30, 40, 50]\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const filter = /*#__PURE__*/dual(2, (self, predicate) => ({\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n let i = 0;\n return {\n next() {\n let result = iterator.next();\n while (!result.done) {\n if (predicate(result.value, i++)) {\n return {\n done: false,\n value: result.value\n };\n }\n result = iterator.next();\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n}));\n/**\n * Transforms elements using a function that may return null or undefined, filtering out the null/undefined results.\n *\n * **When to use**\n *\n * Use when working with APIs or functions that return nullable values,\n * providing a clean way to filter out null or undefined while transforming.\n *\n * **Example** (Flat mapping nullable results)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Extract valid elements from nullable function results\n * const data = [\"1\", \"2\", \"invalid\", \"4\"]\n * const parsed = Iterable.flatMapNullishOr(data, (s) => {\n * const num = parseInt(s)\n * return isNaN(num) ? null : num * 2\n * })\n * Array.from(parsed) // => [2, 4, 8]\n *\n * // Safe property access\n * const objects = [\n * { nested: { value: 10 } },\n * { nested: null },\n * { nested: { value: 20 } },\n * {}\n * ]\n * const values = Iterable.flatMapNullishOr(objects, (obj) => obj.nested?.value)\n * Array.from(values) // => [10, 20]\n *\n * // Working with Map.get (returns undefined for missing keys)\n * const map = new Map([\n * [\"a\", 1],\n * [\"b\", 2],\n * [\"c\", 3]\n * ])\n * const keys = [\"a\", \"x\", \"b\", \"y\", \"c\"]\n * const foundValues = Iterable.flatMapNullishOr(keys, (key) => map.get(key))\n * Array.from(foundValues) // => [1, 2, 3]\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const flatMapNullishOr = /*#__PURE__*/dual(2, (self, f) => filterMap(self, a => {\n const b = f(a);\n return b == null ? R.failVoid : R.succeed(b);\n}));\n/**\n * Checks whether a predicate holds true for some `Iterable` element.\n *\n * **Example** (Checking whether some element matches)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 3, 5, 7, 8]\n * const hasEven = Iterable.some(numbers, (x) => x % 2 === 0)\n * hasEven // => true\n *\n * const allOdd = [1, 3, 5, 7]\n * const hasEvenInAllOdd = Iterable.some(allOdd, (x) => x % 2 === 0)\n * hasEvenInAllOdd // => false\n *\n * // With index\n * const letters = [\"a\", \"b\", \"c\"]\n * const hasElementAtIndex2 = Iterable.some(letters, (_, i) => i === 2)\n * hasElementAtIndex2 // => true\n *\n * // Early termination - stops at first match\n * const infiniteOdds = Iterable.filter(Iterable.range(1), (x) => x % 2 === 1)\n * const hasEvenInInfiniteOdds = Iterable.some(\n * Iterable.take(infiniteOdds, 1000),\n * (x) => x % 2 === 0\n * )\n * hasEvenInInfiniteOdds // => false\n *\n * // Type guard usage\n * const mixed: Array<string | number> = [1, 2, \"hello\"]\n * const hasString = Iterable.some(\n * mixed,\n * (x): x is string => typeof x === \"string\"\n * )\n * hasString // => true\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const some = /*#__PURE__*/dual(2, (self, predicate) => {\n let i = 0;\n for (const a of self) {\n if (predicate(a, i++)) {\n return true;\n }\n }\n return false;\n});\n/**\n * Generates an iterable by repeatedly applying a function that produces the\n * next element and state.\n *\n * **Details**\n *\n * This is useful for creating iterables from a generating function that\n * maintains state. The function should return `Option.some([value, nextState])`\n * to continue or `Option.none()` to stop.\n *\n * **Example** (Unfolding state into values)\n *\n * ```ts import.meta.vitest\n * import { Iterable, Option } from \"effect\"\n *\n * // Generate Fibonacci sequence\n * const fibonacci = Iterable.unfold([0, 1], ([a, b]) => Option.some([a, [b, a + b]]))\n * const first10Fib = Iterable.take(fibonacci, 10)\n * Array.from(first10Fib) // => [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n *\n * // Generate powers of 2 up to a limit\n * const powersOf2 = Iterable.unfold(1, (n) => n <= 1000 ? Option.some([n, n * 2]) : Option.none())\n * Array.from(powersOf2) // => [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]\n *\n * // Generate countdown\n * const countdown = Iterable.unfold(5, (n) => n > 0 ? Option.some([n, n - 1]) : Option.none())\n * Array.from(countdown) // => [5, 4, 3, 2, 1]\n *\n * // Generate collatz sequence\n * const collatz = Iterable.unfold(7, (n) => {\n * if (n === 1) return Option.none()\n * const next = n % 2 === 0 ? n / 2 : n * 3 + 1\n * return Option.some([n, next])\n * })\n * Array.from(collatz) // => [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const unfold = (b, f) => ({\n [Symbol.iterator]() {\n let next = b;\n return {\n next() {\n const ab = f(next);\n if (O.isNone(ab)) {\n return {\n done: true,\n value: undefined\n };\n }\n const [a, b] = ab.value;\n next = b;\n return {\n done: false,\n value: a\n };\n }\n };\n }\n});\n/**\n * Iterates over the `Iterable`, applying `f` to each element.\n *\n * **Example** (Iterating with side effects)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Collect each visited element\n * const numbers = [1, 2, 3, 4, 5]\n * const visited: Array<number> = []\n * Iterable.forEach(numbers, (n) => visited.push(n))\n * visited // => [1, 2, 3, 4, 5]\n *\n * // Use index in the callback\n * const letters = [\"a\", \"b\", \"c\"]\n * const indexed: Array<string> = []\n * Iterable.forEach(letters, (letter, i) => {\n * indexed.push(`${i}: ${letter}`)\n * })\n * indexed // => [\"0: a\", \"1: b\", \"2: c\"]\n *\n * // Side effects with any iterable\n * const results: Array<number> = []\n * Iterable.forEach(Iterable.range(1, 5), (n) => {\n * results.push(n * n)\n * })\n * results // => [1, 4, 9, 16, 25]\n *\n * // Process in chunks\n * const data = Iterable.chunksOf([1, 2, 3, 4, 5, 6], 2)\n * const processed: Array<Array<number>> = []\n * Iterable.forEach(data, (chunk) => {\n * processed.push(Array.from(chunk))\n * })\n * processed // => [[1, 2], [3, 4], [5, 6]]\n * ```\n *\n * @category traversing\n * @since 2.0.0\n */\nexport const forEach = /*#__PURE__*/dual(2, (self, f) => {\n let i = 0;\n for (const a of self) {\n f(a, i++);\n }\n});\n/**\n * Reduces an iterable to a single value by applying a function to each element and accumulating the result.\n *\n * **Details**\n *\n * This function applies a reducing function against an accumulator and each element\n * of the iterable (from left to right) to reduce it to a single value.\n *\n * **Example** (Reducing an iterable)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Sum all numbers\n * const numbers = [1, 2, 3, 4, 5]\n * const sum = Iterable.reduce(numbers, 0, (acc, n) => acc + n)\n * sum // => 15\n *\n * // Find maximum value\n * const values = [3, 1, 4, 1, 5, 9, 2]\n * Iterable.reduce(values, -Infinity, (max, value) => Math.max(max, value)) // => 9\n *\n * // Build an object from key-value pairs\n * const pairs = [[\"a\", 1], [\"b\", 2], [\"c\", 3]] as const\n * const obj = Iterable.reduce(\n * pairs,\n * {} as Record<string, number>,\n * (acc, [key, value]) => {\n * acc[key] = value\n * return acc\n * }\n * )\n * obj // => { a: 1, b: 2, c: 3 }\n *\n * // Use index in the reducer\n * const letters = [\"a\", \"b\", \"c\"]\n * const indexed = Iterable.reduce(\n * letters,\n * [] as Array<string>,\n * (acc, letter, i) => {\n * acc.push(`${i}: ${letter}`)\n * return acc\n * }\n * )\n * indexed // => [\"0: a\", \"1: b\", \"2: c\"]\n * ```\n *\n * @category folding\n * @since 2.0.0\n */\nexport const reduce = /*#__PURE__*/dual(3, (self, b, f) => {\n if (Array.isArray(self)) {\n return self.reduce(f, b);\n }\n let i = 0;\n let result = b;\n for (const n of self) {\n result = f(result, n, i++);\n }\n return result;\n});\n/**\n * Deduplicates adjacent elements that are identical using the provided `isEquivalent` function.\n *\n * **Example** (Deduplicating adjacent elements with custom equivalence)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Remove adjacent duplicates with custom equality\n * const numbers = [1, 1, 2, 2, 3, 1, 1]\n * const dedupedNumbers = Iterable.dedupeAdjacentWith(numbers, (a, b) => a === b)\n * Array.from(dedupedNumbers) // => [1, 2, 3, 1]\n *\n * // Case-insensitive deduplication\n * const words = [\"Hello\", \"HELLO\", \"world\", \"World\", \"test\"]\n * const caseInsensitive = (a: string, b: string) =>\n * a.toLowerCase() === b.toLowerCase()\n * const dedupedWords = Iterable.dedupeAdjacentWith(words, caseInsensitive)\n * Array.from(dedupedWords) // => [\"Hello\", \"world\", \"test\"]\n *\n * // Deduplication by object property\n * const users = [\n * { id: 1, name: \"Alice\" },\n * { id: 1, name: \"Alice Updated\" }, // different name, same id\n * { id: 2, name: \"Bob\" },\n * { id: 2, name: \"Bob\" },\n * { id: 3, name: \"Charlie\" }\n * ]\n * const byId = (a: typeof users[0], b: typeof users[0]) => a.id === b.id\n * const dedupedUsers = Iterable.dedupeAdjacentWith(users, byId)\n * Array.from(dedupedUsers, (user) => user.id) // => [1, 2, 3]\n *\n * // Approximate numeric equality\n * const floats = [1.0, 1.01, 1.02, 2.0, 2.01, 3.0]\n * const approxEqual = (a: number, b: number) => Math.abs(a - b) < 0.1\n * const dedupedFloats = Iterable.dedupeAdjacentWith(floats, approxEqual)\n * Array.from(dedupedFloats) // => [1, 2, 3]\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const dedupeAdjacentWith = /*#__PURE__*/dual(2, (self, isEquivalent) => ({\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n let first = true;\n let last;\n function next() {\n const result = iterator.next();\n if (result.done) {\n return {\n done: true,\n value: undefined\n };\n }\n if (first) {\n first = false;\n last = result.value;\n return result;\n }\n const current = result.value;\n if (isEquivalent(last, current)) {\n return next();\n }\n last = current;\n return result;\n }\n return {\n next\n };\n }\n}));\n/**\n * Deduplicates adjacent elements that are identical.\n *\n * **Example** (Deduplicating adjacent elements)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Remove adjacent duplicate numbers\n * const numbers = [1, 1, 2, 2, 2, 3, 1, 1]\n * const deduped = Iterable.dedupeAdjacent(numbers)\n * Array.from(deduped) // => [1, 2, 3, 1]\n *\n * // Remove adjacent duplicate characters\n * const letters = \"aabbccaa\"\n * const dedupedLetters = Iterable.dedupeAdjacent(letters)\n * Array.from(dedupedLetters) // => [\"a\", \"b\", \"c\", \"a\"]\n *\n * // Works with objects using deep equality\n * const objects = [\n * { type: \"A\" },\n * { type: \"A\" },\n * { type: \"B\" },\n * { type: \"B\" },\n * { type: \"A\" }\n * ]\n * const dedupedObjects = Iterable.dedupeAdjacent(objects)\n * Array.from(dedupedObjects, (object) => object.type) // => [\"A\", \"B\", \"A\"]\n *\n * // Clean up streaming data\n * const sensorData = [100, 100, 100, 101, 101, 102, 102, 102, 100]\n * const cleanedData = Iterable.dedupeAdjacent(sensorData)\n * Array.from(cleanedData) // => [100, 101, 102, 100]\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const dedupeAdjacent = /*#__PURE__*/dedupeAdjacentWith(/*#__PURE__*/Equal.asEquivalence());\n/**\n * Zips this Iterable crosswise with the specified Iterable using the specified combiner.\n *\n * **Example** (Combining cartesian products)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Create coordinate pairs\n * const xs = [1, 2]\n * const ys = [\"a\", \"b\", \"c\"]\n * const coordinates = Iterable.cartesianWith(xs, ys, (x, y) => `(${x},${y})`)\n * Array.from(coordinates) // => [\"(1,a)\", \"(1,b)\", \"(1,c)\", \"(2,a)\", \"(2,b)\", \"(2,c)\"]\n *\n * // Generate all combinations of options\n * const sizes = [\"S\", \"M\", \"L\"]\n * const colors = [\"red\", \"blue\"]\n * const products = Iterable.cartesianWith(\n * sizes,\n * colors,\n * (size, color) => ({ size, color })\n * )\n * Array.from(products, ({ color, size }) => `${size}:${color}`) // => [\"S:red\", \"S:blue\", \"M:red\", \"M:blue\", \"L:red\", \"L:blue\"]\n *\n * // Mathematical operations on all pairs\n * const a = [1, 2, 3]\n * const b = [10, 20]\n * const mathProducts = Iterable.cartesianWith(a, b, (x, y) => x * y)\n * Array.from(mathProducts) // => [10, 20, 20, 40, 30, 60]\n *\n * // Create test data combinations\n * const userTypes = [\"admin\", \"user\"]\n * const features = [\"read\", \"write\", \"delete\"]\n * const testCases = Iterable.cartesianWith(\n * userTypes,\n * features,\n * (user, feature) => `${user}_can_${feature}`\n * )\n * Array.from(testCases) // => [\"admin_can_read\", \"admin_can_write\", \"admin_can_delete\", \"user_can_read\", \"user_can_write\", \"user_can_delete\"]\n * ```\n *\n * @category combining\n * @since 2.0.0\n */\nexport const cartesianWith = /*#__PURE__*/dual(3, (self, that, f) => ({\n [Symbol.iterator]() {\n const cache = [];\n let iterator;\n let done = false;\n const replay = {\n [Symbol.iterator]() {\n let index = 0;\n return {\n next() {\n if (index < cache.length) {\n return {\n done: false,\n value: cache[index++]\n };\n }\n if (done) {\n return {\n done: true,\n value: undefined\n };\n }\n iterator ??= that[Symbol.iterator]();\n const result = iterator.next();\n if (result.done) {\n done = true;\n return {\n done: true,\n value: undefined\n };\n }\n cache.push(result.value);\n index++;\n return result;\n }\n };\n }\n };\n return flatMap(self, a => map(replay, b => f(a, b)))[Symbol.iterator]();\n }\n}));\n/**\n * Zips this Iterable crosswise with the specified Iterable.\n *\n * **Example** (Generating cartesian pairs)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // All pairs of numbers and letters\n * const numbers = [1, 2, 3]\n * const letters = [\"a\", \"b\"]\n * const pairs = Iterable.cartesian(numbers, letters)\n * Array.from(pairs) // => [[1, \"a\"], [1, \"b\"], [2, \"a\"], [2, \"b\"], [3, \"a\"], [3, \"b\"]]\n *\n * // Generate coordinate grid\n * const x = [0, 1, 2]\n * const y = [0, 1]\n * const grid = Iterable.cartesian(x, y)\n * Array.from(grid) // => [[0, 0], [0, 1], [1, 0], [1, 1], [2, 0], [2, 1]]\n *\n * // All combinations for testing\n * const browsers = [\"chrome\", \"firefox\"]\n * const devices = [\"desktop\", \"mobile\", \"tablet\"]\n * const testMatrix = Iterable.cartesian(browsers, devices)\n * Array.from(testMatrix, ([browser, device]) => `${browser}:${device}`) // => [\"chrome:desktop\", \"chrome:mobile\", \"chrome:tablet\", \"firefox:desktop\", \"firefox:mobile\", \"firefox:tablet\"]\n *\n * // Empty iterable results in empty cartesian product\n * const empty = Iterable.empty<number>()\n * const withEmpty = Iterable.cartesian([1, 2], empty)\n * Array.from(withEmpty) // => []\n * ```\n *\n * @category combining\n * @since 2.0.0\n */\nexport const cartesian = /*#__PURE__*/dual(2, (self, that) => cartesianWith(self, that, (a, b) => [a, b]));\n/**\n * Computes how many elements of the iterable pass the given predicate.\n *\n * **Example** (Counting matching elements)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * Iterable.countBy([1, 2, 3, 4, 5], (n) => n % 2 === 0) // => 2\n * ```\n *\n * @category folding\n * @since 3.16.0\n */\nexport const countBy = /*#__PURE__*/dual(2, (self, f) => {\n let count = 0;\n let i = 0;\n for (const a of self) {\n if (f(a, i)) {\n count++;\n }\n i++;\n }\n return count;\n});\n//# sourceMappingURL=Iterable.js.map","/**\n * Works with JavaScript arrays, readonly arrays, and non-empty arrays.\n *\n * The helpers cover common collection work such as creating arrays, reading\n * elements, transforming values, sorting, grouping, splitting, combining, and\n * reducing many values to one result. Helpers that change contents return new\n * arrays and preserve non-empty array types when the result is guaranteed to\n * contain values.\n *\n * @since 2.0.0\n */\nimport * as Equal from \"./Equal.js\";\nimport * as Equivalence from \"./Equivalence.js\";\nimport { dual, identity } from \"./Function.js\";\nimport * as Hash from \"./Hash.js\";\nimport * as internalArray from \"./internal/array.js\";\nimport * as Count from \"./internal/count.js\";\nimport * as internalDoNotation from \"./internal/doNotation.js\";\nimport * as InternalRecord from \"./internal/record.js\";\nimport * as moduleIterable from \"./Iterable.js\";\nimport * as Option from \"./Option.js\";\nimport * as Order from \"./Order.js\";\nimport * as Record from \"./Record.js\";\nimport * as Reducer from \"./Reducer.js\";\nimport * as Result from \"./Result.js\";\nimport * as Tuple from \"./Tuple.js\";\n/**\n * Exposes the global array constructor.\n *\n * **When to use**\n *\n * Use to access native JavaScript array constructor methods such as `isArray`\n * or `from` from the Effect module namespace.\n *\n * **Example** (Accessing the Array constructor)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.Array === globalThis.Array // => true\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Array = globalThis.Array;\n/**\n * Creates a `NonEmptyArray` from one or more elements.\n *\n * **When to use**\n *\n * Use when you need to create a typed non-empty array from literal values.\n *\n * **Details**\n *\n * The element type is inferred as the union of all arguments. Because at least\n * one argument is required, this always returns a `NonEmptyArray`.\n *\n * **Example** (Creating an array from values)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.make(1, 2, 3) // => [1, 2, 3]\n * ```\n *\n * @see {@link of} — create a single-element array\n * @see {@link fromIterable} — create from any iterable\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const make = (...elements) => elements;\n/**\n * Creates a new `Array` of the specified length with all slots uninitialized.\n *\n * **When to use**\n *\n * Use when you need a pre-sized array that will be filled imperatively.\n *\n * **Details**\n *\n * `n` is rounded down. `NaN` and non-positive values are treated as `0`.\n * Elements are typed as `A | undefined` because the slots are empty.\n *\n * **Example** (Allocating a fixed-size array)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.allocate<number>(3).length // => 3\n * ```\n *\n * @see {@link makeBy} — create an array by computing each element\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const allocate = n => new Array(Count.normalize(n));\n/**\n * Creates a `NonEmptyArray` of length `n` where element `i` is computed by `f(i)`.\n *\n * **When to use**\n *\n * Use when you need to compute each array element from its index.\n *\n * **Details**\n *\n * `n` is rounded down and normalized to an integer greater than or equal to 1.\n * `NaN` is treated as `1`, so this function always returns at least one\n * element. Supports both data-first and data-last usage.\n *\n * **Example** (Generating values from indices)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.makeBy(5, (n) => n * 2) // => [0, 2, 4, 6, 8]\n * ```\n *\n * @see {@link range} — create a range of integers\n * @see {@link replicate} — repeat a single value\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const makeBy = /*#__PURE__*/dual(2, (n, f) => {\n const max = Count.normalizeNonEmpty(n);\n const out = new Array(max);\n for (let i = 0; i < max; i++) {\n out[i] = f(i);\n }\n return out;\n});\n/**\n * Creates a `NonEmptyArray` containing a range of integers, inclusive on both\n * ends.\n *\n * **When to use**\n *\n * Use when you need a non-empty sequence of consecutive integers.\n *\n * **Details**\n *\n * If `start > end`, returns `[start]`.\n *\n * **Example** (Creating a range)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.range(1, 3) // => [1, 2, 3]\n * ```\n *\n * @see {@link makeBy} — generate values from a function\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const range = (start, end) => start <= end ? makeBy(end - start + 1, i => start + i) : [start];\n/**\n * Creates a `NonEmptyArray` containing a value repeated `n` times.\n *\n * **When to use**\n *\n * Use when you need a non-empty array containing repeated copies of one value.\n *\n * **Details**\n *\n * `n` is normalized to an integer greater than or equal to 1, so this function\n * always returns at least one element. Supports both data-first and data-last\n * usage.\n *\n * **Example** (Repeating a value)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.replicate(\"a\", 3) // => [\"a\", \"a\", \"a\"]\n * ```\n *\n * @see {@link makeBy} — vary values based on index\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const replicate = /*#__PURE__*/dual(2, (a, n) => makeBy(n, () => a));\n/**\n * Converts an `Iterable` to an `Array`.\n *\n * **When to use**\n *\n * Use to convert any `Iterable` (Set, Generator, etc.) into an array.\n *\n * **Details**\n *\n * If the input is already an array, this returns it by reference without\n * copying. Otherwise, it creates a new array from the iterable. Use `copy` if\n * you need a fresh array even when the input is already an array.\n *\n * **Example** (Converting a Set to an array)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3]\n * ```\n *\n * @see {@link ensure} — wrap a single value or return an existing array\n * @see {@link copy} — create a shallow copy of an array\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromIterable = collection => Array.isArray(collection) ? collection : Array.from(collection);\n/**\n * Normalizes a value that is either a single element or an array into an array.\n *\n * **When to use**\n *\n * Use to normalize input that may be a single value or an array into a consistent\n * array.\n *\n * **Details**\n *\n * If the input is already an array, this returns it by reference. If the input\n * is a single value, this wraps it in a one-element array. This is useful for\n * APIs that accept `A | Array<A>`.\n *\n * **Example** (Normalizing input)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.ensure(\"a\") // => [\"a\"]\n * Array.ensure([\"a\", \"b\", \"c\"]) // => [\"a\", \"b\", \"c\"]\n * ```\n *\n * @see {@link of} — always wrap in a single-element array\n * @see {@link fromIterable} — convert any iterable\n *\n * @category constructors\n * @since 3.3.0\n */\nexport const ensure = self => Array.isArray(self) ? self : [self];\n/**\n * Converts a record into an array of `[key, value]` tuples.\n *\n * **When to use**\n *\n * Use to convert a record into an array of key-value tuples for iteration or\n * transformation.\n *\n * **Details**\n *\n * Key order follows `Object.entries` semantics. Empty records produce an empty\n * array.\n *\n * **Example** (Converting a record to entries)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.fromRecord({ a: 1, b: 2, c: 3 }) // => [[\"a\", 1], [\"b\", 2], [\"c\", 3]]\n * ```\n *\n * @see {@link Record.toEntries} the equivalent function from the Record module\n * @see {@link Record.fromEntries} to build a record from an array of tuples\n *\n * @category converting\n * @since 2.0.0\n */\nexport const fromRecord = Record.toEntries;\n/**\n * Converts an `Option` to an array: `Some(a)` becomes `[a]`, `None` becomes `[]`.\n *\n * **When to use**\n *\n * Use to convert a single `Option` into an array for downstream array operations.\n *\n * **Example** (Converting an Option to an array)\n *\n * ```ts import.meta.vitest\n * import { Array, Option } from \"effect\"\n *\n * Array.fromOption(Option.some(1)) // => [1]\n * Array.fromOption(Option.none()) // => []\n * ```\n *\n * @see {@link getSomes} — extract `Some` values from an array of Options\n *\n * @category converting\n * @since 2.0.0\n */\nexport const fromOption = Option.toArray;\n/**\n * Pattern-matches on an array, handling empty and non-empty cases separately.\n *\n * **When to use**\n *\n * Use when you need to branch on whether an array is empty.\n *\n * **Details**\n *\n * `onNonEmpty` receives a `NonEmptyReadonlyArray`. Supports both data-first and\n * data-last usage.\n *\n * **Example** (Branching on emptiness)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * const describe = Array.match({\n * onEmpty: () => \"empty\",\n * onNonEmpty: ([head, ...tail]) => `head: ${head}, tail: ${tail.length}`\n * })\n *\n * describe([]) // => \"empty\"\n * describe([1, 2, 3]) // => \"head: 1, tail: 2\"\n * ```\n *\n * @see {@link matchLeft} — destructures into head + tail\n * @see {@link matchRight} — destructures into init + last\n *\n * @category pattern matching\n * @since 2.0.0\n */\nexport const match = /*#__PURE__*/dual(2, (self, {\n onEmpty,\n onNonEmpty\n}) => isReadonlyArrayNonEmpty(self) ? onNonEmpty(self) : onEmpty());\n/**\n * Pattern-matches on an array from the left, providing the first element and\n * the remaining elements separately.\n *\n * **When to use**\n *\n * Use when you need to branch on an array and handle the non-empty case as the\n * first element plus the remaining elements.\n *\n * **Details**\n *\n * `onNonEmpty` receives `(head, tail)` where `tail` is the rest of the array.\n *\n * **Example** (Destructuring head and tail)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * const matchLeft = Array.matchLeft({\n * onEmpty: () => \"empty\",\n * onNonEmpty: (head, tail) => `head: ${head}, tail: ${tail.length}`\n * })\n *\n * matchLeft([]) // => \"empty\"\n * matchLeft([1, 2, 3]) // => \"head: 1, tail: 2\"\n * ```\n *\n * @see {@link match} — receives the full non-empty array\n * @see {@link matchRight} — destructures into init + last\n *\n * @category pattern matching\n * @since 2.0.0\n */\nexport const matchLeft = /*#__PURE__*/dual(2, (self, {\n onEmpty,\n onNonEmpty\n}) => isReadonlyArrayNonEmpty(self) ? onNonEmpty(headNonEmpty(self), tailNonEmpty(self)) : onEmpty());\n/**\n * Pattern-matches on an array from the right, providing all elements except the\n * last and the last element separately.\n *\n * **When to use**\n *\n * Use when you need to branch on an array and handle the non-empty case as the\n * elements before the last plus the last element.\n *\n * **Details**\n *\n * `onNonEmpty` receives `(init, last)` where `init` is everything but the last element.\n *\n * **Example** (Destructuring init and last)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * const matchRight = Array.matchRight({\n * onEmpty: () => \"empty\",\n * onNonEmpty: (init, last) => `init: ${init.length}, last: ${last}`\n * })\n *\n * matchRight([]) // => \"empty\"\n * matchRight([1, 2, 3]) // => \"init: 2, last: 3\"\n * ```\n *\n * @see {@link match} — receives the full non-empty array\n * @see {@link matchLeft} — destructures into head + tail\n *\n * @category pattern matching\n * @since 2.0.0\n */\nexport const matchRight = /*#__PURE__*/dual(2, (self, {\n onEmpty,\n onNonEmpty\n}) => isReadonlyArrayNonEmpty(self) ? onNonEmpty(initNonEmpty(self), lastNonEmpty(self)) : onEmpty());\n/**\n * Adds a single element to the front of an iterable, returning a `NonEmptyArray`.\n *\n * **When to use**\n *\n * Use when you need to guarantee a non-empty result after adding a required\n * leading value.\n *\n * **Example** (Prepending an element)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.prepend([2, 3, 4], 1) // => [1, 2, 3, 4]\n * ```\n *\n * @see {@link append} — add to the end\n * @see {@link prependAll} — prepend multiple elements\n *\n * @category combining\n * @since 2.0.0\n */\nexport const prepend = /*#__PURE__*/dual(2, (self, head) => [head, ...self]);\n/**\n * Prepends all elements from a prefix iterable to the front of an array.\n *\n * **When to use**\n *\n * Use to prepend multiple elements from an iterable to the front of an array.\n *\n * **Details**\n *\n * If either input is non-empty, the result is a `NonEmptyArray`.\n *\n * **Example** (Prepending multiple elements)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.prependAll([2, 3], [0, 1]) // => [0, 1, 2, 3]\n * ```\n *\n * @see {@link prepend} — add a single element to the front\n * @see {@link appendAll} — add elements to the end\n *\n * @category combining\n * @since 2.0.0\n */\nexport const prependAll = /*#__PURE__*/dual(2, (self, that) => fromIterable(that).concat(fromIterable(self)));\n/**\n * Adds a single element to the end of an iterable, returning a `NonEmptyArray`.\n *\n * **When to use**\n *\n * Use when you need to guarantee a non-empty result after adding a required\n * trailing value.\n *\n * **Example** (Appending an element)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.append([1, 2, 3], 4) // => [1, 2, 3, 4]\n * ```\n *\n * @see {@link prepend} — add to the front\n * @see {@link appendAll} — append multiple elements\n *\n * @category combining\n * @since 2.0.0\n */\nexport const append = /*#__PURE__*/dual(2, (self, last) => [...self, last]);\n/**\n * Concatenates two iterables into a single array.\n *\n * **When to use**\n *\n * Use to combine two iterable inputs into a new array with the second input's\n * elements after the first.\n *\n * **Details**\n *\n * If either input is non-empty, the result is a `NonEmptyArray`.\n *\n * **Example** (Concatenating arrays)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.appendAll([1, 2], [3, 4]) // => [1, 2, 3, 4]\n * ```\n *\n * @see {@link append} — add a single element to the end\n * @see {@link prependAll} — add elements to the front\n *\n * @category combining\n * @since 2.0.0\n */\nexport const appendAll = /*#__PURE__*/dual(2, (self, that) => fromIterable(self).concat(fromIterable(that)));\n/**\n * Folds left-to-right while keeping every intermediate accumulator value.\n *\n * **When to use**\n *\n * Use to compute a running accumulator where each intermediate value is needed.\n *\n * **Details**\n *\n * The output length is `input.length + 1` because it starts with the initial\n * value. The result is always a `NonEmptyArray`. Use `reduce` if you only need\n * the final accumulated value.\n *\n * **Example** (Running totals)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.scan([1, 2, 3, 4], 0, (acc, value) => acc + value) // => [0, 1, 3, 6, 10]\n * ```\n *\n * @see {@link scanRight} — right-to-left scan\n * @see {@link reduce} — fold without intermediate values\n *\n * @category folding\n * @since 2.0.0\n */\nexport const scan = /*#__PURE__*/dual(3, (self, b, f) => {\n const out = [b];\n let i = 0;\n for (const a of self) {\n out[i + 1] = f(out[i], a);\n i++;\n }\n return out;\n});\n/**\n * Folds right-to-left while keeping every intermediate accumulator value.\n *\n * **When to use**\n *\n * Use to compute a running accumulator from right to left where each intermediate\n * value is needed.\n *\n * **Details**\n *\n * The output length is `input.length + 1` because it ends with the initial\n * value. The result is always a `NonEmptyArray`.\n *\n * **Example** (Scanning running totals in reverse)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.scanRight([1, 2, 3, 4], 0, (acc, value) => acc + value) // => [10, 9, 7, 4, 0]\n * ```\n *\n * @see {@link scan} — left-to-right scan\n * @see {@link reduceRight} — fold without intermediate values\n *\n * @category folding\n * @since 2.0.0\n */\nexport const scanRight = /*#__PURE__*/dual(3, (self, b, f) => {\n const input = fromIterable(self);\n const out = new Array(input.length + 1);\n out[input.length] = b;\n for (let i = input.length - 1; i >= 0; i--) {\n out[i] = f(out[i + 1], input[i]);\n }\n return out;\n});\n/**\n * Checks whether a value is an `Array`.\n *\n * **When to use**\n *\n * Use to verify a value is a mutable array, narrowing its type to `Array<unknown>`.\n *\n * **Details**\n *\n * Acts as a type guard narrowing the input to `Array<unknown>` and delegates to\n * `globalThis.Array.isArray`.\n *\n * **Example** (Type-guarding an unknown value)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.isArray(null) // => false\n * Array.isArray([1, 2, 3]) // => true\n * ```\n *\n * @see {@link isArrayEmpty} — check for an empty array\n * @see {@link isArrayNonEmpty} — check for a non-empty array\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isArray = Array.isArray;\n/**\n * Checks whether a mutable `Array` is empty, narrowing the type to `[]`.\n *\n * **Example** (Checking for an empty array)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.isArrayEmpty([]) // => true\n * Array.isArrayEmpty([1, 2, 3]) // => false\n * ```\n *\n * @see {@link isReadonlyArrayEmpty} — readonly variant\n * @see {@link isArrayNonEmpty} — opposite check\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isArrayEmpty = self => self.length === 0;\n/**\n * Checks whether a `ReadonlyArray` is empty, narrowing the type to `readonly []`.\n *\n * **Example** (Checking for an empty readonly array)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.isReadonlyArrayEmpty([]) // => true\n * Array.isReadonlyArrayEmpty([1, 2, 3]) // => false\n * ```\n *\n * @see {@link isArrayEmpty} — mutable variant\n * @see {@link isReadonlyArrayNonEmpty} — opposite check\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isReadonlyArrayEmpty = isArrayEmpty;\n/**\n * Checks whether a mutable `Array` is non-empty, narrowing the type to\n * `NonEmptyArray`.\n *\n * **When to use**\n *\n * Use when you need the narrowed value to remain a mutable `Array` after proving\n * it has at least one element.\n *\n * **Example** (Checking for a non-empty array)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.isArrayNonEmpty([]) // => false\n * Array.isArrayNonEmpty([1, 2, 3]) // => true\n * ```\n *\n * @see {@link isReadonlyArrayNonEmpty} — readonly variant\n * @see {@link isArrayEmpty} — opposite check\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isArrayNonEmpty = internalArray.isArrayNonEmpty;\n/**\n * Checks whether a `ReadonlyArray` is non-empty, narrowing the type to\n * `NonEmptyReadonlyArray`.\n *\n * **When to use**\n *\n * Use when you need to prove a readonly array has at least one element without\n * requiring mutable array methods afterward.\n *\n * **Example** (Checking for a non-empty readonly array)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.isReadonlyArrayNonEmpty([]) // => false\n * Array.isReadonlyArrayNonEmpty([1, 2, 3]) // => true\n * ```\n *\n * @see {@link isArrayNonEmpty} — mutable variant\n * @see {@link isReadonlyArrayEmpty} — opposite check\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isReadonlyArrayNonEmpty = internalArray.isArrayNonEmpty;\n/**\n * Returns the number of elements in a `ReadonlyArray`.\n *\n * **When to use**\n *\n * Use when you need length as a composable function rather than a property access.\n *\n * **Example** (Getting the length)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.length([1, 2, 3]) // => 3\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const length = self => self.length;\n/**\n * Checks whether a string represents a JavaScript array index: a non-negative\n * integer below `2 ** 32 - 1`, written without leading zeroes, a sign, or\n * exponent notation.\n *\n * @internal\n */\nexport function isCanonicalArrayIndex(key) {\n const index = Number(key);\n return String(index) === key && Number.isInteger(index) && index >= 0 && index < 2 ** 32 - 1;\n}\n/** @internal */\nexport function isOutOfBounds(i, as) {\n return !Number.isFinite(i) || i < 0 || i >= as.length;\n}\n/**\n * Reads an element at the given index safely, returning `Option.some` or\n * `Option.none` if the index is out of bounds.\n *\n * **When to use**\n *\n * Use when you need to read an array element by index and handle an\n * out-of-bounds index as `Option.none`.\n *\n * **Details**\n *\n * The index is floored to an integer. This never throws.\n *\n * **Example** (Accessing indexes safely)\n *\n * ```ts import.meta.vitest\n * import { Array, Option } from \"effect\"\n *\n * Array.get([1, 2, 3], 1) // => Option.some(2)\n * Array.get([1, 2, 3], 10) // => Option.none()\n * ```\n *\n * @see {@link getUnsafe} for indexed access that throws when the index is out of bounds\n * @see {@link head} for reading the first element as an `Option`\n * @see {@link last} for reading the last element as an `Option`\n *\n * @category getters\n * @since 2.0.0\n */\nexport const get = /*#__PURE__*/dual(2, (self, index) => {\n const i = Math.floor(index);\n return isOutOfBounds(i, self) ? Option.none() : Option.some(self[i]);\n});\n/**\n * Reads an element at the given index, throwing if the index is out of bounds.\n *\n * **When to use**\n *\n * Use to read an array element at a known valid index when out-of-bounds would\n * be a programming error.\n *\n * **Details**\n *\n * Throws an `Error` with the message `\"Index out of bounds: <i>\"`. Prefer\n * `get` for safe access.\n *\n * **Example** (Accessing indexes unsafely)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.getUnsafe([1, 2, 3], 1) // => 2\n * // Array.getUnsafe([1, 2, 3], 10) // throws Error\n * ```\n *\n * @see {@link get} — safe version returning `Option`\n *\n * @category unsafe\n * @since 4.0.0\n */\nexport const getUnsafe = /*#__PURE__*/dual(2, (self, index) => {\n const i = Math.floor(index);\n if (isOutOfBounds(i, self)) {\n throw new Error(`Index out of bounds: ${i}`);\n }\n return self[i];\n});\n/**\n * Splits a non-empty array into its first element and the remaining elements.\n *\n * **When to use**\n *\n * Use when you have a `NonEmptyReadonlyArray` and need both its first element\n * and the remaining elements as separate values.\n *\n * **Details**\n *\n * Returns a tuple `[head, tail]` and requires a `NonEmptyReadonlyArray`.\n *\n * **Example** (Destructuring head and tail)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.unprepend([1, 2, 3, 4]) // => [1, [2, 3, 4]]\n * ```\n *\n * @see {@link unappend} for splitting a non-empty array into init and last\n * @see {@link headNonEmpty} for getting only the first element\n * @see {@link tailNonEmpty} for getting only the elements after the first\n *\n * @category splitting\n * @since 2.0.0\n */\nexport const unprepend = self => [headNonEmpty(self), tailNonEmpty(self)];\n/**\n * Splits a non-empty array into all elements except the last, and the last\n * element.\n *\n * **When to use**\n *\n * Use when you need to split a non-empty array into the elements before the\n * last element and the last element.\n *\n * **Details**\n *\n * Returns a tuple `[init, last]` and requires a `NonEmptyReadonlyArray`.\n *\n * **Example** (Destructuring init and last)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.unappend([1, 2, 3, 4]) // => [[1, 2, 3], 4]\n * ```\n *\n * @see {@link unprepend} for splitting a non-empty array into head and tail\n * @see {@link initNonEmpty} for getting only the elements before the last\n * @see {@link lastNonEmpty} for getting only the last element\n *\n * @category splitting\n * @since 2.0.0\n */\nexport const unappend = self => [initNonEmpty(self), lastNonEmpty(self)];\n/**\n * Returns the first element of an array safely wrapped in `Option.some`, or\n * `Option.none` if the array is empty.\n *\n * **When to use**\n *\n * Use to safely get the first element of an array that may be empty.\n *\n * **Example** (Getting the first element)\n *\n * ```ts import.meta.vitest\n * import { Array, Option } from \"effect\"\n *\n * Array.head([1, 2, 3]) // => Option.some(1)\n * Array.head([]) // => Option.none()\n * ```\n *\n * @see {@link headNonEmpty} — direct access when array is known non-empty\n * @see {@link last} — get the last element\n *\n * @category getters\n * @since 2.0.0\n */\nexport const head = /*#__PURE__*/get(0);\n/**\n * Returns the first element of a `NonEmptyReadonlyArray` directly (no `Option`\n * wrapper).\n *\n * **When to use**\n *\n * Use to get the first element without `Option` wrapping when the array is known\n * to be non-empty.\n *\n * **Example** (Getting the head of a non-empty array)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.headNonEmpty([1, 2, 3, 4]) // => 1\n * ```\n *\n * @see {@link head} — safe version for possibly-empty arrays\n *\n * @category getters\n * @since 2.0.0\n */\nexport const headNonEmpty = /*#__PURE__*/getUnsafe(0);\n/**\n * Returns the last element of an array safely wrapped in `Option.some`, or\n * `Option.none` if the array is empty.\n *\n * **When to use**\n *\n * Use to safely get the last element of an array that may be empty.\n *\n * **Example** (Getting the last element)\n *\n * ```ts import.meta.vitest\n * import { Array, Option } from \"effect\"\n *\n * Array.last([1, 2, 3]) // => Option.some(3)\n * Array.last([]) // => Option.none()\n * ```\n *\n * @see {@link lastNonEmpty} — direct access when array is known non-empty\n * @see {@link head} — get the first element\n *\n * @category getters\n * @since 2.0.0\n */\nexport const last = self => isReadonlyArrayNonEmpty(self) ? Option.some(lastNonEmpty(self)) : Option.none();\n/**\n * Returns the last element of a `NonEmptyReadonlyArray` directly (no `Option`\n * wrapper).\n *\n * **When to use**\n *\n * Use to get the last element without `Option` wrapping when the array is known\n * to be non-empty.\n *\n * **Example** (Getting the last of a non-empty array)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.lastNonEmpty([1, 2, 3, 4]) // => 4\n * ```\n *\n * @see {@link last} — safe version for possibly-empty arrays\n *\n * @category getters\n * @since 2.0.0\n */\nexport const lastNonEmpty = self => self[self.length - 1];\n/**\n * Returns all elements except the first safely, wrapped in an `Option`.\n *\n * **When to use**\n *\n * Use to safely get all elements after the first when the iterable may be empty.\n *\n * **Details**\n *\n * Allocates a new array via `slice(1)`. Empty inputs return `Option.none()`.\n *\n * **Example** (Getting the tail)\n *\n * ```ts import.meta.vitest\n * import { Array, Option } from \"effect\"\n *\n * Array.tail([1, 2, 3, 4]) // => Option.some([2, 3, 4])\n * Array.tail([]) // => Option.none()\n * ```\n *\n * @see {@link tailNonEmpty} — when the array is known non-empty\n * @see {@link init} — all elements except the last\n *\n * @category getters\n * @since 2.0.0\n */\nexport function tail(self) {\n const as = fromIterable(self);\n return isReadonlyArrayNonEmpty(as) ? Option.some(tailNonEmpty(as)) : Option.none();\n}\n/**\n * Returns all elements except the first of a `NonEmptyReadonlyArray`.\n *\n * **When to use**\n *\n * Use to get all elements after the first when the array is known to be non-empty.\n *\n * **Example** (Getting the tail of a non-empty array)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.tailNonEmpty([1, 2, 3, 4]) // => [2, 3, 4]\n * ```\n *\n * @see {@link tail} — safe version for possibly-empty arrays\n * @see {@link initNonEmpty} — all elements except the last\n *\n * @category getters\n * @since 2.0.0\n */\nexport const tailNonEmpty = self => self.slice(1);\n/**\n * Returns all elements except the last safely, wrapped in an `Option`.\n *\n * **When to use**\n *\n * Use to safely get all elements before the last when the iterable may be empty.\n *\n * **Details**\n *\n * Allocates a new array via `slice(0, -1)`. Empty inputs return\n * `Option.none()`.\n *\n * **Example** (Getting init)\n *\n * ```ts import.meta.vitest\n * import { Array, Option } from \"effect\"\n *\n * Array.init([1, 2, 3, 4]) // => Option.some([1, 2, 3])\n * Array.init([]) // => Option.none()\n * ```\n *\n * @see {@link initNonEmpty} — when the array is known non-empty\n * @see {@link tail} — all elements except the first\n *\n * @category getters\n * @since 2.0.0\n */\nexport function init(self) {\n const as = fromIterable(self);\n return isReadonlyArrayNonEmpty(as) ? Option.some(initNonEmpty(as)) : Option.none();\n}\n/**\n * Returns all elements except the last of a `NonEmptyReadonlyArray`.\n *\n * **When to use**\n *\n * Use to get all elements before the last when the array is known to be non-empty.\n *\n * **Example** (Getting init of a non-empty array)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.initNonEmpty([1, 2, 3, 4]) // => [1, 2, 3]\n * ```\n *\n * @see {@link init} — safe version for possibly-empty arrays\n * @see {@link tailNonEmpty} — all elements except the first\n *\n * @category getters\n * @since 2.0.0\n */\nexport const initNonEmpty = self => self.slice(0, -1);\nconst clampCount = (n, length) => Math.min(Count.normalize(n), length);\n/**\n * Keeps the first `n` elements, creating a new array.\n *\n * **When to use**\n *\n * Use to keep up to the first `n` elements from an iterable as a new array.\n *\n * **Details**\n *\n * `n` is rounded down and clamped to `[0, length]`. `NaN` is treated as `0`.\n * Returns an empty array when `n <= 0`.\n *\n * **Example** (Taking from the start)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.take([1, 2, 3, 4, 5], 3) // => [1, 2, 3]\n * ```\n *\n * @see {@link takeRight} for keeping elements from the end\n * @see {@link takeWhile} for keeping an initial prefix while a predicate holds\n * @see {@link drop} for removing elements from the start\n *\n * @category getters\n * @since 2.0.0\n */\nexport const take = /*#__PURE__*/dual(2, (self, n) => {\n const input = fromIterable(self);\n return input.slice(0, clampCount(n, input.length));\n});\n/**\n * Keeps the last `n` elements, creating a new array.\n *\n * **When to use**\n *\n * Use to keep the last `n` elements of an iterable.\n *\n * **Details**\n *\n * `n` is rounded down and clamped to `[0, length]`. `NaN` is treated as `0`.\n * Returns an empty array when `n <= 0`.\n *\n * **Example** (Taking from the end)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.takeRight([1, 2, 3, 4, 5], 3) // => [3, 4, 5]\n * ```\n *\n * @see {@link take} — keep from the start\n * @see {@link dropRight} — remove from the end\n *\n * @category getters\n * @since 2.0.0\n */\nexport const takeRight = /*#__PURE__*/dual(2, (self, n) => {\n const input = fromIterable(self);\n const i = clampCount(n, input.length);\n return i === 0 ? [] : input.slice(-i);\n});\n/**\n * Takes elements from the start while the predicate holds, stopping at the\n * first element that fails.\n *\n * **When to use**\n *\n * Use to keep the leading elements of an iterable while each element satisfies\n * a predicate, returning the retained prefix as an array.\n *\n * **Details**\n *\n * Supports refinements for type narrowing. The predicate receives\n * `(element, index)`.\n *\n * **Example** (Taking while condition holds)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.takeWhile([1, 3, 2, 4, 1, 2], (x) => x < 4) // => [1, 3, 2]\n * ```\n *\n * @see {@link take} for keeping a fixed number of leading elements\n * @see {@link dropWhile} for removing the matching prefix and keeping the rest\n * @see {@link span} for splitting the matching prefix from the remaining elements\n *\n * @category getters\n * @since 2.0.0\n */\nexport const takeWhile = /*#__PURE__*/dual(2, (self, predicate) => {\n let i = 0;\n const out = [];\n for (const a of self) {\n if (!predicate(a, i)) {\n break;\n }\n out.push(a);\n i++;\n }\n return out;\n});\n/**\n * Takes elements from the start while a `Filter` succeeds, collecting transformed values.\n *\n * **When to use**\n *\n * Use when you need to take a prefix from an iterable while a function can\n * successfully extract or transform elements, stopping at the first element\n * that produces a failure result.\n *\n * **Details**\n *\n * The filter receives `(element, index)` and processing stops at the first\n * filter failure.\n *\n * @see {@link takeWhile} for taking a prefix based on a boolean predicate\n *\n * @category getters\n * @since 4.0.0\n */\nexport const takeWhileFilter = /*#__PURE__*/dual(2, (self, f) => {\n let i = 0;\n const out = [];\n for (const a of self) {\n const result = f(a, i);\n if (Result.isFailure(result)) {\n break;\n }\n out.push(result.success);\n i++;\n }\n return out;\n});\nconst spanIndex = (self, predicate) => {\n let i = 0;\n for (const a of self) {\n if (!predicate(a, i)) {\n break;\n }\n i++;\n }\n return i;\n};\n/**\n * Splits an iterable into two arrays: the longest prefix where the predicate\n * holds, and the remaining elements.\n *\n * **When to use**\n *\n * Use when you need both the longest predicate-matching prefix and the\n * remaining elements.\n *\n * **Details**\n *\n * Equivalent to `[takeWhile(pred), dropWhile(pred)]`, but more efficient\n * because it runs in a single pass. Supports refinements for type narrowing of\n * the prefix.\n *\n * **Example** (Splitting at predicate boundary)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.span([1, 3, 2, 4, 5], (x) => x % 2 === 1) // => [[1, 3], [2, 4, 5]]\n * ```\n *\n * @see {@link takeWhile} for keeping only the matching prefix\n * @see {@link dropWhile} for keeping only the elements after the matching prefix\n * @see {@link splitWhere} for splitting at the first element that satisfies a predicate\n *\n * @category splitting\n * @since 2.0.0\n */\nexport const span = /*#__PURE__*/dual(2, (self, predicate) => {\n const input = fromIterable(self);\n return splitAt(input, spanIndex(input, predicate));\n});\n/**\n * Removes the first `n` elements, creating a new array.\n *\n * **When to use**\n *\n * Use to keep the suffix of an iterable after skipping a fixed number of\n * leading elements.\n *\n * **Details**\n *\n * `n` is rounded down and clamped to `[0, length]`. `NaN` is treated as `0`.\n * When `n <= 0`, this returns a copy of the full array.\n *\n * **Example** (Dropping from the start)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.drop([1, 2, 3, 4, 5], 2) // => [3, 4, 5]\n * ```\n *\n * @see {@link dropRight} for removing a fixed number of elements from the end\n * @see {@link dropWhile} for removing a prefix based on a predicate instead of a fixed count\n * @see {@link take} for keeping a fixed number of elements from the start\n *\n * @category getters\n * @since 2.0.0\n */\nexport const drop = /*#__PURE__*/dual(2, (self, n) => {\n const input = fromIterable(self);\n return input.slice(clampCount(n, input.length), input.length);\n});\n/**\n * Removes the last `n` elements, creating a new array.\n *\n * **When to use**\n *\n * Use to remove the last `n` elements from an iterable.\n *\n * **Details**\n *\n * `n` is rounded down and clamped to `[0, length]`. `NaN` is treated as `0`.\n *\n * **Example** (Dropping from the end)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.dropRight([1, 2, 3, 4, 5], 2) // => [1, 2, 3]\n * ```\n *\n * @see {@link drop} — remove from the start\n * @see {@link takeRight} — keep from the end\n *\n * @category getters\n * @since 2.0.0\n */\nexport const dropRight = /*#__PURE__*/dual(2, (self, n) => {\n const input = fromIterable(self);\n return input.slice(0, input.length - clampCount(n, input.length));\n});\n/**\n * Drops elements from the start while the predicate holds, returning the rest.\n *\n * **When to use**\n *\n * Use to remove a leading prefix of elements that satisfy a predicate.\n *\n * **Details**\n *\n * The predicate receives `(element, index)`.\n *\n * **Example** (Dropping while condition holds)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.dropWhile([1, 2, 3, 4, 5], (x) => x < 4) // => [4, 5]\n * ```\n *\n * @see {@link takeWhile} — keep the matching prefix instead\n * @see {@link drop} — drop a fixed count\n *\n * @category getters\n * @since 2.0.0\n */\nexport const dropWhile = /*#__PURE__*/dual(2, (self, predicate) => {\n const input = fromIterable(self);\n let i = 0;\n while (i < input.length) {\n if (!predicate(input[i], i)) {\n break;\n }\n i++;\n }\n return input.slice(i);\n});\n/**\n * Drops elements from the start while a `Filter` succeeds.\n *\n * **When to use**\n *\n * Use when you need to drop a prefix from an iterable by computing a `Result`\n * per element instead of using a simple boolean predicate.\n *\n * **Details**\n *\n * The filter receives `(element, index)`. The result contains the remaining\n * original elements after the first filter failure.\n *\n * @see {@link dropWhile} for dropping a prefix with a simple boolean predicate\n * @see {@link takeWhileFilter} for keeping only the matching prefix\n *\n * @category getters\n * @since 4.0.0\n */\nexport const dropWhileFilter = /*#__PURE__*/dual(2, (self, f) => {\n const input = fromIterable(self);\n let i = 0;\n while (i < input.length) {\n if (Result.isFailure(f(input[i], i))) {\n break;\n }\n i++;\n }\n return input.slice(i);\n});\n/**\n * Returns the index of the first element matching the predicate, wrapped in an\n * `Option`.\n *\n * **When to use**\n *\n * Use to find the index of the first matching element from the start of an\n * iterable.\n *\n * **Example** (Finding an index)\n *\n * ```ts import.meta.vitest\n * import { Array, Option } from \"effect\"\n *\n * Array.findFirstIndex([5, 3, 8, 9], (x) => x > 5) // => Option.some(2)\n * ```\n *\n * @see {@link findLastIndex} — search from the end\n * @see {@link findFirst} — get the element itself\n *\n * @category searching\n * @since 2.0.0\n */\nexport const findFirstIndex = /*#__PURE__*/dual(2, (self, predicate) => {\n let i = 0;\n for (const a of self) {\n if (predicate(a, i)) {\n return Option.some(i);\n }\n i++;\n }\n return Option.none();\n});\n/**\n * Returns the index of the last element matching the predicate, wrapped in an\n * `Option`.\n *\n * **When to use**\n *\n * Use to find the index of the last matching element from the end of an array.\n *\n * **Example** (Finding the last matching index)\n *\n * ```ts import.meta.vitest\n * import { Array, Option } from \"effect\"\n *\n * Array.findLastIndex([1, 3, 8, 9], (x) => x < 5) // => Option.some(1)\n * ```\n *\n * @see {@link findFirstIndex} — search from the start\n * @see {@link findLast} — get the element itself\n *\n * @category searching\n * @since 2.0.0\n */\nexport const findLastIndex = /*#__PURE__*/dual(2, (self, predicate) => {\n const input = fromIterable(self);\n for (let i = input.length - 1; i >= 0; i--) {\n if (predicate(input[i], i)) {\n return Option.some(i);\n }\n }\n return Option.none();\n});\n/**\n * Returns the first element matching a predicate, refinement, or mapping\n * function, wrapped in `Option`.\n *\n * **When to use**\n *\n * Use to scan an iterable in iteration order and return the first selected\n * element or mapped value as an `Option`.\n *\n * **Details**\n *\n * Accepts a predicate `(a, i) => boolean`, a refinement, or a function\n * `(a, i) => Option<B>` for simultaneous find-and-transform. If no element\n * matches, this returns `Option.none()`.\n *\n * **Example** (Finding the first match)\n *\n * ```ts import.meta.vitest\n * import { Array, Option } from \"effect\"\n *\n * Array.findFirst([1, 2, 3, 4, 5], (x) => x > 3) // => Option.some(4)\n * ```\n *\n * @see {@link findLast} — search from the end\n * @see {@link findFirstIndex} — get the index instead\n * @see {@link findFirstWithIndex} — get both element and index\n *\n * @category searching\n * @since 2.0.0\n */\nexport const findFirst = moduleIterable.findFirst;\n/**\n * Returns the first selected value together with its index, wrapped in an\n * `Option`.\n *\n * **When to use**\n *\n * Use to find both the first matching element and its index in one pass.\n *\n * **Details**\n *\n * Accepts a predicate, a refinement, or a function returning `Option`. For an\n * `Option`-returning function, returns `[mappedValue, index]` for the first\n * `Some`, or `Option.none()` if no element is selected.\n *\n * **Example** (Finding element with its index)\n *\n * ```ts import.meta.vitest\n * import { Array, Option } from \"effect\"\n *\n * Array.findFirstWithIndex([1, 2, 3, 4, 5], (x) => x > 3) // => Option.some([4, 3])\n * ```\n *\n * @see {@link findFirst} — get only the element\n * @see {@link findFirstIndex} — get only the index\n *\n * @category searching\n * @since 3.17.0\n */\nexport const findFirstWithIndex = /*#__PURE__*/dual(2, (self, f) => {\n let i = 0;\n for (const a of self) {\n const o = f(a, i);\n if (typeof o === \"boolean\") {\n if (o) {\n return Option.some([a, i]);\n }\n } else {\n if (Option.isSome(o)) {\n return Option.some([o.value, i]);\n }\n }\n i++;\n }\n return Option.none();\n});\n/**\n * Returns the last element matching a predicate, refinement, or mapping\n * function, wrapped in `Option`.\n *\n * **When to use**\n *\n * Use to find the last matching element from the end of an array.\n *\n * **Details**\n *\n * Searches from the end of the array. If no element matches, this returns\n * `Option.none()`.\n *\n * **Example** (Finding the last match)\n *\n * ```ts import.meta.vitest\n * import { Array, Option } from \"effect\"\n *\n * Array.findLast([1, 2, 3, 4, 5], (n) => n % 2 === 0) // => Option.some(4)\n * ```\n *\n * @see {@link findFirst} — search from the start\n * @see {@link findLastIndex} — get the index instead\n *\n * @category searching\n * @since 2.0.0\n */\nexport const findLast = /*#__PURE__*/dual(2, (self, f) => {\n const input = fromIterable(self);\n for (let i = input.length - 1; i >= 0; i--) {\n const a = input[i];\n const o = f(a, i);\n if (typeof o === \"boolean\") {\n if (o) {\n return Option.some(a);\n }\n } else {\n if (Option.isSome(o)) {\n return o;\n }\n }\n }\n return Option.none();\n});\n/**\n * Inserts an element at the specified index safely, returning a new `NonEmptyArray`\n * wrapped in an `Option`.\n *\n * **When to use**\n *\n * Use to insert a single element at a specific position in an array.\n *\n * **Details**\n *\n * Valid indices are `0` to `length`, inclusive. Inserting at `length` appends.\n *\n * **Example** (Inserting at an index)\n *\n * ```ts import.meta.vitest\n * import { Array, Option } from \"effect\"\n *\n * Array.insertAt([\"a\", \"b\", \"c\", \"e\"], 3, \"d\") // => Option.some([\"a\", \"b\", \"c\", \"d\", \"e\"])\n * ```\n *\n * @see {@link replace} — replace an existing element\n * @see {@link modify} — transform an element at an index\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const insertAt = /*#__PURE__*/dual(3, (self, i, b) => {\n const out = Array.from(self); // copy because `splice` mutates the array\n const index = Math.floor(i);\n if (index !== out.length && isOutOfBounds(index, out)) {\n return Option.none();\n }\n out.splice(index, 0, b);\n return Option.some(out);\n});\n/**\n * Replaces the element at the specified index safely with a new value, returning the\n * updated array in `Option.some`.\n *\n * **When to use**\n *\n * Use to set a fixed replacement value at a specific index.\n *\n * **Details**\n *\n * Returns `Option.none()` when the index is out of bounds.\n *\n * **Example** (Replacing an element)\n *\n * ```ts import.meta.vitest\n * import { Array, Option } from \"effect\"\n *\n * Array.replace([1, 2, 3], 1, 4) // => Option.some([1, 4, 3])\n * ```\n *\n * @see {@link modify} — transform an element with a function\n * @see {@link insertAt} — insert without removing\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const replace = /*#__PURE__*/dual(3, (self, i, b) => modify(self, i, () => b));\n/**\n * Applies a function to the element at the specified index safely, returning the\n * updated array in `Option.some`.\n *\n * **When to use**\n *\n * Use to derive a replacement value from an array element at a specific index\n * while leaving the other elements unchanged.\n *\n * **Details**\n *\n * Returns `Option.none()` when the index is out of bounds.\n *\n * **Example** (Modifying an element)\n *\n * ```ts import.meta.vitest\n * import { Array, Option } from \"effect\"\n *\n * const values = [1, 2, 3, 4]\n * const double = (n: number) => n * 2\n *\n * Array.modify(values, 2, double) // => Option.some([1, 2, 6, 4])\n * Array.modify(values, 5, double) // => Option.none()\n * ```\n *\n * @see {@link replace} — set a fixed value at an index\n * @see {@link modifyHeadNonEmpty} — modify the first element\n * @see {@link modifyLastNonEmpty} — modify the last element\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const modify = /*#__PURE__*/dual(3, (self, i, f) => {\n const arr = Array.from(self);\n const index = Math.floor(i);\n if (isOutOfBounds(index, arr)) {\n return Option.none();\n }\n const out = arr;\n const b = f(arr[index]);\n out[index] = b;\n return Option.some(out);\n});\n/**\n * Removes the element at the specified index, returning a new array. If the\n * index is out of bounds, returns a copy of the original.\n *\n * **When to use**\n *\n * Use when you want a missing index to be a no-op and need a fresh array result\n * instead of an optional failure.\n *\n * **Example** (Removing an element)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.remove([1, 2, 3, 4], 2) // => [1, 2, 4]\n * Array.remove([1, 2, 3, 4], 5) // => [1, 2, 3, 4]\n * ```\n *\n * @see {@link insertAt} — insert an element\n * @see {@link filter} — remove elements by predicate\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const remove = /*#__PURE__*/dual(2, (self, i) => {\n const out = Array.from(self);\n const index = Math.floor(i);\n if (isOutOfBounds(index, out)) {\n return out;\n }\n out.splice(index, 1);\n return out;\n});\n/**\n * Reverses an iterable into a new array.\n *\n * **When to use**\n *\n * Use to reverse an iterable into a new array without mutating the original\n * input.\n *\n * **Details**\n *\n * Preserves `NonEmptyArray` in the return type.\n *\n * **Example** (Reversing an array)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.reverse([1, 2, 3, 4]) // => [4, 3, 2, 1]\n * ```\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const reverse = self => Array.from(self).reverse();\n/**\n * Sorts an array by the given `Order`, returning a new array.\n *\n * **When to use**\n *\n * Use to sort an array using a single `Order` comparator.\n *\n * **Details**\n *\n * Preserves `NonEmptyArray` in the return type. Use `sortWith` to sort by a\n * derived key, or `sortBy` for multi-key sorting.\n *\n * **Example** (Sorting numbers)\n *\n * ```ts import.meta.vitest\n * import { Array, Order } from \"effect\"\n *\n * Array.sort([3, 1, 4, 1, 5], Order.Number) // => [1, 1, 3, 4, 5]\n * ```\n *\n * @see {@link sortWith} — sort by a mapping function\n * @see {@link sortBy} — sort by multiple orders\n *\n * @category sorting\n * @since 2.0.0\n */\nexport const sort = /*#__PURE__*/dual(2, (self, O) => {\n const out = Array.from(self);\n out.sort(O);\n return out;\n});\n/**\n * Sorts an array by a derived key using a mapping function and an `Order` for\n * that key.\n *\n * **When to use**\n *\n * Use when you need to sort values by a derived key, such as a string length or\n * object field, while keeping the original values.\n *\n * **Details**\n *\n * Equivalent to `sort(Order.mapInput(order, f))`, but more convenient.\n *\n * **Example** (Sorting strings by length)\n *\n * ```ts import.meta.vitest\n * import { Array, Order } from \"effect\"\n *\n * Array.sortWith([\"aaa\", \"b\", \"cc\"], (s) => s.length, Order.Number) // => [\"b\", \"cc\", \"aaa\"]\n * ```\n *\n * @see {@link sort} for sorting with an `Order` that compares the elements directly\n * @see {@link sortBy} for sorting with multiple `Order`s applied in sequence\n *\n * @category sorting\n * @since 2.0.0\n */\nexport const sortWith = /*#__PURE__*/dual(3, (self, f, order) => Array.from(self).map(a => [a, f(a)]).sort(([, a], [, b]) => order(a, b)).map(([_]) => _));\n/**\n * Sorts an array by multiple `Order`s applied in sequence: the first order is\n * used first; ties are broken by the second order, and so on.\n *\n * **When to use**\n *\n * Use to sort by multiple criteria where later orders break ties from earlier\n * ones.\n *\n * **Details**\n *\n * This is data-last only and returns a function. The return type preserves\n * `NonEmptyArray`.\n *\n * **Example** (Sorting by multiple keys)\n *\n * ```ts import.meta.vitest\n * import { Array, Order, pipe } from \"effect\"\n *\n * const users = [\n * { name: \"Alice\", age: 30 },\n * { name: \"Bob\", age: 25 },\n * { name: \"Charlie\", age: 30 }\n * ]\n *\n * const sortedUsers = pipe(\n * users,\n * Array.sortBy(\n * Order.mapInput(Order.Number, (user: (typeof users)[number]) => user.age),\n * Order.mapInput(Order.String, (user: (typeof users)[number]) => user.name)\n * )\n * )\n *\n * sortedUsers.map((user) => user.name).join(\",\") // => \"Bob,Alice,Charlie\"\n * ```\n *\n * @see {@link sort} — sort by a single `Order`\n * @see {@link sortWith} — sort by a derived key\n *\n * @category sorting\n * @since 2.0.0\n */\nexport const sortBy = (...orders) => {\n const sortByAll = sort(Order.combineAll(orders));\n return self => {\n const input = fromIterable(self);\n if (isReadonlyArrayNonEmpty(input)) {\n return sortByAll(input);\n }\n return [];\n };\n};\n/**\n * Pairs elements from two iterables by position. If the iterables differ in\n * length, the extra elements from the longer one are discarded.\n *\n * **When to use**\n *\n * Use when you need simple pairs of corresponding elements from two iterables.\n *\n * **Details**\n *\n * Returns `NonEmptyArray` when both inputs are non-empty.\n *\n * **Example** (Zipping two arrays)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.zip([1, 2, 3], [\"a\", \"b\"]) // => [[1, \"a\"], [2, \"b\"]]\n * ```\n *\n * @see {@link zipWith} — zip with a combiner function\n * @see {@link unzip} — inverse operation\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zip = /*#__PURE__*/dual(2, (self, that) => zipWith(self, that, Tuple.make));\n/**\n * Combines elements from two iterables pairwise using a function. If the\n * iterables differ in length, extra elements are discarded.\n *\n * **When to use**\n *\n * Use when zipping two iterables in an array pipeline and each pair should\n * become a computed array element instead of a tuple.\n *\n * **Example** (Zipping with addition)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.zipWith([1, 2, 3], [4, 5, 6], (a, b) => a + b) // => [5, 7, 9]\n * ```\n *\n * @see {@link zip} — zip into tuples\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipWith = /*#__PURE__*/dual(3, (self, that, f) => {\n const as = fromIterable(self);\n const bs = fromIterable(that);\n if (isReadonlyArrayNonEmpty(as) && isReadonlyArrayNonEmpty(bs)) {\n const out = [f(headNonEmpty(as), headNonEmpty(bs))];\n const len = Math.min(as.length, bs.length);\n for (let i = 1; i < len; i++) {\n out[i] = f(as[i], bs[i]);\n }\n return out;\n }\n return [];\n});\n/**\n * Splits an array of pairs into two arrays. Inverse of {@link zip}.\n *\n * **Example** (Unzipping pairs)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.unzip([[1, \"a\"], [2, \"b\"], [3, \"c\"]]) // => [[1, 2, 3], [\"a\", \"b\", \"c\"]]\n * ```\n *\n * @see {@link zip} — combine two arrays into pairs\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const unzip = self => {\n const input = fromIterable(self);\n if (isReadonlyArrayNonEmpty(input)) {\n const fa = [input[0][0]];\n const fb = [input[0][1]];\n for (let i = 1; i < input.length; i++) {\n fa[i] = input[i][0];\n fb[i] = input[i][1];\n }\n return [fa, fb];\n }\n return [[], []];\n};\n/**\n * Places a separator element between every pair of elements.\n *\n * **When to use**\n *\n * Use to insert a separator between elements, for example when preparing data for display or concatenation.\n *\n * **Details**\n *\n * The return type preserves `NonEmptyArray`. Empty inputs produce an empty\n * result.\n *\n * **Example** (Interspersing a separator)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.intersperse([1, 2, 3], 0) // => [1, 0, 2, 0, 3]\n * ```\n *\n * @see {@link join} — intersperse and join into a string\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const intersperse = /*#__PURE__*/dual(2, (self, middle) => {\n const input = fromIterable(self);\n if (isReadonlyArrayNonEmpty(input)) {\n const out = [headNonEmpty(input)];\n const tail = tailNonEmpty(input);\n for (let i = 0; i < tail.length; i++) {\n if (i < tail.length) {\n out.push(middle);\n }\n out.push(tail[i]);\n }\n return out;\n }\n return [];\n});\n/**\n * Applies a function to the first element of a non-empty array, returning a\n * new array.\n *\n * **When to use**\n *\n * Use to transform the first element of a non-empty array while preserving the rest.\n *\n * **Example** (Modifying the head)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.modifyHeadNonEmpty([1, 2, 3], (n) => n * 10) // => [10, 2, 3]\n * ```\n *\n * @see {@link setHeadNonEmpty} — replace with a fixed value\n * @see {@link modifyLastNonEmpty} — modify the last element\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const modifyHeadNonEmpty = /*#__PURE__*/dual(2, (self, f) => [f(headNonEmpty(self)), ...tailNonEmpty(self)]);\n/**\n * Replaces the first element of a non-empty array with a new value.\n *\n * **When to use**\n *\n * Use when you already know the array is non-empty and the replacement value\n * does not depend on the current first element.\n *\n * **Example** (Setting the head)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.setHeadNonEmpty([1, 2, 3], 10) // => [10, 2, 3]\n * ```\n *\n * @see {@link modifyHeadNonEmpty} — transform the head with a function\n * @see {@link setLastNonEmpty} — replace the last element\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const setHeadNonEmpty = /*#__PURE__*/dual(2, (self, b) => modifyHeadNonEmpty(self, () => b));\n/**\n * Applies a function to the last element of a non-empty array, returning a\n * new array.\n *\n * **When to use**\n *\n * Use when you already know the array is non-empty and the new last element\n * depends on the current last element.\n *\n * **Example** (Modifying the last element)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.modifyLastNonEmpty([1, 2, 3], (n) => n * 2) // => [1, 2, 6]\n * ```\n *\n * @see {@link setLastNonEmpty} — replace with a fixed value\n * @see {@link modifyHeadNonEmpty} — modify the first element\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const modifyLastNonEmpty = /*#__PURE__*/dual(2, (self, f) => append(initNonEmpty(self), f(lastNonEmpty(self))));\n/**\n * Replaces the last element of a non-empty array with a new value.\n *\n * **When to use**\n *\n * Use when you already know the array is non-empty and the replacement value\n * does not depend on the current last element.\n *\n * **Example** (Setting the last element)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.setLastNonEmpty([1, 2, 3], 4) // => [1, 2, 4]\n * ```\n *\n * @see {@link modifyLastNonEmpty} — transform the last element with a function\n * @see {@link setHeadNonEmpty} — replace the first element\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const setLastNonEmpty = /*#__PURE__*/dual(2, (self, b) => modifyLastNonEmpty(self, () => b));\n/**\n * Transforms an array by rotating it `n` steps. Positive `n` rotates right; negative `n`\n * rotates left.\n *\n * **When to use**\n *\n * Use when elements should wrap around the end of the array rather than being\n * dropped.\n *\n * **Details**\n *\n * `n` is rounded to the nearest integer before rotating. The return type\n * preserves `NonEmptyArray`. Empty arrays, or rotations normalized to `0`,\n * return a copy.\n *\n * **Example** (Rotating elements)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.rotate([\"a\", \"b\", \"c\", \"d\"], 2) // => [\"c\", \"d\", \"a\", \"b\"]\n * ```\n *\n * @see {@link take} for taking a fixed number of elements from the start\n * @see {@link drop} for dropping a fixed number of elements from the start\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const rotate = /*#__PURE__*/dual(2, (self, n) => {\n const input = fromIterable(self);\n if (isReadonlyArrayNonEmpty(input)) {\n const len = input.length;\n const m = Math.round(n) % len;\n if (isOutOfBounds(Math.abs(m), input) || m === 0) {\n return copy(input);\n }\n if (m < 0) {\n const [f, s] = splitAtNonEmpty(input, -m);\n return appendAll(s, f);\n } else {\n return rotate(input, m - len);\n }\n }\n return [];\n});\n/**\n * Returns a membership-test function using a custom equivalence.\n *\n * **When to use**\n *\n * Use when checking membership with caller-provided equality instead of\n * `Equal.equivalence()`.\n *\n * **Example** (Checking with custom equality)\n *\n * ```ts import.meta.vitest\n * import { Array, pipe } from \"effect\"\n *\n * const containsNumber = Array.containsWith((a: number, b: number) => a === b)\n *\n * pipe([1, 2, 3, 4], containsNumber(3)) // => true\n * ```\n *\n * @see {@link contains} for the `Equal.equivalence()` variant\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const containsWith = isEquivalent => dual(2, (self, a) => {\n for (const i of self) {\n if (isEquivalent(a, i)) {\n return true;\n }\n }\n return false;\n});\n/**\n * Checks whether an array contains a value, using `Equal.equivalence()` for\n * comparison.\n *\n * **When to use**\n *\n * Use to check whether an iterable contains a value using Effect's default\n * equality instead of providing a comparison function.\n *\n * **Example** (Checking membership)\n *\n * ```ts import.meta.vitest\n * import { Array, pipe } from \"effect\"\n *\n * pipe([\"a\", \"b\", \"c\", \"d\"], Array.contains(\"c\")) // => true\n * ```\n *\n * @see {@link containsWith} — use custom equality\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const contains = /*#__PURE__*/containsWith(/*#__PURE__*/Equal.asEquivalence());\n/**\n * Applies a function repeatedly to consume prefixes of the array and collect\n * the values it produces.\n *\n * **When to use**\n *\n * Use when you need custom grouping logic where each step returns both a value\n * and the remaining input.\n *\n * **Details**\n *\n * The function receives a `NonEmptyReadonlyArray` and returns `[value, rest]`.\n * Processing continues until the remaining array is empty.\n *\n * **Example** (Chopping an array)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.chop([1, 2, 3, 4, 5], (as): [number, Array<number>] => [as[0] * 2, as.slice(1)]) // => [2, 4, 6, 8, 10]\n * ```\n *\n * @see {@link chunksOf} — split into fixed-size chunks\n * @see {@link splitAt} — split at an index\n *\n * @category splitting\n * @since 2.0.0\n */\nexport const chop = /*#__PURE__*/dual(2, (self, f) => {\n const input = fromIterable(self);\n if (isReadonlyArrayNonEmpty(input)) {\n const [b, rest] = f(input);\n const out = [b];\n let next = rest;\n while (internalArray.isArrayNonEmpty(next)) {\n const [b, rest] = f(next);\n out.push(b);\n next = rest;\n }\n return out;\n }\n return [];\n});\n/**\n * Splits an iterable into two arrays at the given index.\n *\n * **When to use**\n *\n * Use to divide an array into a prefix and suffix at a specific position.\n *\n * **Details**\n *\n * `n` is rounded down and clamped to `[0, length]`. `NaN` is treated as `0`,\n * which places all elements in the second array.\n *\n * **Example** (Splitting at an index)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.splitAt([1, 2, 3, 4, 5], 3) // => [[1, 2, 3], [4, 5]]\n * ```\n *\n * @see {@link splitAtNonEmpty} — for non-empty arrays\n * @see {@link splitWhere} — split at a predicate boundary\n *\n * @category splitting\n * @since 2.0.0\n */\nexport const splitAt = /*#__PURE__*/dual(2, (self, n) => {\n const input = Array.from(self);\n const _n = Count.normalize(n);\n if (isReadonlyArrayNonEmpty(input)) {\n if (_n >= 1) {\n return splitAtNonEmpty(input, _n);\n }\n return [[], input];\n }\n return [input, []];\n});\n/**\n * Splits a non-empty array into two parts at the given index. The first part\n * is guaranteed to be non-empty (`n` is clamped to >= 1).\n *\n * **When to use**\n *\n * Use when downstream code requires the left side of the split to contain at\n * least one element.\n *\n * **Details**\n *\n * `n` is rounded down and clamped to `[1, length]`. `NaN` is treated as `1`.\n *\n * **Example** (Splitting a non-empty array)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.splitAtNonEmpty([\"a\", \"b\", \"c\", \"d\", \"e\"], 3) // => [[\"a\", \"b\", \"c\"], [\"d\", \"e\"]]\n * ```\n *\n * @see {@link splitAt} — for possibly-empty arrays\n *\n * @category splitting\n * @since 4.0.0\n */\nexport const splitAtNonEmpty = /*#__PURE__*/dual(2, (self, n) => {\n const _n = Count.normalizeNonEmpty(n);\n return _n >= self.length ? [copy(self), []] : [prepend(self.slice(1, _n), headNonEmpty(self)), self.slice(_n)];\n});\n/**\n * Splits an iterable into `n` roughly equal-sized chunks.\n *\n * **When to use**\n *\n * Use to distribute elements across a fixed number of groups, such as when splitting work across threads.\n *\n * **Details**\n *\n * `n` is rounded down and normalized to at least `1`, with `NaN` treated as\n * `1`. The last chunk may be shorter.\n *\n * **Example** (Splitting into groups)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.split([1, 2, 3, 4, 5, 6, 7, 8], 3) // => [[1, 2, 3], [4, 5, 6], [7, 8]]\n * ```\n *\n * @see {@link chunksOf} — split into fixed-size chunks\n *\n * @category splitting\n * @since 2.0.0\n */\nexport const split = /*#__PURE__*/dual(2, (self, n) => {\n const input = fromIterable(self);\n return chunksOf(input, Math.ceil(input.length / Count.normalizeNonEmpty(n)));\n});\n/**\n * Splits an iterable at the first element matching the predicate. The matching\n * element is included in the second array.\n *\n * **When to use**\n *\n * Use when you need to split an array at the first element that marks a\n * condition boundary.\n *\n * **Example** (Splitting at a condition)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.splitWhere([1, 2, 3, 4, 5], (n) => n > 3) // => [[1, 2, 3], [4, 5]]\n * ```\n *\n * @see {@link span} — splits at the first element that fails the predicate\n * @see {@link splitAt} — split at a fixed index\n *\n * @category splitting\n * @since 2.0.0\n */\nexport const splitWhere = /*#__PURE__*/dual(2, (self, predicate) => span(self, (a, i) => !predicate(a, i)));\n/**\n * Creates a shallow copy of an array.\n *\n * **When to use**\n *\n * Use to create a distinct array reference for an existing array, for example\n * before mutating the returned array.\n *\n * **Details**\n *\n * The return type preserves `NonEmptyArray`. Use this when you need a distinct\n * reference, for example before mutating the returned array.\n *\n * **Example** (Copying an array)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * const original = [1, 2, 3]\n * const copied = Array.copy(original)\n *\n * copied // => [1, 2, 3]\n * original === copied // => false\n * ```\n *\n * @see {@link fromIterable} — returns the same reference for arrays\n *\n * @category transforming\n * @since 2.0.0\n */\nexport const copy = self => self.slice();\n/**\n * Pads or truncates an array to exactly `n` elements, filling with `fill`\n * if the array is shorter, or slicing if longer.\n *\n * **When to use**\n *\n * Use to ensure an array has a specific length, padding with a fill value or truncating as needed.\n *\n * **Details**\n *\n * `n` is rounded down. `NaN` and non-positive values are treated as `0`, which\n * returns an empty array.\n *\n * **Example** (Padding an array)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.pad([1, 2, 3], 6, 0) // => [1, 2, 3, 0, 0, 0]\n * ```\n *\n * @see {@link take} — truncate without padding\n * @see {@link replicate} — create an array of a single repeated value\n *\n * @category transforming\n * @since 3.8.4\n */\nexport const pad = /*#__PURE__*/dual(3, (self, n, fill) => {\n const length = Count.normalize(n);\n if (self.length >= length) {\n return take(self, length);\n }\n return appendAll(self, makeBy(length - self.length, () => fill));\n});\n/**\n * Splits an iterable into chunks of length `n`. The last chunk may be shorter\n * if `n` does not evenly divide the length.\n *\n * **When to use**\n *\n * Use to divide an iterable into a new array of non-overlapping chunks with a\n * maximum chunk size.\n *\n * **Details**\n *\n * `n` is rounded down and normalized to at least `1`; `NaN` and non-positive\n * values therefore produce singleton chunks. `chunksOf(n)([])` is `[]`, not\n * `[[]]`. Each chunk is a `NonEmptyArray`, and the outer return type preserves\n * `NonEmptyArray`.\n *\n * **Example** (Chunking an array)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.chunksOf([1, 2, 3, 4, 5], 2) // => [[1, 2], [3, 4], [5]]\n * ```\n *\n * @see {@link split} — split into a given number of groups\n * @see {@link window} — sliding windows\n *\n * @category splitting\n * @since 2.0.0\n */\nexport const chunksOf = /*#__PURE__*/dual(2, (self, n) => {\n const input = fromIterable(self);\n if (isReadonlyArrayNonEmpty(input)) {\n return chop(input, splitAtNonEmpty(n));\n }\n return [];\n});\n/**\n * Creates overlapping sliding windows of size `n`.\n *\n * **When to use**\n *\n * Use to process sequences with a moving window, such as for computing running averages or detecting patterns.\n *\n * **Details**\n *\n * `n` is rounded down, with `NaN` and non-positive values treated as `0`.\n * Returns an empty array if the normalized size is `0` or exceeds the array\n * length. Each window is a tuple of exactly the normalized size.\n *\n * **Example** (Creating sliding windows)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * const values = [1, 2, 3, 4, 5]\n *\n * Array.window(values, 3) // => [[1, 2, 3], [2, 3, 4], [3, 4, 5]]\n * Array.window(values, 6) // => []\n * ```\n *\n * @see {@link chunksOf} — non-overlapping chunks\n *\n * @category splitting\n * @since 3.13.2\n */\nexport const window = /*#__PURE__*/dual(2, (self, n) => {\n const input = fromIterable(self);\n const size = Count.normalize(n);\n if (size > 0 && size <= input.length && isReadonlyArrayNonEmpty(input)) {\n return Array.from({\n length: input.length - (size - 1)\n }, (_, index) => input.slice(index, index + size));\n }\n return [];\n});\n/**\n * Groups consecutive equal elements using a custom equivalence function.\n *\n * **When to use**\n *\n * Use when you already have a non-empty array arranged so matching elements are\n * adjacent and need a custom equivalence function.\n *\n * **Details**\n *\n * Only adjacent elements are grouped. Non-adjacent duplicates stay separate.\n * Requires a `NonEmptyReadonlyArray`.\n *\n * **Example** (Grouping consecutive equal elements)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.groupWith(\n * [\"a\", \"a\", \"b\", \"b\", \"b\", \"c\", \"a\"],\n * (x, y) => x === y\n * ) // => [[\"a\", \"a\"], [\"b\", \"b\", \"b\"], [\"c\"], [\"a\"]]\n * ```\n *\n * @see {@link group} for grouping adjacent elements with `Equal.equivalence()`\n * @see {@link groupBy} for grouping all elements into a record by key, regardless of adjacency\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const groupWith = /*#__PURE__*/dual(2, (self, isEquivalent) => chop(self, as => {\n const h = headNonEmpty(as);\n const out = [h];\n let i = 1;\n for (; i < as.length; i++) {\n const a = as[i];\n if (isEquivalent(a, h)) {\n out.push(a);\n } else {\n break;\n }\n }\n return [out, as.slice(i)];\n}));\n/**\n * Groups consecutive equal elements using `Equal.equivalence()`.\n *\n * **When to use**\n *\n * Use when you already have adjacent equal values and Effect's default equality\n * is the right comparison.\n *\n * **Details**\n *\n * Only adjacent elements are grouped.\n *\n * **Example** (Grouping adjacent equal elements)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.group([1, 1, 2, 2, 2, 3, 1]) // => [[1, 1], [2, 2, 2], [3], [1]]\n * ```\n *\n * @see {@link groupWith} — use custom equality\n * @see {@link groupBy} — group by a key function into a record\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const group = /*#__PURE__*/groupWith(/*#__PURE__*/Equal.asEquivalence());\n/**\n * Groups elements into a record by a key-returning function. Each key maps\n * to a `NonEmptyArray` of elements that produced that key.\n *\n * **When to use**\n *\n * Use to build buckets of elements indexed by a computed string or symbol key.\n *\n * **Details**\n *\n * Unlike `group` and `groupWith`, elements do not need to be adjacent to be\n * grouped together. The key function must return a `string` or `symbol`.\n *\n * **Gotchas**\n *\n * When the key function returns a finite union of string literals or unique\n * symbols, the result preserves those keys as optional properties because the\n * input may not produce every key. Open `string` and `symbol` key types retain\n * their record index signatures.\n *\n * **Example** (Grouping by a property)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * const people = [\n * { name: \"Alice\", group: \"A\" },\n * { name: \"Bob\", group: \"B\" },\n * { name: \"Charlie\", group: \"A\" }\n * ]\n *\n * Object.keys(Array.groupBy(people, (person) => person.group)).join(\",\") // => \"A,B\"\n * ```\n *\n * @see {@link group} — group adjacent equal elements\n * @see {@link groupWith} — group adjacent elements by custom equality\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const groupBy = /*#__PURE__*/dual(2, (self, f) => {\n const out = {};\n for (const a of self) {\n const k = f(a);\n if (Object.hasOwn(out, k)) {\n out[k].push(a);\n } else {\n InternalRecord.assignProperty(out, k, [a]);\n }\n }\n return out;\n});\nconst hashBucketsAdd = (buckets, value) => {\n const hash = Hash.hash(value);\n const bucket = buckets.get(hash);\n if (bucket === undefined) {\n buckets.set(hash, [value]);\n return true;\n }\n // Hash collisions still require an Effect equality check.\n for (const previous of bucket) {\n if (Equal.equals(previous, value)) {\n return false;\n }\n }\n bucket.push(value);\n return true;\n};\nconst makeHashBuckets = values => {\n const buckets = new Map();\n for (const value of values) {\n hashBucketsAdd(buckets, value);\n }\n return buckets;\n};\nconst hashBucketsHas = (buckets, value) => {\n const bucket = buckets.get(Hash.hash(value));\n if (bucket === undefined) {\n return false;\n }\n for (const candidate of bucket) {\n if (Equal.equals(candidate, value)) {\n return true;\n }\n }\n return false;\n};\n/**\n * Computes the union of two arrays using a custom equivalence, removing\n * duplicates.\n *\n * **When to use**\n *\n * Use when you need the union of two arrays but duplicate detection must use a\n * custom equivalence instead of the default `Equal.equivalence()`.\n *\n * **Example** (Computing unions with custom equality)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.unionWith([1, 2], [2, 3], (a, b) => a === b) // => [1, 2, 3]\n * ```\n *\n * @see {@link union} for the `Equal.equivalence()` variant\n * @see {@link intersectionWith} for keeping elements present in both arrays\n * @see {@link differenceWith} for keeping elements present only in the first array\n *\n * @category set operations\n * @since 2.0.0\n */\nexport const unionWith = /*#__PURE__*/dual(3, (self, that, isEquivalent) => {\n const a = fromIterable(self);\n const b = fromIterable(that);\n if (isReadonlyArrayNonEmpty(a)) {\n if (isReadonlyArrayNonEmpty(b)) {\n const dedupe = dedupeWith(isEquivalent);\n return dedupe(appendAll(a, b));\n }\n return a;\n }\n return b;\n});\n/**\n * Computes the union of two arrays, removing duplicates using\n * `Equal.equivalence()`.\n *\n * **Example** (Computing array unions)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.union([1, 2], [2, 3]) // => [1, 2, 3]\n * ```\n *\n * @see {@link unionWith} — use custom equality\n * @see {@link intersection} — elements in both arrays\n * @see {@link difference} — elements only in the first array\n *\n * @category set operations\n * @since 2.0.0\n */\nexport const union = /*#__PURE__*/dual(2, (self, that) => {\n const a = fromIterable(self);\n const b = fromIterable(that);\n if (isReadonlyArrayNonEmpty(a)) {\n return isReadonlyArrayNonEmpty(b) ? dedupe(appendAll(a, b)) : a;\n }\n return b;\n});\n/**\n * Computes the intersection of two arrays using a custom equivalence. Order is\n * determined by the first array.\n *\n * **When to use**\n *\n * Use when you need to keep only values present in both arrays and equality\n * must be defined by a custom comparator, such as matching objects by id.\n *\n * **Example** (Computing intersections with custom equality)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }]\n * const array2 = [{ id: 3 }, { id: 4 }, { id: 1 }]\n * const isEquivalent = (a: { id: number }, b: { id: number }) => a.id === b.id\n *\n * Array.intersectionWith(isEquivalent)(array2)(array1) // => [{ id: 1 }, { id: 3 }]\n * ```\n *\n * @see {@link intersection} for the `Equal.equivalence()` variant\n * @see {@link unionWith} for keeping values from either array with custom equality\n * @see {@link differenceWith} for keeping values only from the first array with custom equality\n *\n * @category set operations\n * @since 2.0.0\n */\nexport const intersectionWith = isEquivalent => {\n const has = containsWith(isEquivalent);\n return dual(2, (self, that) => {\n const thatArray = fromIterable(that);\n return fromIterable(self).filter(a => has(thatArray, a));\n });\n};\n/**\n * Computes the intersection of two arrays using `Equal.equivalence()`. Order is\n * determined by the first array.\n *\n * **When to use**\n *\n * Use when Effect equality is the right membership test and you want to keep\n * values present in both inputs while preserving the first input's order.\n *\n * **Example** (Computing array intersections)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.intersection([1, 2, 3], [3, 4, 1]) // => [1, 3]\n * ```\n *\n * @see {@link intersectionWith} — use custom equality\n * @see {@link union} — elements in either array\n * @see {@link difference} — elements only in the first array\n *\n * @category set operations\n * @since 2.0.0\n */\nexport const intersection = /*#__PURE__*/dual(2, (self, that) => {\n const thatArray = fromIterable(that);\n const selfArray = fromIterable(self);\n if (selfArray.length === 0 || thatArray.length === 0) {\n return [];\n }\n const buckets = makeHashBuckets(thatArray);\n return selfArray.filter(value => hashBucketsHas(buckets, value));\n});\n/**\n * Computes elements in the first array that are not in the second, using a\n * custom equivalence.\n *\n * **When to use**\n *\n * Use when you need to keep only values from the first array and equality must\n * be defined by a custom comparator, such as matching objects by id.\n *\n * **Example** (Computing differences with custom equality)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.differenceWith<number>((a, b) => a === b)([1, 2, 3], [2, 3, 4]) // => [1]\n * ```\n *\n * @see {@link difference} for the `Equal.equivalence()` variant\n * @see {@link unionWith} for keeping values from either array with custom equality\n * @see {@link intersectionWith} for keeping values present in both arrays with custom equality\n *\n * @category set operations\n * @since 2.0.0\n */\nexport const differenceWith = isEquivalent => {\n const has = containsWith(isEquivalent);\n return dual(2, (self, that) => {\n const thatArray = fromIterable(that);\n return fromIterable(self).filter(a => !has(thatArray, a));\n });\n};\n/**\n * Computes elements in the first array that are not in the second, using\n * `Equal.equivalence()`.\n *\n * **When to use**\n *\n * Use when you need to keep values from the first array that are absent from\n * the second and the default `Equal.equivalence()` comparison is appropriate.\n *\n * **Example** (Computing array differences)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.difference([1, 2, 3], [2, 3, 4]) // => [1]\n * ```\n *\n * @see {@link differenceWith} — use custom equality\n * @see {@link union} — elements in either array\n * @see {@link intersection} — elements in both arrays\n *\n * @category set operations\n * @since 2.0.0\n */\nexport const difference = /*#__PURE__*/dual(2, (self, that) => {\n const thatArray = fromIterable(that);\n const selfArray = fromIterable(self);\n if (selfArray.length === 0) {\n return [];\n }\n if (thatArray.length === 0) {\n return selfArray.filter(() => true);\n }\n const buckets = makeHashBuckets(thatArray);\n return selfArray.filter(value => !hashBucketsHas(buckets, value));\n});\n/**\n * Creates an empty array.\n *\n * **When to use**\n *\n * Use to create a typed empty array without allocating placeholder elements.\n *\n * **Example** (Creating an empty array)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.empty<number>() // => []\n * ```\n *\n * @see {@link of} — create a single-element array\n * @see {@link make} — create from multiple values\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const empty = () => [];\n/**\n * Wraps a single value in a `NonEmptyArray`.\n *\n * **Example** (Creating a single-element array)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.of(1) // => [1]\n * ```\n *\n * @see {@link make} — create from multiple values\n * @see {@link empty} — create an empty array\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const of = a => [a];\n/**\n * Transforms each element using a function, returning a new array.\n *\n * **When to use**\n *\n * Use to transform each element independently while preserving the array shape.\n *\n * **Details**\n *\n * The function receives `(element, index)`. The return type preserves\n * `NonEmptyArray`.\n *\n * **Example** (Doubling values)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.map([1, 2, 3], (x) => x * 2) // => [2, 4, 6]\n * ```\n *\n * @see {@link flatMap} — map and flatten\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => self.map(f));\n/**\n * Maps each element to an array and flattens the results into a single array.\n *\n * **When to use**\n *\n * Use to map each array element to zero or more values and concatenate the\n * results in one pass.\n *\n * **Details**\n *\n * The function receives `(element, index)`. This returns `NonEmptyArray` when\n * both the input and mapped arrays are non-empty.\n *\n * **Example** (Flat mapping an array)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.flatMap([1, 2, 3], (x) => [x, x * 2]) // => [1, 2, 2, 4, 3, 6]\n * ```\n *\n * @see {@link map} — transform without flattening\n * @see {@link flatten} — flatten without mapping\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const flatMap = /*#__PURE__*/dual(2, (self, f) => {\n if (isReadonlyArrayEmpty(self)) {\n return [];\n }\n const out = [];\n for (let i = 0; i < self.length; i++) {\n const inner = f(self[i], i);\n for (let j = 0; j < inner.length; j++) {\n out.push(inner[j]);\n }\n }\n return out;\n});\n/**\n * Flattens a nested array of arrays into a single array.\n *\n * **When to use**\n *\n * Use to collapse one level of nested arrays when no per-element mapping is\n * needed.\n *\n * **Example** (Flattening nested arrays)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.flatten([[1, 2], [], [3, 4], [], [5, 6]]) // => [1, 2, 3, 4, 5, 6]\n * ```\n *\n * @see {@link flatMap} — map then flatten in one step\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const flatten = /*#__PURE__*/flatMap(identity);\n/**\n * Extracts all `Some` values from an iterable of `Option`s, discarding `None`s.\n *\n * **When to use**\n *\n * Use to collect only present values from an iterable of `Option` values while\n * discarding `None` values.\n *\n * **Example** (Extracting Some values)\n *\n * ```ts import.meta.vitest\n * import { Array, Option } from \"effect\"\n *\n * Array.getSomes([Option.some(1), Option.none(), Option.some(2)]) // => [1, 2]\n * ```\n *\n * @see {@link fromOption} — convert a single Option\n * @see {@link getSuccesses} — extract successes from Results\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const getSomes = self => {\n const out = [];\n for (const a of self) {\n if (Option.isSome(a)) {\n out.push(a.value);\n }\n }\n return out;\n};\n/**\n * Extracts all failure values from an iterable of `Result`s, discarding\n * successes.\n *\n * **When to use**\n *\n * Use when you can drop the success channel and only need the failure\n * payloads, not the original result wrappers.\n *\n * **Example** (Extracting failures)\n *\n * ```ts import.meta.vitest\n * import { Array, Result } from \"effect\"\n *\n * Array.getFailures([Result.succeed(1), Result.fail(\"err\"), Result.succeed(2)]) // => [\"err\"]\n * ```\n *\n * @see {@link getSuccesses} — extract success values\n * @see {@link separate} — split into failures and successes\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const getFailures = self => {\n const out = [];\n for (const a of self) {\n if (Result.isFailure(a)) {\n out.push(a.failure);\n }\n }\n return out;\n};\n/**\n * Extracts all success values from an iterable of `Result`s, discarding\n * failures.\n *\n * **When to use**\n *\n * Use when you can drop the failure channel and only need the success\n * payloads, not the original result wrappers.\n *\n * **Example** (Extracting successes)\n *\n * ```ts import.meta.vitest\n * import { Array, Result } from \"effect\"\n *\n * Array.getSuccesses([Result.succeed(1), Result.fail(\"err\"), Result.succeed(2)]) // => [1, 2]\n * ```\n *\n * @see {@link getFailures} — extract failure values\n * @see {@link separate} — split into failures and successes\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const getSuccesses = self => {\n const out = [];\n for (const a of self) {\n if (Result.isSuccess(a)) {\n out.push(a.success);\n }\n }\n return out;\n};\n/**\n * Keeps transformed values for elements where a `Filter` succeeds.\n *\n * **When to use**\n *\n * Use to filter an iterable with a `Result`-returning transformation while\n * discarding failures.\n *\n * **Details**\n *\n * The filter receives `(element, index)`. Failures are discarded.\n *\n * **Example** (Filtering and transforming)\n *\n * ```ts import.meta.vitest\n * import { Array, Result } from \"effect\"\n *\n * Array.filterMap([1, 2, 3, 4], (n) => n % 2 === 0 ? Result.succeed(n * 10) : Result.failVoid) // => [20, 40]\n * ```\n *\n * @see {@link filter} — keep original elements matching a predicate\n * @see {@link partition} for keeping both failures and successes\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const filterMap = /*#__PURE__*/dual(2, (self, f) => {\n const as = fromIterable(self);\n const out = [];\n for (let i = 0; i < as.length; i++) {\n const result = f(as[i], i);\n if (Result.isSuccess(result)) {\n out.push(result.success);\n }\n }\n return out;\n});\n/**\n * Keeps only elements satisfying a predicate (or refinement).\n *\n * **When to use**\n *\n * Use to filter an iterable into a new array of original elements that satisfy\n * a boolean predicate or refinement.\n *\n * **Details**\n *\n * The predicate receives `(element, index)`. Refinements are supported for type\n * narrowing.\n *\n * **Example** (Filtering even numbers)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.filter([1, 2, 3, 4], (x) => x % 2 === 0) // => [2, 4]\n * ```\n *\n * @see {@link partition} — split into matching and non-matching\n * @see {@link filterMap} for transforming while filtering\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const filter = /*#__PURE__*/dual(2, (self, predicate) => {\n const as = fromIterable(self);\n const out = [];\n for (let i = 0; i < as.length; i++) {\n if (predicate(as[i], i)) {\n out.push(as[i]);\n }\n }\n return out;\n});\n/**\n * Splits an iterable using a `Filter` into failures and successes.\n *\n * **When to use**\n *\n * Use to partition an iterable by evaluating each element with a\n * `Result`-returning filter and keeping both failure and success values.\n *\n * **Details**\n *\n * Returns `[excluded, satisfying]`. The filter receives `(element, index)`.\n *\n * **Example** (Partitioning with a filter)\n *\n * ```ts import.meta.vitest\n * import { Array, Result } from \"effect\"\n *\n * Array.partition([1, -2, 3], (n, i) =>\n * n > 0 ? Result.succeed(n + i) : Result.fail(`negative:${n}`)\n * ) // => [[\"negative:-2\"], [1, 5]]\n * ```\n *\n * @see {@link filter} — keep only matching elements\n * @see {@link filterMap} for discarding failures\n * @see {@link separate} — split an iterable of `Result` values\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const partition = /*#__PURE__*/dual(2, (self, f) => {\n const excluded = [];\n const satisfying = [];\n let i = 0;\n for (const a of self) {\n const result = f(a, i++);\n if (Result.isSuccess(result)) {\n satisfying.push(result.success);\n } else {\n excluded.push(result.failure);\n }\n }\n return [excluded, satisfying];\n});\n/**\n * Separates an iterable of `Result`s into failure values and success values.\n *\n * **When to use**\n *\n * Use to split an iterable of `Result` values into failure and success arrays.\n *\n * **Details**\n *\n * Returns `[failures, successes]`. This is equivalent to\n * `partition(identity)`.\n *\n * **Example** (Separating Results)\n *\n * ```ts import.meta.vitest\n * import { Array, Result } from \"effect\"\n *\n * Array.separate([Result.succeed(1), Result.fail(\"error\"), Result.succeed(2)]) // => [[\"error\"], [1, 2]]\n * ```\n *\n * @see {@link getFailures} — extract only failures\n * @see {@link getSuccesses} — extract only successes\n * @see {@link partition} for computing `Result` values while splitting\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const separate = /*#__PURE__*/partition(identity);\n/**\n * Folds an iterable from left to right into a single value.\n *\n * **When to use**\n *\n * Use to combine all elements into one accumulated value from left to right.\n *\n * **Details**\n *\n * The function receives `(accumulator, element, index)`.\n *\n * **Example** (Summing an array)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.reduce([1, 2, 3], 0, (acc, n) => acc + n) // => 6\n * ```\n *\n * @see {@link reduceRight} — fold from right to left\n * @see {@link scan} — fold keeping intermediate values\n *\n * @category folding\n * @since 2.0.0\n */\nexport const reduce = /*#__PURE__*/dual(3, (self, b, f) => fromIterable(self).reduce((b, a, i) => f(b, a, i), b));\n/**\n * Folds an iterable from right to left into a single value.\n *\n * **When to use**\n *\n * Use when you need to fold values from right to left.\n *\n * **Details**\n *\n * The function receives `(accumulator, element, index)`.\n *\n * **Example** (Folding from right to left)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.reduceRight([1, 2, 3], 0, (acc, n) => acc + n) // => 6\n * ```\n *\n * @see {@link reduce} — fold from left to right\n * @see {@link scanRight} — fold keeping intermediate values\n *\n * @category folding\n * @since 2.0.0\n */\nexport const reduceRight = /*#__PURE__*/dual(3, (self, b, f) => fromIterable(self).reduceRight((b, a, i) => f(b, a, i), b));\n/**\n * Lifts a predicate into an array: returns `[value]` if the predicate holds,\n * `[]` otherwise.\n *\n * **Example** (Wrapping values conditionally)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * const fromEven = Array.liftPredicate((n: number) => n % 2 === 0)\n *\n * fromEven(1) // => []\n * fromEven(2) // => [2]\n * ```\n *\n * @see {@link liftOption} — lift an Option-returning function\n *\n * @category lifting\n * @since 2.0.0\n */\nexport const liftPredicate = predicate => b => predicate(b) ? [b] : [];\n/**\n * Lifts an `Option`-returning function into one that returns an array:\n * `Some(a)` becomes `[a]`, `None` becomes `[]`.\n *\n * **When to use**\n *\n * Use when an optional parser or lookup should participate in array pipelines\n * as zero-or-one results.\n *\n * **Example** (Lifting an Option function)\n *\n * ```ts import.meta.vitest\n * import { Array, Option } from \"effect\"\n *\n * const parseNumber = Array.liftOption((s: string) => {\n * const n = Number(s)\n * return isNaN(n) ? Option.none() : Option.some(n)\n * })\n *\n * parseNumber(\"123\") // => [123]\n * parseNumber(\"abc\") // => []\n * ```\n *\n * @see {@link liftPredicate} — lift a boolean predicate\n * @see {@link liftResult} — lift a Result-returning function\n *\n * @category lifting\n * @since 2.0.0\n */\nexport const liftOption = f => (...a) => fromOption(f(...a));\n/**\n * Converts a nullable value to an array: `null`/`undefined` becomes `[]`,\n * anything else becomes `[value]`.\n *\n * **When to use**\n *\n * Use to treat a nullable single value as zero or one array element.\n *\n * **Example** (Converting nullable values to an array)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.fromNullishOr(1) // => [1]\n * Array.fromNullishOr(null) // => []\n * Array.fromNullishOr(undefined) // => []\n * ```\n *\n * @see {@link liftNullishOr} — lift a nullable-returning function\n * @see {@link fromOption} — convert from Option\n *\n * @category converting\n * @since 4.0.0\n */\nexport const fromNullishOr = a => a == null ? empty() : [a];\n/**\n * Lifts a nullable-returning function into one that returns an array:\n * `null`/`undefined` becomes `[]`, anything else becomes `[value]`.\n *\n * **Example** (Lifting a nullable function)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * const parseNumber = Array.liftNullishOr((s: string) => {\n * const n = Number(s)\n * return isNaN(n) ? null : n\n * })\n *\n * parseNumber(\"123\") // => [123]\n * parseNumber(\"abc\") // => []\n * ```\n *\n * @see {@link fromNullishOr} — convert a single nullable value\n * @see {@link liftOption} — lift an Option-returning function\n *\n * @category lifting\n * @since 4.0.0\n */\nexport const liftNullishOr = f => (...a) => fromNullishOr(f(...a));\n/**\n * Maps each element with a nullable-returning function, keeping only non-null /\n * non-undefined results.\n *\n * **When to use**\n *\n * Use when you need to map and filter in one step, where the mapper can return\n * `null` or `undefined` to skip elements.\n *\n * **Example** (Flat mapping with nullable values)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.flatMapNullishOr([1, 2, 3], (n) => (n % 2 === 0 ? null : n)) // => [1, 3]\n * ```\n *\n * @see {@link flatMap} for mapping each element to an array and flattening\n * @see {@link fromNullishOr} for converting a single nullable value to an array\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const flatMapNullishOr = /*#__PURE__*/dual(2, (self, f) => flatMap(self, a => fromNullishOr(f(a))));\n/**\n * Lifts a `Result`-returning function into one that returns an array: failures\n * produce `[]`, successes produce `[value]`.\n *\n * **When to use**\n *\n * Use when a fallible parser or lookup should participate in array pipelines as\n * zero-or-one results and the failure value should be discarded.\n *\n * **Example** (Lifting a Result function)\n *\n * ```ts import.meta.vitest\n * import { Array, Result } from \"effect\"\n *\n * const parseNumber = (s: string): Result.Result<number, Error> =>\n * isNaN(Number(s))\n * ? Result.fail(new Error(\"Not a number\"))\n * : Result.succeed(Number(s))\n *\n * const liftedParseNumber = Array.liftResult(parseNumber)\n *\n * liftedParseNumber(\"42\") // => [42]\n * liftedParseNumber(\"not a number\") // => []\n * ```\n *\n * @see {@link liftOption} — lift an Option-returning function\n * @see {@link liftPredicate} — lift a boolean predicate\n *\n * @category lifting\n * @since 4.0.0\n */\nexport const liftResult = f => (...a) => {\n const e = f(...a);\n return Result.isFailure(e) ? [] : [e.success];\n};\n/**\n * Checks whether all elements satisfy the predicate. Supports refinements for\n * type narrowing.\n *\n * **When to use**\n *\n * Use to check whether every array element satisfies a predicate, including\n * refinement-based type narrowing.\n *\n * **Example** (Testing all elements)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.every([2, 4, 6], (x) => x % 2 === 0) // => true\n * Array.every([2, 3, 6], (x) => x % 2 === 0) // => false\n * ```\n *\n * @see {@link some} — test if any element matches\n *\n * @category guards\n * @since 2.0.0\n */\nexport const every = /*#__PURE__*/dual(2, (self, refinement) => self.every(refinement));\n/**\n * Checks whether at least one element satisfies the predicate. Narrows the type\n * to `NonEmptyReadonlyArray` on success.\n *\n * **Example** (Testing for any match)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.some([1, 3, 4], (x) => x % 2 === 0) // => true\n * Array.some([1, 3, 5], (x) => x % 2 === 0) // => false\n * ```\n *\n * @see {@link every} — test if all elements match\n * @see {@link contains} — test for a specific value\n *\n * @category guards\n * @since 2.0.0\n */\nexport const some = /*#__PURE__*/dual(2, (self, predicate) => self.some(predicate));\n/**\n * Applies a function to each suffix of the array (starting from each index),\n * collecting the results.\n *\n * **When to use**\n *\n * Use when you need to compute a result from every suffix of an array, such as\n * cumulative aggregations from each position.\n *\n * **Details**\n *\n * For index `i`, the function receives `self.slice(i)`.\n *\n * **Example** (Computing suffix lengths)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.extend([1, 2, 3], (as) => as.length) // => [3, 2, 1]\n * ```\n *\n * @see {@link scan} for keeping intermediate accumulator values during a fold\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const extend = /*#__PURE__*/dual(2, (self, f) => self.map((_, i, as) => f(as.slice(i))));\n/**\n * Returns the minimum element of a non-empty array according to the given\n * `Order`.\n *\n * **Example** (Finding the minimum)\n *\n * ```ts import.meta.vitest\n * import { Array, Order } from \"effect\"\n *\n * Array.min([3, 1, 2], Order.Number) // => 1\n * ```\n *\n * @see {@link max} — find the maximum\n * @see {@link sort} — sort the entire array\n *\n * @category getters\n * @since 2.0.0\n */\nexport const min = /*#__PURE__*/dual(2, (self, O) => self.reduce(Order.min(O)));\n/**\n * Returns the maximum element of a non-empty array according to the given\n * `Order`.\n *\n * **Example** (Finding the maximum)\n *\n * ```ts import.meta.vitest\n * import { Array, Order } from \"effect\"\n *\n * Array.max([3, 1, 2], Order.Number) // => 3\n * ```\n *\n * @see {@link min} — find the minimum\n * @see {@link sort} — sort the entire array\n *\n * @category getters\n * @since 2.0.0\n */\nexport const max = /*#__PURE__*/dual(2, (self, O) => self.reduce(Order.max(O)));\n/**\n * Builds an array by repeatedly applying a function to a seed value. The\n * function returns `Option.some([element, nextSeed])` to continue, or\n * `Option.none()` to stop.\n *\n * **Example** (Generating a sequence)\n *\n * ```ts import.meta.vitest\n * import { Array, Option } from \"effect\"\n *\n * Array.unfold(1, (n) => n <= 5 ? Option.some([n, n + 1]) : Option.none()) // => [1, 2, 3, 4, 5]\n * ```\n *\n * @see {@link makeBy} — generate from index\n * @see {@link range} — generate a numeric range\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const unfold = (b, f) => {\n const out = [];\n let next = b;\n while (true) {\n const o = f(next);\n if (Option.isNone(o)) {\n break;\n }\n const [a, b] = o.value;\n out.push(a);\n next = b;\n }\n return out;\n};\n/**\n * Creates an `Order` for arrays based on an element `Order`. Arrays are\n * compared element-wise; if all compared elements are equal, shorter arrays\n * come first.\n *\n * **Example** (Comparing arrays)\n *\n * ```ts import.meta.vitest\n * import { Array, Order } from \"effect\"\n *\n * const arrayOrder = Array.makeOrder(Order.Number)\n *\n * arrayOrder([1, 2], [1, 3]) // => -1\n * ```\n *\n * @see {@link makeEquivalence} — create an equivalence for arrays\n *\n * @category instances\n * @since 4.0.0\n */\nexport const makeOrder = Order.Array;\n/**\n * Creates an `Equivalence` for arrays based on an element `Equivalence`. Two\n * arrays are equivalent when they have the same length and all elements are\n * pairwise equivalent.\n *\n * **Example** (Comparing arrays for equality)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * const eq = Array.makeEquivalence<number>((a, b) => a === b)\n *\n * eq([1, 2, 3], [1, 2, 3]) // => true\n * ```\n *\n * @see {@link makeOrder} — create an ordering for arrays\n *\n * @category instances\n * @since 4.0.0\n */\nexport const makeEquivalence = Equivalence.Array;\n/**\n * Runs a side-effect for each element. The callback receives `(element, index)`.\n *\n * **When to use**\n *\n * Use to iterate over an array for side-effects only, when no transformed\n * result is needed.\n *\n * **Example** (Iterating with side-effects)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * const visited: Array<number> = []\n * Array.forEach([1, 2, 3], (n) => visited.push(n))\n *\n * visited // => [1, 2, 3]\n * ```\n *\n * @see {@link map} for transforming each element into a new array\n *\n * @category traversing\n * @since 2.0.0\n */\nexport const forEach = /*#__PURE__*/dual(2, (self, f) => fromIterable(self).forEach((a, i) => f(a, i)));\n/**\n * Removes duplicates using a custom equivalence, preserving the order of the\n * first occurrence.\n *\n * **When to use**\n *\n * Use to remove all duplicate elements with a custom equivalence when default\n * equality is not appropriate.\n *\n * **Example** (Deduplicating with custom equality)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.dedupeWith([1, 2, 2, 3, 3, 3], (a, b) => a === b) // => [1, 2, 3]\n * ```\n *\n * @see {@link dedupe} — uses default equality\n * @see {@link dedupeAdjacentWith} — only dedupes consecutive elements\n *\n * @category deduplication\n * @since 2.0.0\n */\nexport const dedupeWith = /*#__PURE__*/dual(2, (self, isEquivalent) => {\n const input = fromIterable(self);\n if (isReadonlyArrayNonEmpty(input)) {\n const out = [headNonEmpty(input)];\n const rest = tailNonEmpty(input);\n for (const r of rest) {\n if (out.every(a => !isEquivalent(r, a))) {\n out.push(r);\n }\n }\n return out;\n }\n return [];\n});\n/**\n * Removes duplicates using `Equal.equivalence()`, preserving the order of the\n * first occurrence.\n *\n * **When to use**\n *\n * Use to remove repeated values from an iterable when Effect's default equality\n * is the right comparison, preserving the first occurrence.\n *\n * **Example** (Removing duplicates)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.dedupe([1, 2, 1, 3, 2, 4]) // => [1, 2, 3, 4]\n * ```\n *\n * @see {@link dedupeWith} — use custom equality\n * @see {@link dedupeAdjacent} — only dedupes consecutive elements\n *\n * @category deduplication\n * @since 2.0.0\n */\nexport const dedupe = self => {\n const input = fromIterable(self);\n if (input.length < 2) {\n return [...input];\n }\n const buckets = new Map();\n const out = [];\n for (const value of input) {\n if (hashBucketsAdd(buckets, value)) {\n out.push(value);\n }\n }\n return out;\n};\n/**\n * Removes consecutive duplicate elements using a custom equivalence.\n *\n * **When to use**\n *\n * Use when consecutive duplicates should be collapsed using a custom\n * equivalence, while equivalent values that appear later should remain in the\n * result.\n *\n * **Details**\n *\n * Non-adjacent duplicates are preserved.\n *\n * **Example** (Deduplicating adjacent elements)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.dedupeAdjacentWith([1, 1, 2, 2, 3, 3], (a, b) => a === b) // => [1, 2, 3]\n * ```\n *\n * @see {@link dedupeAdjacent} — uses default equality\n * @see {@link dedupeWith} — dedupes all duplicates, not just adjacent\n *\n * @category deduplication\n * @since 2.0.0\n */\nexport const dedupeAdjacentWith = /*#__PURE__*/dual(2, (self, isEquivalent) => {\n const out = [];\n let lastA = Option.none();\n for (const a of self) {\n if (Option.isNone(lastA) || !isEquivalent(a, lastA.value)) {\n out.push(a);\n lastA = Option.some(a);\n }\n }\n return out;\n});\n/**\n * Removes consecutive duplicate elements using `Equal.equivalence()`.\n *\n * **When to use**\n *\n * Use when you need to collapse consecutive duplicates while preserving later\n * non-consecutive repeats, and the default equality is sufficient.\n *\n * **Example** (Removing adjacent duplicates)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.dedupeAdjacent([1, 1, 2, 2, 3, 3]) // => [1, 2, 3]\n * ```\n *\n * @see {@link dedupeAdjacentWith} — use custom equality\n * @see {@link dedupe} — remove all duplicates\n *\n * @category deduplication\n * @since 2.0.0\n */\nexport const dedupeAdjacent = /*#__PURE__*/dedupeAdjacentWith(/*#__PURE__*/Equal.asEquivalence());\n/**\n * Joins string elements with a separator.\n *\n * **Example** (Joining strings)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.join([\"a\", \"b\", \"c\"], \"-\") // => \"a-b-c\"\n * ```\n *\n * @see {@link intersperse} — insert separator elements without joining\n *\n * @category folding\n * @since 2.0.0\n */\nexport const join = /*#__PURE__*/dual(2, (self, sep) => fromIterable(self).join(sep));\n/**\n * Maps over an array while threading an accumulator through each step, returning both the final state and the mapped array.\n *\n * **When to use**\n *\n * Use when you need to map while threading state through each element and keep\n * the final state.\n *\n * **Details**\n *\n * Combines `map` and `reduce` in a single pass. The callback receives the\n * current state, element, and index, and returns `[nextState, mappedValue]`.\n * The result is `[finalState, mappedArray]`. This can be used in both\n * data-first and data-last style.\n *\n * **Example** (Running sum alongside mapped values)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.mapAccum([1, 2, 3], 0, (acc, n) => [acc + n, acc + n]) // => [6, [1, 3, 6]]\n * ```\n *\n * @see {@link scan} — when you only need the accumulated results (not the final state)\n * @see {@link reduce} — when you only need the final accumulated value\n *\n * @category folding\n * @since 2.0.0\n */\nexport const mapAccum = /*#__PURE__*/dual(3, (self, s, f) => {\n let i = 0;\n let s1 = s;\n const out = [];\n for (const a of self) {\n const r = f(s1, a, i);\n s1 = r[0];\n out.push(r[1]);\n i++;\n }\n return [s1, out];\n});\n/**\n * Computes the cartesian product of two arrays, applying a combiner to each pair.\n *\n * **When to use**\n *\n * Use to compute every combination from two arrays and immediately transform\n * each pair into a custom result.\n *\n * **Details**\n *\n * Produces every combination of an element from `self` with an element from\n * `that`, so the result length is `self.length * that.length`. Iteration visits\n * every element of `that` for each element of `self`.\n *\n * **Example** (Combining numbers and letters)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.cartesianWith([1, 2], [\"a\", \"b\"], (a, b) => `${a}-${b}`) // => [\"1-a\", \"1-b\", \"2-a\", \"2-b\"]\n * ```\n *\n * @see {@link cartesian} for returning tuples instead of applying a combiner\n *\n * @category combining\n * @since 2.0.0\n */\nexport const cartesianWith = /*#__PURE__*/dual(3, (self, that, f) => flatMap(self, a => map(that, b => f(a, b))));\n/**\n * Computes the cartesian product of two arrays, returning all pairs as tuples.\n *\n * **When to use**\n *\n * Use when you need every `[a, b]` pair from two arrays as tuples.\n *\n * **Details**\n *\n * Produces every `[a, b]` combination of an element from `self` with an element\n * from `that`, so the result length is `self.length * that.length`.\n *\n * **Example** (Generating all pairs from two arrays)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.cartesian([1, 2], [\"a\", \"b\"]) // => [[1, \"a\"], [1, \"b\"], [2, \"a\"], [2, \"b\"]]\n * ```\n *\n * @see {@link cartesianWith} — apply a combiner to each pair\n *\n * @category combining\n * @since 2.0.0\n */\nexport const cartesian = /*#__PURE__*/dual(2, (self, that) => cartesianWith(self, that, (a, b) => [a, b]));\n// -------------------------------------------------------------------------------------\n// do notation\n// -------------------------------------------------------------------------------------\n/**\n * Provides the starting point for the \"do simulation\" — an array comprehension pattern.\n *\n * **When to use**\n *\n * Use when you want array-comprehension style code with do notation.\n *\n * **Details**\n *\n * Use {@link bind} to introduce array variables and {@link let_ let} for plain\n * values. Each `bind` produces the cartesian product of all bound variables,\n * like nested loops. Use `filter` and `map` in the pipeline to add conditions\n * and transformations.\n *\n * **Example** (Building array comprehensions with do notation)\n *\n * ```ts import.meta.vitest\n * import { Array, pipe } from \"effect\"\n *\n * pipe(\n * Array.Do,\n * Array.bind(\"x\", () => [1, 3, 5]),\n * Array.bind(\"y\", () => [2, 4, 6]),\n * Array.filter(({ x, y }) => x < y),\n * Array.map(({ x, y }) => [x, y] as const)\n * ) // => [[1, 2], [1, 4], [1, 6], [3, 4], [3, 6], [5, 6]]\n * ```\n *\n * @see {@link bind} — introduce an array variable into the scope\n * @see {@link bindTo} — start a pipeline by naming the first array\n * @see {@link let_ let} — introduce a plain computed value\n *\n * @category constructors\n * @since 3.2.0\n */\nexport const Do = /*#__PURE__*/of({});\n/**\n * Adds a new array variable to a do-notation scope, producing the cartesian product with all previous bindings.\n *\n * **When to use**\n *\n * Use to add another array-producing binding to an `Array.Do` pipeline, pairing\n * each existing scope with every value returned by the callback.\n *\n * **Details**\n *\n * Each `bind` call adds a named property to the accumulated object. The\n * callback receives the current scope and must return an array. This is\n * equivalent to `flatMap` plus merging the new value into the scope object.\n *\n * **Example** (Binding two arrays)\n *\n * ```ts import.meta.vitest\n * import { Array, pipe } from \"effect\"\n *\n * pipe(\n * Array.Do,\n * Array.bind(\"x\", () => [1, 2]),\n * Array.bind(\"y\", () => [\"a\", \"b\"])\n * ) // => [{ x: 1, y: \"a\" }, { x: 1, y: \"b\" }, { x: 2, y: \"a\" }, { x: 2, y: \"b\" }]\n * ```\n *\n * @see {@link Do} — start a do-notation pipeline\n * @see {@link bindTo} — name the first array in a pipeline\n * @see {@link let_ let} — add a plain computed value\n *\n * @category sequencing\n * @since 3.2.0\n */\nexport const bind = /*#__PURE__*/internalDoNotation.bind(map, flatMap);\n/**\n * Wraps each array element in an object with the given key, starting a do-notation scope.\n *\n * **When to use**\n *\n * Use when you already have an array and want to start a do-notation pipeline\n * by naming each element.\n *\n * **Details**\n *\n * Equivalent to `Array.map(self, (a) => ({ [tag]: a }))`. This is an\n * alternative to starting with `Do` plus `bind` when you already have an array.\n *\n * **Example** (Naming an existing array)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.bindTo([1, 2, 3], \"x\") // => [{ x: 1 }, { x: 2 }, { x: 3 }]\n * ```\n *\n * @see {@link Do} — start with an empty scope\n * @see {@link bind} — add another array variable to the scope\n *\n * @category mapping\n * @since 3.2.0\n */\nexport const bindTo = /*#__PURE__*/internalDoNotation.bindTo(map);\nconst let_ = /*#__PURE__*/internalDoNotation.let_(map);\nexport {\n/**\n * Adds a computed plain value to the do-notation scope without introducing a new array dimension.\n *\n * **When to use**\n *\n * Use when each do-notation branch needs a derived field from the current\n * bindings without multiplying the number of branches.\n *\n * **Details**\n *\n * Unlike `bind`, the callback returns a single value instead of an array, so\n * no cartesian product occurs. Use this for derived or intermediate values\n * that depend on previously bound variables.\n *\n * **Example** (Adding a computed value)\n *\n * ```ts import.meta.vitest\n * import { Array, pipe } from \"effect\"\n *\n * pipe(\n * Array.Do,\n * Array.bind(\"x\", () => [1, 2, 3]),\n * Array.let(\"doubled\", ({ x }) => x * 2)\n * ) // => [{ x: 1, doubled: 2 }, { x: 2, doubled: 4 }, { x: 3, doubled: 6 }]\n * ```\n *\n * @see {@link Do} — start a do-notation pipeline\n * @see {@link bind} — introduce an array variable (produces cartesian product)\n *\n * @category mapping\n * @since 3.2.0\n */\nlet_ as let };\nconst reducer = /*#__PURE__*/Reducer.make((a, b) => a.concat(b), []);\n/**\n * Returns a `Reducer` that combines `ReadonlyArray` values by concatenation.\n *\n * @see {@link makeReducerConcat} — mutable `Array` variant\n *\n * @category folding\n * @since 4.0.0\n */\nexport function getReadonlyReducerConcat() {\n return reducer;\n}\n/**\n * Returns a `Reducer` that combines `Array` values by concatenation.\n *\n * @see {@link getReadonlyReducerConcat} — readonly variant\n *\n * @category folding\n * @since 4.0.0\n */\nexport function makeReducerConcat() {\n return reducer;\n}\n/**\n * Computes the number of elements in an iterable that satisfy a predicate.\n *\n * **When to use**\n *\n * Use when you need to count how many elements of an iterable satisfy a\n * predicate.\n *\n * **Details**\n *\n * The predicate receives both the element and its index. Empty iterables return\n * `0`.\n *\n * **Example** (Counting even numbers)\n *\n * ```ts import.meta.vitest\n * import { Array } from \"effect\"\n *\n * Array.countBy([1, 2, 3, 4, 5], (n) => n % 2 === 0) // => 2\n * ```\n *\n * @see {@link filter} — when you need the matching elements, not just the count\n *\n * @category folding\n * @since 3.16.0\n */\nexport const countBy = /*#__PURE__*/dual(2, (self, f) => {\n let count = 0;\n const as = fromIterable(self);\n for (let i = 0; i < as.length; i++) {\n const a = as[i];\n if (f(a, i)) {\n count++;\n }\n }\n return count;\n});\n//# sourceMappingURL=Array.js.map","/**\n * Controls how runnable Effect fiber tasks are dispatched.\n *\n * A scheduler decides how tasks are queued, when queued tasks run, and when a\n * fiber should pause so other work can continue. This module includes the\n * scheduler service reference, the default `MixedScheduler`, dispatcher types\n * for queued tasks, and references for tuning or disabling automatic scheduler\n * yields.\n *\n * @since 2.0.0\n */\nimport * as Context from \"./Context.js\";\n/**\n * Context reference for the scheduler used by the Effect runtime.\n *\n * **When to use**\n *\n * Use when you need to replace scheduling behavior globally in tests or runtime\n * setup, such as forcing deterministic task dispatch.\n *\n * **Details**\n *\n * The default value creates a `MixedScheduler`. Provide this service to\n * customize execution mode, task dispatching, or yield behavior.\n *\n * @category services\n * @since 2.0.0\n */\nexport const Scheduler = /*#__PURE__*/Context.Reference(\"effect/Scheduler\", {\n fiberCached: true,\n defaultValue: () => new MixedScheduler()\n});\nconst setMicrotask = f => {\n let cancelled = false;\n Promise.resolve().then(() => {\n if (!cancelled) f();\n });\n return () => {\n cancelled = true;\n };\n};\nconst setTimer = \"setImmediate\" in globalThis ? f => {\n // @ts-ignore\n const timer = globalThis.setImmediate(f);\n // @ts-ignore\n return () => globalThis.clearImmediate(timer);\n} : f => {\n const timer = setTimeout(f, 0);\n return () => clearTimeout(timer);\n};\n// Some runtimes (e.g. Cloudflare Workers) throw when a timer is set in global\n// scope. Fall back to a microtask so effects can still yield at module load.\nconst setImmediate = f => {\n try {\n return setTimer(f);\n } catch {\n return setMicrotask(f);\n }\n};\nclass PriorityBuckets {\n buckets = [];\n scheduleTask(task, priority) {\n const buckets = this.buckets;\n const len = buckets.length;\n let bucket;\n let index = 0;\n for (; index < len; index++) {\n if (buckets[index][0] > priority) break;\n bucket = buckets[index];\n }\n if (bucket && bucket[0] === priority) {\n bucket[1].push(task);\n } else if (index === len) {\n buckets.push([priority, [task]]);\n } else {\n buckets.splice(index, 0, [priority, [task]]);\n }\n }\n drain() {\n const buckets = this.buckets;\n this.buckets = [];\n return buckets;\n }\n}\n/**\n * Provides a scheduler implementation that batches queued tasks and dispatches them by\n * priority.\n *\n * **When to use**\n *\n * Use when you need the default runtime scheduler directly, including a\n * scheduler that batches queued work by priority and preserves FIFO order within\n * each priority.\n *\n * **Details**\n *\n * `MixedScheduler` supports synchronous and asynchronous execution modes, uses\n * operation counts to decide when fibers should yield, and is the default\n * scheduler implementation.\n *\n * @category models\n * @since 2.0.0\n */\nexport class MixedScheduler {\n executionMode;\n setImmediate;\n constructor(executionMode = \"async\", setImmediateFn) {\n this.executionMode = executionMode;\n this.setImmediate = setImmediateFn ?? (executionMode === \"sync\" ? setMicrotask : setImmediate);\n }\n /**\n * Returns whether the fiber has reached its operation budget and should yield.\n *\n * **When to use**\n *\n * Use to decide whether a fiber should yield after consuming its current\n * operation budget.\n *\n * @since 2.0.0\n */\n shouldYield(fiber) {\n return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield;\n }\n /**\n * Creates a dispatcher that schedules work through this scheduler.\n *\n * **When to use**\n *\n * Use when you need a standalone dispatcher from a scheduler instance, for\n * example in tests that enqueue tasks and then flush them deterministically.\n *\n * @since 4.0.0\n */\n makeDispatcher() {\n return new MixedSchedulerDispatcher(this.setImmediate);\n }\n}\nclass MixedSchedulerDispatcher {\n tasks = /*#__PURE__*/new PriorityBuckets();\n running = undefined;\n setImmediate;\n constructor(setImmediateFn = setImmediate) {\n this.setImmediate = setImmediateFn;\n }\n /**\n * @since 2.0.0\n */\n scheduleTask(task, priority) {\n this.tasks.scheduleTask(task, priority);\n if (this.running === undefined) {\n this.running = this.setImmediate(this.afterScheduled);\n }\n }\n /**\n * @since 2.0.0\n */\n afterScheduled = () => {\n this.running = undefined;\n this.runTasks();\n };\n /**\n * @since 2.0.0\n */\n runTasks() {\n const buckets = this.tasks.drain();\n for (let i = 0; i < buckets.length; i++) {\n const toRun = buckets[i][1];\n for (let j = 0; j < toRun.length; j++) {\n toRun[j]();\n }\n }\n }\n /**\n * @since 2.0.0\n */\n flush() {\n while (this.tasks.buckets.length > 0) {\n if (this.running !== undefined) {\n this.running();\n this.running = undefined;\n }\n this.runTasks();\n }\n }\n}\n/**\n * Context reference that controls the maximum number of operations a fiber\n * can perform before yielding control back to the scheduler.\n *\n * **When to use**\n *\n * Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler\n * operation budget that triggers a yield.\n *\n * **Details**\n *\n * The default value is `2048` operations, which balances performance and\n * fairness by helping prevent long-running fibers from monopolizing the\n * execution thread.\n *\n * @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget\n *\n * @category services\n * @since 4.0.0\n */\nexport const MaxOpsBeforeYield = /*#__PURE__*/Context.Reference(\"effect/Scheduler/MaxOpsBeforeYield\", {\n fiberCached: true,\n defaultValue: () => 2048\n});\n/**\n * Context reference that controls whether the runtime should bypass scheduler\n * yield checks. When set to `true`, the fiber run loop won't call\n * `Scheduler.shouldYield`.\n *\n * **When to use**\n *\n * Use to bypass scheduler yield checks for controlled runtime workloads where\n * cooperative yielding should be disabled.\n *\n * **Gotchas**\n *\n * Setting this reference to `true` can let long-running fibers monopolize the\n * JavaScript thread.\n *\n * @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks\n * @see {@link Scheduler} for providing custom scheduler yield behavior\n *\n * @category services\n * @since 4.0.0\n */\nexport const PreventSchedulerYield = /*#__PURE__*/Context.Reference(\"effect/Scheduler/PreventSchedulerYield\", {\n fiberCached: true,\n defaultValue: () => false\n});\n//# sourceMappingURL=Scheduler.js.map","import * as core from \"./internal/core.js\";\nimport * as InternalRecord from \"./internal/record.js\";\nimport * as Pipeable from \"./Pipeable.js\";\nimport * as Predicate from \"./Predicate.js\";\n/**\n * Provides a base class for immutable data types.\n *\n * **When to use**\n *\n * Use when you need a lightweight immutable value type with `.pipe()` support.\n *\n * **Details**\n *\n * Extend `Class` with a type parameter to declare fields. The constructor\n * accepts those fields as a single object argument. When there are no fields\n * the argument is optional. Instances are `Readonly` and `Pipeable`.\n *\n * **Example** (Defining a value class)\n *\n * ```ts import.meta.vitest\n * import { Data, Equal } from \"effect\"\n *\n * class Person extends Data.Class<{ readonly name: string }> {}\n *\n * Equal.equals(new Person({ name: \"Mike\" }), new Person({ name: \"Mike\" })) // => true\n * ```\n *\n * @see {@link TaggedClass} — adds a `_tag` field\n * @see {@link Error} — yieldable error variant\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const Class = class extends Pipeable.Class {\n constructor(props) {\n super();\n if (props) {\n InternalRecord.assignProperties(this, props);\n }\n }\n};\n/**\n * Provides a base class for immutable data types with a `_tag` discriminator.\n *\n * **When to use**\n *\n * Use when you need a single-variant tagged type or an ad-hoc discriminator.\n *\n * **Details**\n *\n * Like {@link Class}, but the resulting instances also carry a\n * `readonly _tag: Tag` property. The `_tag` is excluded from the constructor\n * argument.\n *\n * **Example** (Defining a tagged class)\n *\n * ```ts import.meta.vitest\n * import { Data } from \"effect\"\n *\n * class Person extends Data.TaggedClass(\"Person\")<{\n * readonly name: string\n * }> {}\n *\n * new Person({ name: \"Mike\" })._tag // => \"Person\"\n * ```\n *\n * @see {@link Class} — without a `_tag`\n * @see {@link TaggedError} — tagged error variant\n * @see {@link TaggedEnum} — multi-variant unions\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const TaggedClass = tag => class extends Class {\n _tag = tag;\n};\n/**\n * Creates constructors and matchers for a `TaggedEnum` type.\n *\n * **When to use**\n *\n * Use when you model a closed union with plain data objects and want\n * construction, tag checks, and exhaustive matching from the same definition.\n *\n * **Details**\n *\n * Returns an object with:\n * - One constructor per variant (keyed by tag name)\n * - `$is(tag)` — returns a type-guard function that checks only the `_tag` field\n * - `$match` — exhaustive pattern matching (data-first or data-last)\n *\n * **Gotchas**\n *\n * - Constructors produce **plain objects**, not class instances.\n * - `$is(tag)` only checks the `_tag` field, not the full structure. It relies\n * on the tag being globally unique and the value being produced by your\n * constructors. For untrusted input, validate with the `Schema` module first.\n *\n * **Example** (Creating and matching tagged enum values)\n *\n * ```ts import.meta.vitest\n * import { Data } from \"effect\"\n *\n * type HttpError = Data.TaggedEnum<{\n * BadRequest: { readonly message: string }\n * NotFound: { readonly url: string }\n * }>\n *\n * const { BadRequest, NotFound, $is, $match } = Data.taggedEnum<HttpError>()\n *\n * const err = NotFound({ url: \"/missing\" })\n *\n * $is(\"NotFound\")(err) // => true\n *\n * $match(err, {\n * BadRequest: (e) => e.message,\n * NotFound: (e) => `${e.url} not found`\n * }) // => \"/missing not found\"\n * ```\n *\n * **Example** (Defining a generic tagged enum)\n *\n * ```ts import.meta.vitest\n * import { Data } from \"effect\"\n *\n * type MyResult<E, A> = Data.TaggedEnum<{\n * Failure: { readonly error: E }\n * Success: { readonly value: A }\n * }>\n * interface MyResultDef extends Data.TaggedEnum.WithGenerics<2> {\n * readonly taggedEnum: MyResult<this[\"A\"], this[\"B\"]>\n * }\n * const { Failure, Success } = Data.taggedEnum<MyResultDef>()\n *\n * const ok = Success({ value: 42 })\n * // ok: { readonly _tag: \"Success\"; readonly value: number }\n * ok // => { value: 42, _tag: \"Success\" }\n * ```\n *\n * @see {@link TaggedEnum} — the type-level companion\n * @see {@link TaggedEnum.Constructor} — the returned object type\n * @see {@link TaggedEnum.WithGenerics} — generic enum support\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const taggedEnum = () => new Proxy({}, {\n get(_target, tag, _receiver) {\n if (tag === \"$is\") {\n return Predicate.isTagged;\n } else if (tag === \"$match\") {\n return taggedMatch;\n }\n return props => ({\n ...props,\n _tag: tag\n });\n }\n});\nfunction taggedMatch() {\n if (arguments.length === 1) {\n const cases = arguments[0];\n return function (value) {\n return cases[value._tag](value);\n };\n }\n const value = arguments[0];\n const cases = arguments[1];\n return cases[value._tag](value);\n}\n/**\n * Provides a base class for yieldable errors.\n *\n * **When to use**\n *\n * Use when you need yieldable errors that do **not** need tag-based\n * discrimination.\n *\n * **Details**\n *\n * Extends `Cause.YieldableError`, so instances can be yielded inside\n * `Effect.gen` to fail the enclosing effect. Fields are passed as a single\n * object; when there are no fields the argument is optional. If a `message`\n * field is provided, it becomes the error's `.message`.\n *\n * **Example** (Defining a yieldable error)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect, Exit } from \"effect\"\n *\n * class NetworkError extends Data.Error<{\n * readonly code: number\n * readonly message: string\n * }> {}\n *\n * const program = Effect.gen(function*() {\n * return yield* new NetworkError({ code: 500, message: \"timeout\" })\n * })\n *\n * Effect.runSync(Effect.exit(program)) // => Exit.fail(new NetworkError({ code: 500, message: \"timeout\" }))\n * ```\n *\n * @see {@link TaggedError} — adds a `_tag` for `Effect.catchTag`\n * @see {@link Class} — non-error data class\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const Error = core.Error;\n/**\n * Creates a tagged error class with a `_tag` discriminator.\n *\n * **When to use**\n *\n * Use when you need domain errors with discriminated-union handling.\n *\n * **Details**\n *\n * Like {@link Error}, but instances also carry a `readonly _tag` property,\n * enabling `Effect.catchTag` and `Effect.catchTags` for tag-based recovery.\n * The `_tag` is excluded from the constructor argument. Yielding an instance\n * inside `Effect.gen` fails the effect with this error.\n *\n * **Example** (Recovering by tag)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect } from \"effect\"\n *\n * class NotFound extends Data.TaggedError(\"NotFound\")<{\n * readonly resource: string\n * }> {}\n *\n * class Forbidden extends Data.TaggedError(\"Forbidden\")<{\n * readonly reason: string\n * }> {}\n *\n * const program = Effect.gen(function*() {\n * return yield* new NotFound({ resource: \"/users/42\" })\n * })\n *\n * const recovered = program.pipe(\n * Effect.catchTag(\"NotFound\", (e) =>\n * Effect.succeed(`missing: ${e.resource}`))\n * )\n *\n * await Effect.runPromise(recovered) // => \"missing: /users/42\"\n * ```\n *\n * @see {@link Error} — without a `_tag`\n * @see {@link TaggedClass} — tagged class that is not an error\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const TaggedError = core.TaggedError;\n//# sourceMappingURL=Data.js.map","/**\n * Encoding and decoding helpers for Base64, Base64Url, and hexadecimal text.\n * The functions convert between strings, UTF-8 text, and `Uint8Array` bytes.\n * Encode functions return strings directly, while decode functions return\n * `Result.Result` so invalid input is reported as an `EncodingError` instead of\n * being thrown.\n *\n * @since 4.0.0\n */\nimport * as Data from \"./Data.js\";\nimport { hasProperty } from \"./Predicate.js\";\nimport * as Result from \"./Result.js\";\n// -------------------------------------------------------------------------------------\n// EncodingError\n// -------------------------------------------------------------------------------------\n/**\n * Type identifier stored on `EncodingError` values and used by\n * `isEncodingError`.\n *\n * **When to use**\n *\n * Use when implementing low-level `EncodingError`-compatible values that need\n * to carry the runtime marker.\n *\n * **Details**\n *\n * This marker is part of the runtime representation of `EncodingError`. Prefer\n * `isEncodingError` when narrowing unknown values.\n *\n * @see {@link isEncodingError} for the public guard that checks this marker\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const EncodingErrorTypeId = \"~effect/Encoding/EncodingError\";\n/**\n * Error returned when an encoding or decoding operation cannot process its\n * input.\n *\n * **When to use**\n *\n * Use when you need to handle or inspect failures from encoding or decoding\n * operations.\n *\n * **Details**\n *\n * The error records whether the failure happened during encoding or decoding,\n * which encoding module reported it, the original input, and a human-readable\n * message.\n *\n * @see {@link isEncodingError} for checking whether a value is an EncodingError\n * @category errors\n * @since 4.0.0\n */\nexport class EncodingError extends /*#__PURE__*/Data.TaggedError(\"EncodingError\") {\n /**\n * Marks this value as an encoding or decoding error for runtime guards.\n *\n * **When to use**\n *\n * Use to identify `EncodingError` instances through `isEncodingError`.\n *\n * @since 4.0.0\n */\n [EncodingErrorTypeId] = EncodingErrorTypeId;\n}\n/**\n * Checks whether a value is an `EncodingError`.\n *\n * **When to use**\n *\n * Use to narrow an unknown value before handling it as an `EncodingError` from\n * encoding or decoding code.\n *\n * **Details**\n *\n * Returns `true` when the value carries the `EncodingErrorTypeId` marker and\n * narrows the value to `EncodingError`.\n *\n * @see {@link EncodingError} for the structured error produced by failed\n * encoding and decoding operations\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isEncodingError = u => hasProperty(u, EncodingErrorTypeId);\n// -------------------------------------------------------------------------------------\n// Base64\n// -------------------------------------------------------------------------------------\n/**\n * Encodes the given value into a base64 (RFC4648) `string`.\n *\n * **When to use**\n *\n * Use to encode text or bytes as a standard padded Base64 string for storage or\n * transport.\n *\n * **Details**\n *\n * String inputs are encoded as UTF-8 bytes before Base64 encoding.\n * `Uint8Array` inputs are encoded directly. The output uses the standard\n * RFC4648 alphabet with `=` padding.\n *\n * **Example** (Encoding Base64 strings and bytes)\n *\n * ```ts import.meta.vitest\n * import { Encoding } from \"effect\"\n *\n * // Encode a string\n * Encoding.encodeBase64(\"hello\") // => \"aGVsbG8=\"\n *\n * // Encode binary data\n * const bytes = new Uint8Array([72, 101, 108, 108, 111])\n * Encoding.encodeBase64(bytes) // => \"SGVsbG8=\"\n * ```\n *\n * @see {@link decodeBase64} for decoding standard Base64 to bytes\n * @see {@link decodeBase64String} for decoding standard Base64 to UTF-8 text\n * @see {@link encodeBase64Url} for URL-safe unpadded Base64 output\n *\n * @category encoding\n * @since 2.0.0\n */\nexport const encodeBase64 = input => typeof input === \"string\" ? base64EncodeUint8Array(encoder.encode(input)) : base64EncodeUint8Array(input);\n/**\n * Decodes a base64 (RFC4648) string into bytes safely.\n *\n * **When to use**\n *\n * Use to decode a standard padded Base64 string into bytes without throwing on\n * invalid input.\n *\n * **Details**\n *\n * Returns `Result.succeed` with a `Uint8Array` when decoding succeeds, or\n * `Result.fail` with an `EncodingError` when the input is not valid base64.\n *\n * **Example** (Decoding Base64 bytes)\n *\n * ```ts import.meta.vitest\n * import { Encoding, Result } from \"effect\"\n *\n * Encoding.decodeBase64(\"SGVsbG8=\") // => Result.succeed(new Uint8Array([72, 101, 108, 108, 111]))\n * ```\n *\n * @category decoding\n * @since 2.0.0\n */\nexport const decodeBase64 = str => {\n const stripped = stripCrlf(str);\n const length = stripped.length;\n if (length % 4 !== 0) {\n return Result.fail(new EncodingError({\n kind: \"Decode\",\n module: \"Base64\",\n input: stripped,\n message: `Length must be a multiple of 4, but is ${length}`\n }));\n }\n const index = stripped.indexOf(\"=\");\n if (index !== -1 && (index < length - 2 || index === length - 2 && stripped[length - 1] !== \"=\")) {\n return Result.fail(new EncodingError({\n kind: \"Decode\",\n module: \"Base64\",\n input: stripped,\n message: `Found a '=' character, but it is not at the end`\n }));\n }\n try {\n const missingOctets = stripped.endsWith(\"==\") ? 2 : stripped.endsWith(\"=\") ? 1 : 0;\n const result = new Uint8Array(3 * (length / 4) - missingOctets);\n for (let i = 0, j = 0; i < length; i += 4, j += 3) {\n const buffer = getBase64Code(stripped.charCodeAt(i)) << 18 | getBase64Code(stripped.charCodeAt(i + 1)) << 12 | getBase64Code(stripped.charCodeAt(i + 2)) << 6 | getBase64Code(stripped.charCodeAt(i + 3));\n result[j] = buffer >> 16;\n result[j + 1] = buffer >> 8 & 0xff;\n result[j + 2] = buffer & 0xff;\n }\n return Result.succeed(result);\n } catch (e) {\n return Result.fail(new EncodingError({\n kind: \"Decode\",\n module: \"Base64\",\n input: stripped,\n message: e instanceof Error ? e.message : \"Invalid input\"\n }));\n }\n};\n/**\n * Decodes a base64 (RFC4648) string into a UTF-8 string safely.\n *\n * **When to use**\n *\n * Use to decode a standard padded Base64 string into UTF-8 text without\n * throwing on invalid input.\n *\n * **Details**\n *\n * Returns `Result.succeed` with the decoded text when decoding succeeds, or\n * `Result.fail` with an `EncodingError` when the input is not valid base64.\n *\n * **Example** (Decoding Base64 strings)\n *\n * ```ts import.meta.vitest\n * import { Encoding, Result } from \"effect\"\n *\n * Encoding.decodeBase64String(\"aGVsbG8=\") // => Result.succeed(\"hello\")\n * ```\n *\n * @category decoding\n * @since 2.0.0\n */\nexport const decodeBase64String = str => Result.map(decodeBase64(str), _ => decoder.decode(_));\n// -------------------------------------------------------------------------------------\n// Base64Url\n// -------------------------------------------------------------------------------------\n/**\n * Encodes the given value into a base64 (URL) `string`.\n *\n * **When to use**\n *\n * Use to encode text or bytes as an unpadded Base64Url string for contexts that\n * require the URL-safe alphabet.\n *\n * **Details**\n *\n * String inputs are encoded as UTF-8 bytes before Base64Url encoding.\n * `Uint8Array` inputs are encoded directly. The output removes `=` padding and\n * replaces `+` with `-` and `/` with `_`.\n *\n * **Example** (Encoding URL-safe Base64)\n *\n * ```ts import.meta.vitest\n * import { Encoding } from \"effect\"\n *\n * // URL-safe base64 encoding (uses - and _ instead of + and /)\n * Encoding.encodeBase64Url(\"hello?\") // => \"aGVsbG8_\"\n *\n * const bytes = new Uint8Array([72, 101, 108, 108, 111, 63])\n * Encoding.encodeBase64Url(bytes) // => \"SGVsbG8_\"\n * ```\n *\n * @see {@link decodeBase64Url} for decoding URL-safe Base64 to bytes\n * @see {@link decodeBase64UrlString} for decoding URL-safe Base64 to UTF-8 text\n * @see {@link encodeBase64} for standard padded Base64 output\n *\n * @category encoding\n * @since 2.0.0\n */\nexport const encodeBase64Url = input => typeof input === \"string\" ? base64UrlEncodeUint8Array(encoder.encode(input)) : base64UrlEncodeUint8Array(input);\n/**\n * Decodes a URL-safe base64 string into bytes safely.\n *\n * **When to use**\n *\n * Use to decode padded or unpadded Base64Url text into bytes without throwing\n * on invalid input.\n *\n * **Details**\n *\n * Returns `Result.succeed` with a `Uint8Array` when decoding succeeds, or\n * `Result.fail` with an `EncodingError` when the input is not valid URL-safe\n * base64. Both padded and unpadded URL-safe base64 forms are accepted when\n * otherwise valid.\n *\n * **Example** (Decoding URL-safe Base64 bytes)\n *\n * ```ts import.meta.vitest\n * import { Encoding, Result } from \"effect\"\n *\n * Encoding.decodeBase64Url(\"SGVsbG8_\") // => Result.succeed(new Uint8Array([72, 101, 108, 108, 111, 63]))\n * ```\n *\n * @category decoding\n * @since 2.0.0\n */\nexport const decodeBase64Url = str => {\n const stripped = stripCrlf(str);\n const length = stripped.length;\n if (length % 4 === 1) {\n return Result.fail(new EncodingError({\n module: \"Base64Url\",\n kind: \"Decode\",\n input: stripped,\n message: `Length should be a multiple of 4, but is ${length}`\n }));\n }\n if (!/^[-_A-Z0-9]*?={0,2}$/i.test(stripped)) {\n return Result.fail(new EncodingError({\n module: \"Base64Url\",\n kind: \"Decode\",\n input: stripped,\n message: \"Invalid input\"\n }));\n }\n // Some variants allow or require omitting the padding '=' signs\n let sanitized = length % 4 === 2 ? `${stripped}==` : length % 4 === 3 ? `${stripped}=` : stripped;\n sanitized = sanitized.replace(/-/g, \"+\").replace(/_/g, \"/\");\n return decodeBase64(sanitized);\n};\n/**\n * Decodes a URL-safe base64 string into a UTF-8 string safely.\n *\n * **When to use**\n *\n * Use to decode padded or unpadded Base64Url text into UTF-8 text without\n * throwing on invalid input.\n *\n * **Details**\n *\n * Returns `Result.succeed` with the decoded text when decoding succeeds, or\n * `Result.fail` with an `EncodingError` when the input is not valid URL-safe\n * base64.\n *\n * **Example** (Decoding URL-safe Base64 strings)\n *\n * ```ts import.meta.vitest\n * import { Encoding, Result } from \"effect\"\n *\n * Encoding.decodeBase64UrlString(\"aGVsbG8_\") // => Result.succeed(\"hello?\")\n * ```\n *\n * @category decoding\n * @since 2.0.0\n */\nexport const decodeBase64UrlString = str => Result.map(decodeBase64Url(str), _ => decoder.decode(_));\n// -------------------------------------------------------------------------------------\n// Hex\n// -------------------------------------------------------------------------------------\n/**\n * Encodes the given value into a hex `string`.\n *\n * **When to use**\n *\n * Use to encode text or bytes as lowercase hexadecimal text.\n *\n * **Example** (Encoding hex strings and bytes)\n *\n * ```ts import.meta.vitest\n * import { Encoding } from \"effect\"\n *\n * // Encode a string to hex\n * Encoding.encodeHex(\"hello\") // => \"68656c6c6f\"\n *\n * // Encode binary data to hex\n * const bytes = new Uint8Array([72, 101, 108, 108, 111])\n * Encoding.encodeHex(bytes) // => \"48656c6c6f\"\n * ```\n *\n * @category encoding\n * @since 2.0.0\n */\nexport const encodeHex = input => typeof input === \"string\" ? hexEncodeUint8Array(encoder.encode(input)) : hexEncodeUint8Array(input);\n/**\n * Generates a random lowercase hexadecimal string, optimized for lengths that\n * are multiples of 8.\n *\n * **Details**\n *\n * `length` is not validated. The function generates `length >>> 3` random\n * 8-character words, so non-negative lengths below `2 ** 32` are rounded down\n * to a multiple of 8 and other values follow JavaScript's unsigned 32-bit\n * coercion rules.\n *\n * This function uses `Math.random()` and is not cryptographically secure. For\n * security-sensitive values, use the `Crypto.Crypto` service's `randomBytes`\n * method and encode the result with {@link encodeHex}.\n *\n * @category encoding\n * @since 4.0.0\n */\nexport const randomHex = length => {\n switch (length) {\n case 16:\n return randomHex16();\n case 32:\n return randomHex32();\n default:\n {\n let result = \"\";\n for (let i = length >>> 3; i > 0; i--) {\n result += randomHex8();\n }\n return result;\n }\n }\n};\nconst hexCharCodes = /*#__PURE__*/Uint8Array.from(\"0123456789abcdef\", c => c.charCodeAt(0));\nconst randomWord = () => Math.random() * 0x100000000 >>> 0;\n// Trace and span identifiers are the common lengths. A single\n// String.fromCharCode call produces a flat string, which avoids rope\n// flattening when the identifier is later serialized.\nconst randomHex8 = () => {\n const a = randomWord();\n return String.fromCharCode(hexCharCodes[a >>> 28], hexCharCodes[a >>> 24 & 15], hexCharCodes[a >>> 20 & 15], hexCharCodes[a >>> 16 & 15], hexCharCodes[a >>> 12 & 15], hexCharCodes[a >>> 8 & 15], hexCharCodes[a >>> 4 & 15], hexCharCodes[a & 15]);\n};\nconst randomHex16 = () => {\n const a = randomWord();\n const b = randomWord();\n return String.fromCharCode(hexCharCodes[a >>> 28], hexCharCodes[a >>> 24 & 15], hexCharCodes[a >>> 20 & 15], hexCharCodes[a >>> 16 & 15], hexCharCodes[a >>> 12 & 15], hexCharCodes[a >>> 8 & 15], hexCharCodes[a >>> 4 & 15], hexCharCodes[a & 15], hexCharCodes[b >>> 28], hexCharCodes[b >>> 24 & 15], hexCharCodes[b >>> 20 & 15], hexCharCodes[b >>> 16 & 15], hexCharCodes[b >>> 12 & 15], hexCharCodes[b >>> 8 & 15], hexCharCodes[b >>> 4 & 15], hexCharCodes[b & 15]);\n};\nconst randomHex32 = () => {\n const a = randomWord();\n const b = randomWord();\n const c = randomWord();\n const d = randomWord();\n return String.fromCharCode(hexCharCodes[a >>> 28], hexCharCodes[a >>> 24 & 15], hexCharCodes[a >>> 20 & 15], hexCharCodes[a >>> 16 & 15], hexCharCodes[a >>> 12 & 15], hexCharCodes[a >>> 8 & 15], hexCharCodes[a >>> 4 & 15], hexCharCodes[a & 15], hexCharCodes[b >>> 28], hexCharCodes[b >>> 24 & 15], hexCharCodes[b >>> 20 & 15], hexCharCodes[b >>> 16 & 15], hexCharCodes[b >>> 12 & 15], hexCharCodes[b >>> 8 & 15], hexCharCodes[b >>> 4 & 15], hexCharCodes[b & 15], hexCharCodes[c >>> 28], hexCharCodes[c >>> 24 & 15], hexCharCodes[c >>> 20 & 15], hexCharCodes[c >>> 16 & 15], hexCharCodes[c >>> 12 & 15], hexCharCodes[c >>> 8 & 15], hexCharCodes[c >>> 4 & 15], hexCharCodes[c & 15], hexCharCodes[d >>> 28], hexCharCodes[d >>> 24 & 15], hexCharCodes[d >>> 20 & 15], hexCharCodes[d >>> 16 & 15], hexCharCodes[d >>> 12 & 15], hexCharCodes[d >>> 8 & 15], hexCharCodes[d >>> 4 & 15], hexCharCodes[d & 15]);\n};\n/**\n * Decodes a hexadecimal string into bytes safely.\n *\n * **When to use**\n *\n * Use to decode hexadecimal text into bytes without throwing on invalid input.\n *\n * **Details**\n *\n * Returns `Result.succeed` with a `Uint8Array` when decoding succeeds, or\n * `Result.fail` with an `EncodingError` when the input has an odd length or\n * contains invalid hex characters.\n *\n * **Example** (Decoding hex bytes)\n *\n * ```ts import.meta.vitest\n * import { Encoding, Result } from \"effect\"\n *\n * Encoding.decodeHex(\"48656c6c6f\") // => Result.succeed(new Uint8Array([72, 101, 108, 108, 111]))\n * ```\n *\n * @category decoding\n * @since 2.0.0\n */\nexport const decodeHex = str => {\n const bytes = new TextEncoder().encode(str);\n if (bytes.length % 2 !== 0) {\n return Result.fail(new EncodingError({\n module: \"Hex\",\n kind: \"Decode\",\n input: str,\n message: `Length must be a multiple of 2, but is ${bytes.length}`\n }));\n }\n try {\n const length = bytes.length / 2;\n const result = new Uint8Array(length);\n for (let i = 0; i < length; i++) {\n const a = fromHexChar(bytes[i * 2]);\n const b = fromHexChar(bytes[i * 2 + 1]);\n result[i] = a << 4 | b;\n }\n return Result.succeed(result);\n } catch (e) {\n return Result.fail(new EncodingError({\n module: \"Hex\",\n kind: \"Decode\",\n input: str,\n message: e instanceof Error ? e.message : \"Invalid input\"\n }));\n }\n};\n/**\n * Decodes a hexadecimal string into a UTF-8 string safely.\n *\n * **When to use**\n *\n * Use to decode hexadecimal text into UTF-8 text without throwing on invalid\n * input.\n *\n * **Details**\n *\n * Returns `Result.succeed` with the decoded text when decoding succeeds, or\n * `Result.fail` with an `EncodingError` when the input is not valid hex.\n *\n * **Example** (Decoding hex strings)\n *\n * ```ts import.meta.vitest\n * import { Encoding, Result } from \"effect\"\n *\n * Encoding.decodeHexString(\"68656c6c6f\") // => Result.succeed(\"hello\")\n * ```\n *\n * @category decoding\n * @since 2.0.0\n */\nexport const decodeHexString = str => Result.map(decodeHex(str), _ => decoder.decode(_));\n// -------------------------------------------------------------------------------------\n// internals\n// -------------------------------------------------------------------------------------\nconst encoder = /*#__PURE__*/new TextEncoder();\nconst decoder = /*#__PURE__*/new TextDecoder();\nconst stripCrlf = str => str.replace(/[\\n\\r]/g, \"\");\n// Base64 internals\nconst base64EncodeUint8Array = bytes => {\n const length = bytes.length;\n let result = \"\";\n let i;\n for (i = 2; i < length; i += 3) {\n result += base64abc[bytes[i - 2] >> 2];\n result += base64abc[(bytes[i - 2] & 0x03) << 4 | bytes[i - 1] >> 4];\n result += base64abc[(bytes[i - 1] & 0x0f) << 2 | bytes[i] >> 6];\n result += base64abc[bytes[i] & 0x3f];\n }\n if (i === length + 1) {\n result += base64abc[bytes[i - 2] >> 2];\n result += base64abc[(bytes[i - 2] & 0x03) << 4];\n result += \"==\";\n }\n if (i === length) {\n result += base64abc[bytes[i - 2] >> 2];\n result += base64abc[(bytes[i - 2] & 0x03) << 4 | bytes[i - 1] >> 4];\n result += base64abc[(bytes[i - 1] & 0x0f) << 2];\n result += \"=\";\n }\n return result;\n};\nfunction getBase64Code(charCode) {\n if (charCode >= base64codes.length) {\n throw new TypeError(`Invalid character ${String.fromCharCode(charCode)}`);\n }\n const code = base64codes[charCode];\n if (code === 255) {\n throw new TypeError(`Invalid character ${String.fromCharCode(charCode)}`);\n }\n return code;\n}\nconst base64abc = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\", \"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\", \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"+\", \"/\"];\nconst base64codes = [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 255, 0, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255, 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51];\n// Base64Url internals\nconst base64UrlEncodeUint8Array = data => base64EncodeUint8Array(data).replace(/=/g, \"\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\");\n// Hex internals\nconst byteToHex = /*#__PURE__*/Array.from({\n length: 256\n}, (_, i) => i.toString(16).padStart(2, \"0\"));\nconst hexEncodeUint8Array = bytes => {\n let result = \"\";\n for (let i = 0; i < bytes.length; i++) {\n result += byteToHex[bytes[i]];\n }\n return result;\n};\nconst fromHexChar = byte => {\n if (48 <= byte && byte <= 57) {\n return byte - 48;\n }\n if (97 <= byte && byte <= 102) {\n return byte - 97 + 10;\n }\n if (65 <= byte && byte <= 70) {\n return byte - 65 + 10;\n }\n throw new TypeError(\"Invalid input\");\n};\n//# sourceMappingURL=Encoding.js.map","/**\n * Defines the low-level tracing model used by Effect.\n *\n * A span records the lifetime of an operation, including its name, parent,\n * attributes, links, annotations, sampling decision, kind, and completion\n * status. The module also defines the tracer service, parent-span context,\n * external span support, trace propagation settings, and the default in-memory\n * span implementation.\n *\n * @since 2.0.0\n */\nimport * as Context from \"./Context.js\";\nimport * as Encoding from \"./Encoding.js\";\nimport { constFalse } from \"./Function.js\";\nimport * as Option from \"./Option.js\";\nconst evaluate = \"~effect/Effect/evaluate\";\n/**\n * Defines the string key for the parent-span context service.\n *\n * **When to use**\n *\n * Use when you need the raw context key for parent span lookup in lower-level\n * tracing code.\n *\n * **Example** (Reading the parent span key)\n *\n * ```ts import.meta.vitest\n * import { Tracer } from \"effect\"\n *\n * // The key used to identify parent spans in the context\n * Tracer.ParentSpanKey // => \"effect/Tracer/ParentSpan\"\n * ```\n *\n * @category constants\n * @since 4.0.0\n */\nexport const ParentSpanKey = \"effect/Tracer/ParentSpan\";\n/**\n * Context service containing the `Span` or `ExternalSpan` to use as the parent\n * of newly-created child spans.\n *\n * **Example** (Accessing the parent span)\n *\n * ```ts import.meta.vitest\n * import { Effect, Tracer } from \"effect\"\n *\n * // Access the parent span from the context\n * const program = Effect.gen(function*() {\n * const parentSpan = yield* Effect.service(Tracer.ParentSpan)\n * return parentSpan.spanId\n * })\n *\n * const parent = Tracer.externalSpan({ spanId: \"span-123\", traceId: \"trace-456\" })\n * await Effect.runPromise(Effect.provideService(program, Tracer.ParentSpan, parent)) // => \"span-123\"\n * ```\n *\n * @category services\n * @since 2.0.0\n */\nexport class ParentSpan extends /*#__PURE__*/Context.Service()(ParentSpanKey, {\n fiberCached: true\n}) {}\n/**\n * Creates a `Tracer` value from a tracer implementation object.\n *\n * **When to use**\n *\n * Use to create a custom tracing backend value that Effect can use when\n * creating spans.\n *\n * **Details**\n *\n * `make` returns the supplied implementation object unchanged. The object must\n * satisfy the `Tracer` contract, including a `span` method that returns a\n * `Span`.\n *\n * @see {@link Span} for the span values returned by tracer implementations\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const make = options => options;\n/**\n * Creates an `ExternalSpan` from trace and span identifiers, defaulting\n * `sampled` to `true` and annotations to an empty context when they are not\n * provided.\n *\n * **Example** (Creating an external span)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, Tracer } from \"effect\"\n *\n * // Create an external span from another tracing system\n * const span = Tracer.externalSpan({\n * spanId: \"span-abc-123\",\n * traceId: \"trace-xyz-789\",\n * sampled: true\n * })\n *\n * // Use the external span as a parent\n * const program = Effect.succeed(\"Hello\").pipe(\n * Effect.withSpan(\"child-operation\", { parent: span })\n * )\n *\n * const spans: Array<Tracer.NativeSpan> = []\n * const tracer = Tracer.make({\n * span(options) {\n * const span = new Tracer.NativeSpan(options)\n * spans.push(span)\n * return span\n * }\n * })\n * const value = await Effect.runPromise(Effect.provideService(program, Tracer.Tracer, tracer))\n *\n * value // => \"Hello\"\n * spans.map((span) => Option.getOrUndefined(span.parent)?.spanId) // => [\"span-abc-123\"]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const externalSpan = options => ({\n _tag: \"ExternalSpan\",\n spanId: options.spanId,\n traceId: options.traceId,\n sampled: options.sampled ?? true,\n annotations: options.annotations ?? Context.empty()\n});\n/**\n * Context reference for disabling trace propagation.\n *\n * **When to use**\n *\n * Use to prevent spans in a scope from propagating tracing context.\n *\n * **Details**\n *\n * When enabled on fiber or span annotations, new spans are created as\n * non-propagating no-op spans and disabled spans are skipped when deriving a\n * parent span.\n *\n * **Example** (Disabling span propagation)\n *\n * ```ts import.meta.vitest\n * import { Effect, Tracer } from \"effect\"\n *\n * // Disable span propagation for a specific effect\n * const program = Tracer.DisablePropagation.pipe(\n * Effect.provideService(Tracer.DisablePropagation, true)\n * )\n *\n * await Effect.runPromise(program) // => true\n * ```\n *\n * @category services\n * @since 3.12.0\n */\nexport const DisablePropagation = /*#__PURE__*/Context.Reference(\"effect/Tracer/DisablePropagation\", {\n defaultValue: constFalse\n});\n/**\n * Context reference for controlling the current trace level for dynamic filtering.\n *\n * **When to use**\n *\n * Use to set the default trace level for spans in a scope when span options do\n * not provide `level`.\n *\n * **Details**\n *\n * The default value is `\"Info\"`. Span creation uses `options.level ??\n * CurrentTraceLevel` before applying `MinimumTraceLevel`.\n *\n * @see {@link MinimumTraceLevel} for the threshold that decides whether spans at that level are sampled\n *\n * @category services\n * @since 4.0.0\n */\nexport const CurrentTraceLevel = /*#__PURE__*/Context.Reference(\"effect/Tracer/CurrentTraceLevel\", {\n defaultValue: () => \"Info\"\n});\n/**\n * Context reference for setting the minimum trace level threshold. Spans and their\n * descendants below this level will have their sampling decision forced to\n * false, preventing them from being exported.\n *\n * **When to use**\n *\n * Use to set the trace-level threshold that controls whether spans are sampled\n * by default.\n *\n * **Details**\n *\n * The default value is `\"All\"`. Span creation compares the span level from\n * `options.level ?? CurrentTraceLevel` against this threshold.\n *\n * **Gotchas**\n *\n * Explicit `options.sampled` bypasses threshold computation.\n *\n * @see {@link CurrentTraceLevel} for the default span level used when options do not specify one\n *\n * @category services\n * @since 4.0.0\n */\nexport const MinimumTraceLevel = /*#__PURE__*/Context.Reference(\"effect/Tracer/MinimumTraceLevel\", {\n defaultValue: () => \"All\"\n});\n/**\n * Defines the string key for the active tracer context reference.\n *\n * **When to use**\n *\n * Use when you need the raw context key for active tracer lookup in lower-level\n * tracing code.\n *\n * @category constants\n * @since 4.0.0\n */\nexport const TracerKey = \"effect/Tracer\";\n/**\n * Context reference for the active tracer service. By default it uses the\n * native tracer, which creates `NativeSpan` instances.\n *\n * **Example** (Accessing the current tracer)\n *\n * ```ts import.meta.vitest\n * import { Effect, Tracer } from \"effect\"\n *\n * // Access the current tracer from the context\n * const program = Effect.gen(function*() {\n * const tracer = yield* Effect.service(Tracer.Tracer)\n * // Or use the built-in tracer effect\n * const tracerFromAccessor = yield* Effect.tracer\n * return tracer === tracerFromAccessor\n * })\n *\n * await Effect.runPromise(program) // => true\n * ```\n *\n * @category services\n * @since 2.0.0\n */\nexport const Tracer = /*#__PURE__*/Context.Reference(TracerKey, {\n fiberCached: true,\n defaultValue: () => nativeTracer\n});\n/**\n * The default `Tracer` implementation backing the `Tracer` reference. It\n * creates in-memory `NativeSpan` instances and does not export them anywhere.\n *\n * **Details**\n *\n * Runtime code can compare the active tracer against `nativeTracer` to detect\n * that no tracing backend is installed and skip work that only a backend could\n * observe, such as recording span attributes.\n *\n * @category references\n * @since 4.0.0\n */\nexport const nativeTracer = /*#__PURE__*/make({\n span: options => new NativeSpan(options)\n});\n/**\n * Default in-memory `Span` implementation used by the native tracer. It\n * generates span and trace identifiers, stores attributes, events, and links,\n * and records `Started` or `Ended` status.\n *\n * **Details**\n *\n * The constructor initializes the span with `Started` status. Trace and span\n * identifiers, the attribute map, and the event list are created lazily on\n * first access, so spans that are never inspected allocate as little as\n * possible. Attributes, events, links, and status are mutated through `Span`\n * methods.\n *\n * @see {@link Span} for the interface implemented by native spans\n *\n * @category models\n * @since 4.0.0\n */\nexport class NativeSpan {\n _tag = \"Span\";\n sampled;\n name;\n parent;\n annotations;\n links;\n startTime;\n kind;\n status;\n _traceId = undefined;\n _spanId = undefined;\n _attributes = undefined;\n _events = undefined;\n constructor(options) {\n this.name = options.name;\n this.parent = options.parent;\n this.annotations = options.annotations;\n this.links = options.links;\n this.startTime = options.startTime;\n this.kind = options.kind;\n this.sampled = options.sampled;\n this.status = {\n _tag: \"Started\",\n startTime: options.startTime\n };\n }\n get traceId() {\n return this._traceId ??= Option.getOrUndefined(this.parent)?.traceId ?? Encoding.randomHex(32);\n }\n get spanId() {\n return this._spanId ??= Encoding.randomHex(16);\n }\n get attributes() {\n return this._attributes ??= new Map();\n }\n get events() {\n return this._events ??= [];\n }\n end(endTime, exit) {\n this.status = {\n _tag: \"Ended\",\n endTime,\n exit,\n startTime: this.status.startTime\n };\n }\n attribute(key, value) {\n this.attributes.set(key, value);\n }\n event(name, startTime, attributes) {\n this.events.push([name, startTime, attributes ?? {}]);\n }\n addLinks(links) {\n // oxlint-disable-next-line no-restricted-syntax\n this.links.push(...links);\n }\n}\n//# sourceMappingURL=Tracer.js.map","/** @internal */\nexport const FiberRuntimeMetricsKey = \"effect/Metric/FiberRuntimeMetrics\";\n//# sourceMappingURL=metric.js.map","import * as Context from \"../Context.js\";\nimport { constTrue, constUndefined } from \"../Function.js\";\n/** @internal */\nexport const CurrentErrorReporters = /*#__PURE__*/Context.Reference(\"effect/ErrorReporter/CurrentErrorReporters\", {\n defaultValue: () => new Set()\n});\n/** @internal */\nexport const CurrentStackFrame = /*#__PURE__*/Context.Reference(\"effect/References/CurrentStackFrame\", {\n fiberCached: true,\n defaultValue: constUndefined\n});\n/** @internal */\nexport const TracerEnabled = /*#__PURE__*/Context.Reference(\"effect/References/TracerEnabled\", {\n fiberCached: true,\n defaultValue: constTrue\n});\n/** @internal */\nexport const TracerTimingEnabled = /*#__PURE__*/Context.Reference(\"effect/References/TracerTimingEnabled\", {\n defaultValue: constTrue\n});\n/** @internal */\nexport const TracerSpanAnnotations = /*#__PURE__*/Context.Reference(\"effect/References/TracerSpanAnnotations\", {\n defaultValue: () => ({})\n});\n/** @internal */\nexport const TracerSpanLinks = /*#__PURE__*/Context.Reference(\"effect/References/TracerSpanLinks\", {\n defaultValue: () => []\n});\n/** @internal */\nexport const CurrentLogAnnotations = /*#__PURE__*/Context.Reference(\"effect/References/CurrentLogAnnotations\", {\n defaultValue: () => ({})\n});\n/** @internal */\nexport const CurrentLogLevel = /*#__PURE__*/Context.Reference(\"effect/References/CurrentLogLevel\", {\n fiberCached: true,\n defaultValue: () => \"Info\"\n});\n/** @internal */\nexport const MinimumLogLevel = /*#__PURE__*/Context.Reference(\"effect/References/MinimumLogLevel\", {\n fiberCached: true,\n defaultValue: () => \"Info\"\n});\n/** @internal */\nexport const UnhandledLogLevel = /*#__PURE__*/Context.Reference(\"effect/References/UnhandledLogLevel\", {\n defaultValue: () => \"Error\"\n});\n/** @internal */\nexport const CurrentLogSpans = /*#__PURE__*/Context.Reference(\"effect/References/CurrentLogSpans\", {\n defaultValue: () => []\n});\n//# sourceMappingURL=references.js.map","import { getStackTraceLimit, setStackTraceLimit } from \"./stackTraceLimit.js\";\n/** @internal */\nexport const addSpanStackTrace = options => {\n if (options?.captureStackTrace === false) {\n return options;\n } else if (options?.captureStackTrace !== undefined && typeof options.captureStackTrace !== \"boolean\") {\n return options;\n }\n const limit = getStackTraceLimit();\n if (limit === 0 && options?.captureStackTrace !== true) {\n return {\n ...options,\n captureStackTrace: false\n };\n }\n setStackTraceLimit(3);\n const traceError = new Error();\n setStackTraceLimit(limit);\n return {\n ...options,\n captureStackTrace: spanCleaner(() => traceError.stack)\n };\n};\n/** @internal */\nexport const makeStackCleaner = line => stack => {\n let cache;\n return () => {\n if (cache !== undefined) return cache;\n const trace = stack();\n if (!trace) return undefined;\n const lines = trace.split(\"\\n\");\n if (lines[line] !== undefined) {\n cache = lines[line].trim();\n return cache;\n }\n };\n};\nconst spanCleaner = /*#__PURE__*/makeStackCleaner(3);\n//# sourceMappingURL=tracer.js.map","import * as Arr from \"../Array.js\";\nimport * as Context from \"../Context.js\";\nimport * as Duration from \"../Duration.js\";\nimport * as Equal from \"../Equal.js\";\nimport * as Filter from \"../Filter.js\";\nimport { formatJson } from \"../Formatter.js\";\nimport { constant, constFalse, constTrue, constUndefined, constVoid, dual, identity } from \"../Function.js\";\nimport * as Hash from \"../Hash.js\";\nimport { toJson, toStringUnknown } from \"../Inspectable.js\";\nimport * as Iterable from \"../Iterable.js\";\nimport * as Option from \"../Option.js\";\nimport * as Order from \"../Order.js\";\nimport { pipeArguments } from \"../Pipeable.js\";\nimport { hasProperty, isIterable, isString, isTagged } from \"../Predicate.js\";\nimport { currentFiberTypeId, redact } from \"../Redactable.js\";\nimport * as Result from \"../Result.js\";\nimport * as Scheduler from \"../Scheduler.js\";\nimport * as Tracer from \"../Tracer.js\";\nimport { internalCall } from \"../Utils.js\";\nimport { args, causeAnnotate, causeDie, causeEmpty, causeFromReasons, CauseImpl, constEmptyAnnotations, contA, contAll, contE, evaluate, exitDie, exitFail, exitFailCause, exitSucceed, ExitTypeId, Fail, InterruptorStackTrace, isCause, isDieReason, isEffect, isFailReason, isInterruptReason, isNoSuchElementError, makePrimitive, makePrimitiveProto, NoSuchElementError, ReasonBase, StackTraceKey as CauseStackTrace, TaggedError, withFiber, Yield } from \"./core.js\";\nimport * as doNotation from \"./doNotation.js\";\nimport * as InternalMetric from \"./metric.js\";\nimport * as InternalRecord from \"./record.js\";\nimport { CurrentErrorReporters, CurrentLogAnnotations, CurrentLogLevel, CurrentLogSpans, CurrentStackFrame, MinimumLogLevel, TracerEnabled, TracerSpanAnnotations, TracerSpanLinks, TracerTimingEnabled } from \"./references.js\";\nimport { getStackTraceLimit, setStackTraceLimit } from \"./stackTraceLimit.js\";\nimport { addSpanStackTrace, makeStackCleaner } from \"./tracer.js\";\n// ----------------------------------------------------------------------------\n// Cause\n// ----------------------------------------------------------------------------\n/** @internal */\nexport class Interrupt extends ReasonBase {\n constructor(fiberId, annotations = constEmptyAnnotations) {\n super(\"Interrupt\", annotations, \"Interrupted\");\n this.fiberId = fiberId;\n }\n toString() {\n return `Interrupt(${this.fiberId})`;\n }\n toJSON() {\n return {\n _tag: \"Interrupt\",\n fiberId: this.fiberId\n };\n }\n [Equal.symbol](that) {\n return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations;\n }\n [Hash.symbol]() {\n return Hash.combine(Hash.string(`${this._tag}:${this.fiberId}`))(Hash.random(this.annotations));\n }\n}\n/** @internal */\nexport const makeInterruptReason = fiberId => new Interrupt(fiberId);\n/** @internal */\nexport const causeInterrupt = fiberId => new CauseImpl([new Interrupt(fiberId)]);\n/** @internal */\nexport const hasFails = self => self.reasons.some(isFailReason);\n/** @internal */\nexport const findFail = self => {\n const reason = self.reasons.find(isFailReason);\n return reason ? Result.succeed(reason) : Result.fail(self);\n};\n/** @internal */\nexport const findError = self => {\n for (let i = 0; i < self.reasons.length; i++) {\n const reason = self.reasons[i];\n if (reason._tag === \"Fail\") {\n return Result.succeed(reason.error);\n }\n }\n return Result.fail(self);\n};\n/** @internal */\nexport const findErrorOption = /*#__PURE__*/Filter.toOption(findError);\n/** @internal */\nexport const hasDies = self => self.reasons.some(isDieReason);\n/** @internal */\nexport const findDie = self => {\n const reason = self.reasons.find(isDieReason);\n return reason ? Result.succeed(reason) : Result.fail(self);\n};\n/** @internal */\nexport const findDefect = self => {\n const reason = self.reasons.find(isDieReason);\n return reason ? Result.succeed(reason.defect) : Result.fail(self);\n};\n/** @internal */\nexport const hasInterrupts = self => self.reasons.some(isInterruptReason);\n/** @internal */\nexport const findInterrupt = self => {\n const reason = self.reasons.find(isInterruptReason);\n return reason ? Result.succeed(reason) : Result.fail(self);\n};\n/** @internal */\nexport const causeFilterInterruptors = self => {\n let interruptors;\n for (let i = 0; i < self.reasons.length; i++) {\n const f = self.reasons[i];\n if (f._tag !== \"Interrupt\") continue;\n interruptors ??= new Set();\n if (f.fiberId !== undefined) {\n interruptors.add(f.fiberId);\n }\n }\n return interruptors ? Result.succeed(interruptors) : Result.fail(self);\n};\n/** @internal */\nexport const causeInterruptors = self => {\n const result = causeFilterInterruptors(self);\n return Result.isFailure(result) ? emptySet : result.success;\n};\nconst emptySet = /*#__PURE__*/new Set();\n/** @internal */\nexport const hasInterruptsOnly = self => self.reasons.length > 0 && self.reasons.every(isInterruptReason);\n/** @internal */\nexport const reasonAnnotations = self => Context.makeUnsafe(self.annotations);\n/** @internal */\nexport const causeAnnotations = self => {\n const map = new Map();\n for (const f of self.reasons) {\n if (f.annotations.size > 0) {\n for (const [key, value] of f.annotations) {\n map.set(key, value);\n }\n }\n }\n return Context.makeUnsafe(map);\n};\nconst dedupeReasons = (self, that) => {\n // Keep deduplication local so causeCombine does not retain Array.ts in the core bundle.\n // Snapshot both arrays before invoking user-defined hash or equality methods.\n const buckets = new Map();\n const out = [];\n for (const reason of self.concat(that)) {\n const hash = Hash.hash(reason);\n const bucket = buckets.get(hash);\n if (bucket === undefined) {\n buckets.set(hash, [reason]);\n } else if (bucket.some(previous => Equal.equals(previous, reason))) {\n continue;\n } else {\n bucket.push(reason);\n }\n out.push(reason);\n }\n return out;\n};\n/** @internal */\nexport const causeCombine = /*#__PURE__*/dual(2, (self, that) => {\n if (self.reasons.length === 0) {\n return that;\n } else if (that.reasons.length === 0) {\n return self;\n }\n const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons));\n return Equal.equals(self, newCause) ? self : newCause;\n});\n/** @internal */\nexport const causeMap = /*#__PURE__*/dual(2, (self, f) => {\n let hasFail = false;\n const failures = self.reasons.map(failure => {\n if (isFailReason(failure)) {\n hasFail = true;\n return new Fail(f(failure.error), failure.annotations);\n }\n return failure;\n });\n return hasFail ? causeFromReasons(failures) : self;\n});\n/** @internal */\nexport const causePartition = self => {\n const obj = {\n Fail: [],\n Die: [],\n Interrupt: []\n };\n for (let i = 0; i < self.reasons.length; i++) {\n obj[self.reasons[i]._tag].push(self.reasons[i]);\n }\n return obj;\n};\n/** @internal */\nexport const causeSquash = self => {\n const partitioned = causePartition(self);\n if (partitioned.Fail.length > 0) {\n return partitioned.Fail[0].error;\n } else if (partitioned.Die.length > 0) {\n return partitioned.Die[0].defect;\n } else if (partitioned.Interrupt.length > 0) {\n return new globalThis.Error(\"All fibers interrupted without error\");\n }\n return new globalThis.Error(\"Empty cause\");\n};\n/** @internal */\nexport const causePrettyErrors = (self, options) => {\n const errors = [];\n const interrupts = [];\n if (self.reasons.length === 0) return errors;\n const prevStackLimit = getStackTraceLimit();\n if (prevStackLimit !== 0) setStackTraceLimit(1);\n for (const failure of self.reasons) {\n if (failure._tag === \"Interrupt\") {\n interrupts.push(failure);\n continue;\n }\n errors.push(causePrettyError(failure._tag === \"Die\" ? failure.defect : failure.error, failure.annotations, options));\n }\n if (errors.length === 0) {\n const cause = new Error(\"The fiber was interrupted by:\");\n cause.name = \"InterruptCause\";\n cause.stack = interruptCauseStack(cause, interrupts);\n const error = new globalThis.Error(\"All fibers interrupted without error\", {\n cause\n });\n error.name = \"InterruptError\";\n error.stack = `${error.name}: ${error.message}`;\n errors.push(causePrettyError(error, interrupts[0].annotations, options));\n }\n if (prevStackLimit !== 0) setStackTraceLimit(prevStackLimit);\n return errors;\n};\n/** @internal */\nexport const causePrettyError = (original, annotations, options) => {\n const kind = typeof original;\n let error;\n if (original && kind === \"object\") {\n error = new globalThis.Error(causePrettyMessage(original), {\n cause: original.cause ? causePrettyError(original.cause) : undefined\n });\n if (typeof original.name === \"string\") {\n error.name = original.name;\n }\n if (typeof original.stack === \"string\") {\n error.stack = cleanErrorStack(original.stack, error, annotations);\n } else {\n const stack = `${error.name}: ${error.message}`;\n error.stack = annotations ? addStackAnnotations(stack, annotations) : stack;\n }\n if (options?.includeCauseInStack) {\n error.stack = renderPrettyError(error);\n }\n for (const key of Object.keys(original)) {\n if (!(key in error)) {\n ;\n error[key] = original[key];\n }\n }\n } else {\n error = new globalThis.Error(!original ? `Unknown error: ${original}` : kind === \"string\" ? original : formatJson(original));\n }\n return error;\n};\nconst causePrettyMessage = u => {\n if (typeof u.message === \"string\") {\n return u.message;\n } else if (typeof u.toString === \"function\" && u.toString !== Object.prototype.toString && u.toString !== Array.prototype.toString) {\n try {\n return u.toString();\n } catch {\n // something's off, rollback to json\n }\n }\n return formatJson(u);\n};\nconst locationRegExp = /\\((.*)\\)/g;\nconst cleanErrorStack = (stack, error, annotations) => {\n const message = `${error.name}: ${error.message}`;\n const lines = (stack.startsWith(message) ? stack.slice(message.length) : stack).split(\"\\n\");\n const out = [message];\n for (let i = 1; i < lines.length; i++) {\n if (/(?:Generator\\.next|~effect\\/Effect)/.test(lines[i])) {\n break;\n }\n out.push(lines[i]);\n }\n return annotations ? addStackAnnotations(out.join(\"\\n\"), annotations) : out.join(\"\\n\");\n};\nconst addStackAnnotations = (stack, annotations) => {\n const frame = annotations?.get(CauseStackTrace.key);\n if (frame) {\n stack = `${stack}\\n${currentStackTrace(frame)}`;\n }\n return stack;\n};\nconst interruptCauseStack = (error, interrupts) => {\n const out = [`${error.name}: ${error.message}`];\n for (const current of interrupts) {\n const fiberId = current.fiberId !== undefined ? `#${current.fiberId}` : \"unknown\";\n const frame = current.annotations.get(InterruptorStackTrace.key);\n out.push(` at fiber (${fiberId})`);\n if (frame) out.push(currentStackTrace(frame));\n }\n return out.join(\"\\n\");\n};\nconst currentStackTrace = frame => {\n const out = [];\n let current = frame;\n let i = 0;\n while (current && i < 10) {\n const stack = current.stack();\n if (stack) {\n const locationMatchAll = stack.matchAll(locationRegExp);\n let match = false;\n for (const [, location] of locationMatchAll) {\n match = true;\n out.push(` at ${current.name} (${location})`);\n }\n if (!match) {\n out.push(` at ${current.name} (${stack.replace(/^at /, \"\")})`);\n }\n } else {\n out.push(` at ${current.name}`);\n }\n current = current.parent;\n i++;\n }\n return out.join(\"\\n\");\n};\n/** @internal */\nexport const causePretty = cause => causePrettyErrors(cause).map(renderPrettyError).join(\"\\n\");\nconst renderPrettyError = e => e.cause ? `${e.stack} {\\n${renderErrorCause(e.cause, \" \")}\\n}` : e.stack;\nconst renderErrorCause = (cause, prefix) => {\n const lines = cause.stack.split(\"\\n\");\n let stack = `${prefix}[cause]: ${lines[0]}`;\n for (let i = 1, len = lines.length; i < len; i++) {\n stack += `\\n${prefix}${lines[i]}`;\n }\n if (cause.cause) {\n stack += ` {\\n${renderErrorCause(cause.cause, `${prefix} `)}\\n${prefix}}`;\n }\n return stack;\n};\n// ----------------------------------------------------------------------------\n// Fiber\n// ----------------------------------------------------------------------------\n/** @internal */\nexport const FiberTypeId = \"~effect/Fiber\";\nconst fiberVariance = {\n _A: identity,\n _E: identity\n};\nconst fiberIdStore = {\n id: 0\n};\n/** @internal */\nexport const getCurrentFiber = () => globalThis[currentFiberTypeId];\n/** @internal */\nexport class FiberImpl {\n constructor(context, interruptible = true) {\n this[FiberTypeId] = fiberVariance;\n this.setContext(context);\n this.id = ++fiberIdStore.id;\n this.currentOpCount = 0;\n this.interruptible = interruptible;\n this._stack = [];\n this._observers = undefined;\n this._exit = undefined;\n this._children = undefined;\n this._interruptedCause = undefined;\n this._yielded = undefined;\n this._running = false;\n this._deferredInterrupt = false;\n this._parent = undefined;\n this.cache.runtimeMetrics?.recordFiberStart(this.context);\n }\n [FiberTypeId];\n id;\n interruptible;\n currentOpCount;\n _stack;\n _observers;\n _exit;\n _children;\n _interruptedCause;\n _yielded;\n _running;\n _deferredInterrupt;\n _parent;\n // set in setContext\n context;\n cache;\n _dispatcher = undefined;\n get currentDispatcher() {\n return this._dispatcher ??= this.cache.scheduler.makeDispatcher();\n }\n getRef(ref) {\n return Context.get(this.context, ref);\n }\n addObserver(cb) {\n if (this._exit) {\n cb(this._exit);\n return constVoid;\n }\n if (this._observers === undefined) {\n this._observers = [cb];\n } else {\n this._observers.push(cb);\n }\n return () => {\n if (this._exit || this._observers === undefined) return;\n const index = this._observers.indexOf(cb);\n if (index >= 0) {\n this._observers.splice(index, 1);\n }\n };\n }\n interruptUnsafe(fiberId, annotations) {\n if (this._exit) {\n return;\n }\n let cause = causeInterrupt(fiberId);\n if (this.cache.stackFrame) {\n cause = causeAnnotate(cause, Context.make(CauseStackTrace, this.cache.stackFrame));\n }\n if (annotations) {\n cause = causeAnnotate(cause, annotations);\n }\n this._interruptedCause = this._interruptedCause ? causeCombine(this._interruptedCause, cause) : cause;\n if (this.interruptible) {\n if (this._running) {\n this._deferredInterrupt = true;\n } else {\n this.evaluate(failCause(this._interruptedCause));\n }\n }\n }\n pollUnsafe() {\n return this._exit;\n }\n evaluate(effect) {\n if (this._exit) {\n return;\n } else if (this._yielded !== undefined) {\n const yielded = this._yielded;\n this._yielded = undefined;\n yielded();\n }\n const exit = this.runLoop(effect);\n if (exit === Yield) {\n return;\n }\n // the interruptChildren middleware is added in Effect.forkChild, so it can be\n // tree-shaken if not used\n const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this);\n if (interruptChildren !== undefined) {\n return this.evaluate(flatMap(interruptChildren, () => exit));\n }\n this._exit = exit;\n this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit);\n if (this._parent) {\n this._parent._children?.delete(this);\n this._parent = undefined;\n }\n if (this._observers !== undefined) {\n const observers = this._observers;\n this._observers = undefined;\n for (let i = 0; i < observers.length; i++) {\n observers[i](exit);\n }\n }\n this._stack.length = 0;\n this._children = undefined;\n this.context = Context.empty();\n }\n runLoop(effect) {\n const prevFiber = globalThis[currentFiberTypeId];\n globalThis[currentFiberTypeId] = this;\n const prevRunning = this._running;\n this._running = true;\n let yielding = false;\n let current = effect;\n this.currentOpCount = 0;\n try {\n while (true) {\n if (this._deferredInterrupt) {\n this._deferredInterrupt = false;\n current = failCause(this._interruptedCause);\n }\n this.currentOpCount++;\n // Refresh the cache because a primitive can replace the fiber context.\n const cache = this.cache;\n if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) {\n yielding = true;\n const prev = current;\n current = flatMap(yieldNow, () => prev);\n }\n current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this);\n if (current === Yield) {\n const yielded = this._yielded;\n if (ExitTypeId in yielded) {\n this._deferredInterrupt = false;\n this._yielded = undefined;\n return yielded;\n } else if (this._deferredInterrupt) {\n this._yielded = undefined;\n yielded();\n continue;\n }\n return Yield;\n }\n }\n } catch (error) {\n if (!hasProperty(current, evaluate)) {\n return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`);\n }\n return this.runLoop(exitDie(error));\n } finally {\n this._running = prevRunning;\n globalThis[currentFiberTypeId] = prevFiber;\n }\n }\n getCont(symbol) {\n if (this._deferredInterrupt) {\n this._deferredInterrupt = false;\n return deferredInterruptCont;\n }\n while (true) {\n const op = this._stack.pop();\n if (!op) return undefined;\n const all = op[contAll];\n if (all !== undefined) {\n const cont = all.call(op, this);\n if (cont) {\n ;\n cont[symbol] = cont;\n return cont;\n }\n }\n if (op[symbol]) return op;\n }\n }\n yieldWith(value) {\n this._yielded = value;\n return Yield;\n }\n children() {\n return this._children ??= new Set();\n }\n pipe() {\n return pipeArguments(this, arguments);\n }\n setContext(context) {\n const previous = this.context;\n this.context = context;\n // Every key cached below opts in to Context caching, so contexts related\n // only by non-caching adds cannot have changed any of them\n if (previous !== undefined && Context.hasSameCache(previous, context)) return;\n // Contexts sharing a cacheRoot resolve every cached key identically, so\n // the derived cache object is computed once per root and shared by all\n // fibers running with that root (forked fibers reuse the parent's).\n const root = context.cacheRoot;\n const cache = root._fiberCache ??= makeFiberContextCache(context);\n if (this.cache !== undefined && this.cache.scheduler !== cache.scheduler) {\n this._dispatcher = undefined;\n }\n this.cache = cache;\n }\n get currentSpanLocal() {\n const span = this.cache.span;\n return span?._tag === \"Span\" ? span : undefined;\n }\n}\nconst makeFiberContextCache = context => {\n // The string-keyed lookups keep the Tracer key values (and the native\n // tracer behind Tracer.Tracer's default) out of every bundle\n const currentTracer = Context.getOrUndefinedUnsafe(context, Tracer.TracerKey);\n return {\n scheduler: Context.get(context, Scheduler.Scheduler),\n tracer: currentTracer,\n tracerContext: currentTracer ? currentTracer[\"context\"] : undefined,\n tracerEnabled: Context.get(context, TracerEnabled),\n span: Context.getOrUndefinedUnsafe(context, Tracer.ParentSpanKey),\n logLevel: Context.get(context, CurrentLogLevel),\n minimumLogLevel: Context.get(context, MinimumLogLevel),\n stackFrame: Context.get(context, CurrentStackFrame),\n runtimeMetrics: Context.getOrUndefinedUnsafe(context, InternalMetric.FiberRuntimeMetricsKey),\n maxOpsBeforeYield: Context.get(context, Scheduler.MaxOpsBeforeYield),\n preventYield: Context.get(context, Scheduler.PreventSchedulerYield)\n };\n};\nconst deferredInterruptCont = {\n [contA](_value, fiber) {\n return failCause(fiber._interruptedCause);\n },\n [contE](_cause, fiber) {\n return failCause(fiber._interruptedCause);\n }\n};\nconst fiberMiddleware = {\n interruptChildren: undefined\n};\nconst fiberStackAnnotations = fiber => {\n if (!fiber.cache.stackFrame) return undefined;\n const annotations = new Map();\n annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame);\n return Context.makeUnsafe(annotations);\n};\nconst fiberInterruptChildren = fiber => {\n if (fiber._children === undefined || fiber._children.size === 0) {\n return undefined;\n }\n return fiberInterruptAll(fiber._children);\n};\n/** @internal */\nexport const fiberAwait = self => {\n const impl = self;\n if (impl._exit) return succeed(impl._exit);\n return callback(resume => {\n if (impl._exit) return resume(succeed(impl._exit));\n return sync(self.addObserver(exit => resume(succeed(exit))));\n });\n};\n/** @internal */\nexport const fiberAwaitAll = self => callback(resume => {\n const iter = self[Symbol.iterator]();\n const exits = [];\n let cancel = undefined;\n function loop() {\n let result = iter.next();\n while (!result.done) {\n if (result.value._exit) {\n exits.push(result.value._exit);\n result = iter.next();\n continue;\n }\n cancel = result.value.addObserver(exit => {\n exits.push(exit);\n loop();\n });\n return;\n }\n resume(succeed(exits));\n }\n loop();\n return sync(() => cancel?.());\n});\n/** @internal */\nexport const fiberJoin = self => {\n const impl = self;\n if (impl._exit) return impl._exit;\n return callback(resume => {\n if (impl._exit) return resume(impl._exit);\n return sync(self.addObserver(resume));\n });\n};\n/** @internal */\nexport const fiberJoinAll = self => callback(resume => {\n const fibers = Array.from(self);\n if (fibers.length === 0) return resume(succeed(Arr.empty()));\n const out = new Array(fibers.length);\n const cancels = Arr.empty();\n let done = 0;\n let failed = false;\n for (let i = 0; i < fibers.length; i++) {\n if (failed) break;\n cancels.push(fibers[i].addObserver(exit => {\n done++;\n if (exit._tag === \"Failure\") {\n failed = true;\n cancels.forEach(cancel => cancel());\n return resume(exit);\n }\n out[i] = exit.value;\n if (done === fibers.length) {\n resume(succeed(out));\n }\n }));\n }\n return sync(() => {\n failed = true;\n cancels.forEach(cancel => cancel());\n });\n});\n/** @internal */\nexport const fiberInterrupt = self => withFiber(fiber => fiberInterruptAs(self, fiber.id));\n/** @internal */\nexport const fiberInterruptAs = /*#__PURE__*/dual(args => hasProperty(args[0], FiberTypeId), (self, fiberId, annotations) => withFiber(parent => {\n let ann = fiberStackAnnotations(parent);\n ann = ann && annotations ? Context.merge(ann, annotations) : ann ?? annotations;\n self.interruptUnsafe(fiberId, ann);\n return asVoid(fiberAwait(self));\n}));\n/** @internal */\nexport const fiberInterruptAll = fibers => withFiber(parent => {\n const annotations = fiberStackAnnotations(parent);\n let fiberArr = Arr.empty();\n for (const fiber of fibers) {\n fiber.interruptUnsafe(parent.id, annotations);\n fiberArr.push(fiber);\n }\n return asVoid(fiberAwaitAll(fiberArr));\n});\n/** @internal */\nexport const fiberInterruptAllAs = /*#__PURE__*/dual(2, (fibers, fiberId) => withFiber(parent => {\n const annotations = fiberStackAnnotations(parent);\n const fiberArr = Arr.empty();\n for (const fiber of fibers) {\n fiber.interruptUnsafe(fiberId, annotations);\n fiberArr.push(fiber);\n }\n return asVoid(fiberAwaitAll(fiberArr));\n}));\n/** @internal */\nexport const succeed = exitSucceed;\n/** @internal */\nexport const failCause = exitFailCause;\n/** @internal */\nexport const fail = exitFail;\n/** @internal */\nexport const sync = /*#__PURE__*/makePrimitive({\n op: \"Sync\",\n [evaluate](fiber) {\n const value = this[args]();\n const cont = fiber.getCont(contA);\n return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value));\n }\n});\n/** @internal */\nexport const suspend = /*#__PURE__*/makePrimitive({\n op: \"Suspend\",\n [evaluate](_fiber) {\n return this[args]();\n }\n});\n/** @internal */\nexport const fromOption = /*#__PURE__*/dual(args => args.length >= 2 || Option.isOption(args[0]), (option, onNone) => Option.isNone(option) ? fail(onNone ? onNone() : new NoSuchElementError(\"Effect.fromOption: Option.none\")) : succeed(option.value));\n/** @internal */\nexport const fromResult = /*#__PURE__*/Result.match({\n onFailure: fail,\n onSuccess: succeed\n});\n/** @internal */\nexport const fromNullishOr = value => value == null ? fail(new NoSuchElementError()) : succeed(value);\n/** @internal */\nexport const yieldNowWith = /*#__PURE__*/makePrimitive({\n op: \"Yield\",\n [evaluate](fiber) {\n let resumed = false;\n fiber.currentDispatcher.scheduleTask(() => {\n if (resumed) return;\n fiber.evaluate(exitVoid);\n }, this[args] ?? 0);\n return fiber.yieldWith(() => {\n resumed = true;\n });\n }\n});\n/** @internal */\nexport const yieldNow = /*#__PURE__*/yieldNowWith(0);\n/** @internal */\nexport const succeedSome = a => succeed(Option.some(a));\n/** @internal */\nexport const succeedNone = /*#__PURE__*/succeed(/*#__PURE__*/Option.none());\n/** @internal */\nexport const transposeOption = self => Option.isNone(self) ? succeedNone : map(self.value, Option.some);\n/** @internal */\nexport const failCauseSync = evaluate => suspend(() => failCause(internalCall(evaluate)));\n/** @internal */\nexport const die = defect => exitDie(defect);\n/** @internal */\nexport const failSync = error => suspend(() => fail(internalCall(error)));\n/** @internal */\nconst void_ = /*#__PURE__*/succeed(void 0);\n/** @internal */\nexport { void_ as void };\n/** @internal */\nconst try_ = options => {\n const evaluate = typeof options === \"function\" ? options : options.try;\n const catcher = typeof options === \"function\" ? cause => new UnknownError(cause, \"An error occurred in Effect.try\") : options.catch;\n return suspend(() => {\n try {\n return succeed(internalCall(evaluate));\n } catch (err) {\n return fail(internalCall(() => catcher(err)));\n }\n });\n};\n/** @internal */\nexport { try_ as try };\n/** @internal */\nexport const promise = evaluate => callbackOptions(function (resume, signal) {\n internalCall(() => evaluate(signal)).then(a => resume(succeed(a)), e => resume(die(e)));\n}, evaluate.length !== 0);\n/** @internal */\nexport const tryPromise = options => {\n const f = typeof options === \"function\" ? options : options.try;\n const catcher = typeof options === \"function\" ? cause => new UnknownError(cause, \"An error occurred in Effect.tryPromise\") : options.catch;\n return callbackOptions(function (resume, signal) {\n const failWithCatch = cause => {\n try {\n resume(fail(internalCall(() => catcher(cause))));\n } catch (err) {\n resume(die(err));\n }\n };\n try {\n internalCall(() => f(signal)).then(a => resume(succeed(a)), failWithCatch);\n } catch (err) {\n failWithCatch(err);\n }\n }, f.length !== 0);\n};\n/** @internal */\nexport const withFiberId = f => withFiber(fiber => f(fiber.id));\n/** @internal */\nexport const fiber = /*#__PURE__*/withFiber(succeed);\n/** @internal */\nexport const fiberId = /*#__PURE__*/withFiberId(succeed);\nconst callbackOptions = /*#__PURE__*/function () {\n const Proto = /*#__PURE__*/makePrimitiveProto({\n op: \"Async\",\n [evaluate](fiber) {\n const register = internalCall(() => this.register.bind(fiber.cache.scheduler));\n let resumed = false;\n let yielded = false;\n const controller = this.withSignal ? new AbortController() : undefined;\n const onCancel = register(effect => {\n if (resumed) return;\n resumed = true;\n if (yielded) {\n fiber.evaluate(effect);\n } else {\n yielded = effect;\n }\n }, controller?.signal);\n if (yielded !== false) return yielded;\n yielded = true;\n fiber._yielded = () => {\n resumed = true;\n };\n if (controller === undefined && onCancel === undefined) {\n return Yield;\n }\n fiber._stack.push(asyncFinalizer(() => {\n resumed = true;\n controller?.abort();\n return onCancel ?? exitVoid;\n }));\n return Yield;\n }\n });\n const AsyncImpl = function (register, withSignal) {\n this.register = register;\n this.withSignal = withSignal;\n };\n AsyncImpl.prototype = Proto;\n return function (register, withSignal) {\n return new AsyncImpl(register, withSignal);\n };\n}();\nconst asyncFinalizer = /*#__PURE__*/makePrimitive({\n op: \"AsyncFinalizer\",\n [contAll](fiber) {\n if (fiber.interruptible) {\n fiber.interruptible = false;\n fiber._stack.push(setInterruptibleTrue);\n }\n },\n [contE](cause, _fiber) {\n return hasInterrupts(cause) ? flatMap(this[args](), () => failCause(cause)) : failCause(cause);\n }\n});\n/** @internal */\nexport const callback = register => callbackOptions(register, register.length >= 2);\n/** @internal */\nexport const never = /*#__PURE__*/callback(constVoid);\n/** @internal */\nexport const gen = (...args) => {\n if (args.length === 1) {\n const body = args[0];\n return suspend(() => fromIteratorUnsafe(body()));\n }\n const [options, body] = args;\n return suspend(() => fromIteratorUnsafe(body.call(options.self)));\n};\n/** @internal */\nexport const fnUntraced = (body, ...pipeables) => {\n const fn = pipeables.length === 0 ? function () {\n return suspend(() => fromIteratorUnsafe(body.apply(this, arguments)));\n } : function () {\n let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments)));\n for (let i = 0; i < pipeables.length; i++) {\n effect = pipeables[i](effect, ...arguments);\n }\n return effect;\n };\n return defineFunctionLength(body.length, fn);\n};\nconst defineFunctionLength = (length, fn) => Object.defineProperty(fn, \"length\", {\n value: length,\n configurable: true\n});\nconst fnStackCleaner = /*#__PURE__*/makeStackCleaner(2);\n/** @internal */\nexport const fn = function () {\n const nameFirst = typeof arguments[0] === \"string\";\n const name = nameFirst ? arguments[0] : \"Effect.fn\";\n const spanOptions = nameFirst ? arguments[1] : undefined;\n const prevLimit = getStackTraceLimit();\n let defError;\n if (prevLimit !== 0) {\n setStackTraceLimit(2);\n defError = new globalThis.Error();\n setStackTraceLimit(prevLimit);\n }\n if (nameFirst) {\n return (body, ...pipeables) => makeFn(name, body, defError, pipeables, nameFirst, spanOptions);\n }\n return makeFn(name, arguments[0], defError, Array.prototype.slice.call(arguments, 1), nameFirst, spanOptions);\n};\nconst makeFn = (name, bodyOrOptions, defError, pipeables, addSpan, spanOptions) => {\n const body = typeof bodyOrOptions === \"function\" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self);\n return defineFunctionLength(body.length, function (...args) {\n let result = suspend(() => {\n const iter = body.apply(this, arguments);\n return isEffect(iter) ? iter : fromIteratorUnsafe(iter);\n });\n for (let i = 0; i < pipeables.length; i++) {\n result = pipeables[i](result, ...args);\n }\n if (!isEffect(result)) {\n return result;\n }\n const prevLimit = getStackTraceLimit();\n let callError;\n if (prevLimit !== 0) {\n setStackTraceLimit(2);\n callError = new globalThis.Error();\n setStackTraceLimit(prevLimit);\n }\n return updateService(addSpan ? useSpan(name, spanOptions, span => provideParentSpan(result, span)) : result, CurrentStackFrame, prev => ({\n name,\n stack: callError ? fnStackCleaner(() => callError.stack) : constUndefined,\n parent: {\n name: `${name} (definition)`,\n stack: defError ? fnStackCleaner(() => defError.stack) : constUndefined,\n parent: prev\n }\n }));\n });\n};\n/** @internal */\nexport const fnUntracedEager = (body, ...pipeables) => defineFunctionLength(body.length, pipeables.length === 0 ? function () {\n return fromIteratorEagerUnsafe(() => body.apply(this, arguments));\n} : function () {\n let effect = fromIteratorEagerUnsafe(() => body.apply(this, arguments));\n for (const pipeable of pipeables) {\n effect = pipeable(effect, ...arguments);\n }\n return effect;\n});\nconst fromIteratorEagerUnsafe = evaluate => {\n try {\n const iterator = evaluate();\n let value = undefined;\n // Try to resolve synchronously in a loop\n while (true) {\n const state = iterator.next(value);\n if (state.done) {\n return succeed(state.value);\n }\n const primitive = state.value;\n if (primitive && primitive._tag === \"Success\") {\n value = primitive.value;\n continue;\n } else if (primitive && primitive._tag === \"Failure\") {\n return state.value;\n } else {\n let isFirstExecution = true;\n return suspend(() => {\n if (isFirstExecution) {\n isFirstExecution = false;\n return flatMap(state.value, value => fromIteratorUnsafe(iterator, value));\n } else {\n return suspend(() => fromIteratorUnsafe(evaluate()));\n }\n });\n }\n }\n } catch (error) {\n return die(error);\n }\n};\nconst fromIteratorUnsafe = /*#__PURE__*/function () {\n const Proto = /*#__PURE__*/makePrimitiveProto({\n op: \"Iterator\",\n [contA](value, fiber) {\n const iter = this.iterator;\n while (true) {\n const state = iter.next(value);\n if (state.done) return succeed(state.value);\n if (!effectIsExit(state.value)) {\n fiber._stack.push(this);\n return state.value;\n } else if (state.value._tag === \"Failure\") {\n return state.value;\n }\n value = state.value.value;\n }\n },\n [evaluate](fiber) {\n return this[contA](this.initial, fiber);\n }\n });\n const IteratorImpl = function (iterator, initial) {\n this.iterator = iterator;\n this.initial = initial;\n };\n IteratorImpl.prototype = Proto;\n return function (iterator, initial) {\n return new IteratorImpl(iterator, initial);\n };\n}();\n// ----------------------------------------------------------------------------\n// mapping & sequencing\n// ----------------------------------------------------------------------------\n/** @internal */\nexport const as = /*#__PURE__*/dual(2, (self, value) => new ContImpl(self, returnPayload, succeed(value)));\nconst evaluateCont = function (fiber) {\n fiber._stack.push(this);\n return this[args];\n};\nconst OnSuccessProto = /*#__PURE__*/makePrimitiveProto({\n op: \"OnSuccess\",\n [evaluate]: evaluateCont\n});\nconst OnSuccessImpl = function (self, f) {\n this[args] = self;\n this[contA] = f;\n};\nOnSuccessImpl.prototype = OnSuccessProto;\n// A success continuation with an extra payload slot. The stored continuation\n// receives the primitive as `this` and reads `this.payload`, so combinators\n// like map / as / tap / andThen can share module-level continuation functions\n// instead of allocating a closure per call.\nconst ContImpl = function (self, cont, payload) {\n this[args] = self;\n this[contA] = cont;\n this.payload = payload;\n};\nContImpl.prototype = OnSuccessProto;\nconst returnPayload = function () {\n return this.payload;\n};\nconst mapCont = function (value) {\n const f = this.payload;\n return succeed(internalCall(() => f(value)));\n};\nconst andThenCont = function (value) {\n const f = this.payload;\n return internalCall(() => f(value));\n};\nconst tapCont = function (value) {\n const f = this.payload;\n return new ContImpl(internalCall(() => f(value)), returnPayload, exitSucceed(value));\n};\nconst tapEffectCont = function (value) {\n return new ContImpl(this.payload, returnPayload, exitSucceed(value));\n};\n/** @internal */\nexport const asSome = self => map(self, Option.some);\n/** @internal */\nexport const flip = self => matchEffect(self, {\n onFailure: succeed,\n onSuccess: fail\n});\n/** @internal */\nexport const andThen = /*#__PURE__*/dual(2, (self, f) => new ContImpl(self, isEffect(f) ? returnPayload : andThenCont, f));\n/** @internal */\nexport const tap = /*#__PURE__*/dual(2, (self, f) => new ContImpl(self, isEffect(f) ? tapEffectCont : tapCont, f));\n/** @internal */\nexport const asVoid = self => new ContImpl(self, returnPayload, exitVoid);\n/** @internal */\nexport const sandbox = self => catchCause(self, fail);\n/** @internal */\nexport const raceAll = (all, options) => withFiber(parent => callback(resume => {\n const effects = Arr.fromIterable(all);\n const len = effects.length;\n let doneCount = 0;\n let done = false;\n const fibers = new Set();\n const failures = [];\n const onExit = (exit, fiber, i) => {\n doneCount++;\n if (exit._tag === \"Failure\") {\n failures.push(...exit.cause.reasons);\n if (doneCount >= len) {\n resume(failCause(causeFromReasons(failures)));\n }\n return;\n }\n const isWinner = !done;\n done = true;\n resume(fibers.size === 0 ? exit : flatMap(uninterruptible(fiberInterruptAll(fibers)), () => exit));\n if (isWinner && options?.onWinner) {\n options.onWinner({\n fiber,\n index: i,\n parentFiber: parent\n });\n }\n };\n for (let i = 0; i < len; i++) {\n const fiber = forkUnsafe(parent, effects[i], true, true, false);\n fibers.add(fiber);\n fiber.addObserver(exit => {\n fibers.delete(fiber);\n onExit(exit, fiber, i);\n });\n if (done) break;\n }\n return fiberInterruptAll(fibers);\n}));\n/** @internal */\nexport const raceAllFirst = (all, options) => withFiber(parent => callback(resume => {\n let done = false;\n const fibers = new Set();\n const onExit = exit => {\n done = true;\n resume(fibers.size === 0 ? exit : flatMap(uninterruptible(fiberInterruptAll(fibers)), () => exit));\n };\n let i = 0;\n for (const effect of all) {\n if (done) break;\n const index = i++;\n const fiber = forkUnsafe(parent, effect, true, true, false);\n fibers.add(fiber);\n fiber.addObserver(exit => {\n fibers.delete(fiber);\n const isWinner = !done;\n onExit(exit);\n if (isWinner && options?.onWinner) {\n options.onWinner({\n fiber,\n index,\n parentFiber: parent\n });\n }\n });\n }\n return fiberInterruptAll(fibers);\n}));\n/** @internal */\nexport const race = /*#__PURE__*/dual(args => isEffect(args[1]), (self, that, options) => raceAll([self, that], options));\n/** @internal */\nexport const raceFirst = /*#__PURE__*/dual(args => isEffect(args[1]), (self, that, options) => raceAllFirst([self, that], options));\n/** @internal */\nexport const flatMap = /*#__PURE__*/dual(2, (self, f) => new OnSuccessImpl(self, f.length !== 1 ? a => f(a) : f));\n/** @internal */\nexport const matchCauseEffectEager = /*#__PURE__*/dual(2, (self, options) => {\n if (effectIsExit(self)) {\n return self._tag === \"Success\" ? options.onSuccess(self.value) : options.onFailure(self.cause);\n }\n return matchCauseEffect(self, options);\n});\n/** @internal */\nexport const effectIsExit = effect => effect[ExitTypeId] !== undefined;\n/** @internal */\nexport const flatMapEager = /*#__PURE__*/dual(2, (self, f) => {\n if (effectIsExit(self)) {\n return self._tag === \"Success\" ? f(self.value) : self;\n }\n return flatMap(self, f);\n});\n// ----------------------------------------------------------------------------\n// mapping & sequencing\n// ----------------------------------------------------------------------------\n/** @internal */\nexport const flatten = self => flatMap(self, identity);\n/** @internal */\nexport const map = /*#__PURE__*/dual(2, (self, f) => new ContImpl(self, mapCont, f));\n/** @internal */\nexport const mapEager = /*#__PURE__*/dual(2, (self, f) => effectIsExit(self) ? exitMap(self, f) : map(self, f));\n/** @internal */\nexport const mapErrorEager = /*#__PURE__*/dual(2, (self, f) => effectIsExit(self) ? exitMapError(self, f) : mapError(self, f));\n/** @internal */\nexport const mapBothEager = /*#__PURE__*/dual(2, (self, options) => effectIsExit(self) ? exitMapBoth(self, options) : mapBoth(self, options));\n/** @internal */\nexport const catchEager = /*#__PURE__*/dual(2, (self, f) => {\n if (effectIsExit(self)) {\n if (self._tag === \"Success\") return self;\n const error = findError(self.cause);\n if (Result.isFailure(error)) return self;\n return f(error.success);\n }\n return catch_(self, f);\n});\n// ----------------------------------------------------------------------------\n// Exit\n// ----------------------------------------------------------------------------\n/** @internal */\nexport const exitInterrupt = fiberId => exitFailCause(causeInterrupt(fiberId));\n/** @internal */\nexport const exitIsSuccess = self => self._tag === \"Success\";\n/** @internal */\nexport const exitFilterSuccess = self => self._tag === \"Success\" ? Result.succeed(self) : Result.fail(self);\n/** @internal */\nexport const exitFilterValue = self => self._tag === \"Success\" ? Result.succeed(self.value) : Result.fail(self);\n/** @internal */\nexport const exitIsFailure = self => self._tag === \"Failure\";\n/** @internal */\nexport const exitFilterFailure = self => self._tag === \"Failure\" ? Result.succeed(self) : Result.fail(self);\n/** @internal */\nexport const exitFilterCause = self => self._tag === \"Failure\" ? Result.succeed(self.cause) : Result.fail(self);\n/** @internal */\nexport const exitFindError = /*#__PURE__*/Filter.composePassthrough(exitFilterCause, findError);\n/** @internal */\nexport const exitFindDefect = /*#__PURE__*/Filter.composePassthrough(exitFilterCause, findDefect);\n/** @internal */\nexport const exitHasInterrupts = self => self._tag === \"Failure\" && hasInterrupts(self.cause);\n/** @internal */\nexport const exitHasDies = self => self._tag === \"Failure\" && hasDies(self.cause);\n/** @internal */\nexport const exitHasFails = self => self._tag === \"Failure\" && hasFails(self.cause);\n/** @internal */\nexport const exitVoid = /*#__PURE__*/exitSucceed(void 0);\n/** @internal */\nexport const exitMap = /*#__PURE__*/dual(2, (self, f) => self._tag === \"Success\" ? exitSucceed(f(self.value)) : self);\n/** @internal */\nexport const exitMapError = /*#__PURE__*/dual(2, (self, f) => {\n if (self._tag === \"Success\") return self;\n const error = findError(self.cause);\n if (Result.isFailure(error)) return self;\n return exitFail(f(error.success));\n});\n/** @internal */\nexport const exitMapBoth = /*#__PURE__*/dual(2, (self, options) => {\n if (self._tag === \"Success\") return exitSucceed(options.onSuccess(self.value));\n const error = findError(self.cause);\n if (Result.isFailure(error)) return self;\n return exitFail(options.onFailure(error.success));\n});\n/** @internal */\nexport const exitAs = /*#__PURE__*/dual(2, (self, b) => exitIsSuccess(self) ? exitSucceed(b) : self);\n/** @internal */\nexport const exitZipRight = /*#__PURE__*/dual(2, (self, that) => exitIsSuccess(self) ? that : self);\n/** @internal */\nexport const exitMatch = /*#__PURE__*/dual(2, (self, options) => exitIsSuccess(self) ? options.onSuccess(self.value) : options.onFailure(self.cause));\n/** @internal */\nexport const exitAsVoid = /*#__PURE__*/exitAs(void 0);\n/** @internal */\nexport const exitAsVoidAll = exits => {\n const failures = [];\n for (const exit of exits) {\n if (exit._tag === \"Failure\") {\n failures.push(...exit.cause.reasons);\n }\n }\n return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures));\n};\n/** @internal */\nexport const exitGetSuccess = self => exitIsSuccess(self) ? Option.some(self.value) : Option.none();\n/** @internal */\nexport const exitGetCause = self => exitIsFailure(self) ? Option.some(self.cause) : Option.none();\n/** @internal */\nexport const exitFindErrorOption = self => {\n const error = exitFindError(self);\n return Result.isFailure(error) ? Option.none() : Option.some(error.success);\n};\n// ----------------------------------------------------------------------------\n// environment\n// ----------------------------------------------------------------------------\n/** @internal */\nexport const service = service => service;\n/** @internal */\nexport const serviceOption = service => withFiber(fiber => succeed(Context.getOption(fiber.context, service)));\n/** @internal */\nexport const serviceOptional = service => withFiber(fiber => fromOption(Context.getOption(fiber.context, service)));\n/** @internal */\nexport const updateContext = /*#__PURE__*/dual(2, (self, f) => withFiber(fiber => {\n const prevContext = fiber.context;\n const nextContext = f(prevContext);\n if (prevContext === nextContext) return self;\n fiber.setContext(nextContext);\n return onExitPrimitive(self, () => {\n fiber.setContext(prevContext);\n return undefined;\n });\n}));\n/** @internal */\nexport const updateService = /*#__PURE__*/dual(3, (self, service, f) => updateContext(self, s => {\n const prev = Context.getUnsafe(s, service);\n const next = f(prev);\n if (prev === next) return s;\n return Context.add(s, service, next);\n}));\n/** @internal */\nexport const updateServiceScoped = (service, update, options) => uninterruptible(withFiber(fiber => {\n const original = Context.getUnsafe(fiber.context, service);\n const updated = update(original);\n fiber.setContext(Context.add(fiber.context, service, updated));\n return scopeAddFinalizerExit(Context.getUnsafe(fiber.context, scopeTag), _ => {\n const currentOption = Context.getOption(fiber.context, service);\n if (Option.isNone(currentOption)) return void_;\n const current = currentOption.value;\n let next;\n if (options?.reset === undefined) {\n if (current !== updated) return void_;\n next = original;\n } else {\n next = options.reset(original, updated, current);\n }\n fiber.setContext(Context.add(fiber.context, service, next));\n return void_;\n });\n}));\n/** @internal */\nexport const context = () => getContext;\nconst getContext = /*#__PURE__*/withFiber(fiber => succeed(fiber.context));\n/** @internal */\nexport const contextWith = f => withFiber(fiber => f(fiber.context));\n/** @internal */\nexport const setContext = /*#__PURE__*/dual(2, (self, context) => updateContext(self, constant(context)));\n/** @internal */\nexport const provideContext = /*#__PURE__*/dual(2, (self, context) => {\n if (effectIsExit(self)) return self;\n return updateContext(self, Context.merge(context));\n});\n/** @internal */\nexport const provideService = function () {\n if (arguments.length === 1) {\n return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl));\n }\n return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments);\n};\nconst provideServiceImpl = (self, service, implementation) => updateContext(self, Context.add(service, implementation));\n/** @internal */\nexport const provideServiceEffect = /*#__PURE__*/dual(3, (self, service, acquire) => flatMap(acquire, implementation => provideService(self, service, implementation)));\n// ----------------------------------------------------------------------------\n// zipping\n// ----------------------------------------------------------------------------\n/** @internal */\nexport const zip = /*#__PURE__*/dual(args => isEffect(args[1]), (self, that, options) => zipWith(self, that, (a, a2) => [a, a2], options));\n/** @internal */\nexport const zipWith = /*#__PURE__*/dual(args => isEffect(args[1]), (self, that, f, options) => options?.concurrent\n// Use `all` exclusively for concurrent cases, as it introduces additional overhead due to the management of concurrency\n? map(all([self, that], {\n concurrency: 2\n}), ([a, a2]) => internalCall(() => f(a, a2))) : flatMap(self, a => map(that, a2 => internalCall(() => f(a, a2)))));\n// ----------------------------------------------------------------------------\n// filtering & conditionals\n// ----------------------------------------------------------------------------\n/** @internal */\nexport const filterOrFail = /*#__PURE__*/dual(args => isEffect(args[0]), (self, predicate, orFailWith) => filterOrElse(self, predicate, orFailWith ? a => fail(orFailWith(a)) : () => fail(new NoSuchElementError())));\n/** @internal */\nexport const when = /*#__PURE__*/dual(2, (self, condition) => flatMap(condition, pass => pass ? asSome(self) : succeedNone));\n// ----------------------------------------------------------------------------\n// repetition\n// ----------------------------------------------------------------------------\n/** @internal */\nexport const replicate = /*#__PURE__*/dual(2, (self, n) => Array.from({\n length: n\n}, () => self));\n/** @internal */\nexport const replicateEffect = /*#__PURE__*/dual(args => isEffect(args[0]), (self, n, options) => all(replicate(self, n), options));\n/** @internal */\nexport const forever = /*#__PURE__*/dual(args => isEffect(args[0]), (self, options) => whileLoop({\n while: constTrue,\n body: constant(options?.disableYield ? self : flatMap(self, _ => yieldNow)),\n step: constVoid\n}));\n// ----------------------------------------------------------------------------\n// error handling\n// ----------------------------------------------------------------------------\n/** @internal */\nexport const catchCause = /*#__PURE__*/dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? cause => f(cause) : f));\nconst OnFailureProto = /*#__PURE__*/makePrimitiveProto({\n op: \"OnFailure\",\n [evaluate]: evaluateCont\n});\nconst OnFailureImpl = function (self, f) {\n this[args] = self;\n this[contE] = f;\n};\nOnFailureImpl.prototype = OnFailureProto;\n/** @internal */\nexport const catchCauseIf = /*#__PURE__*/dual(3, (self, predicate, f) => catchCause(self, cause => {\n if (!predicate(cause)) {\n return failCause(cause);\n }\n return internalCall(() => f(cause));\n}));\n/** @internal */\nexport const catchCauseFilter = /*#__PURE__*/dual(3, (self, filter, f) => catchCause(self, cause => {\n const eb = filter(cause);\n return Result.isFailure(eb) ? failCause(eb.failure) : internalCall(() => f(eb.success, cause));\n}));\n/** @internal */\nexport const catch_ = /*#__PURE__*/dual(2, (self, f) => catchCauseFilter(self, findError, e => f(e)));\n/** @internal */\nexport const catchNoSuchElement = self => matchEffect(self, {\n onFailure: error => isNoSuchElementError(error) ? succeedNone : fail(error),\n onSuccess: succeedSome\n});\n/** @internal */\nexport const catchDefect = /*#__PURE__*/dual(2, (self, f) => catchCauseFilter(self, findDefect, f));\n/** @internal */\nexport const tapCause = /*#__PURE__*/dual(2, (self, f) => catchCause(self, cause => andThen(internalCall(() => f(cause)), failCause(cause))));\n/** @internal */\nexport const tapCauseIf = /*#__PURE__*/dual(3, (self, predicate, f) => catchCauseIf(self, predicate, cause => andThen(internalCall(() => f(cause)), failCause(cause))));\n/** @internal */\nexport const tapCauseFilter = /*#__PURE__*/dual(3, (self, filter, f) => catchCause(self, cause => {\n const result = filter(cause);\n if (Result.isFailure(result)) {\n return failCause(cause);\n }\n return andThen(internalCall(() => f(result.success, cause)), failCause(cause));\n}));\n/** @internal */\nexport const tapError = /*#__PURE__*/dual(2, (self, f) => tapCauseFilter(self, findError, e => f(e)));\n/** @internal */\nexport const tapErrorTag = /*#__PURE__*/dual(3, (self, k, f) => {\n const predicate = Array.isArray(k) ? e => hasProperty(e, \"_tag\") && k.includes(e._tag) : isTagged(k);\n return tapError(self, error => predicate(error) ? f(error) : void_);\n});\n/** @internal */\nexport const tapDefect = /*#__PURE__*/dual(2, (self, f) => tapCauseFilter(self, findDefect, _ => f(_)));\n/** @internal */\nexport const catchIf = /*#__PURE__*/dual(args => isEffect(args[0]), (self, predicate, f, orElse) => catchCause(self, cause => {\n const error = findError(cause);\n if (Result.isFailure(error)) return failCause(error.failure);\n if (!predicate(error.success)) {\n return orElse ? internalCall(() => orElse(error.success)) : failCause(cause);\n }\n return internalCall(() => f(error.success));\n}));\n/** @internal */\nexport const catchFilter = /*#__PURE__*/dual(args => isEffect(args[0]), (self, filter, f, orElse) => catchCause(self, cause => {\n const error = findError(cause);\n if (Result.isFailure(error)) return failCause(error.failure);\n const result = filter(error.success);\n if (Result.isFailure(result)) {\n return orElse ? internalCall(() => orElse(result.failure)) : failCause(cause);\n }\n return internalCall(() => f(result.success));\n}));\n/** @internal */\nexport const catchTag = /*#__PURE__*/dual(args => isEffect(args[0]), (self, k, f, orElse) => {\n const pred = Array.isArray(k) ? e => hasProperty(e, \"_tag\") && k.includes(e._tag) : isTagged(k);\n return catchIf(self, pred, f, orElse);\n});\n/** @internal */\nexport const catchTags = /*#__PURE__*/dual(args => isEffect(args[0]), (self, cases, orElse) => {\n let keys;\n return catchFilter(self, e => {\n keys ??= Object.keys(cases);\n return hasProperty(e, \"_tag\") && isString(e[\"_tag\"]) && keys.includes(e[\"_tag\"]) ? Result.succeed(e) : Result.fail(e);\n }, e => internalCall(() => cases[e[\"_tag\"]](e)), orElse);\n});\n/** @internal */\nexport const catchReason = /*#__PURE__*/dual(args => isEffect(args[0]), (self, errorTag, reasonTag, f, orElse) => catchIf(self, e => isTagged(e, errorTag) && hasProperty(e, \"reason\") && (orElse !== undefined || isTagged(e.reason, reasonTag)), e => {\n const reason = e.reason;\n if (isTagged(reason, reasonTag)) return f(reason, e);\n return orElse ? internalCall(() => orElse(reason, e)) : fail(e);\n}));\n/** @internal */\nexport const catchReasons = /*#__PURE__*/dual(args => isEffect(args[0]), (self, errorTag, cases, orElse) => {\n let keys;\n return catchIf(self, e => isTagged(e, errorTag) && hasProperty(e, \"reason\") && hasProperty(e.reason, \"_tag\") && isString(e.reason._tag) && (orElse !== undefined || (keys ??= Object.keys(cases)).includes(e.reason._tag)), e => {\n const reason = e.reason;\n keys ??= Object.keys(cases);\n if (keys.includes(reason._tag)) {\n return internalCall(() => cases[reason._tag](reason, e));\n }\n return orElse ? internalCall(() => orElse(reason, e)) : fail(e);\n });\n});\n/** @internal */\nexport const unwrapReason = /*#__PURE__*/dual(2, (self, errorTag) => catchFilter(self, e => {\n if (isTagged(e, errorTag) && hasProperty(e, \"reason\")) {\n return Result.succeed(e.reason);\n }\n return Result.fail(e);\n}, fail));\n/** @internal */\nexport const mapError = /*#__PURE__*/dual(2, (self, f) => catch_(self, error => failSync(() => f(error))));\n/** @internal */\nexport const mapBoth = /*#__PURE__*/dual(2, (self, options) => matchEffect(self, {\n onFailure: e => failSync(() => options.onFailure(e)),\n onSuccess: a => sync(() => options.onSuccess(a))\n}));\n/** @internal */\nexport const orDie = self => catch_(self, die);\n/** @internal */\nexport const orElseSucceed = /*#__PURE__*/dual(2, (self, f) => catch_(self, _ => sync(f)));\n/** @internal */\nexport const firstSuccessOf = effects => suspend(() => {\n const iterator = effects[Symbol.iterator]();\n let state = iterator.next();\n if (state.done) {\n return die(new Error(\"Received an empty collection of effects\"));\n }\n function loop(current) {\n const next = iterator.next();\n if (next.done) return current.value;\n return catch_(current.value, _ => loop(next));\n }\n return loop(state);\n});\n/** @internal */\nexport const eventually = self => catch_(self, _ => flatMap(yieldNow, () => eventually(self)));\n/** @internal */\nexport const ignore = /*#__PURE__*/dual(args => isEffect(args[0]), (self, options) => {\n if (!options?.log) {\n return matchEffect(self, {\n onFailure: _ => void_,\n onSuccess: _ => void_\n });\n }\n const logEffect = logWithLevel(options.log === true ? undefined : options.log);\n return matchCauseEffect(self, {\n onFailure(cause) {\n const failure = findFail(cause);\n return Result.isFailure(failure) ? failCause(failure.failure) : options.message === undefined ? logEffect(cause) : logEffect(options.message, cause);\n },\n onSuccess: _ => void_\n });\n});\n/** @internal */\nexport const ignoreCause = /*#__PURE__*/dual(args => isEffect(args[0]), (self, options) => {\n if (!options?.log) {\n return matchCauseEffect(self, {\n onFailure: _ => void_,\n onSuccess: _ => void_\n });\n }\n const logEffect = logWithLevel(options.log === true ? undefined : options.log);\n return matchCauseEffect(self, {\n onFailure: cause => options.message === undefined ? logEffect(cause) : logEffect(options.message, cause),\n onSuccess: _ => void_\n });\n});\n/** @internal */\nexport const option = self => match(self, {\n onFailure: Option.none,\n onSuccess: Option.some\n});\n/** @internal */\nexport const result = self => matchEager(self, {\n onFailure: Result.fail,\n onSuccess: Result.succeed\n});\n// ----------------------------------------------------------------------------\n// pattern matching\n// ----------------------------------------------------------------------------\n/** @internal */\nexport const matchCauseEffect = /*#__PURE__*/dual(2, (self, options) => new OnSuccessAndFailureImpl(self, options.onSuccess.length !== 1 ? a => options.onSuccess(a) : options.onSuccess, options.onFailure.length !== 1 ? cause => options.onFailure(cause) : options.onFailure));\nconst OnSuccessAndFailureProto = /*#__PURE__*/makePrimitiveProto({\n op: \"OnSuccessAndFailure\",\n [evaluate]: evaluateCont\n});\nconst OnSuccessAndFailureImpl = function (self, onSuccess, onFailure) {\n this[args] = self;\n this[contA] = onSuccess;\n this[contE] = onFailure;\n};\nOnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto;\n/** @internal */\nexport const matchCause = /*#__PURE__*/dual(2, (self, options) => matchCauseEffect(self, {\n onFailure: cause => sync(() => options.onFailure(cause)),\n onSuccess: value => sync(() => options.onSuccess(value))\n}));\n/** @internal */\nexport const matchEffect = /*#__PURE__*/dual(2, (self, options) => matchCauseEffect(self, {\n onFailure: cause => {\n const fail = cause.reasons.find(isFailReason);\n return fail ? internalCall(() => options.onFailure(fail.error)) : failCause(cause);\n },\n onSuccess: options.onSuccess\n}));\n/** @internal */\nexport const match = /*#__PURE__*/dual(2, (self, options) => matchEffect(self, {\n onFailure: error => sync(() => options.onFailure(error)),\n onSuccess: value => sync(() => options.onSuccess(value))\n}));\n/** @internal */\nexport const matchEager = /*#__PURE__*/dual(2, (self, options) => {\n if (effectIsExit(self)) {\n if (self._tag === \"Success\") return exitSucceed(options.onSuccess(self.value));\n const error = findError(self.cause);\n if (Result.isFailure(error)) return self;\n return exitSucceed(options.onFailure(error.success));\n }\n return match(self, options);\n});\n/** @internal */\nexport const matchCauseEager = /*#__PURE__*/dual(2, (self, options) => {\n if (effectIsExit(self)) {\n if (self._tag === \"Success\") return exitSucceed(options.onSuccess(self.value));\n return exitSucceed(options.onFailure(self.cause));\n }\n return matchCause(self, options);\n});\n/** @internal */\nexport const exit = self => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self);\nconst exitPrimitive = /*#__PURE__*/makePrimitive({\n op: \"Exit\",\n [evaluate](fiber) {\n fiber._stack.push(this);\n return this[args];\n },\n [contA](value, _, exit) {\n return succeed(exit ?? exitSucceed(value));\n },\n [contE](cause, _, exit) {\n return succeed(exit ?? exitFailCause(cause));\n }\n});\n// ----------------------------------------------------------------------------\n// Condition checking\n// ----------------------------------------------------------------------------\n/** @internal */\nexport const isFailure = /*#__PURE__*/matchEager({\n onFailure: () => true,\n onSuccess: () => false\n});\n/** @internal */\nexport const isSuccess = /*#__PURE__*/matchEager({\n onFailure: () => false,\n onSuccess: () => true\n});\n// ----------------------------------------------------------------------------\n// delays & timeouts\n// ----------------------------------------------------------------------------\n/** @internal */\nexport const delay = /*#__PURE__*/dual(2, (self, duration) => andThen(sleep(duration), self));\n/** @internal */\nexport const timeoutOrElse = /*#__PURE__*/dual(2, (self, options) => flatMap(timeoutOption(self, options.duration), option => Option.isNone(option) ? options.orElse() : succeed(option.value)));\n/** @internal */\nconst timeoutErrorFromDuration = duration => new TimeoutError(`Operation timed out after '${Duration.format(duration)}'`);\n/** @internal */\nexport const timeout = /*#__PURE__*/dual(2, (self, duration) => {\n const decoded = Duration.fromInputUnsafe(duration);\n return timeoutOrElse(self, {\n duration: decoded,\n orElse: () => fail(timeoutErrorFromDuration(decoded))\n });\n});\n/** @internal */\nexport const timeoutOption = /*#__PURE__*/dual(2, (self, duration) => raceFirst(asSome(self), as(sleep(duration), Option.none())));\n/** @internal */\nexport const timed = self => clockWith(clock => {\n const start = clock.monotonicTimeNanosUnsafe();\n return map(self, a => [Duration.nanos(clock.monotonicTimeNanosUnsafe() - start), a]);\n});\n// ----------------------------------------------------------------------------\n// resources & finalization\n// ----------------------------------------------------------------------------\n/** @internal */\nexport const ScopeTypeId = \"~effect/Scope\";\n/** @internal */\nexport const ScopeCloseableTypeId = \"~effect/Scope/Closeable\";\n/** @internal */\nexport const scopeTag = /*#__PURE__*/Context.Service(\"effect/Scope\");\n/** @internal */\nexport const scopeClose = (self, exit_) => suspend(() => scopeCloseUnsafe(self, exit_) ?? void_);\n/** @internal */\nexport const scopeCloseUnsafe = (self, exit_) => {\n if (self.state._tag === \"Closed\") return;\n const closed = {\n _tag: \"Closed\",\n exit: exit_\n };\n if (self.state._tag === \"Empty\") {\n self.state = closed;\n return;\n }\n const state = self.state;\n self.state = closed;\n if (state.finalizer !== undefined) {\n return state.finalizer(exit_);\n }\n const finalizers = state.finalizers;\n if (finalizers === undefined || finalizers.size === 0) {\n return;\n } else if (finalizers.size === 1) {\n return finalizers.values().next().value(exit_);\n }\n return scopeCloseFinalizers(self, finalizers, exit_);\n};\nconst combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, cause => failCause(causeCombine(exit_.cause, cause)));\nconst scopeCloseFinalizers = /*#__PURE__*/fnUntraced(function* (self, finalizers, exit_) {\n let exits = [];\n const fibers = [];\n const arr = Array.from(finalizers.values());\n const parent = getCurrentFiber();\n for (let i = arr.length - 1; i >= 0; i--) {\n const finalizer = arr[i];\n if (self.strategy === \"sequential\") {\n exits.push(yield* exit(finalizer(exit_)));\n } else {\n fibers.push(forkUnsafe(parent, finalizer(exit_), true, true, \"inherit\"));\n }\n }\n if (fibers.length > 0) {\n exits = yield* fiberAwaitAll(fibers);\n }\n return yield* exitAsVoidAll(exits);\n});\n/** @internal */\nexport const scopeFork = (scope, finalizerStrategy) => sync(() => scopeForkUnsafe(scope, finalizerStrategy));\n/** @internal */\nexport const scopeForkUnsafe = (scope, finalizerStrategy) => {\n const newScope = scopeMakeUnsafe(finalizerStrategy);\n if (scope.state._tag === \"Closed\") {\n newScope.state = scope.state;\n return newScope;\n }\n const key = {};\n scopeAddFinalizerUnsafe(scope, key, exit => scopeClose(newScope, exit));\n scopeAddFinalizerUnsafe(newScope, key, _ => sync(() => scopeRemoveFinalizerUnsafe(scope, key)));\n return newScope;\n};\n/** @internal */\nexport const scopeAddFinalizerExit = (scope, finalizer) => {\n return suspend(() => {\n if (scope.state._tag === \"Closed\") {\n return finalizer(scope.state.exit);\n }\n scopeAddFinalizerUnsafe(scope, {}, finalizer);\n return void_;\n });\n};\n/** @internal */\nexport const scopeAddFinalizer = (scope, finalizer) => scopeAddFinalizerExit(scope, constant(finalizer));\n/** @internal */\nexport const scopeAddFinalizerUnsafe = (scope, key, finalizer) => {\n if (scope.state._tag === \"Empty\") {\n scope.state = {\n _tag: \"Open\",\n finalizerKey: key,\n finalizer,\n finalizers: undefined\n };\n } else if (scope.state._tag === \"Open\") {\n const state = scope.state;\n if (state.finalizer !== undefined) {\n state.finalizers = new Map([[state.finalizerKey, state.finalizer]]);\n state.finalizerKey = undefined;\n state.finalizer = undefined;\n state.finalizers.set(key, finalizer);\n } else if (state.finalizers === undefined) {\n state.finalizerKey = key;\n state.finalizer = finalizer;\n } else {\n state.finalizers.set(key, finalizer);\n }\n }\n};\n/** @internal */\nexport const scopeRemoveFinalizerUnsafe = (scope, key) => {\n if (scope.state._tag === \"Open\") {\n const state = scope.state;\n if (state.finalizerKey === key) {\n state.finalizerKey = undefined;\n state.finalizer = undefined;\n } else if (state.finalizers !== undefined) {\n state.finalizers.delete(key);\n }\n }\n};\n/** @internal */\nexport const scopeFinalizerCountUnsafe = scope => scope.state._tag !== \"Open\" ? 0 : scope.state.finalizer !== undefined ? 1 : scope.state.finalizers?.size ?? 0;\n/** @internal */\nexport const scopeMakeUnsafe = (finalizerStrategy = \"sequential\") => ({\n [ScopeCloseableTypeId]: ScopeCloseableTypeId,\n [ScopeTypeId]: ScopeTypeId,\n strategy: finalizerStrategy,\n state: constScopeEmpty\n});\nconst constScopeEmpty = {\n _tag: \"Empty\"\n};\n/** @internal */\nexport const scopeMake = finalizerStrategy => sync(() => scopeMakeUnsafe(finalizerStrategy));\n/** @internal */\nexport const scope = scopeTag;\n/** @internal */\nexport const provideScope = /*#__PURE__*/provideService(scopeTag);\n/** @internal */\nexport const scoped = self => withFiber(fiber => {\n const prev = fiber.context;\n const scope = scopeMakeUnsafe();\n fiber.setContext(Context.add(fiber.context, scopeTag, scope));\n return onExitPrimitive(self, exit => {\n fiber.setContext(prev);\n return scopeCloseUnsafe(scope, exit);\n });\n});\n/** @internal */\nexport const scopeUse = /*#__PURE__*/dual(2, (self, scope) => onExit(provideScope(self, scope), exit => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)));\n/** @internal */\nexport const scopedWith = f => suspend(() => {\n const scope = scopeMakeUnsafe();\n return onExit(f(scope), exit => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_));\n});\n/** @internal */\nexport const acquireRelease = (acquire, release, options) => contextWith(context => uninterruptibleMask(restore => flatMap(scope, scope => tap(options?.interruptible ? restore(acquire) : acquire, a => scopeAddFinalizerExit(scope, exit => provideContext(release(a, exit), context))))));\n/** @internal */\nexport const addFinalizer = finalizer => flatMap(scope, scope => contextWith(context => scopeAddFinalizerExit(scope, exit => provideContext(finalizer(exit), context))));\n/** @internal */\nexport const onExitPrimitive = /*#__PURE__*/function () {\n const Proto = /*#__PURE__*/makePrimitiveProto({\n op: \"OnExit\",\n [evaluate](fiber) {\n fiber._stack.push(this);\n return this.effect;\n },\n [contAll](fiber) {\n if (fiber.interruptible && this.interruptible !== true) {\n fiber._stack.push(setInterruptibleTrue);\n fiber.interruptible = false;\n }\n },\n [contA](value, _, exit) {\n exit ??= exitSucceed(value);\n const eff = this.onExit(exit);\n return eff ? flatMap(eff, _ => exit) : exit;\n },\n [contE](cause, _, exit) {\n exit ??= exitFailCause(cause);\n const eff = this.onExit(exit);\n return eff ? flatMap(combineFinalizerCause(exit, eff), _ => exit) : exit;\n }\n });\n const OnExitImpl = function (effect, onExit, interruptible) {\n this.effect = effect;\n this.onExit = onExit;\n this.interruptible = interruptible;\n };\n OnExitImpl.prototype = Proto;\n return function (effect, onExit, interruptible) {\n return new OnExitImpl(effect, onExit, interruptible);\n };\n}();\n/** @internal */\nexport const onExit = /*#__PURE__*/dual(2, onExitPrimitive);\n/** @internal */\nexport const ensuring = /*#__PURE__*/dual(2, (self, finalizer) => onExit(self, _ => finalizer));\n/** @internal */\nexport const onExitIf = /*#__PURE__*/dual(3, (self, predicate, f) => onExit(self, exit => {\n if (!predicate(exit)) {\n return void_;\n }\n return f(exit);\n}));\n/** @internal */\nexport const onExitFilter = /*#__PURE__*/dual(3, (self, filter, f) => onExit(self, exit => {\n const b = filter(exit);\n return Result.isFailure(b) ? void_ : f(b.success, exit);\n}));\n/** @internal */\nexport const onError = /*#__PURE__*/dual(2, (self, f) => onExitFilter(self, exitFilterCause, f));\n/** @internal */\nexport const onErrorIf = /*#__PURE__*/dual(3, (self, predicate, f) => onExitIf(self, exit => {\n if (exit._tag !== \"Failure\") {\n return false;\n }\n return predicate(exit.cause);\n}, exit => f(exit.cause)));\n/** @internal */\nexport const onErrorFilter = /*#__PURE__*/dual(3, (self, filter, f) => onExit(self, exit => {\n if (exit._tag !== \"Failure\") {\n return void_;\n }\n const result = filter(exit.cause);\n return Result.isFailure(result) ? void_ : f(result.success, exit.cause);\n}));\n/** @internal */\nexport const onInterrupt = /*#__PURE__*/dual(2, (self, finalizer) => onErrorFilter(causeFilterInterruptors, finalizer)(self));\n/** @internal */\nexport const acquireUseRelease = (acquire, use, release) => uninterruptibleMask(restore => flatMap(acquire, a => onExitPrimitive(suspend(() => restore(use(a))), exit => release(a, exit), true)));\n/** @internal */\nexport const acquireDisposable = acquire => acquireRelease(acquire, resource => hasProperty(resource, Symbol.asyncDispose) ? promise(() => resource[Symbol.asyncDispose]()) : sync(() => resource[Symbol.dispose]()));\n// ----------------------------------------------------------------------------\n// Caching\n// ----------------------------------------------------------------------------\n/** @internal */\nexport const cachedInvalidateWithTTL = /*#__PURE__*/dual(2, (self, ttl) => sync(() => {\n const ttlMillis = typeof ttl === \"function\" ? exit => Duration.toMillis(Duration.fromInputUnsafe(ttl(exit))) : constant(Duration.toMillis(Duration.fromInputUnsafe(ttl)));\n const latch = makeLatchUnsafe(false);\n let expiresAt = 0;\n let running = false;\n let exit;\n const wait = flatMap(latch.await, () => exit);\n return [withFiber(fiber => {\n const clock = fiber.getRef(ClockRef);\n const now = expiresAt === Infinity ? 0 : clock.currentTimeMillisUnsafe();\n if (running || now < expiresAt) return exit ?? wait;\n running = true;\n latch.closeUnsafe();\n exit = undefined;\n return onExit(self, exit_ => sync(() => {\n try {\n const duration = ttlMillis(exit_);\n expiresAt = clock.currentTimeMillisUnsafe() + duration;\n exit = exit_;\n } catch (error) {\n const cause = causeDie(error);\n // Publish the same combined cause that onExit returns to the owner.\n exit = exitFailCause(exitIsFailure(exit_) ? causeCombine(exit_.cause, cause) : cause);\n throw error;\n } finally {\n running = false;\n latch.openUnsafe();\n }\n }));\n }), sync(() => {\n expiresAt = 0;\n latch.closeUnsafe();\n exit = undefined;\n })];\n}));\n/** @internal */\nexport const cachedWithTTL = /*#__PURE__*/dual(2, (self, timeToLive) => map(cachedInvalidateWithTTL(self, timeToLive), tuple => tuple[0]));\n/** @internal */\nexport const cached = self => sync(() => {\n const latch = makeLatchUnsafe(false);\n let started = false;\n let exit;\n const wait = flatMap(latch.await, () => exit);\n return suspend(() => {\n if (exit !== undefined) return exit;\n if (started) return wait;\n started = true;\n return onExit(self, result => sync(() => {\n exit = result;\n latch.openUnsafe();\n }));\n });\n});\n// ----------------------------------------------------------------------------\n// interruption\n// ----------------------------------------------------------------------------\n/** @internal */\nexport const interrupt = /*#__PURE__*/withFiber(fiber => failCause(causeInterrupt(fiber.id)));\n/** @internal */\nexport const uninterruptible = self => withFiber(fiber => {\n if (!fiber.interruptible) return self;\n fiber.interruptible = false;\n fiber._stack.push(setInterruptibleTrue);\n return self;\n});\nconst setInterruptible = /*#__PURE__*/makePrimitive({\n op: \"SetInterruptible\",\n [contAll](fiber) {\n fiber.interruptible = this[args];\n if (fiber._interruptedCause && fiber.interruptible) {\n return () => failCause(fiber._interruptedCause);\n }\n }\n});\nconst setInterruptibleTrue = /*#__PURE__*/setInterruptible(true);\nconst setInterruptibleFalse = /*#__PURE__*/setInterruptible(false);\nconst setFiberInterruptible = fiber => {\n fiber.interruptible = true;\n fiber._stack.push(setInterruptibleFalse);\n if (fiber._interruptedCause) return failCause(fiber._interruptedCause);\n};\n/**\n * Makes the current fiber uninterruptible for the returned effect without an\n * extra primitive. Call only within `withFiber`.\n *\n * @internal\n */\nexport const fiberEnterUninterruptibleUnsafe = fiber => {\n const impl = fiber;\n if (!impl.interruptible) return;\n impl.interruptible = false;\n impl._stack.push(setInterruptibleTrue);\n};\n/**\n * Makes the current fiber interruptible for the returned effect without an\n * extra primitive. Call only within `withFiber` and return any pending\n * interruption it produces.\n *\n * @internal\n */\nexport const fiberEnterInterruptibleUnsafe = fiber => {\n const impl = fiber;\n if (impl.interruptible) return undefined;\n return setFiberInterruptible(impl);\n};\n/** @internal */\nexport const interruptible = self => withFiber(fiber => {\n if (fiber.interruptible) return self;\n return setFiberInterruptible(fiber) ?? self;\n});\n/** @internal */\nexport const uninterruptibleMask = f => withFiber(fiber => {\n if (!fiber.interruptible) return f(identity);\n fiber.interruptible = false;\n fiber._stack.push(setInterruptibleTrue);\n return f(interruptible);\n});\n/** @internal */\nexport const interruptibleMask = f => withFiber(fiber => {\n if (fiber.interruptible) return f(identity);\n const interrupted = setFiberInterruptible(fiber);\n const effect = f(uninterruptible);\n return interrupted ?? effect;\n});\n/** @internal */\nexport const abortSignal = /*#__PURE__*/map(/*#__PURE__*/acquireRelease(/*#__PURE__*/sync(() => new AbortController()), controller => sync(() => controller.abort())), _ => _.signal);\n// ========================================================================\n// collecting & elements\n// ========================================================================\n/** @internal */\nexport const all = (arg, options) => {\n if (isIterable(arg)) {\n return options?.mode === \"result\" ? forEach(arg, result, options) : forEach(arg, identity, options);\n } else if (options?.discard) {\n return options.mode === \"result\" ? forEach(Object.values(arg), result, options) : forEach(Object.values(arg), identity, options);\n }\n return suspend(() => {\n const out = {};\n return as(forEach(Object.entries(arg), ([key, effect]) => map(options?.mode === \"result\" ? result(effect) : effect, value => {\n InternalRecord.assignProperty(out, key, value);\n }), {\n discard: true,\n concurrency: options?.concurrency\n }), out);\n });\n};\n/** @internal */\nexport const partition = /*#__PURE__*/dual(args => isIterable(args[0]) && !isEffect(args[0]), (elements, f, options) => map(forEach(elements, (a, i) => result(f(a, i)), options), results => Arr.partition(results, identity)));\n/** @internal */\nexport const reduce = /*#__PURE__*/dual(3, (elements, zero, f) => {\n const arr = Arr.fromIterable(elements);\n if (arr.length === 0) return sync(zero);\n return suspend(() => {\n let index = 0;\n let state = zero();\n return map(whileLoop({\n while: () => index < arr.length,\n body: () => f(state, arr[index], index),\n step(next) {\n state = next;\n index++;\n }\n }), () => state);\n });\n});\n/** @internal */\nexport const validate = /*#__PURE__*/dual(args => isIterable(args[0]) && !isEffect(args[0]), (elements, f, options) => flatMap(partition(elements, f, {\n concurrency: options?.concurrency\n}), ([excluded, satisfying]) => {\n if (Arr.isArrayNonEmpty(excluded)) {\n return fail(excluded);\n }\n return options?.discard ? void_ : succeed(satisfying);\n}));\n/** @internal */\nexport const findFirst = /*#__PURE__*/dual(args => isIterable(args[0]) && !isEffect(args[0]), (elements, predicate) => suspend(() => {\n const iterator = elements[Symbol.iterator]();\n const next = iterator.next();\n if (!next.done) {\n return findFirstLoop(iterator, 0, predicate, next.value);\n }\n return succeed(Option.none());\n}));\nconst findFirstLoop = (iterator, index, predicate, value) => flatMap(predicate(value, index), keep => {\n if (keep) {\n return succeed(Option.some(value));\n }\n const next = iterator.next();\n if (!next.done) {\n return findFirstLoop(iterator, index + 1, predicate, next.value);\n }\n return succeed(Option.none());\n});\n/** @internal */\nexport const findFirstFilter = /*#__PURE__*/dual(args => isIterable(args[0]) && !isEffect(args[0]), (elements, filter) => suspend(() => {\n const iterator = elements[Symbol.iterator]();\n const next = iterator.next();\n if (!next.done) {\n return findFirstFilterLoop(iterator, 0, filter, next.value);\n }\n return succeed(Option.none());\n}));\nconst findFirstFilterLoop = (iterator, index, filter, value) => flatMap(filter(value, index), result => {\n if (Result.isSuccess(result)) {\n return succeed(Option.some(result.success));\n }\n const next = iterator.next();\n if (!next.done) {\n return findFirstFilterLoop(iterator, index + 1, filter, next.value);\n }\n return succeed(Option.none());\n});\n/** @internal */\nexport const whileLoop = /*#__PURE__*/makePrimitive({\n op: \"While\",\n [contA](value, fiber) {\n this[args].step(value);\n if (this[args].while()) {\n fiber._stack.push(this);\n return this[args].body();\n }\n return exitVoid;\n },\n [evaluate](fiber) {\n if (this[args].while()) {\n fiber._stack.push(this);\n return this[args].body();\n }\n return exitVoid;\n }\n});\n/** @internal */\nexport const forEach = /*#__PURE__*/dual(args => typeof args[1] === \"function\", (iterable, f, options) => suspend(() => {\n const concurrency = resolveConcurrency(options?.concurrency);\n if (concurrency === 1) {\n return forEachSequential(iterable, f, options);\n }\n const items = Arr.fromIterable(iterable);\n let length = items.length;\n if (length === 0) {\n return options?.discard ? void_ : succeed([]);\n }\n const out = options?.discard ? undefined : new Array(length);\n const eff = forEachConcurrent({\n f,\n out\n }, items, {\n concurrency\n });\n return eff ? as(eff, out) : succeed(out);\n}));\n/** @internal */\nexport const head = self => flatMap(self, elements => {\n const result = elements[Symbol.iterator]().next();\n return result.done ? fail(new NoSuchElementError()) : succeed(result.value);\n});\nconst forEachSequential = (iterable, f, options) => suspend(() => {\n const out = options?.discard ? undefined : [];\n const iterator = iterable[Symbol.iterator]();\n let state = iterator.next();\n let index = 0;\n return as(whileLoop({\n while: () => !state.done,\n body: () => f(state.value, index++),\n step: b => {\n if (out) out.push(b);\n state = iterator.next();\n }\n }), out);\n});\n/** @internal */\nexport const resolveConcurrency = concurrency => concurrency === \"unbounded\" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1);\n/** @internal */\nexport const iterateEager = () => options => {\n const onItem = options.onItem;\n const step = options.step;\n const runSequential = (state, items, index = 0, end = items.length) => {\n for (; index < end; index++) {\n const item = items[index];\n const effect = onItem(state, item, index);\n if (!effectIsExit(effect)) {\n return flatMap(exit(effect), itemExit => step(state, item, itemExit, index) ?? runSequential(state, items, index + 1, end) ?? void_);\n }\n const terminal = step(state, item, effect, index);\n if (terminal) return terminal._tag === \"Failure\" ? terminal : undefined;\n }\n };\n return runSequential;\n};\nconst iterateConcurrentImpl = options => {\n const onItem = options.onItem;\n const step = options.step;\n return (state, items, opts) => {\n let index = 0;\n const end = opts.end ?? items.length;\n const concurrency = opts.concurrency;\n let done = false;\n let parentFiber;\n let fibers;\n let resume;\n let interrupted = false;\n let terminal;\n let effect;\n const failDefect = error => {\n const defect = exitDie(error);\n terminal = defect;\n done = true;\n interrupted = true;\n return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => defect) : defect;\n };\n const go = () => {\n let paused = false;\n for (; !terminal && index < end; index++) {\n const item = items[index];\n const eff = effect ?? onItem(state, item, index);\n // fast case (already an exit)\n if (effectIsExit(eff)) {\n terminal = step(state, item, eff, index);\n if (terminal) break;\n // We have an effect, so enter \"async\" mode\n } else if (!parentFiber) {\n return callback(cb => {\n parentFiber = getCurrentFiber();\n fibers = new Set();\n effect = eff;\n resume = cb;\n let result;\n try {\n result = go();\n } catch (error) {\n return cb(failDefect(error));\n }\n if (result) return cb(result);\n return suspend(() => {\n terminal = exitVoid;\n interrupted = true;\n return fibers ? fiberInterruptAll(fibers) : void_;\n });\n });\n // Fork the effect with concurrency > 1\n } else {\n // Clear the temporary effect from capturing the parentFiber\n effect = undefined;\n const fiber = forkUnsafe(parentFiber, eff, true, true, \"inherit\");\n if (fiber._exit) {\n terminal = step(state, item, fiber._exit, index);\n if (terminal) break;\n continue;\n }\n // Add the fiber to the Set\n fibers.add(fiber);\n const currentIndex = index;\n fiber.addObserver(exit => {\n fibers.delete(fiber);\n try {\n if (terminal) {\n if (!interrupted && exit._tag === \"Failure\") {\n for (const reason of exit.cause.reasons) {\n if (reason._tag === \"Interrupt\") continue;else if (terminal._tag === \"Failure\") {\n ;\n terminal.cause.reasons.push(reason);\n } else {\n terminal = exitFailCause(causeFromReasons([reason]));\n }\n }\n }\n } else {\n const result = step(state, item, exit, currentIndex);\n if (result) {\n terminal = result._tag === \"Failure\" ? exitFailCause(causeFromReasons(result.cause.reasons.slice())) : result;\n go();\n }\n }\n if (paused) {\n const eff = go();\n if (eff) resume(eff);\n } else if (done && fibers.size === 0) {\n resume(terminal ?? void_);\n }\n } catch (error) {\n resume(failDefect(error));\n }\n });\n // Check if we have reached the concurrency limit\n if (fibers.size < concurrency) continue;\n paused = true;\n index++;\n return;\n }\n }\n done = true;\n if (terminal) {\n if (fibers && fibers.size > 0) {\n const annotations = fiberStackAnnotations(parentFiber);\n fibers.forEach(f => f.interruptUnsafe(parentFiber.id, annotations));\n return;\n }\n if (resume || terminal._tag === \"Failure\") {\n return terminal;\n }\n } else if (resume) {\n if (!fibers) {\n return exitVoid;\n } else if (fibers.size === 0) {\n resume(void_);\n }\n }\n };\n return go();\n };\n};\n/** @internal */\nexport const iterateConcurrent = () => options => iterateConcurrentImpl(options);\nconst forEachConcurrent = /*#__PURE__*/iterateConcurrentImpl({\n onItem(state, item, index) {\n return state.f(item, index);\n },\n step(state, _, exit, index) {\n if (exit._tag === \"Failure\") return exit;else if (state.out) {\n state.out[index] = exit.value;\n }\n }\n});\n/** @internal */\nexport const filterOrElse = /*#__PURE__*/dual(3, (self, predicate, orElse) => flatMap(self, a => predicate(a) ? succeed(a) : orElse(a)));\n/** @internal */\nexport const filterMapOrElse = /*#__PURE__*/dual(3, (self, filter, orElse) => flatMap(self, a => {\n const result = filter(a);\n return Result.isFailure(result) ? orElse(result.failure) : succeed(result.success);\n}));\n/** @internal */\nexport const filterMapOrFail = /*#__PURE__*/dual(args => isEffect(args[0]), (self, filter, orFailWith) => filterMapOrElse(self, filter, orFailWith ? x => fail(orFailWith(x)) : () => fail(new NoSuchElementError())));\n/** @internal */\nexport const filter = /*#__PURE__*/dual(args => isIterable(args[0]) && !isEffect(args[0]), (elements, predicate, options) => suspend(() => {\n const out = [];\n return as(forEach(elements, (a, i) => {\n const result = predicate(a, i);\n if (typeof result === \"boolean\") {\n if (result) out.push(a);\n return void_;\n }\n return map(result, keep => {\n if (keep) {\n out.push(a);\n }\n });\n }, {\n discard: true,\n concurrency: options?.concurrency\n }), out);\n}));\n/** @internal */\nexport const filterMap = /*#__PURE__*/dual(args => isIterable(args[0]) && !isEffect(args[0]), (elements, filter) => suspend(() => {\n const out = [];\n for (const a of elements) {\n const result = filter(a);\n if (Result.isSuccess(result)) {\n out.push(result.success);\n }\n }\n return succeed(out);\n}));\n/** @internal */\nexport const filterMapEffect = /*#__PURE__*/dual(args => isIterable(args[0]) && !isEffect(args[0]), (elements, filter, options) => suspend(() => {\n const out = [];\n return as(forEach(elements, a => map(filter(a), result => {\n if (Result.isSuccess(result)) {\n out.push(result.success);\n }\n }), {\n discard: true,\n concurrency: options?.concurrency\n }), out);\n}));\n// ----------------------------------------------------------------------------\n// do notation\n// ----------------------------------------------------------------------------\n/** @internal */\nexport const Do = /*#__PURE__*/succeed({});\n/** @internal */\nexport const bindTo = /*#__PURE__*/doNotation.bindTo(map);\n/** @internal */\nexport const bind = /*#__PURE__*/doNotation.bind(map, flatMap);\n/** @internal */\nconst let_ = /*#__PURE__*/doNotation.let_(map);\n/** @internal */\nexport { let_ as let };\n// ----------------------------------------------------------------------------\n// fibers & forking\n// ----------------------------------------------------------------------------\n/** @internal */\nexport const forkChild = /*#__PURE__*/dual(args => isEffect(args[0]), (self, options) => withFiber(fiber => {\n interruptChildrenPatch();\n return succeed(forkUnsafe(fiber, self, options?.startImmediately, false, options?.uninterruptible ?? false));\n}));\n/** @internal */\nexport const forkUnsafe = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => {\n const parentRuntime = parent;\n const interruptible = uninterruptible === \"inherit\" ? parentRuntime.interruptible : !uninterruptible;\n const child = new FiberImpl(parentRuntime.context, interruptible);\n if (immediate) {\n child.evaluate(effect);\n } else {\n parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0);\n }\n if (!daemon && !child._exit) {\n parentRuntime.children().add(child);\n child._parent = parentRuntime;\n }\n return child;\n};\n/** @internal */\nexport const forkDetach = /*#__PURE__*/dual(args => isEffect(args[0]), (self, options) => withFiber(fiber => succeed(forkUnsafe(fiber, self, options?.startImmediately, true, options?.uninterruptible))));\n/** @internal */\nexport const awaitAllChildren = self => withFiber(fiber => {\n const initialChildren = fiber._children && new Set(fiber._children);\n return onExit(self, _ => {\n let children = fiber._children;\n if (children === undefined || children.size === 0) {\n return void_;\n } else if (initialChildren) {\n children = Iterable.filter(children, child => !initialChildren.has(child));\n }\n return asVoid(fiberAwaitAll(children));\n });\n});\n/** @internal */\nexport const forkIn = /*#__PURE__*/dual(args => isEffect(args[0]), (self, scope, options) => withFiber(parent => {\n const fiber = forkUnsafe(parent, self, options?.startImmediately, true, options?.uninterruptible);\n if (!fiber._exit) {\n if (scope.state._tag !== \"Closed\") {\n const key = {};\n const finalizer = () => withFiberId(interruptor => interruptor === fiber.id ? void_ : fiberInterrupt(fiber));\n scopeAddFinalizerUnsafe(scope, key, finalizer);\n fiber.addObserver(() => scopeRemoveFinalizerUnsafe(scope, key));\n } else {\n fiber.interruptUnsafe(parent.id, fiberStackAnnotations(parent));\n }\n }\n return succeed(fiber);\n}));\n/** @internal */\nexport const forkScoped = /*#__PURE__*/dual(args => isEffect(args[0]), (self, options) => flatMap(scope, scope => forkIn(self, scope, options)));\n// ----------------------------------------------------------------------------\n// execution\n// ----------------------------------------------------------------------------\n/** @internal */\nexport const runForkWith = context => (effect, options) => {\n const fiber = new FiberImpl(options?.scheduler ? Context.add(context, Scheduler.Scheduler, options.scheduler) : context, options?.uninterruptible !== true);\n fiber.evaluate(effect);\n if (fiber._exit) return fiber;\n if (options?.signal) {\n if (options.signal.aborted) {\n fiber.interruptUnsafe();\n } else {\n const abort = () => fiber.interruptUnsafe();\n options.signal.addEventListener(\"abort\", abort, {\n once: true\n });\n fiber.addObserver(() => options.signal.removeEventListener(\"abort\", abort));\n }\n }\n if (options?.onFiberStart) {\n options.onFiberStart(fiber);\n }\n return fiber;\n};\n/** @internal */\nexport const fiberRunIn = /*#__PURE__*/dual(2, (self, scope) => {\n if (self._exit) {\n return self;\n } else if (scope.state._tag === \"Closed\") {\n self.interruptUnsafe(self.id);\n return self;\n }\n const key = {};\n scopeAddFinalizerUnsafe(scope, key, () => fiberInterrupt(self));\n self.addObserver(() => scopeRemoveFinalizerUnsafe(scope, key));\n return self;\n});\n/** @internal */\nexport const runFork = /*#__PURE__*/runForkWith(/*#__PURE__*/Context.empty());\n/** @internal */\nexport const runCallbackWith = context => {\n const runFork = runForkWith(context);\n return (effect, options) => {\n const fiber = runFork(effect, options);\n if (options?.onExit) {\n fiber.addObserver(options.onExit);\n }\n return interruptor => {\n return fiber.interruptUnsafe(interruptor);\n };\n };\n};\n/** @internal */\nexport const runCallback = /*#__PURE__*/runCallbackWith(/*#__PURE__*/Context.empty());\n/** @internal */\nexport const runPromiseExitWith = context => {\n const runFork = runForkWith(context);\n return (effect, options) => {\n const fiber = runFork(effect, options);\n return new Promise(resolve => {\n fiber.addObserver(exit => resolve(exit));\n });\n };\n};\n/** @internal */\nexport const runPromiseExit = /*#__PURE__*/runPromiseExitWith(/*#__PURE__*/Context.empty());\n/** @internal */\nexport const runPromiseWith = context => {\n const runPromiseExit = runPromiseExitWith(context);\n return (effect, options) => runPromiseExit(effect, options).then(exit => {\n if (exit._tag === \"Failure\") {\n throw causeSquash(exit.cause);\n }\n return exit.value;\n });\n};\n/** @internal */\nexport const runPromise = /*#__PURE__*/runPromiseWith(/*#__PURE__*/Context.empty());\n/** @internal */\nexport const runSyncExitWith = context => {\n const runFork = runForkWith(context);\n return effect => {\n if (effectIsExit(effect)) return effect;\n const scheduler = new Scheduler.MixedScheduler(\"sync\");\n const fiber = runFork(effect, {\n scheduler\n });\n fiber._dispatcher?.flush();\n return fiber._exit ?? exitDie(new AsyncFiberError(fiber));\n };\n};\n/** @internal */\nexport const runSyncExit = /*#__PURE__*/runSyncExitWith(/*#__PURE__*/Context.empty());\n/** @internal */\nexport const runSyncWith = context => {\n const runSyncExit = runSyncExitWith(context);\n return effect => {\n const exit = runSyncExit(effect);\n if (exit._tag === \"Failure\") throw causeSquash(exit.cause);\n return exit.value;\n };\n};\n/** @internal */\nexport const runSync = /*#__PURE__*/runSyncWith(/*#__PURE__*/Context.empty());\nconst succeedTrue = /*#__PURE__*/succeed(true);\nconst succeedFalse = /*#__PURE__*/succeed(false);\nclass Latch {\n waiters = [];\n scheduled = undefined;\n _isOpen;\n constructor(isOpen) {\n this._isOpen = isOpen;\n }\n scheduleUnsafe(fiber) {\n if (this.waiters.length === 0) {\n return succeedTrue;\n }\n if (this.scheduled === undefined) {\n this.scheduled = this.waiters;\n fiber.currentDispatcher.scheduleTask(this.flushScheduled, 0);\n } else {\n for (let i = 0; i < this.waiters.length; i++) {\n this.scheduled.push(this.waiters[i]);\n }\n }\n this.waiters = [];\n return succeedTrue;\n }\n flushScheduled = () => {\n if (this.scheduled === undefined) return;\n const waiters = this.scheduled;\n this.scheduled = undefined;\n for (let i = 0; i < waiters.length; i++) {\n waiters[i](exitVoid);\n }\n };\n flushWaiters() {\n // swap both arrays out before any resume runs: a resumed waiter can\n // reentrantly close the latch and register new waiters, which must not\n // be drained by this flush\n const waiters = this.waiters;\n this.waiters = [];\n this.flushScheduled();\n for (let i = 0; i < waiters.length; i++) {\n waiters[i](exitVoid);\n }\n }\n open = /*#__PURE__*/withFiber(fiber => {\n if (this._isOpen) return succeedFalse;\n this._isOpen = true;\n return this.scheduleUnsafe(fiber);\n });\n release = /*#__PURE__*/withFiber(fiber => this._isOpen ? succeedFalse : this.scheduleUnsafe(fiber));\n openUnsafe() {\n if (this._isOpen) return false;\n this._isOpen = true;\n this.flushWaiters();\n return true;\n }\n await = /*#__PURE__*/callback(resume => {\n if (this._isOpen) {\n return resume(void_);\n }\n this.waiters.push(resume);\n return sync(() => {\n let index = this.waiters.indexOf(resume);\n if (index !== -1) {\n this.waiters.splice(index, 1);\n } else if (this.scheduled !== undefined) {\n index = this.scheduled.indexOf(resume);\n if (index !== -1) {\n this.scheduled.splice(index, 1);\n }\n }\n });\n });\n closeUnsafe() {\n if (!this._isOpen) return false;\n this._isOpen = false;\n return true;\n }\n close = /*#__PURE__*/sync(() => this.closeUnsafe());\n whenOpen = self => flatMap(this.await, () => self);\n isOpen() {\n return this._isOpen;\n }\n}\n/** @internal */\nexport const makeLatchUnsafe = open => new Latch(open ?? false);\n/** @internal */\nexport const makeLatch = open => sync(() => makeLatchUnsafe(open));\n// ----------------------------------------------------------------------------\n// Tracer\n// ----------------------------------------------------------------------------\n/** @internal */\nexport const tracer = /*#__PURE__*/withFiber(fiber => succeed(fiber.getRef(Tracer.Tracer)));\n/** @internal */\nexport const withTracer = /*#__PURE__*/dual(2, (effect, tracer) => provideService(effect, Tracer.Tracer, tracer));\n/** @internal */\nexport const withTracerEnabled = /*#__PURE__*/provideService(TracerEnabled);\n/** @internal */\nexport const withTracerTiming = /*#__PURE__*/provideService(TracerTimingEnabled);\nconst bigint0 = /*#__PURE__*/BigInt(0);\nconst NoopSpanProto = {\n _tag: \"Span\",\n spanId: \"noop\",\n traceId: \"noop\",\n sampled: false,\n status: {\n _tag: \"Ended\",\n startTime: bigint0,\n endTime: bigint0,\n exit: exitVoid\n },\n attributes: /*#__PURE__*/new Map(),\n links: [],\n kind: \"internal\",\n attribute() {},\n event() {},\n end() {},\n addLinks() {}\n};\n/** @internal */\nexport const noopSpan = options => Object.assign(Object.create(NoopSpanProto), options);\nconst filterDisablePropagation = span => {\n if (!span) return Option.none();\n return Context.get(span.annotations, Tracer.DisablePropagation) ? span._tag === \"Span\" ? filterDisablePropagation(Option.getOrUndefined(span.parent)) : Option.none() : Option.some(span);\n};\n/** @internal */\nexport const makeSpanUnsafe = (fiber, name, options) => {\n const disablePropagation = !fiber.getRef(TracerEnabled) || options?.annotations && Context.get(options.annotations, Tracer.DisablePropagation);\n const parent = options?.parent !== undefined ? Option.some(options.parent) : options?.root ? Option.none() : filterDisablePropagation(fiber.cache.span);\n let span;\n if (disablePropagation) {\n span = noopSpan({\n name,\n parent,\n annotations: Context.add(options?.annotations ?? Context.empty(), Tracer.DisablePropagation, true)\n });\n } else {\n const tracer = fiber.getRef(Tracer.Tracer);\n const clock = fiber.getRef(ClockRef);\n const timingEnabled = fiber.getRef(TracerTimingEnabled);\n const annotationsFromEnv = fiber.getRef(TracerSpanAnnotations);\n const linksFromEnv = fiber.getRef(TracerSpanLinks);\n const level = options?.level ?? fiber.getRef(Tracer.CurrentTraceLevel);\n const links = options?.links !== undefined ? [...linksFromEnv, ...options.links] : linksFromEnv.length === 0 ? [] : linksFromEnv.slice();\n span = tracer.span({\n name,\n parent,\n annotations: options?.annotations ?? Context.empty(),\n links,\n startTime: timingEnabled ? clock.currentTimeNanosUnsafe() : bigint0,\n kind: options?.kind ?? \"internal\",\n root: options?.root ?? Option.isNone(parent),\n sampled: options?.sampled ?? (Option.isSome(parent) && parent.value.sampled === false ? false : !isLogLevelGreaterThan(fiber.getRef(Tracer.MinimumTraceLevel), level))\n });\n for (const key in annotationsFromEnv) {\n span.attribute(key, annotationsFromEnv[key]);\n }\n if (options?.attributes !== undefined) {\n for (const key in options.attributes) {\n span.attribute(key, options.attributes[key]);\n }\n }\n }\n return span;\n};\n/** @internal */\nexport const makeSpan = (name, options) => withFiber(fiber => succeed(makeSpanUnsafe(fiber, name, options)));\n/** @internal */\nexport const makeSpanScoped = (name, options) => uninterruptible(withFiber(fiber => {\n const scope = Context.getUnsafe(fiber.context, scopeTag);\n const span = makeSpanUnsafe(fiber, name, options ?? {});\n const clock = fiber.getRef(ClockRef);\n const timingEnabled = fiber.getRef(TracerTimingEnabled);\n return as(scopeAddFinalizerExit(scope, exit => endSpan(span, exit, clock, timingEnabled)), span);\n}));\n/** @internal */\nexport const withSpanScoped = function () {\n const dataFirst = typeof arguments[0] !== \"string\";\n const name = dataFirst ? arguments[1] : arguments[0];\n const options = addSpanStackTrace(dataFirst ? arguments[2] : arguments[1]);\n if (dataFirst) {\n const self = arguments[0];\n return flatMap(makeSpanScoped(name, options), span => withParentSpan(self, span, options));\n }\n return self => flatMap(makeSpanScoped(name, options), span => withParentSpan(self, span, options));\n};\nconst provideSpanStackFrame = (name, stack) => {\n stack = typeof stack === \"function\" ? stack : constUndefined;\n return updateService(CurrentStackFrame, parent => ({\n name,\n stack,\n parent\n }));\n};\n/** @internal */\nexport const spanAnnotations = TracerSpanAnnotations;\n/** @internal */\nexport const spanLinks = TracerSpanLinks;\n/** @internal */\nexport const linkSpans = /*#__PURE__*/dual(args => isEffect(args[0]), (self, span, attributes = {}) => {\n const spans = Array.isArray(span) ? span : [span];\n const links = spans.map(span => ({\n span,\n attributes\n }));\n return updateService(self, TracerSpanLinks, current => [...current, ...links]);\n});\n/** @internal */\nexport const endSpan = (span, exit, clock, timingEnabled) => sync(() => {\n if (span.status._tag === \"Ended\") return;\n span.end(timingEnabled ? clock.currentTimeNanosUnsafe() : bigint0, exit);\n});\n/** @internal */\nexport const useSpan = (name, ...args) => {\n const options = args.length === 1 ? undefined : args[0];\n const evaluate = args[args.length - 1];\n return withFiber(fiber => {\n const span = makeSpanUnsafe(fiber, name, options);\n const clock = fiber.getRef(ClockRef);\n const timingEnabled = fiber.getRef(TracerTimingEnabled);\n return onExit(suspend(() => internalCall(() => evaluate(span))), exit => endSpan(span, exit, clock, timingEnabled));\n });\n};\nconst provideParentSpan = /*#__PURE__*/provideService(Tracer.ParentSpan);\n/** @internal */\nexport const withParentSpan = function () {\n const dataFirst = isEffect(arguments[0]);\n const span = dataFirst ? arguments[1] : arguments[0];\n let options = dataFirst ? arguments[2] : arguments[1];\n let provideStackFrame = identity;\n if (span._tag === \"Span\") {\n options = addSpanStackTrace(options);\n provideStackFrame = provideSpanStackFrame(span.name, options?.captureStackTrace);\n }\n if (dataFirst) {\n return provideParentSpan(provideStackFrame(arguments[0]), span);\n }\n return self => provideParentSpan(provideStackFrame(self), span);\n};\n/** @internal */\nexport const withSpan = function () {\n const dataFirst = typeof arguments[0] !== \"string\";\n const name = dataFirst ? arguments[1] : arguments[0];\n const traceOptions = addSpanStackTrace(arguments[2]);\n if (dataFirst) {\n const self = arguments[0];\n return useSpan(name, arguments[2], span => withParentSpan(self, span, traceOptions));\n }\n const fnArg = typeof arguments[1] === \"function\" ? arguments[1] : undefined;\n const options = fnArg ? undefined : arguments[1];\n return (self, ...args) => useSpan(name, fnArg ? fnArg(...args) : options, span => withParentSpan(self, span, traceOptions));\n};\n/** @internal */\nexport const annotateSpans = /*#__PURE__*/dual(args => isEffect(args[0]), (effect, ...args) => updateService(effect, TracerSpanAnnotations, annotations => {\n const newAnnotations = args.length === 1 ? {\n ...annotations,\n ...args[0]\n } : {\n ...annotations\n };\n if (args.length === 1) {\n return newAnnotations;\n } else {\n InternalRecord.assignProperty(newAnnotations, args[0], args[1]);\n }\n return newAnnotations;\n}));\n/** @internal */\nexport const annotateCurrentSpan = (...args) => withFiber(fiber => {\n const span = fiber.currentSpanLocal;\n if (span) {\n if (args.length === 1) {\n for (const [key, value] of Object.entries(args[0])) {\n span.attribute(key, value);\n }\n } else {\n span.attribute(args[0], args[1]);\n }\n }\n return void_;\n});\n/** @internal */\nexport const currentSpan = /*#__PURE__*/withFiber(fiber => {\n const span = fiber.currentSpanLocal;\n return span ? succeed(span) : fail(new NoSuchElementError());\n});\n/** @internal */\nexport const currentParentSpan = /*#__PURE__*/serviceOptional(Tracer.ParentSpan);\n// ----------------------------------------------------------------------------\n// Clock\n// ----------------------------------------------------------------------------\n/** @internal */\nexport const ClockRef = /*#__PURE__*/Context.Reference(\"effect/Clock\", {\n defaultValue: () => new ClockImpl()\n});\nconst MAX_TIMER_MILLIS = 2 ** 31 - 1;\nclass ClockImpl {\n currentTimeMillisUnsafe() {\n return Date.now();\n }\n currentTimeMillis = /*#__PURE__*/sync(() => this.currentTimeMillisUnsafe());\n currentTimeNanosUnsafe() {\n return wallTimeNanos();\n }\n currentTimeNanos = /*#__PURE__*/sync(() => this.currentTimeNanosUnsafe());\n monotonicTimeNanosUnsafe() {\n return monotonicNowNanos();\n }\n monotonicTimeNanos = /*#__PURE__*/sync(() => this.monotonicTimeNanosUnsafe());\n sleep(duration) {\n return this.sleepMillis(Duration.toMillis(duration));\n }\n sleepMillis(millis) {\n if (millis <= 0) return yieldNow;else if (!Number.isFinite(millis)) return never;\n return callback(resume => {\n const continuation = millis > MAX_TIMER_MILLIS ? this.sleepMillis(millis - MAX_TIMER_MILLIS) : void_;\n const handle = setTimeout(() => resume(continuation), Math.min(millis, MAX_TIMER_MILLIS));\n return sync(() => clearTimeout(handle));\n });\n }\n}\nconst nanosPerMilli = /*#__PURE__*/BigInt(1_000_000);\nconst monotonicNowNanos = /*#__PURE__*/function () {\n const processHrtime = globalThis.process?.hrtime;\n if (typeof processHrtime?.bigint === \"function\") {\n return () => processHrtime.bigint();\n }\n if (typeof performance !== \"undefined\" && typeof performance.now === \"function\") {\n return () => BigInt(Math.round(performance.now() * 1_000_000));\n }\n let previous = /*#__PURE__*/BigInt(0);\n return () => {\n const current = BigInt(Date.now()) * nanosPerMilli;\n if (current > previous) {\n previous = current;\n }\n return previous;\n };\n}();\nconst wallTimeNanos = /*#__PURE__*/function () {\n const reanchorThresholdNanos = /*#__PURE__*/BigInt(1_000_000_000);\n let origin;\n return () => {\n const monotonic = monotonicNowNanos();\n const wall = BigInt(Date.now()) * nanosPerMilli;\n if (origin === undefined) {\n origin = wall - monotonic;\n } else {\n const projected = origin + monotonic;\n const skew = wall > projected ? wall - projected : projected - wall;\n if (skew > reanchorThresholdNanos) {\n origin = wall - monotonic;\n }\n }\n return origin + monotonic;\n };\n}();\n/** @internal */\nexport const clockWith = f => withFiber(fiber => f(fiber.getRef(ClockRef)));\n/** @internal */\nexport const sleep = duration => clockWith(clock => clock.sleep(Duration.fromInputUnsafe(duration)));\n/** @internal */\nexport const currentTimeMillis = /*#__PURE__*/clockWith(clock => clock.currentTimeMillis);\n/** @internal */\nexport const currentTimeNanos = /*#__PURE__*/clockWith(clock => clock.currentTimeNanos);\n/** @internal */\nexport const monotonicTimeNanos = /*#__PURE__*/clockWith(clock => clock.monotonicTimeNanos);\n// ----------------------------------------------------------------------------\n// Errors\n// ----------------------------------------------------------------------------\n/** @internal */\nexport const TimeoutErrorTypeId = \"~effect/Cause/TimeoutError\";\n/** @internal */\nexport const isTimeoutError = u => hasProperty(u, TimeoutErrorTypeId);\n/** @internal */\nexport class TimeoutError extends /*#__PURE__*/TaggedError(\"TimeoutError\") {\n [TimeoutErrorTypeId] = TimeoutErrorTypeId;\n constructor(message) {\n super({\n message\n });\n }\n}\n/** @internal */\nexport const IllegalArgumentErrorTypeId = \"~effect/Cause/IllegalArgumentError\";\n/** @internal */\nexport const isIllegalArgumentError = u => hasProperty(u, IllegalArgumentErrorTypeId);\n/** @internal */\nexport class IllegalArgumentError extends /*#__PURE__*/TaggedError(\"IllegalArgumentError\") {\n [IllegalArgumentErrorTypeId] = IllegalArgumentErrorTypeId;\n constructor(message) {\n super({\n message\n });\n }\n}\n/** @internal */\nexport const ExceededCapacityErrorTypeId = \"~effect/Cause/ExceededCapacityError\";\n/** @internal */\nexport const isExceededCapacityError = u => hasProperty(u, ExceededCapacityErrorTypeId);\n/** @internal */\nexport class ExceededCapacityError extends /*#__PURE__*/TaggedError(\"ExceededCapacityError\") {\n [ExceededCapacityErrorTypeId] = ExceededCapacityErrorTypeId;\n constructor(message) {\n super({\n message\n });\n }\n}\n/** @internal */\nexport const AsyncFiberErrorTypeId = \"~effect/Cause/AsyncFiberError\";\n/** @internal */\nexport const isAsyncFiberError = u => hasProperty(u, AsyncFiberErrorTypeId);\n/** @internal */\nexport class AsyncFiberError extends /*#__PURE__*/TaggedError(\"AsyncFiberError\") {\n [AsyncFiberErrorTypeId] = AsyncFiberErrorTypeId;\n constructor(fiber) {\n super({\n message: \"An asynchronous Effect was executed with Effect.runSync\",\n fiber\n });\n }\n}\n/** @internal */\nexport const UnknownErrorTypeId = \"~effect/Cause/UnknownError\";\n/** @internal */\nexport const isUnknownError = u => hasProperty(u, UnknownErrorTypeId);\n/** @internal */\nexport class UnknownError extends /*#__PURE__*/TaggedError(\"UnknownError\") {\n [UnknownErrorTypeId] = UnknownErrorTypeId;\n constructor(cause, message) {\n super({\n message,\n cause\n });\n }\n}\n// ----------------------------------------------------------------------------\n// Console\n// ----------------------------------------------------------------------------\n/** @internal */\nexport const ConsoleRef = /*#__PURE__*/Context.Reference(\"effect/Console\", {\n defaultValue: () => globalThis.console\n});\n// ----------------------------------------------------------------------------\n// LogLevel\n// ----------------------------------------------------------------------------\n/** @internal */\nexport const logLevelToOrder = level => {\n switch (level) {\n case \"All\":\n return Number.MIN_SAFE_INTEGER;\n case \"Fatal\":\n return 50_000;\n case \"Error\":\n return 40_000;\n case \"Warn\":\n return 30_000;\n case \"Info\":\n return 20_000;\n case \"Debug\":\n return 10_000;\n case \"Trace\":\n return 0;\n case \"None\":\n return Number.MAX_SAFE_INTEGER;\n }\n};\n/** @internal */\nexport const LogLevelOrder = /*#__PURE__*/Order.mapInput(Order.Number, logLevelToOrder);\n/** @internal */\nexport const isLogLevelGreaterThan = /*#__PURE__*/Order.isGreaterThan(LogLevelOrder);\n// ----------------------------------------------------------------------------\n// Logger\n// ----------------------------------------------------------------------------\n/** @internal */\nexport const CurrentLoggers = /*#__PURE__*/Context.Reference(\"effect/Logger/CurrentLoggers\", {\n defaultValue: () => new Set([defaultLogger, tracerLogger])\n});\n/** @internal */\nexport const LogToStderr = /*#__PURE__*/Context.Reference(\"effect/Logger/LogToStderr\", {\n defaultValue: constFalse\n});\n/** @internal */\nexport const annotateLogsScoped = function () {\n const entries = typeof arguments[0] === \"string\" ? [[arguments[0], arguments[1]]] : Object.entries(arguments[0]);\n return uninterruptible(withFiber(fiber => {\n const prev = fiber.getRef(CurrentLogAnnotations);\n const next = {\n ...prev\n };\n for (let i = 0; i < entries.length; i++) {\n const [key, value] = entries[i];\n InternalRecord.assignProperty(next, key, value);\n }\n fiber.setContext(Context.add(fiber.context, CurrentLogAnnotations, next));\n return scopeAddFinalizerExit(Context.getUnsafe(fiber.context, scopeTag), _ => {\n const current = fiber.getRef(CurrentLogAnnotations);\n const next = {\n ...current\n };\n for (let i = 0; i < entries.length; i++) {\n const [key, value] = entries[i];\n if (current[key] !== value && !Object.is(current[key], value)) continue;\n if (Object.hasOwn(prev, key)) {\n InternalRecord.assignProperty(next, key, prev[key]);\n } else {\n delete next[key];\n }\n }\n fiber.setContext(Context.add(fiber.context, CurrentLogAnnotations, next));\n return void_;\n });\n }));\n};\n/** @internal */\nexport const LoggerTypeId = \"~effect/Logger\";\nconst LoggerProto = {\n [LoggerTypeId]: {\n _Message: identity,\n _Output: identity\n },\n pipe() {\n return pipeArguments(this, arguments);\n }\n};\n/** @internal */\nexport const loggerMake = log => {\n const self = Object.create(LoggerProto);\n self.log = log;\n return self;\n};\n/**\n * Sanitize a given string by replacing spaces, equal signs, and double quotes\n * with underscores.\n *\n * @internal\n */\nexport const formatLabel = key => key.replace(/[\\s=\"]/g, \"_\");\n/**\n * Formats a log span into a `<label>=<value>ms` string.\n *\n * @internal\n */\nexport const formatLogSpan = (self, now) => {\n const label = formatLabel(self[0]);\n return `${label}=${now - self[1]}ms`;\n};\n/** @internal */\nexport const structuredMessage = u => {\n switch (typeof u) {\n case \"function\":\n case \"symbol\":\n {\n return String(u);\n }\n default:\n {\n return toJson(u);\n }\n }\n};\n/** @internal */\nexport const logWithLevel = level => (...message) => {\n let cause = undefined;\n for (let i = 0, len = message.length; i < len; i++) {\n const msg = message[i];\n if (isCause(msg)) {\n if (cause) {\n ;\n message.splice(i, 1);\n } else {\n message = message.slice(0, i).concat(message.slice(i + 1));\n }\n cause = cause ? causeFromReasons(cause.reasons.concat(msg.reasons)) : msg;\n i--;\n }\n }\n if (cause === undefined) {\n cause = causeEmpty;\n }\n return withFiber(fiber => {\n const logLevel = level ?? fiber.cache.logLevel;\n if (isLogLevelGreaterThan(fiber.cache.minimumLogLevel, logLevel)) {\n return void_;\n }\n const clock = fiber.getRef(ClockRef);\n const loggers = fiber.getRef(CurrentLoggers);\n if (loggers.size > 0) {\n const date = new Date(clock.currentTimeMillisUnsafe());\n for (const logger of loggers) {\n logger.log({\n cause,\n fiber,\n date,\n logLevel,\n message\n });\n }\n }\n return void_;\n });\n};\nconst withColor = (text, ...colors) => {\n let out = \"\";\n for (let i = 0; i < colors.length; i++) {\n out += `\\x1b[${colors[i]}m`;\n }\n return out + text + \"\\x1b[0m\";\n};\nconst withColorNoop = (text, ..._colors) => text;\nconst colors = {\n bold: \"1\",\n red: \"31\",\n green: \"32\",\n yellow: \"33\",\n blue: \"34\",\n cyan: \"36\",\n white: \"37\",\n gray: \"90\",\n black: \"30\",\n bgBrightRed: \"101\"\n};\nconst logLevelColors = {\n None: [],\n All: [],\n Trace: [colors.gray],\n Debug: [colors.blue],\n Info: [colors.green],\n Warn: [colors.yellow],\n Error: [colors.red],\n Fatal: [colors.bgBrightRed, colors.black]\n};\nconst logLevelStyle = {\n None: \"\",\n All: \"\",\n Trace: \"color:gray\",\n Debug: \"color:blue\",\n Info: \"color:green\",\n Warn: \"color:orange\",\n Error: \"color:red\",\n Fatal: \"background-color:red;color:white\"\n};\nconst defaultDateFormat = date => `${date.getHours().toString().padStart(2, \"0\")}:${date.getMinutes().toString().padStart(2, \"0\")}:${date.getSeconds().toString().padStart(2, \"0\")}.${date.getMilliseconds().toString().padStart(3, \"0\")}`;\n/** @internal */\nexport const consolePretty = options => {\n // evaluated lazily so the module-level bundle stays free of `process`\n // property accesses, which bundlers must retain as possible side effects\n const process = globalThis.process;\n const hasProcessStdout = typeof process?.stdout === \"object\" && process.stdout !== null;\n const isDeno = \"Deno\" in globalThis;\n const mode = options?.mode ?? \"auto\";\n const isTtyLogger = mode === \"auto\" ? hasProcessStdout || isDeno : mode === \"tty\";\n return isTtyLogger ? prettyLoggerTty(options) : prettyLoggerBrowser(options);\n};\n/** @internal */\nexport const prettyLoggerTty = options => {\n const formatDate = options?.formatDate ?? defaultDateFormat;\n // evaluated lazily so the module-level bundle stays free of `process`\n // property accesses, which bundlers must retain as possible side effects\n const process = globalThis.process;\n const hasProcessStdout = typeof process?.stdout === \"object\" && process.stdout !== null;\n const processStdoutIsTTY = hasProcessStdout && process.stdout.isTTY === true;\n const showColors = typeof options?.colors === \"boolean\" ? options.colors : processStdoutIsTTY;\n const color = showColors ? withColor : withColorNoop;\n const processIsBun = process?.isBun === true;\n return loggerMake(({\n cause,\n date,\n fiber,\n logLevel,\n message: message_\n }) => {\n const console = fiber.getRef(ConsoleRef);\n // oxlint-disable-next-line no-console\n const log = fiber.getRef(LogToStderr) ? console.error : console.log;\n const message = Array.isArray(message_) ? message_.slice() : [message_];\n let firstLine = color(`[${formatDate(date)}]`, colors.white) + ` ${color(logLevel.toUpperCase(), ...logLevelColors[logLevel])}` + ` (#${fiber.id})`;\n const now = date.getTime();\n const spans = fiber.getRef(CurrentLogSpans);\n for (const span of spans) {\n firstLine += \" \" + formatLogSpan(span, now);\n }\n firstLine += \":\";\n let messageIndex = 0;\n if (message.length > 0) {\n const firstMaybeString = structuredMessage(message[0]);\n if (typeof firstMaybeString === \"string\") {\n firstLine += \" \" + color(firstMaybeString, colors.bold, colors.cyan);\n messageIndex++;\n }\n }\n log(firstLine);\n // oxlint-disable-next-line no-console\n if (!processIsBun) console.group();\n if (cause.reasons.length > 0) {\n log(causePretty(cause));\n }\n if (messageIndex < message.length) {\n for (; messageIndex < message.length; messageIndex++) {\n log(redact(message[messageIndex]));\n }\n }\n const annotations = fiber.getRef(CurrentLogAnnotations);\n for (const [key, value] of Object.entries(annotations)) {\n log(color(`${key}:`, colors.bold, colors.white), redact(value));\n }\n // oxlint-disable-next-line no-console\n if (!processIsBun) console.groupEnd();\n });\n};\n/** @internal */\nexport const prettyLoggerBrowser = options => {\n const showColors = options?.colors !== false;\n const color = showColors ? \"%c\" : \"\";\n const formatDate = options?.formatDate ?? defaultDateFormat;\n return loggerMake(({\n cause,\n date,\n fiber,\n logLevel,\n message: message_\n }) => {\n const console = fiber.getRef(ConsoleRef);\n const message = Array.isArray(message_) ? message_.slice() : [message_];\n let firstLine = `${color}[${formatDate(date)}]`;\n const firstParams = [];\n if (showColors) {\n firstParams.push(\"color:gray\");\n }\n firstLine += ` ${color}${logLevel.toUpperCase()}${color} (#${fiber.id})`;\n if (showColors) {\n firstParams.push(logLevelStyle[logLevel], \"\");\n }\n const now = date.getTime();\n const spans = fiber.getRef(CurrentLogSpans);\n for (const span of spans) {\n firstLine += \" \" + formatLogSpan(span, now);\n }\n firstLine += \":\";\n let messageIndex = 0;\n if (message.length > 0) {\n const firstMaybeString = structuredMessage(message[0]);\n if (typeof firstMaybeString === \"string\") {\n firstLine += ` ${color}${firstMaybeString}`;\n if (showColors) {\n firstParams.push(\"color:deepskyblue\");\n }\n messageIndex++;\n }\n }\n // oxlint-disable-next-line no-console\n console.groupCollapsed(firstLine, ...firstParams);\n if (cause.reasons.length > 0) {\n // oxlint-disable-next-line no-console\n console.error(causePretty(cause));\n }\n if (messageIndex < message.length) {\n for (; messageIndex < message.length; messageIndex++) {\n // oxlint-disable-next-line no-console\n console.log(redact(message[messageIndex]));\n }\n }\n const annotations = fiber.getRef(CurrentLogAnnotations);\n for (const [key, value] of Object.entries(annotations)) {\n const redacted = redact(value);\n if (showColors) {\n // oxlint-disable-next-line no-console\n console.log(`%c${key}:`, \"color:gray\", redacted);\n } else {\n // oxlint-disable-next-line no-console\n console.log(`${key}:`, redacted);\n }\n }\n // oxlint-disable-next-line no-console\n console.groupEnd();\n });\n};\n/** @internal */\nexport const defaultLogger = /*#__PURE__*/loggerMake(({\n cause,\n date,\n fiber,\n logLevel,\n message\n}) => {\n const message_ = Array.isArray(message) ? message.slice() : [message];\n if (cause.reasons.length > 0) {\n message_.push(causePretty(cause));\n }\n const now = date.getTime();\n const spans = fiber.getRef(CurrentLogSpans);\n let spanString = \"\";\n for (const span of spans) {\n spanString += ` ${formatLogSpan(span, now)}`;\n }\n const annotations = fiber.getRef(CurrentLogAnnotations);\n if (Object.keys(annotations).length > 0) {\n message_.push(annotations);\n }\n const console = fiber.getRef(ConsoleRef);\n // oxlint-disable-next-line no-console\n const log = fiber.getRef(LogToStderr) ? console.error : console.log;\n log(`[${defaultDateFormat(date)}] ${logLevel.toUpperCase()} (#${fiber.id})${spanString}:`, ...message_);\n});\n/** @internal */\nexport const tracerLogger = /*#__PURE__*/loggerMake(({\n cause,\n fiber,\n logLevel,\n message\n}) => {\n const clock = fiber.getRef(ClockRef);\n const annotations = fiber.getRef(CurrentLogAnnotations);\n const span = fiber.cache.span;\n if (span === undefined || span._tag === \"ExternalSpan\") return;\n const attributes = {};\n for (const [key, value] of Object.entries(annotations)) {\n InternalRecord.assignProperty(attributes, key, value);\n }\n attributes[\"effect.fiberId\"] = fiber.id;\n attributes[\"effect.logLevel\"] = logLevel.toUpperCase();\n if (cause.reasons.length > 0) {\n attributes[\"effect.cause\"] = causePretty(cause);\n }\n span.event(toStringUnknown(Array.isArray(message) && message.length === 1 ? message[0] : message), clock.currentTimeNanosUnsafe(), attributes);\n});\n/** @internal */\nexport function interruptChildrenPatch() {\n fiberMiddleware.interruptChildren ??= fiberInterruptChildren;\n}\n/** @internal */\nconst undefined_ = /*#__PURE__*/succeed(undefined);\n/** @internal */\nexport { undefined_ as undefined };\n// ----------------------------------------------------------------------------\n// ErrorReporter\n// ----------------------------------------------------------------------------\n/** @internal */\nexport const withErrorReporting = /*#__PURE__*/dual(args => isEffect(args[0]), (self, options) => onError(self, cause => withFiber(fiber => {\n reportCauseUnsafe(fiber, cause, options?.defectsOnly);\n return void_;\n})));\n/** @internal */\nexport const reportCauseUnsafe = (fiber, cause, defectsOnly) => {\n const reporters = fiber.getRef(CurrentErrorReporters);\n if (reporters.size === 0) return;\n if (defectsOnly && !hasDies(cause)) return;\n const opts = {\n cause,\n fiber,\n timestamp: fiber.getRef(ClockRef).currentTimeNanosUnsafe()\n };\n reporters.forEach(reporter => reporter.report(opts));\n};\n//# sourceMappingURL=effect.js.map","import * as core from \"./internal/core.js\";\nimport * as effect from \"./internal/effect.js\";\nconst TypeId = core.ExitTypeId;\n/**\n * Checks whether an unknown value is an Exit.\n *\n * **When to use**\n *\n * Use to validate unknown values at system boundaries and narrow them to\n * `Exit<unknown, unknown>`.\n *\n * **Details**\n *\n * Does not inspect the contents of the Exit. Returns `true` for both Success\n * and Failure exits.\n *\n * **Example** (Checking if a value is an Exit)\n *\n * ```ts import.meta.vitest\n * import { Exit } from \"effect\"\n *\n * Exit.isExit(Exit.succeed(42)) // => true\n * Exit.isExit(Exit.fail(\"err\")) // => true\n * Exit.isExit(\"not an exit\") // => false\n * ```\n *\n * @see {@link isSuccess} to check for a successful Exit\n * @see {@link isFailure} to check for a failed Exit\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isExit = core.isExit;\n/**\n * Creates a successful Exit containing the given value.\n *\n * **When to use**\n *\n * Use when you need an Exit that contains a known success value.\n *\n * **Details**\n *\n * Returns a `Success<A>` with the provided value. Does not perform any\n * computation.\n *\n * **Example** (Creating a successful Exit)\n *\n * ```ts import.meta.vitest\n * import { Exit } from \"effect\"\n *\n * Exit.succeed(42) // => Exit.succeed(42)\n * ```\n *\n * @see {@link fail} to create a failed Exit\n * @see {@link void_ void} for a pre-allocated success with no value\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const succeed = core.exitSucceed;\n/**\n * Creates a failed Exit from a Cause.\n *\n * **When to use**\n *\n * Use when you already have a `Cause<E>` and want to wrap it in an Exit\n * for advanced error handling where you need full control over the Cause\n * structure.\n *\n * **Details**\n *\n * Returns a `Failure<never, E>`. If you only have an error value, use\n * {@link fail} instead.\n *\n * **Example** (Creating a failed Exit from a Cause)\n *\n * ```ts import.meta.vitest\n * import { Cause, Exit } from \"effect\"\n *\n * Exit.failCause(Cause.fail(\"Something went wrong\")) // => Exit.fail(\"Something went wrong\")\n * ```\n *\n * @see {@link fail} to create a Failure from a plain error value\n * @see {@link die} to create a Failure from a defect\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const failCause = core.exitFailCause;\n/**\n * Creates a failed Exit from a typed error value.\n *\n * **When to use**\n *\n * Use when you need to represent an expected typed failure as an `Exit`.\n *\n * **Details**\n *\n * The error is wrapped in a `Cause.Fail` internally.\n *\n * Returns a `Failure<never, E>`.\n *\n * **Example** (Creating a failed Exit)\n *\n * ```ts import.meta.vitest\n * import { Exit } from \"effect\"\n *\n * Exit.fail(\"Something went wrong\") // => Exit.fail(\"Something went wrong\")\n * ```\n *\n * @see {@link succeed} to create a successful Exit\n * @see {@link die} to create a Failure from an unexpected defect\n * @see {@link failCause} to create a Failure from a full Cause\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fail = core.exitFail;\n/**\n * Creates a failed Exit from a defect (unexpected error).\n *\n * **When to use**\n *\n * Use when you need unexpected, unrecoverable errors that should not appear in\n * the typed error channel.\n *\n * **Details**\n *\n * The defect is wrapped in a `Cause.Die` internally.\n *\n * Returns a `Failure<never>` with `E = never`, since defects do not appear in\n * the typed error channel.\n *\n * **Example** (Creating a defect Exit)\n *\n * ```ts import.meta.vitest\n * import { Exit } from \"effect\"\n *\n * Exit.die(\"Unexpected error\") // => Exit.die(\"Unexpected error\")\n * ```\n *\n * @see {@link fail} to create a Failure from a typed error\n * @see {@link hasDies} to check whether an Exit contains defects\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const die = core.exitDie;\n/**\n * Creates a failed Exit representing fiber interruption.\n *\n * **When to use**\n *\n * Use to signal that a fiber was interrupted.\n *\n * **Details**\n *\n * Optionally pass a fiber ID to identify which fiber was interrupted. Returns\n * a `Failure<never>` with an `Interrupt` cause.\n *\n * **Example** (Creating an interruption Exit)\n *\n * ```ts import.meta.vitest\n * import { Exit } from \"effect\"\n *\n * Exit.interrupt(123) // => Exit.interrupt(123)\n * ```\n *\n * @see {@link hasInterrupts} to check whether an Exit contains interruptions\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const interrupt = effect.exitInterrupt;\nconst void_ = effect.exitVoid;\nexport {\n/**\n * Provides a pre-allocated successful Exit with a `void` value.\n *\n * **When to use**\n *\n * Use when you need a shared successful `Exit` with no meaningful value.\n *\n * **Details**\n *\n * Equivalent to `Exit.succeed(undefined)` but shared as a single instance,\n * avoiding allocation for a common case.\n *\n * **Example** (Referencing the void Exit)\n *\n * ```ts import.meta.vitest\n * import { Exit } from \"effect\"\n *\n * Exit.void // => Exit.succeed(undefined)\n * ```\n *\n * @see {@link succeed} to create a success with a specific value\n * @see {@link asVoid} to discard the value of an existing Exit\n *\n * @category constructors\n * @since 2.0.0\n */\nvoid_ as void };\n/**\n * Checks whether an Exit is a Success.\n *\n * **When to use**\n *\n * Use as a type guard to narrow `Exit<A, E>` to `Success<A, E>` and access the\n * `value` property.\n *\n * **Example** (Narrowing to success)\n *\n * ```ts import.meta.vitest\n * import { Exit } from \"effect\"\n *\n * const exit = Exit.succeed(42)\n *\n * if (Exit.isSuccess(exit)) {\n * exit.value // => 42\n * }\n * ```\n *\n * @see {@link isFailure} for the opposite check\n * @see {@link match} for exhaustive pattern matching\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isSuccess = effect.exitIsSuccess;\n/**\n * Checks whether an Exit is a Failure.\n *\n * **When to use**\n *\n * Use as a type guard to narrow `Exit<A, E>` to `Failure<A, E>` and access the\n * `cause` property.\n *\n * **Example** (Narrowing to failure)\n *\n * ```ts import.meta.vitest\n * import { Cause, Exit } from \"effect\"\n *\n * const exit = Exit.fail(\"error\")\n *\n * if (Exit.isFailure(exit)) {\n * exit.cause // => Cause.fail(\"error\")\n * }\n * ```\n *\n * @see {@link isSuccess} for the opposite check\n * @see {@link match} for exhaustive pattern matching\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isFailure = effect.exitIsFailure;\n/**\n * Checks whether a failed Exit contains typed errors (Fail reasons).\n *\n * **When to use**\n *\n * Use to distinguish typed failures from defects or interruptions.\n *\n * **Details**\n *\n * Returns `false` for successful exits. Only checks for `Fail` reasons in the\n * Cause. A Cause with only `Die` or `Interrupt` reasons returns `false`.\n *\n * **Example** (Checking for typed errors)\n *\n * ```ts import.meta.vitest\n * import { Exit } from \"effect\"\n *\n * Exit.hasFails(Exit.fail(\"err\")) // => true\n * Exit.hasFails(Exit.die(\"bug\")) // => false\n * Exit.hasFails(Exit.succeed(42)) // => false\n * ```\n *\n * @see {@link hasDies} to check for defects\n * @see {@link hasInterrupts} to check for interruptions\n *\n * @category guards\n * @since 4.0.0\n */\nexport const hasFails = effect.exitHasFails;\n/**\n * Checks whether a failed Exit contains defects (Die reasons).\n *\n * **When to use**\n *\n * Use to check whether an `Exit` failure cause contains unexpected errors.\n *\n * **Details**\n *\n * Returns `false` for successful exits. Only checks for `Die` reasons in the\n * Cause. A Cause with only `Fail` or `Interrupt` reasons returns `false`.\n *\n * **Example** (Checking for defects)\n *\n * ```ts import.meta.vitest\n * import { Exit } from \"effect\"\n *\n * Exit.hasDies(Exit.die(\"bug\")) // => true\n * Exit.hasDies(Exit.fail(\"err\")) // => false\n * Exit.hasDies(Exit.succeed(42)) // => false\n * ```\n *\n * @see {@link hasFails} to check for typed errors\n * @see {@link hasInterrupts} to check for interruptions\n *\n * @category guards\n * @since 4.0.0\n */\nexport const hasDies = effect.exitHasDies;\n/**\n * Checks whether a failed Exit contains interruptions (Interrupt reasons).\n *\n * **When to use**\n *\n * Use to check whether an `Exit` contains fiber interruption.\n *\n * **Details**\n *\n * Returns `false` for successful exits. Only checks for `Interrupt` reasons in\n * the Cause. A Cause with only `Fail` or `Die` reasons returns `false`.\n *\n * **Example** (Checking for interruptions)\n *\n * ```ts import.meta.vitest\n * import { Exit } from \"effect\"\n *\n * Exit.hasInterrupts(Exit.interrupt(1)) // => true\n * Exit.hasInterrupts(Exit.fail(\"err\")) // => false\n * Exit.hasInterrupts(Exit.succeed(42)) // => false\n * ```\n *\n * @see {@link hasFails} to check for typed errors\n * @see {@link hasDies} to check for defects\n *\n * @category guards\n * @since 4.0.0\n */\nexport const hasInterrupts = effect.exitHasInterrupts;\n/**\n * Extracts the Success variant from an Exit as a Result.\n *\n * **When to use**\n *\n * Use when composing Exit checks with `Filter` or other `Result`-based\n * filtering APIs and you want the full Success wrapper.\n *\n * **Details**\n *\n * Returns `Result.succeed(success)` when the Exit is a Success, or\n * `Result.fail(failure)` with the original Failure otherwise.\n *\n * **Gotchas**\n *\n * This is not an `Option` accessor or an Effect failure. A failed extraction is\n * represented as data in the `Result` failure channel.\n *\n * **Example** (Filtering for success)\n *\n * ```ts import.meta.vitest\n * import { Exit, Result } from \"effect\"\n *\n * Exit.filterSuccess(Exit.succeed(42)) // => Result.succeed(Exit.succeed(42))\n * ```\n *\n * @see {@link filterFailure} for the inverse\n * @see {@link filterValue} to extract the raw value instead of the Success object\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterSuccess = effect.exitFilterSuccess;\n/**\n * Extracts the success value from an Exit as a Result.\n *\n * **When to use**\n *\n * Use when composing Exit checks with `Filter` or other `Result`-based\n * filtering APIs and you want the raw success value rather than the Success\n * wrapper.\n *\n * **Details**\n *\n * Returns `Result.succeed(value)` when the Exit is a Success, or\n * `Result.fail(failure)` with the original Failure otherwise.\n *\n * **Gotchas**\n *\n * This is not an `Option` accessor or an Effect failure. A failed extraction is\n * represented as data in the `Result` failure channel.\n *\n * **Example** (Filtering for the value)\n *\n * ```ts import.meta.vitest\n * import { Exit, Result } from \"effect\"\n *\n * Exit.filterValue(Exit.succeed(42)) // => Result.succeed(42)\n * ```\n *\n * @see {@link filterSuccess} to get the full Success object\n * @see {@link getSuccess} to get the value as an Option instead\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterValue = effect.exitFilterValue;\n/**\n * Extracts the Failure variant from an Exit as a Result.\n *\n * **When to use**\n *\n * Use when composing Exit checks with `Filter` or other `Result`-based\n * filtering APIs and you want the full Failure wrapper.\n *\n * **Details**\n *\n * Returns `Result.succeed(failure)` when the Exit is a Failure, or\n * `Result.fail(success)` with the original Success otherwise.\n *\n * **Gotchas**\n *\n * This is not an `Option` accessor or an Effect failure. A failed extraction is\n * represented as data in the `Result` failure channel.\n *\n * **Example** (Filtering for failure)\n *\n * ```ts import.meta.vitest\n * import { Exit, Result } from \"effect\"\n *\n * Exit.filterFailure(Exit.fail(\"err\")) // => Result.succeed(Exit.fail(\"err\"))\n * ```\n *\n * @see {@link filterSuccess} for the inverse\n * @see {@link filterCause} to extract the Cause directly\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterFailure = effect.exitFilterFailure;\n/**\n * Extracts the Cause from a failed Exit as a Result.\n *\n * **When to use**\n *\n * Use when composing Exit checks with `Filter` or other `Result`-based\n * filtering APIs and you want the raw Cause rather than the Failure wrapper.\n *\n * **Details**\n *\n * Returns `Result.succeed(cause)` when the Exit is a Failure, or\n * `Result.fail(success)` with the original Success otherwise.\n *\n * **Gotchas**\n *\n * This is not an `Option` accessor or an Effect failure. A failed extraction is\n * represented as data in the `Result` failure channel.\n *\n * **Example** (Filtering for the cause)\n *\n * ```ts import.meta.vitest\n * import { Cause, Exit, Result } from \"effect\"\n *\n * Exit.filterCause(Exit.fail(\"err\")) // => Result.succeed(Cause.fail(\"err\"))\n * ```\n *\n * @see {@link filterFailure} to get the full Failure object\n * @see {@link getCause} to get the Cause as an Option instead\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterCause = effect.exitFilterCause;\n/**\n * Extracts the first typed error value from a failed Exit as a Result.\n *\n * **When to use**\n *\n * Use when you need the first typed error from an `Exit` as a `Result` for\n * `Filter` or other `Result`-based filtering APIs.\n *\n * **Details**\n *\n * Returns `Result.succeed(error)` when the Cause contains a Fail reason, or\n * `Result.fail(exit)` with the original Exit otherwise.\n *\n * **Gotchas**\n *\n * Only finds the first Fail reason. If the Cause has multiple errors, the rest\n * are ignored.\n *\n * **Example** (Finding the first typed error)\n *\n * ```ts import.meta.vitest\n * import { Exit, Result } from \"effect\"\n *\n * Exit.findError(Exit.fail(\"not found\")) // => Result.succeed(\"not found\")\n * Exit.findError(Exit.die(\"bug\")) // => Result.fail(Exit.die(\"bug\"))\n * ```\n *\n * @see {@link findErrorOption} to get the error as an Option instead\n * @see {@link findDefect} to find defects instead\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const findError = effect.exitFindError;\n/**\n * Extracts the first defect from a failed Exit as a Result.\n *\n * **When to use**\n *\n * Use when you need the first defect from an `Exit` as a `Result` for\n * `Filter` or other `Result`-based filtering APIs.\n *\n * **Details**\n *\n * Returns `Result.succeed(defect)` when the Cause contains a Die reason, or\n * `Result.fail(exit)` with the original Exit otherwise.\n *\n * **Gotchas**\n *\n * Only finds the first Die reason. If the Cause has multiple defects, the rest\n * are ignored.\n *\n * **Example** (Finding the first defect)\n *\n * ```ts import.meta.vitest\n * import { Exit, Result } from \"effect\"\n *\n * Exit.findDefect(Exit.die(\"boom\")) // => Result.succeed(\"boom\")\n * Exit.findDefect(Exit.fail(\"err\")) // => Result.fail(Exit.fail(\"err\"))\n * ```\n *\n * @see {@link findError} to find typed errors instead\n * @see {@link hasDies} to check for defects without extracting them\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const findDefect = effect.exitFindDefect;\n/**\n * Pattern matches on an Exit, handling both success and failure cases.\n *\n * **When to use**\n *\n * Use when you need exhaustive handling of both `Exit` success and failure\n * outcomes.\n *\n * **Details**\n *\n * Calls `onSuccess` with the value if the Exit is a Success, and calls\n * `onFailure` with the Cause if the Exit is a Failure.\n *\n * **Example** (Matching on an Exit)\n *\n * ```ts import.meta.vitest\n * import { Exit } from \"effect\"\n *\n * Exit.match(Exit.succeed(42), {\n * onSuccess: (value) => `Got: ${value}`,\n * onFailure: () => \"Failed\"\n * }) // => \"Got: 42\"\n * ```\n *\n * @see {@link isSuccess} and {@link isFailure} for simple boolean checks\n *\n * @category pattern matching\n * @since 2.0.0\n */\nexport const match = effect.exitMatch;\n/**\n * Transforms the success value of an Exit using the given function.\n *\n * **When to use**\n *\n * Use to apply a transformation to the value inside a successful Exit\n *\n * **Details**\n *\n * Failures pass through unchanged.\n *\n * Allocates a new Exit if successful.\n *\n * **Example** (Mapping over a success)\n *\n * ```ts import.meta.vitest\n * import { Exit } from \"effect\"\n *\n * Exit.map(Exit.succeed(21), (x) => x * 2) // => Exit.succeed(42)\n * ```\n *\n * @see {@link mapError} to transform the error\n * @see {@link mapBoth} to transform both success and error\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const map = effect.exitMap;\n/**\n * Transforms the typed error of a failed Exit using the given function.\n *\n * **When to use**\n *\n * Use to remap typed errors while preserving the Exit structure\n *\n * **Details**\n *\n * Successes pass through unchanged.\n *\n * Allocates a new Exit if the error is transformed.\n *\n * **Gotchas**\n *\n * Only transforms typed errors (Fail reasons). If the Cause contains only\n * defects or interruptions, the failure passes through unchanged.\n *\n * **Example** (Mapping over an error)\n *\n * ```ts import.meta.vitest\n * import { Exit } from \"effect\"\n *\n * Exit.mapError(Exit.fail(\"bad input\"), (error) => error.toUpperCase()) // => Exit.fail(\"BAD INPUT\")\n * ```\n *\n * @see {@link map} to transform the success value\n * @see {@link mapBoth} to transform both success and error\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const mapError = effect.exitMapError;\n/**\n * Transforms both the success value and typed error of an Exit.\n *\n * **When to use**\n *\n * Use when you need to remap both channels in one step.\n *\n * **Details**\n *\n * `onSuccess` transforms the value if the Exit is a Success. `onFailure`\n * transforms the typed error if the Exit is a Failure with a Fail reason.\n * Allocates a new Exit.\n *\n * **Gotchas**\n *\n * If the Cause contains only defects or interruptions, the failure passes\n * through unchanged.\n *\n * **Example** (Mapping both channels)\n *\n * ```ts import.meta.vitest\n * import { Exit } from \"effect\"\n *\n * Exit.mapBoth(Exit.succeed(42), {\n * onSuccess: (x) => String(x),\n * onFailure: (error: string) => error.toUpperCase()\n * }) // => Exit.succeed(\"42\")\n * ```\n *\n * @see {@link map} to transform only the success value\n * @see {@link mapError} to transform only the error\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const mapBoth = effect.exitMapBoth;\n/**\n * Discards the success value of an Exit, replacing it with `void`.\n *\n * **When to use**\n *\n * Use when you need to discard a successful `Exit` value while preserving\n * whether the `Exit` succeeded or failed.\n *\n * **Details**\n *\n * Failures pass through unchanged.\n *\n * Allocates a new Exit if successful.\n *\n * **Example** (Discarding the success value)\n *\n * ```ts import.meta.vitest\n * import { Exit } from \"effect\"\n *\n * Exit.asVoid(Exit.succeed(42)) // => Exit.succeed(undefined)\n * ```\n *\n * @see {@link void_ void} for a pre-allocated void success\n * @see {@link asVoidAll} to combine multiple exits into a single void Exit\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const asVoid = effect.exitAsVoid;\n/**\n * Combines multiple Exit values into a single `Exit<void, E>`.\n *\n * **When to use**\n *\n * Use to validate that all exits in a collection succeeded\n *\n * **Details**\n *\n * If all exits are successful, this returns a void success. If any exit is a\n * failure, this returns a single failure with all error causes combined.\n *\n * Iterates over the entire collection. Collects all failure causes, not just\n * the first.\n *\n * **Example** (Combining exits)\n *\n * ```ts import.meta.vitest\n * import { Exit } from \"effect\"\n *\n * Exit.asVoidAll([Exit.succeed(1), Exit.succeed(2), Exit.succeed(3)]) // => Exit.succeed(undefined)\n * Exit.asVoidAll([Exit.succeed(1), Exit.fail(\"err\"), Exit.succeed(3)]) // => Exit.fail(\"err\")\n * ```\n *\n * @see {@link asVoid} to discard the value of a single Exit\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const asVoidAll = effect.exitAsVoidAll;\n/**\n * Returns the success value of an Exit as an Option.\n *\n * **When to use**\n *\n * Use when you need the success value from an `Exit` as an `Option` instead of\n * pattern matching.\n *\n * **Details**\n *\n * Returns `Option.some(value)` for a Success and `Option.none()` for a Failure.\n *\n * **Example** (Getting the success value)\n *\n * ```ts import.meta.vitest\n * import { Exit, Option } from \"effect\"\n *\n * Exit.getSuccess(Exit.succeed(42)) // => Option.some(42)\n * Exit.getSuccess(Exit.fail(\"err\")) // => Option.none()\n * ```\n *\n * @see {@link getCause} to extract the Cause of a failure\n * @see {@link filterValue} for filter-pipeline usage\n *\n * @category getters\n * @since 4.0.0\n */\nexport const getSuccess = effect.exitGetSuccess;\n/**\n * Returns the Cause of a failed Exit as an Option.\n *\n * **When to use**\n *\n * Use when you need the failure `Cause` from an `Exit` as an `Option` instead\n * of pattern matching.\n *\n * **Details**\n *\n * Returns `Option.some(cause)` for a Failure and `Option.none()` for a Success.\n *\n * **Example** (Getting the failure cause)\n *\n * ```ts import.meta.vitest\n * import { Cause, Exit, Option } from \"effect\"\n *\n * Exit.getCause(Exit.fail(\"err\")) // => Option.some(Cause.fail(\"err\"))\n * Exit.getCause(Exit.succeed(42)) // => Option.none()\n * ```\n *\n * @see {@link getSuccess} to extract the success value\n * @see {@link filterCause} for filter-pipeline usage\n *\n * @category getters\n * @since 4.0.0\n */\nexport const getCause = effect.exitGetCause;\n/**\n * Returns the first typed error from a failed Exit as an Option.\n *\n * **When to use**\n *\n * Use when you need the first typed error from an `Exit` as an `Option`,\n * ignoring successes and non-typed failures.\n *\n * **Details**\n *\n * Returns `Option.some(error)` if the Cause contains a Fail reason. Successes,\n * defect-only failures, and interrupt-only failures return `Option.none()`.\n *\n * **Gotchas**\n *\n * Only finds the first Fail reason. If the Cause has multiple typed errors,\n * the rest are ignored.\n *\n * **Example** (Getting the first error)\n *\n * ```ts import.meta.vitest\n * import { Exit, Option } from \"effect\"\n *\n * Exit.findErrorOption(Exit.fail(\"err\")) // => Option.some(\"err\")\n * Exit.findErrorOption(Exit.die(\"bug\")) // => Option.none()\n * Exit.findErrorOption(Exit.succeed(42)) // => Option.none()\n * ```\n *\n * @see {@link findError} for filter-pipeline usage\n * @see {@link getCause} to get the full Cause as an Option\n *\n * @category getters\n * @since 4.0.0\n */\nexport const findErrorOption = effect.exitFindErrorOption;\n//# sourceMappingURL=Exit.js.map","import { dual, identity } from \"./Function.js\";\nimport * as core from \"./internal/core.js\";\nimport * as internalEffect from \"./internal/effect.js\";\nimport * as Option from \"./Option.js\";\nimport { pipeArguments } from \"./Pipeable.js\";\nimport { hasProperty } from \"./Predicate.js\";\nconst TypeId = \"~effect/Deferred\";\n/**\n * Checks whether a value is a `Deferred`.\n *\n * **When to use**\n *\n * Use to validate unknown values at runtime boundaries before treating them as\n * `Deferred` values.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isDeferred = u => hasProperty(u, TypeId);\nconst DeferredProto = {\n [TypeId]: {\n _A: identity,\n _E: identity\n },\n pipe() {\n return pipeArguments(this, arguments);\n }\n};\nconst DeferredImpl = function () {\n this.resumes = undefined;\n this.effect = undefined;\n};\nDeferredImpl.prototype = DeferredProto;\n/**\n * Creates an empty `Deferred` synchronously outside the `Effect` runtime.\n *\n * **When to use**\n *\n * Use to allocate a `Deferred` synchronously when direct allocation outside\n * `Effect` is required.\n *\n * **Example** (Creating a Deferred unsafely)\n *\n * ```ts import.meta.vitest\n * import { Deferred } from \"effect\"\n *\n * const deferred = Deferred.makeUnsafe<number>()\n * Deferred.isDoneUnsafe(deferred) // => false\n * ```\n *\n * @category unsafe\n * @since 4.0.0\n */\nexport const makeUnsafe = () => new DeferredImpl();\n/**\n * Creates a new `Deferred`.\n *\n * **When to use**\n *\n * Use to allocate an empty `Deferred` inside an `Effect` workflow.\n *\n * **Example** (Creating a Deferred)\n *\n * ```ts import.meta.vitest\n * import { Deferred, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const deferred = yield* Deferred.make<number>()\n * yield* Deferred.succeed(deferred, 42)\n * return yield* Deferred.await(deferred)\n * })\n *\n * await Effect.runPromise(program) // => 42\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const make = () => internalEffect.sync(() => makeUnsafe());\nconst _await = self => internalEffect.callback(resume => {\n if (self.effect) return resume(self.effect);\n self.resumes ??= [];\n self.resumes.push(resume);\n return internalEffect.sync(() => {\n // Completion resumes all waiters and clears `resumes`, so a cleanup\n // running after completion has nothing to unregister.\n const resumes = self.resumes;\n if (resumes === undefined) return;\n const index = resumes.indexOf(resume);\n if (index >= 0) resumes.splice(index, 1);\n });\n});\nexport {\n/**\n * Retrieves the value of the `Deferred`, suspending the fiber running the\n * workflow until the result is available.\n *\n * **When to use**\n *\n * Use to wait for a `Deferred` to be completed and resume with its success,\n * failure, defect, or interruption.\n *\n * **Details**\n *\n * Awaiters observe the completion effect stored in the `Deferred`.\n *\n * **Example** (Awaiting a Deferred value)\n *\n * ```ts import.meta.vitest\n * import { Deferred, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const deferred = yield* Deferred.make<number>()\n * yield* Deferred.succeed(deferred, 42)\n *\n * return yield* Deferred.await(deferred)\n * })\n *\n * await Effect.runPromise(program) // => 42\n * ```\n *\n * @see {@link complete} for completing from an effect and memoizing its result\n * @see {@link completeWith} for completing with an effect directly\n *\n * @category getters\n * @since 2.0.0\n */\n_await as await };\n/**\n * Runs the supplied `Effect` and attempts to complete the `Deferred` with its\n * memoized result.\n *\n * **When to use**\n *\n * Use when completing a `Deferred` should run an effect once and share its\n * result with all awaiters.\n *\n * **Details**\n *\n * The returned effect succeeds with `true` when this call completed the\n * `Deferred`, or `false` if it was already completed.\n *\n * **Example** (Completing a Deferred from an effect)\n *\n * ```ts import.meta.vitest\n * import { Deferred, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const deferred = yield* Deferred.make<number>()\n * const completed = yield* Deferred.complete(deferred, Effect.succeed(42))\n * const value = yield* Deferred.await(deferred)\n * return [completed, value]\n * })\n *\n * await Effect.runPromise(program) // => [true, 42]\n * ```\n *\n * @see {@link completeWith} for storing an effect directly without memoizing its result\n *\n * @category completion\n * @since 2.0.0\n */\nexport const complete = /*#__PURE__*/dual(2, (self, effect) => internalEffect.suspend(() => self.effect ? internalEffect.succeed(false) : into(effect, self)));\n/**\n * Attempts to complete the `Deferred` with the specified effect directly.\n *\n * **When to use**\n *\n * Use to store an already environment-free effect as the completion without\n * running it during completion.\n *\n * **Details**\n *\n * The returned effect succeeds with `true` when this call completed the\n * `Deferred`, or `false` if it was already completed.\n *\n * **Gotchas**\n *\n * The supplied effect is not memoized by `completeWith`; each awaiter may run\n * the stored effect independently.\n *\n * **Example** (Completing a Deferred with an effect)\n *\n * ```ts import.meta.vitest\n * import { Deferred, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const deferred = yield* Deferred.make<number>()\n * const completed = yield* Deferred.completeWith(deferred, Effect.succeed(42))\n * const value = yield* Deferred.await(deferred)\n * return [completed, value]\n * })\n *\n * await Effect.runPromise(program) // => [true, 42]\n * ```\n *\n * @see {@link complete} for running an effect once and sharing its result\n * @see {@link done} for completing from an already computed `Exit`\n *\n * @category completion\n * @since 2.0.0\n */\nexport const completeWith = /*#__PURE__*/dual(2, (self, effect) => internalEffect.sync(() => doneUnsafe(self, effect)));\n/**\n * Completes the `Deferred` with the specified `Exit` value, which will be\n * propagated to all fibers waiting on the value of the `Deferred`.\n *\n * **When to use**\n *\n * Use to complete a `Deferred` from an already computed `Exit`.\n *\n * **Details**\n *\n * The returned effect succeeds with `true` when this call completed the\n * `Deferred`, or `false` if it was already completed.\n *\n * **Example** (Completing a Deferred with an Exit)\n *\n * ```ts import.meta.vitest\n * import { Deferred, Effect, Exit } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const deferred = yield* Deferred.make<number>()\n * yield* Deferred.done(deferred, Exit.succeed(42))\n * return yield* Effect.exit(Deferred.await(deferred))\n * })\n *\n * await Effect.runPromise(program) // => Exit.succeed(42)\n * ```\n *\n * @see {@link complete} for completing from an effect and memoizing its result\n * @see {@link completeWith} for storing an effect directly\n * @see {@link succeed} for completing with a success value\n * @see {@link failCause} for completing with a failure cause\n *\n * @category completion\n * @since 2.0.0\n */\nexport const done = completeWith;\n/**\n * Attempts to complete the `Deferred` with the specified error.\n *\n * **When to use**\n *\n * Use to complete a `Deferred` with a typed failure value.\n *\n * **Details**\n *\n * Fibers waiting on the `Deferred` fail with that error only if this call\n * completes it. The returned effect succeeds with `true` when this call\n * completed the `Deferred`, or `false` if it was already completed.\n *\n * **Example** (Failing a Deferred with an error)\n *\n * ```ts import.meta.vitest\n * import { Deferred, Effect, Exit } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const deferred = yield* Deferred.make<number, string>()\n * const success = yield* Deferred.fail(deferred, \"Operation failed\")\n * const exit = yield* Effect.exit(Deferred.await(deferred))\n * return [success, exit]\n * })\n *\n * await Effect.runPromise(program) // => [true, Exit.fail(\"Operation failed\")]\n * ```\n *\n * @category completion\n * @since 2.0.0\n */\nexport const fail = /*#__PURE__*/dual(2, (self, error) => done(self, core.exitFail(error)));\n/**\n * Computes an error when the returned effect is run, then attempts to complete\n * the `Deferred` with that error.\n *\n * **When to use**\n *\n * Use to lazily compute a typed failure value when the `Deferred` completion\n * effect runs.\n *\n * **Details**\n *\n * Fibers waiting on the `Deferred` fail with the computed error only if this\n * call completes it. The returned effect succeeds with `true` when this call\n * completed the `Deferred`, or `false` if it was already completed.\n *\n * **Example** (Failing a Deferred with a lazy error)\n *\n * ```ts import.meta.vitest\n * import { Deferred, Effect, Exit } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const deferred = yield* Deferred.make<number, string>()\n * const success = yield* Deferred.failSync(deferred, () => \"Lazy error\")\n * const exit = yield* Effect.exit(Deferred.await(deferred))\n * return [success, exit]\n * })\n *\n * await Effect.runPromise(program) // => [true, Exit.fail(\"Lazy error\")]\n * ```\n *\n * @category completion\n * @since 2.0.0\n */\nexport const failSync = /*#__PURE__*/dual(2, (self, evaluate) => internalEffect.suspend(() => fail(self, evaluate())));\n/**\n * Attempts to complete the `Deferred` with the specified `Cause`.\n *\n * **When to use**\n *\n * Use to complete a `Deferred` with a full failure cause.\n *\n * **Details**\n *\n * Fibers waiting on the `Deferred` observe that cause only if this call\n * completes it. The returned effect succeeds with `true` when this call\n * completed the `Deferred`, or `false` if it was already completed.\n *\n * **Example** (Failing a Deferred with a Cause)\n *\n * ```ts import.meta.vitest\n * import { Cause, Deferred, Effect, Exit } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const deferred = yield* Deferred.make<number, string>()\n * const success = yield* Deferred.failCause(deferred, Cause.fail(\"Operation failed\"))\n * const exit = yield* Effect.exit(Deferred.await(deferred))\n * return [success, exit]\n * })\n *\n * await Effect.runPromise(program) // => [true, Exit.failCause(Cause.fail(\"Operation failed\"))]\n * ```\n *\n * @category completion\n * @since 2.0.0\n */\nexport const failCause = /*#__PURE__*/dual(2, (self, cause) => done(self, core.exitFailCause(cause)));\n/**\n * Computes a `Cause` when the returned effect is run, then attempts to\n * complete the `Deferred` with that cause.\n *\n * **When to use**\n *\n * Use to lazily compute a full failure cause when the `Deferred` completion\n * effect runs.\n *\n * **Details**\n *\n * Fibers waiting on the `Deferred` observe the computed cause only if this\n * call completes it. The returned effect succeeds with `true` when this call\n * completed the `Deferred`, or `false` if it was already completed.\n *\n * **Example** (Failing a Deferred with a lazy Cause)\n *\n * ```ts import.meta.vitest\n * import { Cause, Deferred, Effect, Exit } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const deferred = yield* Deferred.make<number, string>()\n * const success = yield* Deferred.failCauseSync(deferred, () => Cause.fail(\"Lazy error\"))\n * const exit = yield* Effect.exit(Deferred.await(deferred))\n * return [success, exit]\n * })\n *\n * await Effect.runPromise(program) // => [true, Exit.failCause(Cause.fail(\"Lazy error\"))]\n * ```\n *\n * @category completion\n * @since 2.0.0\n */\nexport const failCauseSync = /*#__PURE__*/dual(2, (self, evaluate) => internalEffect.suspend(() => failCause(self, evaluate())));\n/**\n * Attempts to complete the `Deferred` with a defect.\n *\n * **When to use**\n *\n * Use to complete a `Deferred` with an unexpected defect.\n *\n * **Details**\n *\n * Fibers waiting on the `Deferred` die with that defect only if this call\n * completes it. The returned effect succeeds with `true` when this call\n * completed the `Deferred`, or `false` if it was already completed.\n *\n * **Example** (Killing a Deferred with a defect)\n *\n * ```ts import.meta.vitest\n * import { Deferred, Effect, Exit } from \"effect\"\n *\n * const defect = new Error(\"Something went wrong\")\n * const program = Effect.gen(function*() {\n * const deferred = yield* Deferred.make<number>()\n * const success = yield* Deferred.die(deferred, defect)\n * const exit = yield* Effect.exit(Deferred.await(deferred))\n * return [success, exit]\n * })\n *\n * await Effect.runPromise(program) // => [true, Exit.die(defect)]\n * ```\n *\n * @category completion\n * @since 2.0.0\n */\nexport const die = /*#__PURE__*/dual(2, (self, defect) => done(self, core.exitDie(defect)));\n/**\n * Computes a defect when the returned effect is run, then attempts to complete\n * the `Deferred` with that defect.\n *\n * **When to use**\n *\n * Use to lazily compute an unexpected defect when the completion effect runs.\n *\n * **Details**\n *\n * Fibers waiting on the `Deferred` die with the computed defect only if this\n * call completes it. The returned effect succeeds with `true` when this call\n * completed the `Deferred`, or `false` if it was already completed.\n *\n * **Example** (Killing a Deferred with a lazy defect)\n *\n * ```ts import.meta.vitest\n * import { Deferred, Effect, Exit } from \"effect\"\n *\n * const defect = new Error(\"Lazy error\")\n * const program = Effect.gen(function*() {\n * const deferred = yield* Deferred.make<number>()\n * const success = yield* Deferred.dieSync(deferred, () => defect)\n * const exit = yield* Effect.exit(Deferred.await(deferred))\n * return [success, exit]\n * })\n *\n * await Effect.runPromise(program) // => [true, Exit.die(defect)]\n * ```\n *\n * @category completion\n * @since 2.0.0\n */\nexport const dieSync = /*#__PURE__*/dual(2, (self, evaluate) => internalEffect.suspend(() => die(self, evaluate())));\n/**\n * Attempts to complete the `Deferred` with interruption by the current fiber.\n *\n * **When to use**\n *\n * Use to complete a `Deferred` as interrupted by the current fiber.\n *\n * **Details**\n *\n * Fibers waiting on the `Deferred` are interrupted with the current fiber id\n * only if this call completes it. The returned effect succeeds with `true`\n * when this call completed the `Deferred`, or `false` if it was already\n * completed.\n *\n * **Example** (Interrupting a Deferred)\n *\n * ```ts import.meta.vitest\n * import { Deferred, Effect, Exit } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const deferred = yield* Deferred.make<number>()\n * const success = yield* Deferred.interrupt(deferred)\n * const exit = yield* Effect.exit(Deferred.await(deferred))\n * return [success, exit] as const\n * })\n *\n * const [success, exit] = await Effect.runPromise(program)\n * success // => true\n * Exit.hasInterrupts(exit) // => true\n * ```\n *\n * @category completion\n * @since 2.0.0\n */\nexport const interrupt = self => core.withFiber(fiber => interruptWith(self, fiber.id));\n/**\n * Attempts to complete the `Deferred` with interruption by the specified\n * `FiberId`.\n *\n * **When to use**\n *\n * Use to complete a `Deferred` as interrupted by a specific fiber id.\n *\n * **Details**\n *\n * Fibers waiting on the `Deferred` are interrupted with that fiber id only if\n * this call completes it. The returned effect succeeds with `true` when this\n * call completed the `Deferred`, or `false` if it was already completed.\n *\n * **Example** (Interrupting a Deferred with a fiber id)\n *\n * ```ts import.meta.vitest\n * import { Deferred, Effect, Exit } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const deferred = yield* Deferred.make<number>()\n * const success = yield* Deferred.interruptWith(deferred, 42)\n * const exit = yield* Effect.exit(Deferred.await(deferred))\n * return [success, exit]\n * })\n *\n * await Effect.runPromise(program) // => [true, Exit.interrupt(42)]\n * ```\n *\n * @category completion\n * @since 2.0.0\n */\nexport const interruptWith = /*#__PURE__*/dual(2, (self, fiberId) => failCause(self, internalEffect.causeInterrupt(fiberId)));\n/**\n * Returns `true` if this `Deferred` has already been completed with a value or\n * an error, `false` otherwise.\n *\n * **When to use**\n *\n * Use to check completion status inside an `Effect` workflow.\n *\n * **Example** (Checking Deferred completion)\n *\n * ```ts import.meta.vitest\n * import { Deferred, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const deferred = yield* Deferred.make<number>()\n * const beforeCompletion = yield* Deferred.isDone(deferred)\n * yield* Deferred.succeed(deferred, 42)\n * const afterCompletion = yield* Deferred.isDone(deferred)\n * return [beforeCompletion, afterCompletion]\n * })\n *\n * await Effect.runPromise(program) // => [false, true]\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const isDone = self => internalEffect.sync(() => isDoneUnsafe(self));\n/**\n * Returns whether this `Deferred` has already been completed synchronously.\n *\n * **When to use**\n *\n * Use to check `Deferred` completion synchronously in code that cannot return\n * an `Effect`, such as low-level integration code.\n *\n * @see {@link isDone} for checking completion inside `Effect`\n * @see {@link poll} for reading the completed effect when available\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isDoneUnsafe = self => self.effect !== undefined;\n/**\n * Returns the current completion effect as an `Option`. This returns\n * `Option.some(effect)` when the `Deferred` is completed, `Option.none()`\n * otherwise.\n *\n * **When to use**\n *\n * Use to inspect whether a `Deferred` is already completed and retrieve its\n * stored completion effect when available.\n *\n * **Example** (Polling Deferred completion)\n *\n * ```ts import.meta.vitest\n * import { Deferred, Effect, Option } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const deferred = yield* Deferred.make<number>()\n * const beforeCompletion = yield* Deferred.poll(deferred)\n * yield* Deferred.succeed(deferred, 42)\n * const afterCompletion = yield* Deferred.poll(deferred)\n * const afterValue = yield* Effect.transposeOption(afterCompletion)\n * return [beforeCompletion, afterValue]\n * })\n *\n * await Effect.runPromise(program) // => [Option.none(), Option.some(42)]\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport function poll(self) {\n return internalEffect.sync(() => Option.fromUndefinedOr(self.effect));\n}\n/**\n * Attempts to complete the `Deferred` with the specified value.\n *\n * **When to use**\n *\n * Use to complete a `Deferred` with a successful value.\n *\n * **Details**\n *\n * Fibers waiting on the `Deferred` receive the value only if this call\n * completes it. The returned effect succeeds with `true` when this call\n * completed the `Deferred`, or `false` if it was already completed.\n *\n * **Example** (Completing a Deferred with a value)\n *\n * ```ts import.meta.vitest\n * import { Deferred, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const deferred = yield* Deferred.make<number>()\n * yield* Deferred.succeed(deferred, 42)\n *\n * return yield* Deferred.await(deferred)\n * })\n *\n * await Effect.runPromise(program) // => 42\n * ```\n *\n * @category completion\n * @since 2.0.0\n */\nexport const succeed = /*#__PURE__*/dual(2, (self, value) => done(self, core.exitSucceed(value)));\n/**\n * Computes a value when the returned effect is run, then attempts to complete\n * the `Deferred` with that value.\n *\n * **When to use**\n *\n * Use to lazily compute a successful value when the `Deferred` completion\n * effect runs.\n *\n * **Details**\n *\n * Fibers waiting on the `Deferred` receive the computed value only if this call\n * completes it. The returned effect succeeds with `true` when this call\n * completed the `Deferred`, or `false` if it was already completed.\n *\n * **Example** (Completing a Deferred with a lazy value)\n *\n * ```ts import.meta.vitest\n * import { Deferred, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const deferred = yield* Deferred.make<number>()\n * yield* Deferred.sync(deferred, () => 42)\n * return yield* Deferred.await(deferred)\n * })\n *\n * await Effect.runPromise(program) // => 42\n * ```\n *\n * @category completion\n * @since 2.0.0\n */\nexport const sync = /*#__PURE__*/dual(2, (self, evaluate) => internalEffect.suspend(() => succeed(self, evaluate())));\n/**\n * Attempts to complete the `Deferred` synchronously with the specified\n * completion effect.\n *\n * **When to use**\n *\n * Use to complete a `Deferred` synchronously in low-level code that already has\n * the completion effect.\n *\n * **Details**\n *\n * This mutates the `Deferred` directly and should be reserved for low-level\n * code; prefer the effectful completion APIs when possible. Returns `true` if\n * this call completed the `Deferred`, or `false` if it was already completed.\n *\n * **Example** (Completing a Deferred unsafely)\n *\n * ```ts import.meta.vitest\n * import { Deferred, Effect } from \"effect\"\n *\n * const deferred = Deferred.makeUnsafe<number>()\n * Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true\n * ```\n *\n * @category unsafe\n * @since 4.0.0\n */\nexport const doneUnsafe = (self, effect) => {\n if (self.effect) return false;\n self.effect = effect;\n if (self.resumes) {\n // Clear `resumes` before resuming: a waiter resumed with an interrupt\n // cause dies synchronously inside `resume`, and its await cleanup would\n // otherwise splice this array mid-iteration and skip the next waiter.\n const resumes = self.resumes;\n self.resumes = undefined;\n for (let i = 0; i < resumes.length; i++) {\n resumes[i](effect);\n }\n }\n return true;\n};\n/**\n * Runs an `Effect` and attempts to complete a `Deferred` with the effect's\n * result.\n *\n * **When to use**\n *\n * Use to pipe an effect result into a `Deferred` while preserving success,\n * failure, defects, and interruption.\n *\n * **Details**\n *\n * If the effect succeeds, fails, dies, or is interrupted, that result is used\n * as the attempted completion. The returned effect cannot fail; it succeeds\n * with `true` if it completed the `Deferred`, or `false` if the `Deferred` was\n * already completed.\n *\n * **Example** (Completing a Deferred from an effect result)\n *\n * ```ts import.meta.vitest\n * import { Deferred, Effect } from \"effect\"\n *\n * const successEffect = Effect.succeed(42)\n *\n * const program = Effect.gen(function*() {\n * const deferred = yield* Deferred.make<number, string>()\n * const isCompleted = yield* Deferred.into(successEffect, deferred)\n * const value = yield* Deferred.await(deferred)\n * return [isCompleted, value]\n * })\n *\n * await Effect.runPromise(program) // => [true, 42]\n * ```\n *\n * @category completion\n * @since 4.0.0\n */\nexport const into = /*#__PURE__*/dual(2, (self, deferred) => internalEffect.uninterruptibleMask(restore => internalEffect.flatMap(internalEffect.exit(restore(self)), exit => done(deferred, exit))));\n//# sourceMappingURL=Deferred.js.map","import * as internalEffect from \"./internal/effect.js\";\nimport * as references from \"./internal/references.js\";\nimport { MaxOpsBeforeYield, PreventSchedulerYield } from \"./Scheduler.js\";\nimport { CurrentTraceLevel, DisablePropagation, MinimumTraceLevel, Tracer } from \"./Tracer.js\";\nexport {\n/**\n * Context reference for the current trace level used for dynamic trace filtering.\n *\n * **When to use**\n *\n * Use to set the default trace level for spans created in a scope when span\n * options do not provide `level`.\n *\n * @see {@link MinimumTraceLevel} for configuring the threshold that decides whether spans at a given level are sampled or exported\n *\n * @category references\n * @since 4.0.0\n */\nCurrentTraceLevel,\n/**\n * Context reference for disabling trace propagation in the current context.\n *\n * **When to use**\n *\n * Use to mark tracing work as non-propagating while still allowing local span\n * tracking.\n *\n * **Details**\n *\n * Annotated spans become non-propagating no-op spans, and parent selection\n * skips spans marked with disabled propagation.\n *\n * @see {@link TracerEnabled} for disabling span registration instead of only propagation\n *\n * @category references\n * @since 4.0.0\n */\nDisablePropagation,\n/**\n * Context reference for the maximum operation budget before a fiber yields to the scheduler.\n *\n * **When to use**\n *\n * Use to configure the runtime reference for the fiber operation budget that\n * triggers a scheduler yield.\n *\n * **Details**\n *\n * The default value is `2048` operations.\n *\n * @see {@link PreventSchedulerYield} for bypassing scheduler yield checks instead of changing the operation budget\n *\n * @category references\n * @since 4.0.0\n */\nMaxOpsBeforeYield,\n/**\n * Context reference for the minimum trace level threshold for span sampling.\n *\n * **When to use**\n *\n * Use to set the trace-level threshold that decides whether newly created\n * spans are sampled and exported.\n *\n * @see {@link CurrentTraceLevel} for setting the level assigned to spans before this threshold is applied\n *\n * @category references\n * @since 4.0.0\n */\nMinimumTraceLevel,\n/**\n * Context reference for whether the runtime bypasses scheduler yield checks.\n *\n * **When to use**\n *\n * Use to bypass automatic scheduler yield checks in a controlled runtime scope\n * where throughput is preferred over scheduler fairness.\n *\n * **Details**\n *\n * When set to `true`, the fiber run loop skips `Scheduler.shouldYield`. The\n * default value is `false`.\n *\n * **Gotchas**\n *\n * Disabling automatic yield checks can let long-running fibers monopolize the\n * JavaScript thread.\n *\n * @see {@link MaxOpsBeforeYield} for tuning the operation budget while keeping scheduler yield checks enabled\n *\n * @category references\n * @since 4.0.0\n */\nPreventSchedulerYield,\n/**\n * Context reference for the active tracer service used to create spans.\n *\n * **When to use**\n *\n * Use to access or override the active tracer service through the references\n * module when working directly with Effect runtime references.\n *\n * @category references\n * @since 4.0.0\n */\nTracer };\n/**\n * Context reference for managing log annotations that are automatically added to all log entries.\n * These annotations provide contextual metadata that appears in every log message.\n *\n * **When to use**\n *\n * Use to attach shared contextual metadata to every log entry emitted in the\n * current context.\n *\n * **Example** (Managing log annotations)\n *\n * ```ts import.meta.vitest\n * import { Effect, References } from \"effect\"\n *\n * const logAnnotationExample = Effect.gen(function*() {\n * // Get current annotations (empty by default)\n * const current = yield* References.CurrentLogAnnotations\n * const defaultCount = Object.keys(current).length\n *\n * // Run with custom log annotations\n * const custom = yield* Effect.provideService(\n * Effect.gen(function*() {\n * const annotations = yield* References.CurrentLogAnnotations\n * return [annotations.requestId, annotations.userId, annotations.version]\n * }),\n * References.CurrentLogAnnotations,\n * {\n * requestId: \"req-123\",\n * userId: \"user-456\",\n * version: \"1.0.0\"\n * }\n * )\n *\n * // Run with extended annotations\n * const extended = yield* Effect.provideService(\n * Effect.gen(function*() {\n * const annotations = yield* References.CurrentLogAnnotations\n * return [annotations.operation, annotations.timestamp]\n * }),\n * References.CurrentLogAnnotations,\n * {\n * requestId: \"req-123\",\n * userId: \"user-456\",\n * version: \"1.0.0\",\n * operation: \"data-sync\",\n * timestamp: 1234567890\n * }\n * )\n *\n * return [defaultCount, custom, extended]\n * })\n *\n * await Effect.runPromise(logAnnotationExample) // => [0, [\"req-123\", \"user-456\", \"1.0.0\"], [\"data-sync\", 1234567890]]\n * ```\n *\n * @category references\n * @since 4.0.0\n */\nexport const CurrentLogAnnotations = references.CurrentLogAnnotations;\n/**\n * Context reference for the current log severity used by `Effect.log` when no explicit\n * level is provided.\n *\n * **When to use**\n *\n * Use to set the default severity for `Effect.log` entries that do not provide\n * an explicit level.\n *\n * **Details**\n *\n * Use `MinimumLogLevel` to control which log entries are filtered out.\n *\n * **Example** (Changing the level of an unqualified log)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger, References } from \"effect\"\n *\n * const levels: Array<string> = []\n * const logger = Logger.make<unknown, void>(({ logLevel }) => {\n * levels.push(logLevel)\n * })\n *\n * const program = Effect.gen(function*() {\n * yield* Effect.log(\"uses the default level\")\n * yield* Effect.log(\"uses the provided level\").pipe(\n * Effect.provideService(References.CurrentLogLevel, \"Error\")\n * )\n * })\n *\n * await Effect.runPromise(program.pipe(Effect.provide(Logger.layer([logger]))))\n * levels // => [\"Info\", \"Error\"]\n * ```\n *\n * @category references\n * @since 4.0.0\n */\nexport const CurrentLogLevel = references.CurrentLogLevel;\n/**\n * Context reference for managing log spans that track the duration and hierarchy of operations.\n * Each span represents a labeled time period for performance analysis and debugging.\n *\n * **When to use**\n *\n * Use to carry the active log span stack that should be included with log\n * entries in the current context.\n *\n * **Example** (Tracking log spans)\n *\n * ```ts import.meta.vitest\n * import { Effect, References } from \"effect\"\n *\n * const logSpanExample = Effect.gen(function*() {\n * // Get current spans (empty by default)\n * const current = yield* References.CurrentLogSpans\n * const defaultCount = current.length\n *\n * // Add a log span manually\n * const databaseConnectionStartedAt = 0\n * const database = yield* Effect.provideService(\n * Effect.gen(function*() {\n * const spans = yield* References.CurrentLogSpans\n * return spans.map(([label]) => label)\n * }),\n * References.CurrentLogSpans,\n * [[\"database-connection\", databaseConnectionStartedAt]]\n * )\n *\n * // Add another span\n * const dataProcessingStartedAt = 100\n * const processing = yield* Effect.provideService(\n * Effect.gen(function*() {\n * const spans = yield* References.CurrentLogSpans\n * return spans.map(([label]) => label)\n * }),\n * References.CurrentLogSpans,\n * [\n * [\"database-connection\", databaseConnectionStartedAt],\n * [\"data-processing\", dataProcessingStartedAt]\n * ]\n * )\n *\n * // Clear spans when operations complete\n * const cleared = yield* Effect.provideService(\n * Effect.gen(function*() {\n * const spans = yield* References.CurrentLogSpans\n * return spans.length\n * }),\n * References.CurrentLogSpans,\n * []\n * )\n *\n * return [defaultCount, database, processing, cleared]\n * })\n *\n * await Effect.runPromise(logSpanExample) // => [0, [\"database-connection\"], [\"database-connection\", \"data-processing\"], 0]\n * ```\n *\n * @category references\n * @since 4.0.0\n */\nexport const CurrentLogSpans = references.CurrentLogSpans;\n/**\n * Context reference for the current captured stack-frame chain for the running\n * fiber.\n *\n * **When to use**\n *\n * Use when writing low-level tracing or diagnostic integrations that need direct\n * access to the stack-frame chain carried by the current fiber.\n *\n * **Details**\n *\n * Effect and Layer tracing use this reference to attach stack-frame information\n * to failures and interruption causes. It is normally managed by tracing APIs\n * rather than provided directly by application code.\n *\n * @see {@link StackFrame} for the frame node stored in this reference\n *\n * @category references\n * @since 4.0.0\n */\nexport const CurrentStackFrame = references.CurrentStackFrame;\n/**\n * Context reference for setting the minimum log level threshold. Log entries below this\n * level will be filtered out completely.\n *\n * **When to use**\n *\n * Use to filter out log entries below a severity threshold.\n *\n * **Example** (Filtering logs below the minimum level)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger, References } from \"effect\"\n *\n * const levels: Array<string> = []\n * const logger = Logger.make<unknown, void>(({ logLevel }) => {\n * levels.push(logLevel)\n * })\n *\n * const program = Effect.gen(function*() {\n * yield* Effect.logInfo(\"filtered out\")\n * yield* Effect.logWarning(\"included at the threshold\")\n * yield* Effect.logError(\"included above the threshold\")\n * })\n *\n * await Effect.runPromise(program.pipe(\n * Effect.provideService(References.MinimumLogLevel, \"Warn\"),\n * Effect.provide(Logger.layer([logger]))\n * ))\n * levels // => [\"Warn\", \"Error\"]\n * ```\n *\n * @category references\n * @since 4.0.0\n */\nexport const MinimumLogLevel = references.MinimumLogLevel;\n/**\n * Context reference for controlling whether tracing is enabled globally. When set to false,\n * spans will not be registered with the tracer and tracing overhead is minimized.\n *\n * **When to use**\n *\n * Use to disable or re-enable span registration in the current context.\n *\n * **Example** (Toggling tracing)\n *\n * ```ts import.meta.vitest\n * import { Effect, References } from \"effect\"\n *\n * const tracingControl = Effect.gen(function*() {\n * // Check if tracing is enabled (default is true)\n * const current = yield* References.TracerEnabled\n *\n * // Disable tracing globally\n * const disabled = yield* Effect.provideService(\n * References.TracerEnabled,\n * References.TracerEnabled,\n * false\n * )\n *\n * // Re-enable tracing\n * const enabled = yield* Effect.provideService(\n * References.TracerEnabled,\n * References.TracerEnabled,\n * true\n * )\n *\n * return [current, disabled, enabled]\n * })\n *\n * await Effect.runPromise(tracingControl) // => [true, false, true]\n * ```\n *\n * @category references\n * @since 4.0.0\n */\nexport const TracerEnabled = references.TracerEnabled;\n/**\n * Context reference for managing span annotations that are automatically added to all new spans.\n * These annotations provide context and metadata that applies across multiple spans.\n *\n * **When to use**\n *\n * Use to attach shared metadata to every span created in the current context.\n *\n * **Example** (Managing span annotations)\n *\n * ```ts import.meta.vitest\n * import { Effect, References } from \"effect\"\n *\n * const spanAnnotationExample = Effect.gen(function*() {\n * // Get current annotations (empty by default)\n * const current = yield* References.TracerSpanAnnotations\n * const defaultCount = Object.keys(current).length\n *\n * // Set global span annotations\n * const configured = yield* Effect.provideService(\n * Effect.gen(function*() {\n * // Get current annotations\n * const annotations = yield* References.TracerSpanAnnotations\n * return [annotations.service, annotations.version, annotations.environment]\n * }),\n * References.TracerSpanAnnotations,\n * {\n * service: \"user-service\",\n * version: \"1.2.3\",\n * environment: \"production\"\n * }\n * )\n *\n * // Clear annotations\n * const cleared = yield* Effect.provideService(\n * Effect.gen(function*() {\n * const annotations = yield* References.TracerSpanAnnotations\n * return Object.keys(annotations).length\n * }),\n * References.TracerSpanAnnotations,\n * {}\n * )\n *\n * return [defaultCount, configured, cleared]\n * })\n *\n * await Effect.runPromise(spanAnnotationExample) // => [0, [\"user-service\", \"1.2.3\", \"production\"], 0]\n * ```\n *\n * @category references\n * @since 4.0.0\n */\nexport const TracerSpanAnnotations = references.TracerSpanAnnotations;\n/**\n * Context reference for managing span links that are automatically added to all new spans.\n * Span links connect related spans that are not in a parent-child relationship.\n *\n * **When to use**\n *\n * Use to attach shared links to every span created in the current context.\n *\n * **Example** (Managing span links)\n *\n * ```ts import.meta.vitest\n * import { Effect, References, Tracer } from \"effect\"\n *\n * const spanLinksExample = Effect.gen(function*() {\n * // Get current links (empty by default)\n * const current = yield* References.TracerSpanLinks\n * const defaultCount = current.length\n *\n * // Create an external span for the example\n * const externalSpan = Tracer.externalSpan({\n * spanId: \"external-span-123\",\n * traceId: \"trace-456\"\n * })\n *\n * // Create span links\n * const spanLink: Tracer.SpanLink = {\n * span: externalSpan,\n * attributes: {\n * relationship: \"follows-from\",\n * priority: \"high\"\n * }\n * }\n *\n * // Set global span links\n * const configuredCount = yield* Effect.provideService(\n * Effect.map(References.TracerSpanLinks, (links) => links.length),\n * References.TracerSpanLinks,\n * [spanLink]\n * )\n *\n * // Clear links\n * const clearedCount = yield* Effect.provideService(\n * Effect.map(References.TracerSpanLinks, (links) => links.length),\n * References.TracerSpanLinks,\n * []\n * )\n *\n * return [defaultCount, configuredCount, clearedCount]\n * })\n *\n * await Effect.runPromise(spanLinksExample) // => [0, 1, 0]\n * ```\n *\n * @category references\n * @since 4.0.0\n */\nexport const TracerSpanLinks = references.TracerSpanLinks;\n/**\n * Context reference for controlling whether trace timing is enabled globally. When set\n * to false, spans will not contain timing information (trace time will always\n * be set to zero).\n *\n * **When to use**\n *\n * Use to disable or re-enable timing capture for spans in the current context.\n *\n * **Example** (Toggling trace timing)\n *\n * ```ts import.meta.vitest\n * import { Effect, References } from \"effect\"\n *\n * const tracingControl = Effect.gen(function*() {\n * // Check if trace timing is enabled (default is true)\n * const current = yield* References.TracerTimingEnabled\n *\n * // Disable trace timing globally\n * const disabled = yield* Effect.provideService(\n * References.TracerTimingEnabled,\n * References.TracerTimingEnabled,\n * false\n * )\n *\n * // Re-enable trace timing\n * const enabled = yield* Effect.provideService(\n * References.TracerTimingEnabled,\n * References.TracerTimingEnabled,\n * true\n * )\n *\n * return [current, disabled, enabled]\n * })\n *\n * await Effect.runPromise(tracingControl) // => [true, false, true]\n * ```\n *\n * @category references\n * @since 4.0.0\n */\nexport const TracerTimingEnabled = references.TracerTimingEnabled;\n/**\n * Context reference for the log severity used when a pool finalizer reports an\n * unhandled error.\n *\n * **When to use**\n *\n * Use to choose whether and at which severity pool finalizer failures are\n * reported.\n *\n * **Details**\n *\n * The default level is `\"Error\"`.\n *\n * **Gotchas**\n *\n * Providing `undefined` suppresses this report; it does not fall back to\n * `CurrentLogLevel`.\n *\n * @see {@link CurrentLogLevel} for the default severity used by ordinary `Effect.log` calls\n * @see {@link MinimumLogLevel} for filtering emitted log entries by threshold\n *\n * @category references\n * @since 4.0.0\n */\nexport const UnhandledLogLevel = references.UnhandledLogLevel;\n/**\n * Context reference for the set of loggers currently used by Effect logging\n * operations.\n *\n * **When to use**\n *\n * Use to inspect or provide the complete set of loggers used by Effect logging\n * in the current context.\n *\n * **Details**\n *\n * The default set contains the built-in default logger and tracer logger.\n * Providing this reference changes which `Logger` instances receive log entries\n * in the current context.\n *\n * @category references\n * @since 4.0.0\n */\nexport const CurrentLoggers = internalEffect.CurrentLoggers;\n/**\n * Context reference for controlling whether built-in console loggers write to stderr.\n *\n * **When to use**\n *\n * Use to configure the runtime reference that controls whether built-in console\n * loggers write to stderr.\n *\n * **Details**\n *\n * The default value is `false`. When set to `true`, the built-in default logger\n * and TTY pretty console logger call `console.error` instead of `console.log`.\n *\n * @category references\n * @since 4.0.0\n */\nexport const LogToStderr = internalEffect.LogToStderr;\nexport {\n/**\n * Context reference for the current scheduler implementation used by the Effect runtime.\n * Controls how Effects are scheduled and executed.\n *\n * **When to use**\n *\n * Use to provide the scheduler implementation that fibers use in the current\n * context.\n *\n * **Example** (Providing a custom scheduler)\n *\n * ```ts import.meta.vitest\n * import { Effect, References, Scheduler } from \"effect\"\n *\n * const customScheduling = Effect.gen(function*() {\n * // Get current scheduler (default is MixedScheduler)\n * const current = yield* References.Scheduler\n * const isDefaultMixed = current instanceof Scheduler.MixedScheduler\n *\n * // Use a custom scheduler\n * const isCustomMixed = yield* Effect.provideService(\n * Effect.map(References.Scheduler, (scheduler) => scheduler instanceof Scheduler.MixedScheduler),\n * References.Scheduler,\n * new Scheduler.MixedScheduler()\n * )\n *\n * return [isDefaultMixed, isCustomMixed]\n * })\n *\n * await Effect.runPromise(customScheduling) // => [true, true]\n * ```\n *\n * @category references\n * @since 4.0.0\n */\nScheduler } from \"./Scheduler.js\";\n//# sourceMappingURL=References.js.map","/**\n * Controls how long resources stay open.\n *\n * A scope is a lifetime boundary. Code can register cleanup effects on it, and\n * closing the scope runs those cleanups with the `Exit` value that ended the\n * work. Most application code uses higher-level APIs such as `Effect.scoped`\n * and `Layer`, while this module is useful when code needs to create, provide,\n * fork, close, or inspect scopes directly.\n *\n * @since 2.0.0\n */\nimport * as effect from \"./internal/effect.js\";\nconst TypeId = effect.ScopeTypeId;\nconst CloseableTypeId = effect.ScopeCloseableTypeId;\n/**\n * Service tag for the active resource lifetime.\n *\n * **When to use**\n *\n * Use to access the active lifetime when registering finalizers or sharing\n * resources with the surrounding scope.\n *\n * **Example** (Accessing the scope service)\n *\n * ```ts import.meta.vitest\n * import { Effect, Scope } from \"effect\"\n *\n * const cleanups: Array<string> = []\n * const program = Effect.gen(function*() {\n * const scope = yield* Scope.Scope\n * yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push(\"Cleanup\")))\n * })\n *\n * Effect.runSync(Effect.scoped(program))\n * cleanups // => [\"Cleanup\"]\n * ```\n *\n * @category services\n * @since 2.0.0\n */\nexport const Scope = effect.scopeTag;\n/**\n * Creates a new `Scope` with the specified finalizer strategy.\n *\n * **Example** (Creating a scope)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Scope } from \"effect\"\n *\n * const cleanups: Array<string> = []\n * const program = Effect.gen(function*() {\n * const scope = yield* Scope.make(\"sequential\")\n * yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push(\"Cleanup 1\")))\n * yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push(\"Cleanup 2\")))\n * yield* Scope.close(scope, Exit.void)\n * })\n *\n * Effect.runSync(program)\n * cleanups // => [\"Cleanup 2\", \"Cleanup 1\"]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const make = effect.scopeMake;\n/**\n * Creates a new `Scope` synchronously without wrapping it in an `Effect`.\n * This is useful when you need a scope immediately but should be used with caution\n * as it doesn't provide the same safety guarantees as the `Effect`-wrapped version.\n *\n * **When to use**\n *\n * Use when a scope must be allocated synchronously and the caller will close it\n * manually.\n *\n * **Example** (Creating a scope synchronously)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Scope } from \"effect\"\n *\n * const scope = Scope.makeUnsafe(\"sequential\")\n * const cleanups: Array<string> = []\n * const program = Effect.gen(function*() {\n * yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push(\"Cleanup\")))\n * yield* Scope.close(scope, Exit.void)\n * })\n *\n * Effect.runSync(program)\n * cleanups // => [\"Cleanup\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeUnsafe = effect.scopeMakeUnsafe;\n/**\n * Provides a concrete `Scope` to an effect.\n *\n * **When to use**\n *\n * Use to run an effect that requires `Scope` with a scope managed by the\n * caller.\n *\n * **Details**\n *\n * Providing the scope removes the `Scope` requirement from the effect context.\n *\n * **Example** (Providing a scope)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Scope } from \"effect\"\n *\n * const events: Array<string> = []\n * const program = Effect.gen(function*() {\n * const scope = yield* Scope.Scope\n * yield* Scope.addFinalizer(scope, Effect.sync(() => events.push(\"cleanup\")))\n * events.push(\"working\")\n * })\n *\n * const withScope = Effect.gen(function*() {\n * const scope = yield* Scope.make()\n * yield* Scope.provide(scope)(program)\n * yield* Scope.close(scope, Exit.void)\n * })\n *\n * Effect.runSync(withScope)\n * events // => [\"working\", \"cleanup\"]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const provide = effect.provideScope;\n/**\n * Registers an exit-aware finalizer on a scope.\n *\n * **When to use**\n *\n * Use when cleanup needs to know whether the scope closed with success,\n * failure, or interruption.\n *\n * **Details**\n *\n * If the scope is open, the finalizer runs when the scope closes and receives\n * the scope's exit value. If the scope is already closed, the finalizer runs\n * immediately with the stored exit value.\n *\n * **Example** (Adding an exit-aware finalizer)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Scope } from \"effect\"\n *\n * const exits: Array<Exit.Exit<unknown, unknown>> = []\n * const withResource = Effect.gen(function*() {\n * const scope = yield* Scope.make()\n * yield* Scope.addFinalizerExit(scope, (exit) => Effect.sync(() => exits.push(exit)))\n * yield* Scope.close(scope, Exit.void)\n * })\n *\n * Effect.runSync(withResource)\n * exits // => [Exit.void]\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const addFinalizerExit = effect.scopeAddFinalizerExit;\n/**\n * Registers a finalizer effect on a scope.\n *\n * **Details**\n *\n * If the scope is open, the finalizer runs when the scope closes, regardless of\n * whether the scope closes successfully or with an error. If the scope is\n * already closed, the finalizer runs immediately.\n *\n * **Example** (Adding finalizers)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Scope } from \"effect\"\n *\n * const events: Array<string> = []\n * const program = Effect.gen(function*() {\n * const scope = yield* Scope.make()\n * yield* Scope.addFinalizer(scope, Effect.sync(() => events.push(\"cleanup 1\")))\n * yield* Scope.addFinalizer(scope, Effect.sync(() => events.push(\"cleanup 2\")))\n * yield* Scope.addFinalizer(scope, Effect.sync(() => events.push(\"cleanup 3\")))\n * events.push(\"work\")\n * yield* Scope.close(scope, Exit.void)\n * })\n *\n * Effect.runSync(program)\n * events // => [\"work\", \"cleanup 3\", \"cleanup 2\", \"cleanup 1\"]\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const addFinalizer = effect.scopeAddFinalizer;\n/**\n * Creates a closeable child scope registered with a parent scope.\n *\n * **Details**\n *\n * Closing the parent closes the child with the same exit value, and closing the\n * child detaches it from the parent. The optional finalizer strategy configures\n * the child scope and defaults to `\"sequential\"` when omitted.\n *\n * **Example** (Creating a child scope)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Scope } from \"effect\"\n *\n * const cleanups: Array<string> = []\n * const nestedScopes = Effect.gen(function*() {\n * const parentScope = yield* Scope.make(\"sequential\")\n * yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push(\"parent\")))\n * const childScope = yield* Scope.fork(parentScope, \"parallel\")\n * yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push(\"child\")))\n * yield* Scope.close(childScope, Exit.void)\n * yield* Scope.close(parentScope, Exit.void)\n * })\n *\n * Effect.runSync(nestedScopes)\n * cleanups // => [\"child\", \"parent\"]\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const fork = effect.scopeFork;\n/**\n * Creates a closeable child scope synchronously and registers it with a parent scope.\n *\n * **When to use**\n *\n * Use when a child scope must be created synchronously and the caller controls\n * both parent and child scope lifetimes.\n *\n * **Details**\n *\n * Closing the parent closes the child with the same exit value, and closing the\n * child detaches it from the parent. The optional finalizer strategy configures\n * the child scope and defaults to `\"sequential\"` when omitted.\n *\n * **Example** (Creating a child scope synchronously)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Scope } from \"effect\"\n *\n * const cleanups: Array<string> = []\n * const program = Effect.gen(function*() {\n * const parentScope = Scope.makeUnsafe(\"sequential\")\n * const childScope = Scope.forkUnsafe(parentScope, \"parallel\")\n * yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push(\"parent\")))\n * yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push(\"child\")))\n * yield* Scope.close(childScope, Exit.void)\n * yield* Scope.close(parentScope, Exit.void)\n * })\n *\n * Effect.runSync(program)\n * cleanups // => [\"child\", \"parent\"]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const forkUnsafe = effect.scopeForkUnsafe;\n/**\n * Closes a scope and runs its registered finalizers.\n *\n * **When to use**\n *\n * Use to close a scope manually with a specific exit value.\n *\n * **Details**\n *\n * Finalizers run in the scope's configured order and receive the supplied\n * `Exit`.\n *\n * **Example** (Running scope finalizers)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Scope } from \"effect\"\n *\n * const events: Array<string> = []\n * const resourceManagement = Effect.gen(function*() {\n * const scope = yield* Scope.make(\"sequential\")\n * yield* Scope.addFinalizer(scope, Effect.sync(() => events.push(\"database\")))\n * yield* Scope.addFinalizer(scope, Effect.sync(() => events.push(\"file\")))\n * yield* Scope.addFinalizer(scope, Effect.sync(() => events.push(\"memory\")))\n * events.push(\"work\")\n * yield* Scope.close(scope, Exit.succeed(\"Success!\"))\n * })\n *\n * Effect.runSync(resourceManagement)\n * events // => [\"work\", \"memory\", \"file\", \"database\"]\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const close = effect.scopeClose;\n/**\n * Closes a scope unsafely with the provided exit value.\n *\n * **When to use**\n *\n * Use when implementing lower-level scope machinery that must transition a\n * scope to `Closed` immediately and can run the returned finalizer effect when\n * one is produced.\n *\n * **Details**\n *\n * Returns an effect that runs registered finalizers, or `undefined` when the\n * scope was already closed or no finalizers need to run.\n *\n * **Gotchas**\n *\n * Ignoring the returned effect skips registered finalizers.\n *\n * @see {@link close} for the usual effectful close operation that always returns an `Effect`\n *\n * @category unsafe\n * @since 4.0.0\n */\nexport const closeUnsafe = effect.scopeCloseUnsafe;\n/**\n * Runs an effect with the provided closeable scope in its context and closes\n * that scope when the effect exits.\n *\n * **When to use**\n *\n * Use when you already have a `Closeable` scope and want to run an effect that\n * requires `Scope` while automatically closing that scope when the effect exits.\n *\n * **Details**\n *\n * The scope is closed with the same exit value as the effect, so registered\n * finalizers can observe whether the effect succeeded, failed, or was\n * interrupted.\n *\n * @see `provide` for providing a scope without closing it automatically\n * @see `Effect.scoped` for creating and closing a fresh scope around a workflow\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const use = effect.scopeUse;\n//# sourceMappingURL=Scope.js.map","import * as Context from \"./Context.js\";\nimport * as Deferred from \"./Deferred.js\";\nimport { constant, constTrue, constUndefined, dual, identity } from \"./Function.js\";\nimport * as core from \"./internal/core.js\";\nimport * as internalEffect from \"./internal/effect.js\";\nimport { getStackTraceLimit, setStackTraceLimit } from \"./internal/stackTraceLimit.js\";\nimport * as internalTracer from \"./internal/tracer.js\";\nimport { pipeArguments } from \"./Pipeable.js\";\nimport { hasProperty } from \"./Predicate.js\";\nimport { CurrentStackFrame } from \"./References.js\";\nimport * as Scope from \"./Scope.js\";\nimport * as Tracer from \"./Tracer.js\";\nconst TypeId = \"~effect/Layer\";\nconst MemoMapTypeId = \"~effect/Layer/MemoMap\";\nconst memoMapReuse = (entry, scope) => {\n entry.observers++;\n return internalEffect.andThen(internalEffect.scopeAddFinalizerExit(scope, exit => entry.finalizer(exit)), entry.effect);\n};\n/**\n * Returns `true` if the specified value is a `Layer`, `false` otherwise.\n *\n * **Example** (Checking whether a value is a layer)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer } from \"effect\"\n *\n * class Database extends Context.Service<Database, {\n * readonly query: (sql: string) => Effect.Effect<string>\n * }>()(\"Database\") {}\n *\n * const dbLayer = Layer.succeed(Database, {\n * query: Effect.fn(\"Database.query\")((sql: string) => Effect.succeed(\"result\"))\n * })\n * const notALayer = { someProperty: \"value\" }\n *\n * Layer.isLayer(dbLayer) // => true\n * Layer.isLayer(notALayer) // => false\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isLayer = u => hasProperty(u, TypeId);\nconst LayerProto = {\n [TypeId]: {\n _ROut: identity,\n _E: identity,\n _RIn: identity\n },\n pipe() {\n return pipeArguments(this, arguments);\n }\n};\nconst fromBuildUnsafe = build => {\n const self = Object.create(LayerProto);\n self.build = build;\n return self;\n};\n/**\n * Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to\n * build the layer.\n *\n * **Details**\n *\n * The function receives a `MemoMap` for memoization and a `Scope` for resource management.\n * A child scope is created, and if the build fails, the child scope is closed.\n *\n * **Example** (Constructing a layer from a build function)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer } from \"effect\"\n *\n * class Database extends Context.Service<Database, {\n * readonly query: (sql: string) => Effect.Effect<string>\n * }>()(\"Database\") {}\n *\n * const databaseLayer = Layer.fromBuild(() =>\n * Effect.sync(() =>\n * Context.make(Database, {\n * query: (sql: string) => Effect.succeed(\"result\")\n * })\n * )\n * )\n *\n * const program = Database.use((database) => database.query(\"SELECT 1\"))\n * Effect.runSync(Effect.provide(program, databaseLayer)) // => \"result\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromBuild = build => fromBuildUnsafe((memoMap, scope) => {\n const layerScope = Scope.forkUnsafe(scope);\n return internalEffect.onExit(build(memoMap, layerScope), exit => exit._tag === \"Failure\" ? Scope.close(layerScope, exit) : internalEffect.void);\n});\n/**\n * Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to\n * build the layer, with automatic memoization.\n *\n * **Details**\n *\n * This is similar to `fromBuild` but provides automatic memoization of the layer construction.\n * The layer will be memoized based on the provided `MemoMap`.\n *\n * **Example** (Memoizing layer construction)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer } from \"effect\"\n *\n * class Database extends Context.Service<Database, {\n * readonly query: (sql: string) => Effect.Effect<string>\n * }>()(\"Database\") {}\n *\n * const databaseLayer = Layer.fromBuildMemo(() =>\n * Effect.sync(() =>\n * Context.make(Database, {\n * query: (sql: string) => Effect.succeed(\"result\")\n * })\n * )\n * )\n *\n * const program = Database.use((database) => database.query(\"SELECT 1\"))\n * Effect.runSync(Effect.provide(program, databaseLayer)) // => \"result\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromBuildMemo = build => {\n const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build));\n return self;\n};\nconst memoMapBuild = (memoMap, layer, scope, build) => {\n const layerScope = Scope.makeUnsafe();\n const deferred = Deferred.makeUnsafe();\n const entry = {\n observers: 1,\n effect: Deferred.await(deferred),\n finalizer: exit => internalEffect.suspend(() => {\n entry.observers--;\n if (entry.observers === 0) {\n memoMap.map.delete(layer);\n return Scope.close(layerScope, exit);\n }\n return internalEffect.void;\n })\n };\n memoMap.map.set(layer, entry);\n return internalEffect.scopeAddFinalizerExit(scope, entry.finalizer).pipe(internalEffect.flatMap(() => build(memoMap, layerScope)), internalEffect.onExit(exit => {\n entry.effect = exit;\n return Deferred.done(deferred, exit);\n }));\n};\nclass MemoMapImpl {\n get [MemoMapTypeId]() {\n return MemoMapTypeId;\n }\n parent;\n constructor(parent) {\n this.parent = parent;\n }\n map = /*#__PURE__*/new Map();\n get(layer, scope) {\n const local = this.map.get(layer);\n if (local) {\n return memoMapReuse(local, scope);\n }\n return this.parent?.get(layer, scope);\n }\n getOrElseMemoize(layer, scope, build) {\n return internalEffect.suspend(() => {\n const existing = this.get(layer, scope);\n if (existing) {\n return existing;\n }\n return memoMapBuild(this, layer, scope, build);\n });\n }\n}\n/**\n * Constructs a `MemoMap` synchronously so it can be used to build additional layers.\n *\n * **Example** (Creating a memo map unsafely)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer } from \"effect\"\n *\n * class Database extends Context.Service<Database, {\n * readonly query: (sql: string) => Effect.Effect<string>\n * }>()(\"Database\") {}\n *\n * // Create a memo map for manual layer building\n * const program = Effect.gen(function*() {\n * const memoMap = Layer.makeMemoMapUnsafe()\n * const scope = yield* Effect.scope\n *\n * const dbLayer = Layer.succeed(Database, {\n * query: Effect.fn(\"Database.query\")((sql: string) => Effect.succeed(\"result\"))\n * })\n * const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope)\n *\n * return Context.get(context, Database)\n * })\n *\n * const database = Effect.runSync(Effect.scoped(program))\n * Effect.runSync(database.query(\"SELECT 1\")) // => \"result\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeMemoMapUnsafe = () => new MemoMapImpl();\n/**\n * Constructs a child `MemoMap` synchronously, allowing it to reuse layers\n * already memoized in the parent while isolating any new layer allocations to\n * the child map.\n *\n * **When to use**\n *\n * Use to synchronously fork a memo map for manual layer building when child\n * builds should see parent memoized layers without writing newly built layers\n * back to the parent.\n *\n * @see {@link forkMemoMap} for allocating the child memo map inside `Effect`\n * @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const forkMemoMapUnsafe = parent => new MemoMapImpl(parent);\n/**\n * Constructs a `MemoMap` effectfully so it can be used to build additional layers.\n *\n * **Example** (Creating a memo map in an effect)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer } from \"effect\"\n *\n * class Database extends Context.Service<Database, {\n * readonly query: (sql: string) => Effect.Effect<string>\n * }>()(\"Database\") {}\n *\n * // Create a memo map safely within an Effect\n * const program = Effect.gen(function*() {\n * const memoMap = yield* Layer.makeMemoMap\n * const scope = yield* Effect.scope\n *\n * const dbLayer = Layer.succeed(Database, {\n * query: Effect.fn(\"Database.query\")((sql: string) => Effect.succeed(\"result\"))\n * })\n * const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope)\n *\n * return Context.get(context, Database)\n * })\n *\n * const database = Effect.runSync(Effect.scoped(program))\n * Effect.runSync(database.query(\"SELECT 1\")) // => \"result\"\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const makeMemoMap = /*#__PURE__*/internalEffect.sync(makeMemoMapUnsafe);\n/**\n * Constructs a child `MemoMap` effectfully, allowing it to reuse layers already\n * memoized in the parent while isolating any new layer allocations to the child\n * map.\n *\n * **When to use**\n *\n * Use when a layer build should inherit already memoized layers from an\n * existing `MemoMap` while keeping newly memoized layers out of the parent map.\n *\n * @see {@link makeMemoMap} for creating a root memo map in an `Effect`\n * @see {@link forkMemoMapUnsafe} for the synchronous constructor variant\n * @see {@link buildWithMemoMap} for building layers with an explicit memo map\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const forkMemoMap = parent => internalEffect.sync(() => forkMemoMapUnsafe(parent));\n/**\n * Context service for the current `MemoMap` used in layer construction.\n *\n * **When to use**\n *\n * Use when building custom layer operations that need to access the current\n * memoization map from the fiber context.\n *\n * **Details**\n *\n * This service wraps a `MemoMap` as a `Context.Service`, making it available\n * for dependency injection during layer construction.\n *\n * @see {@link MemoMap} the memoization map type wrapped by this service\n *\n * @category services\n * @since 3.13.0\n */\nexport class CurrentMemoMap extends /*#__PURE__*/Context.Service()(\"effect/Layer/CurrentMemoMap\") {\n static forkOrCreate(self) {\n const current = Context.getOrUndefined(self, CurrentMemoMap);\n return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe();\n }\n}\n/**\n * Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize\n * the layer construction.\n *\n * **Example** (Building layers with an explicit memo map)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer } from \"effect\"\n *\n * class Database extends Context.Service<Database, {\n * readonly query: (sql: string) => Effect.Effect<string>\n * }>()(\"Database\") {}\n *\n * class Logger extends Context.Service<Logger, {\n * readonly log: (msg: string) => Effect.Effect<void>\n * }>()(\"Logger\") {}\n *\n * const logs: Array<string> = []\n *\n * // Build layers with explicit memoization control\n * const program = Effect.gen(function*() {\n * const memoMap = yield* Layer.makeMemoMap\n * const scope = yield* Effect.scope\n *\n * // Build database layer with memoization\n * const dbLayer = Layer.succeed(Database, {\n * query: Effect.fn(\"Database.query\")((sql: string) => Effect.succeed(\"result\"))\n * })\n * const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope)\n *\n * // Build logger layer with same memoization (reuses memo if same layer)\n * const loggerLayer = Layer.succeed(Logger, {\n * log: Effect.fn(\"Logger.log\")((msg: string) => Effect.sync(() => logs.push(msg)))\n * })\n * const loggerContext = yield* Layer.buildWithMemoMap(\n * loggerLayer,\n * memoMap,\n * scope\n * )\n *\n * return {\n * database: Context.get(dbContext, Database),\n * logger: Context.get(loggerContext, Logger)\n * }\n * })\n *\n * const services = Effect.runSync(Effect.scoped(program))\n * Effect.runSync(services.logger.log(\"ready\"))\n * logs // => [\"ready\"]\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const buildWithMemoMap = /*#__PURE__*/dual(3, (self, memoMap, scope) => internalEffect.provideService(internalEffect.map(self.build(memoMap, scope), Context.add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap));\n/**\n * Builds a layer into a scoped value.\n *\n * **Example** (Building a layer into a context)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer } from \"effect\"\n *\n * class Database extends Context.Service<Database, {\n * readonly query: (sql: string) => Effect.Effect<string>\n * }>()(\"Database\") {}\n *\n * // Build a layer to get its services\n * const program = Effect.gen(function*() {\n * const dbLayer = Layer.succeed(Database, {\n * query: Effect.fn(\"Database.query\")((sql: string) => Effect.succeed(\"result\"))\n * })\n *\n * // Build the layer into Context - automatically manages scope and memoization\n * const context = yield* Layer.build(dbLayer)\n *\n * // Extract the specific service from the built layer\n * const database = Context.get(context, Database)\n *\n * return yield* database.query(\"SELECT * FROM users\")\n * })\n *\n * Effect.runSync(Effect.scoped(program)) // => \"result\"\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const build = self => core.withFiber(fiber => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), Context.getUnsafe(fiber.context, Scope.Scope)));\n/**\n * Builds a layer using an explicit scope.\n *\n * **When to use**\n *\n * Use to control the lifetime of layer resources with a scope supplied by the\n * caller.\n *\n * **Details**\n *\n * Resources created by the layer are released when the supplied scope is\n * closed, unless a resource extends its own scope.\n *\n * **Example** (Building a layer with an explicit scope)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer, Scope } from \"effect\"\n *\n * class Database extends Context.Service<Database, {\n * readonly query: (sql: string) => Effect.Effect<string>\n * }>()(\"Database\") {}\n *\n * const logs: Array<string> = []\n *\n * // Build a layer with explicit scope control\n * const program = Effect.gen(function*() {\n * const scope = yield* Effect.scope\n *\n * const dbLayer = Layer.effect(Database, Effect.gen(function*() {\n * logs.push(\"Initializing database...\")\n * yield* Scope.addFinalizer(\n * scope,\n * Effect.sync(() => logs.push(\"Database closed\"))\n * )\n * return { query: Effect.fn(\"Database.query\")((sql: string) => Effect.succeed(`Result: ${sql}`)) }\n * }))\n *\n * // Build with specific scope - resources tied to this scope\n * const context = yield* Layer.buildWithScope(dbLayer, scope)\n * const database = Context.get(context, Database)\n *\n * return yield* database.query(\"SELECT * FROM users\")\n * // Database will be closed when scope is closed\n * })\n *\n * Effect.runSync(Effect.scoped(program)) // => \"Result: SELECT * FROM users\"\n * logs // => [\"Initializing database...\", \"Database closed\"]\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const buildWithScope = /*#__PURE__*/dual(2, (self, scope) => core.withFiber(fiber => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope)));\n/**\n * Constructs a layer that provides a single service from an already available\n * value.\n *\n * **When to use**\n *\n * Use when you need a `Layer` that provides a service from an already\n * constructed implementation without effectful acquisition.\n *\n * **Example** (Creating a layer from a service implementation)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer } from \"effect\"\n *\n * class Database extends Context.Service<Database, {\n * readonly query: (sql: string) => Effect.Effect<string>\n * }>()(\"Database\") {}\n *\n * const DatabaseLayer = Layer.succeed(Database, {\n * query: Effect.fn(\"Database.query\")((sql: string) => Effect.succeed(`Query result: ${sql}`))\n * })\n * const program = Database.use((database) => database.query(\"SELECT 1\"))\n * Effect.runSync(Effect.provide(program, DatabaseLayer)) // => \"Query result: SELECT 1\"\n * ```\n *\n * @see {@link sync} for constructing layers from lazy values\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const succeed = function () {\n if (arguments.length === 1) {\n return resource => succeedContext(Context.make(arguments[0], resource));\n }\n return succeedContext(Context.make(arguments[0], arguments[1]));\n};\n/**\n * Constructs a layer that provides all services in an already available\n * `Context`.\n *\n * **When to use**\n *\n * Use when you need a `Layer` built from an existing `Context`, including when\n * you need to provide multiple services at once.\n *\n * **Details**\n *\n * This is a more general version of `succeed` that allows you to provide\n * multiple services at once through a `Context`.\n *\n * **Example** (Providing multiple services from a context)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer } from \"effect\"\n *\n * class Database extends Context.Service<Database, {\n * readonly query: (sql: string) => Effect.Effect<string>\n * }>()(\"Database\") {}\n *\n * class Logger extends Context.Service<Logger, {\n * readonly log: (msg: string) => Effect.Effect<void>\n * }>()(\"Logger\") {}\n *\n * const logs: Array<string> = []\n * const context = Context.make(Database, {\n * query: Effect.fn(\"Database.query\")((sql: string) => Effect.succeed(\"result\"))\n * }).pipe(\n * Context.add(Logger, {\n * log: (msg: string) => Effect.sync(() => logs.push(msg))\n * })\n * )\n *\n * const layer = Layer.succeedContext(context)\n * const program = Logger.use((logger) => logger.log(\"ready\"))\n * Effect.runSync(Effect.provide(program, layer))\n * logs // => [\"ready\"]\n * ```\n *\n * @see {@link succeed} for providing a single service from a value\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const succeedContext = context => fromBuildUnsafe(constant(internalEffect.succeed(context)));\n/**\n * An empty layer that provides no services, cannot fail, has no requirements,\n * and performs no construction or finalization work.\n *\n * **When to use**\n *\n * Use as the no-op branch when conditionally composing layers.\n *\n * **Example** (Disabling optional lifecycle work)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer, Option } from \"effect\"\n *\n * const Service = Context.Service<string>(\"Service\")\n * const context = Effect.runSync(Effect.scoped(Layer.build(Layer.empty)))\n * Context.getOption(context, Service) // => Option.none()\n * ```\n *\n * @see {@link effectDiscard} for running an effect while providing no services\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const empty = /*#__PURE__*/succeedContext(/*#__PURE__*/Context.empty());\n/**\n * Constructs a layer lazily that provides a single service.\n *\n * **When to use**\n *\n * Use when you need a `Layer` that provides one service whose value is created\n * synchronously, but creation should be deferred until the layer is built.\n *\n * **Details**\n *\n * This is a lazy version of `succeed` where the service value is computed\n * synchronously only when the layer is built.\n *\n * **Example** (Lazily providing a service)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer } from \"effect\"\n *\n * class Database extends Context.Service<Database, {\n * readonly query: (sql: string) => Effect.Effect<string>\n * }>()(\"Database\") {}\n *\n * const layer = Layer.sync(Database, () => ({\n * query: (sql: string) => Effect.succeed(`Query: ${sql}`)\n * }))\n * const program = Database.use((database) => database.query(\"SELECT 1\"))\n * Effect.runSync(Effect.provide(program, layer)) // => \"Query: SELECT 1\"\n * ```\n *\n * @see {@link succeed} for constructing layers from static values\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const sync = function () {\n if (arguments.length === 1) {\n return evaluate => syncContext(() => Context.make(arguments[0], evaluate()));\n }\n return syncContext(() => Context.make(arguments[0], arguments[1]()));\n};\n/**\n * Constructs a layer lazily that provides all services in a `Context`.\n *\n * **When to use**\n *\n * Use when you need a `Layer` that creates multiple services synchronously but\n * defers that work until the layer is built.\n *\n * **Details**\n *\n * This is a lazy version of `succeedContext` where the `Context` is computed\n * synchronously only when the layer is built.\n *\n * **Example** (Lazily providing a context)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer } from \"effect\"\n *\n * class Database extends Context.Service<Database, {\n * readonly query: (sql: string) => Effect.Effect<string>\n * }>()(\"Database\") {}\n *\n * const layer = Layer.syncContext(() =>\n * Context.make(Database, {\n * query: (sql: string) => Effect.succeed(`Query: ${sql}`)\n * })\n * )\n * const program = Database.use((database) => database.query(\"SELECT 1\"))\n * Effect.runSync(Effect.provide(program, layer)) // => \"Query: SELECT 1\"\n * ```\n *\n * @see {@link sync} for lazily providing a single service\n * @see {@link succeedContext} for providing an already available context\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const syncContext = evaluate => fromBuildMemo(constant(internalEffect.sync(evaluate)));\n/**\n * Constructs a layer from an effect that produces a single service.\n *\n * **When to use**\n *\n * Use when you need to construct a `Layer`-provided service with an `Effect`,\n * dependencies, or scoped resource acquisition.\n *\n * **Details**\n *\n * This allows you to create a `Layer` from an `Effect` that produces a service.\n * The `Effect` is executed in the scope of the layer, allowing for proper\n * resource management.\n *\n * **Example** (Creating a layer from an effect)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer } from \"effect\"\n *\n * class Database extends Context.Service<Database, {\n * readonly query: (sql: string) => Effect.Effect<string>\n * }>()(\"Database\") {}\n *\n * const layer = Layer.effect(Database,\n * Effect.sync(() => ({\n * query: (sql: string) => Effect.succeed(`Query: ${sql}`)\n * }))\n * )\n * const program = Database.use((database) => database.query(\"SELECT 1\"))\n * Effect.runSync(Effect.provide(program, layer)) // => \"Query: SELECT 1\"\n * ```\n *\n * @see {@link effectContext} for effectfully providing multiple services\n * @see {@link effectDiscard} for running construction work without providing services\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const effect = function () {\n if (arguments.length === 1) {\n return effect => effectImpl(arguments[0], effect);\n }\n return effectImpl(arguments[0], arguments[1]);\n};\nconst effectImpl = (service, effect) => effectContext(internalEffect.map(effect, value => Context.make(service, value)));\n/**\n * Constructs a layer from an effect that produces all services in a `Context`.\n *\n * **When to use**\n *\n * Use when you need a `Layer` that effectfully constructs a `Context` with\n * multiple services.\n *\n * **Details**\n *\n * This allows you to create a `Layer` from an effectful computation that\n * returns multiple services. The `Effect` is executed in the scope of the\n * layer.\n *\n * **Example** (Creating a layer from an effectful context)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer } from \"effect\"\n *\n * class Database extends Context.Service<\n * Database,\n * { readonly query: (sql: string) => Effect.Effect<string> }\n * >()(\"Database\") {}\n *\n * const layer = Layer.effectContext(\n * Effect.succeed(Context.make(Database, {\n * query: (sql: string) => Effect.succeed(`Query: ${sql}`)\n * }))\n * )\n * const program = Database.use((database) => database.query(\"SELECT 1\"))\n * Effect.runSync(Effect.provide(program, layer)) // => \"Query: SELECT 1\"\n * ```\n *\n * @see {@link effect} for effectfully providing a single service\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const effectContext = effect => fromBuildMemo((_, scope) => Scope.provide(effect, scope));\n/**\n * Constructs a layer from an effect, discarding its value and providing no\n * services.\n *\n * **When to use**\n *\n * Use when layer construction should run an Effect for its side effects while providing no\n * services.\n *\n * **Example** (Running an effect during layer construction)\n *\n * ```ts import.meta.vitest\n * import { Effect, Layer } from \"effect\"\n *\n * const logs: Array<string> = []\n * const initLayer = Layer.effectDiscard(\n * Effect.sync(() => {\n * logs.push(\"Initializing application...\")\n * })\n * )\n * Effect.runSync(Effect.scoped(Layer.build(initLayer)))\n * logs // => [\"Initializing application...\"]\n * ```\n *\n * @see {@link empty} for a no-op layer that performs no construction work\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const effectDiscard = effect => effectContext(internalEffect.as(effect, Context.empty()));\n/**\n * Constructs a layer lazily using the specified factory.\n *\n * **Details**\n *\n * The factory is evaluated only when the suspended layer is first built, and\n * the result is memoized with normal layer sharing semantics.\n *\n * **Example** (Choosing a layer lazily)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer } from \"effect\"\n *\n * class Config extends Context.Service<Config, string>()(\"Config\") {}\n *\n * const useProd = true\n *\n * const layer = Layer.suspend(() =>\n * useProd\n * ? Layer.succeed(Config, \"https://api.example.com\")\n * : Layer.succeed(Config, \"http://localhost:3000\")\n * )\n * Effect.runSync(Effect.provide(Config, layer)) // => \"https://api.example.com\"\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const suspend = evaluate => fromBuildMemo((memoMap, scope) => internalEffect.suspend(() => evaluate().build(memoMap, scope)));\nconst unwrapKey = /*#__PURE__*/Context.Service(\"effect/Layer/unwrap\");\n/**\n * Unwraps a `Layer` from an `Effect`, flattening the nested structure.\n *\n * **When to use**\n *\n * Use when you have an `Effect` that produces a `Layer` and you want to\n * use that layer directly.\n *\n * **Details**\n *\n * The resulting Layer will have the combined error and dependency types from\n * both the outer Effect and the inner Layer.\n *\n * **Example** (Unwrapping an effectful layer)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer } from \"effect\"\n *\n * class Database extends Context.Service<Database, {\n * readonly query: (sql: string) => Effect.Effect<string>\n * }>()(\"Database\") {}\n *\n * const layerEffect = Effect.succeed(\n * Layer.succeed(Database, { query: Effect.fn(\"Database.query\")((sql: string) => Effect.succeed(\"result\")) })\n * )\n *\n * const unwrappedLayer = Layer.unwrap(layerEffect)\n * const program = Database.use((database) => database.query(\"SELECT 1\"))\n * Effect.runSync(Effect.provide(program, unwrappedLayer)) // => \"result\"\n * ```\n *\n * @category converting\n * @since 4.0.0\n */\nexport const unwrap = self => flatMap(effect(unwrapKey)(self), Context.get(unwrapKey));\nconst mergeAllEffect = (layers, memoMap, scope) => {\n const parentScope = Scope.forkUnsafe(scope, \"parallel\");\n return internalEffect.forEach(layers, layer => layer.build(memoMap, Scope.forkUnsafe(parentScope, \"sequential\")), {\n concurrency: layers.length\n }).pipe(internalEffect.map(context => Context.mergeAll(...context)));\n};\n/**\n * Combines all the provided layers concurrently, creating a new layer with\n * merged input, error, and output types.\n *\n * **When to use**\n *\n * Use when you need to combine multiple independent layers.\n *\n * **Details**\n *\n * All layers are built concurrently, and their outputs are merged into a single layer.\n *\n * If multiple merged layers depend on the same layer value, that dependency is\n * shared by default. Reuse a named layer value when you want services to share\n * the same resource, such as one database pool.\n *\n * **Example** (Merging independent layers)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer } from \"effect\"\n *\n * class Database extends Context.Service<Database, {\n * readonly query: (sql: string) => Effect.Effect<string>\n * }>()(\"Database\") {}\n *\n * class Logger extends Context.Service<Logger, {\n * readonly log: (msg: string) => Effect.Effect<void>\n * }>()(\"Logger\") {}\n *\n * const dbLayer = Layer.succeed(Database, {\n * query: Effect.fn(\"Database.query\")((sql: string) => Effect.succeed(\"result\"))\n * })\n * const logs: Array<string> = []\n * const loggerLayer = Layer.succeed(Logger, {\n * log: Effect.fn(\"Logger.log\")((msg: string) => Effect.sync(() => logs.push(msg)))\n * })\n *\n * const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer)\n * const program = Logger.use((logger) => logger.log(\"ready\"))\n * Effect.runSync(Effect.provide(program, mergedLayer))\n * logs // => [\"ready\"]\n * ```\n *\n * @see {@link merge} for merging one layer with another layer or array\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const mergeAll = (...layers) => fromBuild((memoMap, scope) => mergeAllEffect(layers, memoMap, scope));\n/**\n * Merges this layer with another layer concurrently, producing a new layer with\n * combined input, error, and output types.\n *\n * **When to use**\n *\n * Use to combine an existing `Layer` with another `Layer` or an array of\n * layers while preserving pipeline style.\n *\n * **Details**\n *\n * This is a binary version of `mergeAll` that merges exactly two layers or one\n * layer with an array of layers. The layers are built concurrently and their\n * outputs are combined.\n *\n * **Example** (Merging two layers)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer } from \"effect\"\n *\n * class Database extends Context.Service<Database, {\n * readonly query: (sql: string) => Effect.Effect<string>\n * }>()(\"Database\") {}\n *\n * class Logger extends Context.Service<Logger, {\n * readonly log: (msg: string) => Effect.Effect<void>\n * }>()(\"Logger\") {}\n *\n * const dbLayer = Layer.succeed(Database, {\n * query: Effect.fn(\"Database.query\")((sql: string) => Effect.succeed(\"result\"))\n * })\n * const loggerLayer = Layer.succeed(Logger, {\n * log: Effect.fn(\"Logger.log\")((_msg: string) => Effect.void)\n * })\n *\n * const mergedLayer = Layer.merge(dbLayer, loggerLayer)\n * const program = Database.use((database) => database.query(\"SELECT 1\"))\n * Effect.runSync(Effect.provide(program, mergedLayer)) // => \"result\"\n * ```\n *\n * @see {@link mergeAll} for merging several layers at once\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const merge = /*#__PURE__*/dual(2, (self, that) => mergeAll(self, ...(Array.isArray(that) ? that : [that])));\nconst provideWith = (self, that, f) => fromBuild((memoMap, scope) => internalEffect.flatMap(Array.isArray(that) ? mergeAllEffect(that, memoMap, scope) : that.build(memoMap, scope), context => self.build(memoMap, scope).pipe(internalEffect.provideContext(context), internalEffect.map(merged => f(merged, context)))));\n/**\n * Feeds the output services of the dependency layer into the requirements of\n * this layer, returning a layer that only provides the services from this layer.\n *\n * **When to use**\n *\n * Use when you need to hide an implementation dependency layer from callers.\n *\n * **Details**\n *\n * In `serviceLayer.pipe(Layer.provide(dependencyLayer))`, the dependency layer is\n * built first and is used to satisfy the requirements of `serviceLayer`.\n *\n * **Example** (Providing layer dependencies)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer } from \"effect\"\n *\n * class Database extends Context.Service<Database, {\n * readonly query: (sql: string) => Effect.Effect<string>\n * }>()(\"Database\") {}\n *\n * class UserService extends Context.Service<UserService, {\n * readonly getUser: (id: string) => Effect.Effect<{\n * id: string\n * name: string\n * }>\n * }>()(\"UserService\") {}\n *\n * class Logger extends Context.Service<Logger, {\n * readonly log: (msg: string) => Effect.Effect<void>\n * }>()(\"Logger\") {}\n *\n * // Create dependency layers\n * const databaseLayer = Layer.succeed(Database, {\n * query: Effect.fn(\"Database.query\")((sql: string) => Effect.succeed(`DB: ${sql}`))\n * })\n *\n * const logs: Array<string> = []\n * const loggerLayer = Layer.succeed(Logger, {\n * log: Effect.fn(\"Logger.log\")((msg: string) => Effect.sync(() => logs.push(`[LOG] ${msg}`)))\n * })\n *\n * // UserService depends on Database and Logger\n * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() {\n * const database = yield* Database\n * const logger = yield* Logger\n *\n * return {\n * getUser: Effect.fn(\"UserService.getUser\")(function*(id: string) {\n * yield* logger.log(`Looking up user ${id}`)\n * const result = yield* database.query(\n * `SELECT * FROM users WHERE id = ${id}`\n * )\n * return { id, name: result }\n * })\n * }\n * }))\n *\n * // Provide dependencies to UserService layer\n * const userServiceWithDependencies = userServiceLayer.pipe(\n * Layer.provide(Layer.mergeAll(databaseLayer, loggerLayer))\n * )\n *\n * // Now UserService layer has no dependencies\n * const program = Effect.gen(function*() {\n * const userService = yield* UserService\n * return yield* userService.getUser(\"123\")\n * }).pipe(\n * Effect.provide(userServiceWithDependencies)\n * )\n * Effect.runSync(program) // => { id: \"123\", name: \"DB: SELECT * FROM users WHERE id = 123\" }\n * logs // => [\"[LOG] Looking up user 123\"]\n * ```\n *\n * @see {@link provideMerge} for retaining the dependency services\n *\n * @category providing services\n * @since 2.0.0\n */\nexport const provide = /*#__PURE__*/dual(2, (self, that) => provideWith(self, that, identity));\n/**\n * Feeds the output services of the dependency layer into the requirements of\n * this layer, returning a layer that provides both sets of services.\n *\n * **When to use**\n *\n * Use when you need to compose `Layer`s while keeping both the constructed\n * service and the dependency used to build it available.\n *\n * **Details**\n *\n * Prefer {@link provide} when the dependency should stay private.\n *\n * **Example** (Providing dependencies while retaining services)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer } from \"effect\"\n *\n * class Database extends Context.Service<Database, {\n * readonly query: (sql: string) => Effect.Effect<string>\n * }>()(\"Database\") {}\n *\n * class Logger extends Context.Service<Logger, {\n * readonly log: (msg: string) => Effect.Effect<void>\n * }>()(\"Logger\") {}\n *\n * class UserService extends Context.Service<UserService, {\n * readonly getUser: (id: string) => Effect.Effect<{\n * id: string\n * name: string\n * }>\n * }>()(\"UserService\") {}\n *\n * // Create dependency layers\n * const databaseLayer = Layer.succeed(Database, {\n * query: Effect.fn(\"Database.query\")((sql: string) => Effect.succeed(`DB: ${sql}`))\n * })\n *\n * const logs: Array<string> = []\n * const loggerLayer = Layer.succeed(Logger, {\n * log: Effect.fn(\"Logger.log\")((msg: string) => Effect.sync(() => logs.push(`[LOG] ${msg}`)))\n * })\n *\n * // UserService depends on Database and Logger\n * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() {\n * const database = yield* Database\n * const logger = yield* Logger\n *\n * return {\n * getUser: Effect.fn(\"UserService.getUser\")(function*(id: string) {\n * yield* logger.log(`Looking up user ${id}`)\n * const result = yield* database.query(\n * `SELECT * FROM users WHERE id = ${id}`\n * )\n * return { id, name: result }\n * })\n * }\n * }))\n *\n * // Provide dependencies and merge all services together\n * const allServicesLayer = userServiceLayer.pipe(\n * Layer.provideMerge(Layer.mergeAll(databaseLayer, loggerLayer))\n * )\n *\n * // Now the resulting layer provides UserService, Database, AND Logger\n * const program = Effect.gen(function*() {\n * const userService = yield* UserService\n * const logger = yield* Logger // Still available!\n * const database = yield* Database // Still available!\n *\n * const user = yield* userService.getUser(\"123\")\n * yield* logger.log(`Found user: ${user.name}`)\n *\n * return user\n * }).pipe(\n * Effect.provide(allServicesLayer)\n * )\n * Effect.runSync(program) // => { id: \"123\", name: \"DB: SELECT * FROM users WHERE id = 123\" }\n * logs // => [\"[LOG] Looking up user 123\", \"[LOG] Found user: DB: SELECT * FROM users WHERE id = 123\"]\n * ```\n *\n * @see {@link provide} for keeping dependency services private\n *\n * @category providing services\n * @since 2.0.0\n */\nexport const provideMerge = /*#__PURE__*/dual(2, (self, that) => provideWith(self, that, (self, that) => Context.merge(that, self)));\n/**\n * Constructs a layer dynamically based on the output of this layer.\n *\n * **Example** (Creating services from layer output)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer } from \"effect\"\n *\n * class Config extends Context.Service<Config, {\n * readonly dbUrl: string\n * readonly logLevel: string\n * }>()(\"Config\") {}\n *\n * class Database extends Context.Service<Database, {\n * readonly query: (sql: string) => Effect.Effect<string>\n * }>()(\"Database\") {}\n *\n * class Logger extends Context.Service<Logger, {\n * readonly log: (msg: string) => Effect.Effect<void>\n * }>()(\"Logger\") {}\n *\n * const logs: Array<string> = []\n *\n * // Base config layer\n * const configLayer = Layer.succeed(Config, {\n * dbUrl: \"postgres://localhost:5432/mydb\",\n * logLevel: \"debug\"\n * })\n *\n * // Dynamically create services based on config\n * const dynamicServiceLayer = configLayer.pipe(\n * Layer.flatMap((context) => {\n * const config = Context.get(context, Config)\n *\n * // Create database layer based on config\n * const dbLayer = Layer.succeed(Database, {\n * query: Effect.fn(\"Database.query\")((sql: string) =>\n * Effect.succeed(\n * `Querying ${config.dbUrl}: ${sql}`\n * ))\n * })\n *\n * // Create logger layer based on config\n * const loggerLayer = Layer.succeed(Logger, {\n * log: Effect.fn(\"Logger.log\")((msg: string) =>\n * config.logLevel === \"debug\"\n * ? Effect.sync(() => logs.push(`[DEBUG] ${msg}`))\n * : Effect.sync(() => logs.push(msg))\n * )\n * })\n *\n * // Return combined layer\n * return Layer.mergeAll(dbLayer, loggerLayer)\n * })\n * )\n *\n * // Use the dynamic services\n * const program = Effect.gen(function*() {\n * const database = yield* Database\n * const logger = yield* Logger\n *\n * yield* logger.log(\"Starting database query\")\n * const result = yield* database.query(\"SELECT * FROM users\")\n *\n * return result\n * }).pipe(\n * Effect.provide(dynamicServiceLayer)\n * )\n * Effect.runSync(program) // => \"Querying postgres://localhost:5432/mydb: SELECT * FROM users\"\n * logs // => [\"[DEBUG] Starting database query\"]\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const flatMap = /*#__PURE__*/dual(2, (self, f) => fromBuild((memoMap, scope) => internalEffect.flatMap(self.build(memoMap, scope), context => f(context).build(memoMap, scope))));\n/**\n * Performs the specified effect if this layer succeeds.\n *\n * **When to use**\n *\n * Use to run an effectful observation after a layer has been built\n * successfully, such as logging or metrics, without changing the services the\n * layer provides.\n *\n * **Details**\n *\n * The callback receives the services produced by this layer. Its result is\n * discarded, and the original layer output is preserved.\n *\n * @see {@link tapError} for running an effect when layer construction fails with a typed error\n * @see {@link tapCause} for running an effect when layer construction fails with any cause\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const tap = /*#__PURE__*/dual(2, (self, f) => fromBuild((memoMap, scope) => internalEffect.flatMap(self.build(memoMap, scope), context => Scope.provide(internalEffect.as(f(context), context), scope))));\n/**\n * Performs the specified effect if this layer fails.\n *\n * **When to use**\n *\n * Use to run logging, metrics, or other effects when layer construction fails\n * while preserving the original typed error.\n *\n * **Details**\n *\n * The callback receives the typed error. If the callback succeeds, the layer\n * still fails with the original error; if the callback fails, that failure is\n * added to the layer's error type.\n *\n * @see {@link tap} for running an effect when layer construction succeeds\n * @see {@link tapCause} for inspecting the full failure cause, including defects and interruption\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const tapError = /*#__PURE__*/dual(2, (self, f) => fromBuild((memoMap, scope) => internalEffect.catch_(self.build(memoMap, scope), error => Scope.provide(internalEffect.andThen(f(error), internalEffect.fail(error)), scope))));\n/**\n * Performs the specified effect when this layer fails with any cause.\n *\n * **When to use**\n *\n * Use to run diagnostics or reporting when layer construction fails and the\n * full `Cause` is needed.\n *\n * **Details**\n *\n * The callback receives the layer's `Cause`, so it can inspect typed errors,\n * defects, and interruption information. If the callback succeeds, the layer\n * fails again with the original cause; if the callback fails, that failure is\n * added to the layer's error type.\n *\n * @see {@link tapError} for observing only typed layer construction errors\n * @see {@link catchCause} for recovering from a layer construction failure by switching to another layer\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const tapCause = /*#__PURE__*/dual(2, (self, f) => fromBuild((memoMap, scope) => internalEffect.catchCause(self.build(memoMap, scope), cause => Scope.provide(internalEffect.andThen(f(cause), internalEffect.failCause(cause)), scope))));\n/**\n * Converts layer construction failures into defects, removing them from the\n * layer's error type.\n *\n * **Details**\n *\n * Use this only when failures should be treated as unrecoverable defects rather\n * than typed errors that callers can handle.\n *\n * **Example** (Converting layer failures to defects)\n *\n * ```ts import.meta.vitest\n * import { Context, Data, Effect, Exit, Layer } from \"effect\"\n *\n * class DatabaseError extends Data.TaggedError(\"DatabaseError\")<{\n * message: string\n * }> {}\n *\n * class Database extends Context.Service<Database, {\n * readonly query: (sql: string) => Effect.Effect<string>\n * }>()(\"Database\") {}\n *\n * // Layer that can fail during construction\n * const error = new DatabaseError({ message: \"Connection failed\" })\n * const flakyDatabaseLayer = Layer.effect(\n * Database,\n * Effect.fail(error)\n * )\n *\n * // Convert failures to fiber death - removes error from type\n * const reliableDatabaseLayer = flakyDatabaseLayer.pipe(Layer.orDie)\n *\n * // Now the layer type is Layer<Database, never, never> - no error in type\n * const program = Effect.gen(function*() {\n * const database = yield* Database\n * return yield* database.query(\"SELECT * FROM users\")\n * }).pipe(\n * Effect.provide(reliableDatabaseLayer)\n * )\n *\n * Effect.runSync(Effect.exit(program)) // => Exit.die(error)\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const orDie = self => fromBuildUnsafe((memoMap, scope) => internalEffect.orDie(self.build(memoMap, scope)));\nconst catch_ = /*#__PURE__*/dual(2, (self, onError) => fromBuildUnsafe((memoMap, scope) => internalEffect.catch_(self.build(memoMap, scope), e => onError(e).build(memoMap, scope))));\nexport {\n/**\n * Recovers from all typed errors by switching to another layer.\n *\n * **When to use**\n *\n * Use when every typed `Layer` construction error should use the same\n * recovery path.\n *\n * @see {@link catchTag} for recovering from specific tagged errors\n * @see {@link catchCause} for recovering with access to the full cause\n *\n * @category error handling\n * @since 4.0.0\n */\ncatch_ as catch };\n/**\n * Recovers from specific tagged errors.\n *\n * **When to use**\n *\n * Use when only some tagged `Layer` construction errors should be recovered.\n *\n * **Example** (Recovering from tagged layer errors)\n *\n * ```ts import.meta.vitest\n * import { Context, Data, Effect, Layer } from \"effect\"\n *\n * class ConfigError extends Data.TaggedError(\"ConfigError\") {}\n *\n * class Config extends Context.Service<Config, {\n * readonly apiUrl: string\n * }>()(\"Config\") {}\n *\n * const configLayer = Layer.effect(Config, Effect.fail(new ConfigError()))\n *\n * const fallbackLayer = Layer.succeed(Config, { apiUrl: \"http://localhost\" })\n *\n * const recovered = configLayer.pipe(\n * Layer.catchTag(\"ConfigError\", () => fallbackLayer)\n * )\n * const program = Config.useSync((config) => config.apiUrl)\n * Effect.runSync(Effect.provide(program, recovered)) // => \"http://localhost\"\n * ```\n *\n * @see {@link catchCause} for recovering with access to the full cause\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchTag = /*#__PURE__*/dual(3, (self, k, f) => fromBuildUnsafe((memoMap, scope) => internalEffect.catchTag(self.build(memoMap, scope), k, error => f(error).build(memoMap, scope))));\n/**\n * Recovers from any failure cause by switching to another layer.\n *\n * **When to use**\n *\n * Use when you need `Layer` recovery to inspect more than the typed error,\n * such as defects or interruption information.\n *\n * **Details**\n *\n * The handler receives the full `Cause` of the failed layer, including typed\n * errors, unexpected defects, and interruption information, and returns the\n * fallback layer to build instead. Finalizers for resources acquired by the\n * failed layer are still run before the fallback layer is acquired.\n *\n * **Example** (Recovering from layer failures by cause)\n *\n * ```ts import.meta.vitest\n * import { Context, Data, Effect, Layer } from \"effect\"\n *\n * class DatabaseError extends Data.TaggedError(\"DatabaseError\")<{\n * message: string\n * }> {}\n *\n * class Database extends Context.Service<Database, {\n * readonly query: (sql: string) => Effect.Effect<string>\n * }>()(\"Database\") {}\n *\n * const primaryDatabaseLayer = Layer.effect(Database,\n * Effect.fail(new DatabaseError({ message: \"Primary DB unreachable\" }))\n * )\n *\n * const databaseWithFallback = primaryDatabaseLayer.pipe(\n * Layer.catchCause(() => {\n * return Layer.succeed(Database, {\n * query: Effect.fn(\"Database.query\")((sql: string) => Effect.succeed(`Memory: ${sql}`))\n * })\n * })\n * )\n *\n * const program = Effect.gen(function*() {\n * const database = yield* Database\n * return yield* database.query(\"SELECT * FROM users\")\n * }).pipe(\n * Effect.provide(databaseWithFallback)\n * )\n *\n * await Effect.runPromise(program) // => \"Memory: SELECT * FROM users\"\n * ```\n *\n * @see {@link catchTag} for recovering from specific tagged errors\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchCause = /*#__PURE__*/dual(2, (self, onError) => fromBuildUnsafe((memoMap, scope) => internalEffect.catchCause(self.build(memoMap, scope), cause => onError(cause).build(memoMap, scope))));\n/**\n * Updates a service in the context with a new implementation.\n *\n * **When to use**\n *\n * Use to adapt or extend a service's behavior during the creation of a\n * layer.\n *\n * **Details**\n *\n * This function modifies the existing implementation of a service in the\n * context. It retrieves the current service, applies the provided\n * transformation function `f`, and replaces the old service with the\n * transformed one.\n *\n * @category providing services\n * @since 3.13.0\n */\nexport const updateService = /*#__PURE__*/dual(3, (layer, service, f) => provide(layer, effect(service, internalEffect.map(service, f))));\n/**\n * Creates a fresh version of this layer that will not be shared.\n *\n * **When to use**\n *\n * Use when you need two parts of an application to receive separate instances\n * of a resource, such as two independent client sessions.\n *\n * **Gotchas**\n *\n * Do not use it just to work around confusing composition. By default, sharing\n * the same layer value is usually the desired behavior.\n *\n * **Example** (Creating non-shared layer instances)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer, Ref } from \"effect\"\n *\n * class Counter extends Context.Service<Counter, {\n * readonly id: number\n * }>()(\"Counter\") {}\n *\n * class Left extends Context.Service<Left, {\n * readonly counterId: number\n * }>()(\"Left\") {}\n *\n * class Right extends Context.Service<Right, {\n * readonly counterId: number\n * }>()(\"Right\") {}\n *\n * const leftLayer = Layer.effect(Left, Effect.gen(function*() {\n * const counter = yield* Counter\n * return { counterId: counter.id }\n * }))\n *\n * const rightLayer = Layer.effect(Right, Effect.gen(function*() {\n * const counter = yield* Counter\n * return { counterId: counter.id }\n * }))\n *\n * const compareIds = Effect.gen(function*() {\n * const left = yield* Left\n * const right = yield* Right\n * return left.counterId === right.counterId\n * })\n *\n * const program = Effect.gen(function*() {\n * const nextId = yield* Ref.make(0)\n *\n * const counterLayer = Layer.effect(Counter, Effect.gen(function*() {\n * const id = yield* Ref.updateAndGet(nextId, (n) => n + 1)\n * return { id }\n * }))\n *\n * const shared = Layer.merge(\n * Layer.provide(leftLayer, counterLayer),\n * Layer.provide(rightLayer, counterLayer)\n * )\n *\n * const sharedResult = yield* Effect.provide(compareIds, shared)\n *\n * const freshCounterLayer = Layer.fresh(counterLayer)\n * const fresh = Layer.merge(\n * Layer.provide(leftLayer, freshCounterLayer),\n * Layer.provide(rightLayer, freshCounterLayer)\n * )\n *\n * const freshResult = yield* Effect.provide(compareIds, fresh)\n *\n * return { shared: sharedResult, fresh: freshResult }\n * })\n *\n * await Effect.runPromise(program) // => { shared: true, fresh: false }\n * ```\n *\n * @category layers\n * @since 2.0.0\n */\nexport const fresh = self => fromBuildUnsafe((_, scope) => self.build(makeMemoMapUnsafe(), scope));\n/**\n * Builds this layer and keeps it alive until the returned effect is interrupted.\n *\n * **When to use**\n *\n * Use when you model your entire application as a layer, such as an HTTP\n * server.\n *\n * **Details**\n *\n * When the returned effect is interrupted, the layer scope is closed and all\n * finalizers registered during layer acquisition are run.\n *\n * **Example** (Launching an application layer)\n *\n * ```ts import.meta.vitest\n * import { Context, Deferred, Effect, Fiber, Layer, Ref } from \"effect\"\n *\n * class HttpServer extends Context.Service<HttpServer, {\n * readonly port: number\n * }>()(\"HttpServer\") {}\n *\n * const program = Effect.gen(function*() {\n * const events = yield* Ref.make<Array<string>>([])\n * const started = yield* Deferred.make<void>()\n *\n * const serverLayer = Layer.effect(HttpServer, Effect.gen(function*() {\n * yield* Ref.update(events, (events) => [...events, \"Starting HTTP server...\"])\n * yield* Deferred.succeed(started, undefined)\n * return { port: 3000 }\n * }))\n *\n * const fiber = yield* Effect.forkChild(Layer.launch(serverLayer))\n * yield* Deferred.await(started)\n * yield* Fiber.interrupt(fiber)\n * return yield* Ref.get(events)\n * })\n *\n * await Effect.runPromise(program) // => [\"Starting HTTP server...\"]\n * ```\n *\n * @category converting\n * @since 2.0.0\n */\nexport const launch = self => internalEffect.scoped(internalEffect.andThen(build(self), internalEffect.never));\n/**\n * Creates a mock layer for testing purposes. You can provide a partial\n * implementation of the service. Any missing members that are `Effect`s,\n * `Stream`s, `Channel`s, or functions returning them will fail with an\n * unimplemented defect when used.\n *\n * **Details**\n *\n * Missing members are represented by a value that can be used as an `Effect`,\n * `Stream`, `Channel`, or as a function returning an `Effect`. This lets the\n * mock preserve the shape of common service methods while still failing loudly\n * when an unimplemented member is exercised.\n *\n * **Example** (Mocking services for tests)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer } from \"effect\"\n *\n * class UserService extends Context.Service<UserService, {\n * readonly config: { apiUrl: string }\n * readonly getUser: (\n * id: string\n * ) => Effect.Effect<{ id: string; name: string }, Error>\n * readonly deleteUser: (id: string) => Effect.Effect<void, Error>\n * readonly updateUser: (\n * id: string,\n * data: object\n * ) => Effect.Effect<{ id: string; name: string }, Error>\n * }>()(\"UserService\") {}\n *\n * // Create a partial mock - only implement what you need for testing\n * const testUserLayer = Layer.mock(UserService, {\n * config: { apiUrl: \"https://test-api.com\" }, // Required - non-Effect property\n * getUser: (id: string) => Effect.succeed({ id, name: \"Test User\" }) // Mock implementation\n * // deleteUser and updateUser are omitted - will throw UnimplementedError if called\n * })\n *\n * // Use in tests\n * const testProgram = Effect.gen(function*() {\n * const userService = yield* UserService\n *\n * // This works - we provided an implementation\n * const user = yield* userService.getUser(\"123\")\n *\n * // This would throw - we didn't implement deleteUser\n * // yield* userService.deleteUser(\"123\") // UnimplementedError\n *\n * return user.name\n * }).pipe(\n * Effect.provide(testUserLayer)\n * )\n * Effect.runSync(testProgram) // => \"Test User\"\n * ```\n *\n * @category testing\n * @since 3.17.0\n */\nexport const mock = function () {\n if (arguments.length === 1) {\n return implementation => mockImpl(arguments[0], implementation);\n }\n return mockImpl(arguments[0], arguments[1]);\n};\nconst mockImpl = (service, implementation) => succeed(service)(new Proxy({\n ...implementation\n}, {\n get(target, prop, _receiver) {\n if (prop in target) {\n return target[prop];\n }\n const prevLimit = getStackTraceLimit();\n setStackTraceLimit(2);\n const error = new Error(`${service.key}: Unimplemented method \"${prop.toString()}\"`);\n setStackTraceLimit(prevLimit);\n error.name = \"UnimplementedError\";\n return makeUnimplemented(error);\n },\n has: constTrue\n}));\nconst makeUnimplemented = error => {\n const dead = Object.assign(internalEffect.die(error), {\n [StreamTypeId]: StreamTypeId,\n channel: {\n [ChannelTypeId]: ChannelTypeId,\n transform: () => internalEffect.succeed(dead),\n pipe() {\n return pipeArguments(this, arguments);\n }\n },\n [ChannelTypeId]: ChannelTypeId,\n transform: () => internalEffect.succeed(dead)\n });\n function unimplemented() {\n return dead;\n }\n // @effect-diagnostics-next-line floatingEffect:off\n Object.assign(unimplemented, dead);\n Object.setPrototypeOf(unimplemented, Object.getPrototypeOf(dead));\n return unimplemented;\n};\nconst StreamTypeId = \"~effect/Stream\";\nconst ChannelTypeId = \"~effect/Channel\";\n// -----------------------------------------------------------------------------\n// Type constraints\n// -----------------------------------------------------------------------------\n/**\n * Ensures that a layer's success type extends a given type `ROut`.\n *\n * **Details**\n *\n * This function provides compile-time type checking to ensure that the success\n * value of a layer conforms to a specific type constraint.\n *\n * **Example** (Constraining layer success types)\n *\n * ```ts import.meta.vitest\n * import { Context, Layer } from \"effect\"\n *\n * const NumberService = Context.Service<number>(\"Number\")\n * const numberLayer = Layer.succeed(NumberService, 42)\n *\n * // Define a constraint that the success type must be a number\n * const satisfiesNumber = Layer.satisfiesSuccessType<number>()\n *\n * // This works - Layer<42, never, never> extends Layer<number, never, never>\n * const validLayer = satisfiesNumber(numberLayer)\n * ```\n *\n * @category utility types\n * @since 4.0.0\n */\nexport const satisfiesSuccessType = () => layer => layer;\n/**\n * Ensures that a layer's error type extends a given type `E`.\n *\n * **Details**\n *\n * This function provides compile-time type checking to ensure that the error\n * type of a layer conforms to a specific type constraint.\n *\n * **Example** (Constraining layer error types)\n *\n * ```ts import.meta.vitest\n * import { Effect, Layer } from \"effect\"\n *\n * const typeErrorLayer = Layer.effectDiscard(Effect.fail(new TypeError(\"boom\")))\n *\n * // Define a constraint that the error type must be an Error\n * const satisfiesError = Layer.satisfiesErrorType<Error>()\n *\n * // This works - Layer<never, TypeError, never> extends Layer<never, Error, never>\n * const validLayer = satisfiesError(typeErrorLayer)\n * ```\n *\n * @category utility types\n * @since 4.0.0\n */\nexport const satisfiesErrorType = () => layer => layer;\n/**\n * Ensures that a layer's requirements type extends a given type `R`.\n *\n * **Details**\n *\n * This function provides compile-time type checking to ensure that the\n * requirements type of a layer conforms to a specific type constraint.\n *\n * **Example** (Constraining layer service requirements)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer } from \"effect\"\n *\n * const NumberService = Context.Service<number>(\"Number\")\n * const numberLayer = Layer.effectDiscard(Effect.asVoid(NumberService))\n *\n * // Define a constraint that the service requirements must be numbers\n * const satisfiesNumber = Layer.satisfiesServicesType<number>()\n *\n * // This works - Layer<never, never, 42> extends Layer<never, never, number>\n * const validLayer = satisfiesNumber(numberLayer)\n * ```\n *\n * @category utility types\n * @since 4.0.0\n */\nexport const satisfiesServicesType = () => layer => layer;\n/**\n * Constructs a new `Layer` which creates a span and registers it as the current\n * parent span.\n *\n * **Details**\n *\n * This allows you to create a traced scope for layer construction, making all\n * operations within the layer constructor part of the same trace span. The span\n * is automatically ended when the layer's scope is closed. If `onEnd` is\n * provided, it receives the span and the layer scope's exit value when the span\n * ends.\n *\n * **Example** (Tracing layer construction with a span)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer } from \"effect\"\n * import type { Tracer } from \"effect\"\n *\n * class Database extends Context.Service<Database, {\n * readonly query: (sql: string) => Effect.Effect<string>\n * }>()(\"Database\") {}\n *\n * const logs: Array<string> = []\n *\n * // Create a traced layer - all operations performed during construction of\n * // the `Database` service are part of the \"database-init\" span\n * const databaseLayer = Layer.effect(Database, Effect.gen(function*() {\n * // These operations are traced under \"database-init\" span\n * logs.push(\"Connecting to database\")\n * logs.push(\"Database connected\")\n *\n * const parentSpan = yield* Effect.currentParentSpan\n * logs.push((parentSpan as Tracer.Span).name)\n *\n * return {\n * query: Effect.fn(\"Database.query\")((sql: string) => Effect.succeed(`Result: ${sql}`))\n * }\n * })).pipe(Layer.provide(Layer.span(\"database-init\", {\n * onEnd: (span, exit) =>\n * Effect.sync(() => logs.push(`Span ${span.name} ended with: ${exit._tag}`))\n * })))\n *\n * const program = Database.use((database) => database.query(\"SELECT 1\"))\n * Effect.runSync(Effect.provide(program, databaseLayer)) // => \"Result: SELECT 1\"\n * logs // => [\"Connecting to database\", \"Database connected\", \"database-init\", \"Span database-init ended with: Success\"]\n * ```\n *\n * @category tracing\n * @since 2.0.0\n */\nexport const span = (name, options) => {\n options = internalTracer.addSpanStackTrace(options);\n return effect(Tracer.ParentSpan, options?.onEnd ? internalEffect.tap(internalEffect.makeSpanScoped(name, options), span => internalEffect.addFinalizer(exit => options.onEnd(span, exit))) : internalEffect.makeSpanScoped(name, options));\n};\n/**\n * Constructs a layer that provides an existing span as the current parent span.\n *\n * **Details**\n *\n * The supplied span is made available through `Tracer.ParentSpan` for layers\n * that are built with this layer. This API does not create, end, or close the\n * span; the caller remains responsible for the span's lifetime.\n *\n * **Example** (Referencing an existing parent span)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer, Tracer } from \"effect\"\n *\n * class Database extends Context.Service<Database, {\n * readonly spanId: string\n * readonly query: (sql: string) => Effect.Effect<string>\n * }>()(\"Database\") {}\n *\n * // Create a layer that uses an existing span as parent\n * const databaseLayer = Layer.effect(\n * Database,\n * Effect.gen(function*() {\n * const parentSpan = yield* Effect.currentParentSpan\n *\n * return {\n * spanId: parentSpan.spanId,\n * query: Effect.fn(\"Database.query\")((sql: string) => Effect.succeed(`Result: ${sql}`))\n * }\n * })\n * ).pipe(Layer.provide(Layer.parentSpan(Tracer.externalSpan({\n * spanId: \"42\",\n * traceId: \"000\"\n * }))))\n * const program = Database.use((database) =>\n * Effect.map(database.query(\"SELECT 1\"), (result) => ({ spanId: database.spanId, result })))\n * Effect.runSync(Effect.provide(program, databaseLayer)) // => { spanId: \"42\", result: \"Result: SELECT 1\" }\n * ```\n *\n * @category tracing\n * @since 2.0.0\n */\nexport const parentSpan = span => succeedContext(Tracer.ParentSpan.context(span));\n/**\n * Wraps a `Layer` with a new tracing span, making all operations in the layer\n * constructor part of the named trace span.\n *\n * **Details**\n *\n * This creates a new span for the layer's construction and execution. The span\n * is automatically ended when the layer's scope is closed. This is useful for\n * tracking the lifecycle and performance of layer initialization.\n *\n * **Example** (Wrapping a layer with a span)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer } from \"effect\"\n *\n * class Database extends Context.Service<Database, {\n * readonly query: (sql: string) => Effect.Effect<string>\n * }>()(\"Database\") {}\n *\n * class Logger extends Context.Service<Logger, {\n * readonly log: (msg: string) => Effect.Effect<void>\n * }>()(\"Logger\") {}\n *\n * const logs: Array<string> = []\n *\n * // Create layers with tracing\n * const databaseLayer = Layer.effect(Database, Effect.gen(function*() {\n * return {\n * query: Effect.fn(\"Database.query\")((sql: string) => Effect.succeed(`Result: ${sql}`))\n * }\n * })).pipe(Layer.withSpan(\"database-initialization\", {\n * attributes: { dbType: \"postgres\" }\n * }))\n *\n * const loggerLayer = Layer.succeed(Logger, {\n * log: Effect.fn(\"Logger.log\")((msg: string) => Effect.sync(() => logs.push(msg)))\n * }).pipe(Layer.withSpan(\"logger-initialization\"))\n *\n * // Combine traced layers\n * const appLayer = Layer.mergeAll(databaseLayer, loggerLayer).pipe(\n * Layer.withSpan(\"app-initialization\", {\n * onEnd: (span, exit) =>\n * Effect.sync(() => logs.push(`Application initialization completed: ${exit._tag}`))\n * })\n * )\n *\n * const program = Effect.gen(function*() {\n * const database = yield* Database\n * const logger = yield* Logger\n *\n * yield* logger.log(\"Application ready\")\n * return yield* database.query(\"SELECT * FROM users\")\n * }).pipe(Effect.provide(appLayer))\n * Effect.runSync(program) // => \"Result: SELECT * FROM users\"\n * logs // => [\"Application ready\", \"Application initialization completed: Success\"]\n * ```\n *\n * @category tracing\n * @since 2.0.0\n */\nexport const withSpan = function () {\n const dataFirst = typeof arguments[0] !== \"string\";\n const name = dataFirst ? arguments[1] : arguments[0];\n const options = internalTracer.addSpanStackTrace(dataFirst ? arguments[2] : arguments[1]);\n if (dataFirst) {\n const self = arguments[0];\n return unwrap(internalEffect.map(options?.onEnd !== undefined ? internalEffect.tap(internalEffect.makeSpanScoped(name, options), span => internalEffect.addFinalizer(exit => options.onEnd(span, exit))) : internalEffect.makeSpanScoped(name, options), span => withParentSpan(self, span, options)));\n }\n return self => unwrap(internalEffect.map(options?.onEnd !== undefined ? internalEffect.tap(internalEffect.makeSpanScoped(name, options), span => internalEffect.addFinalizer(exit => options.onEnd(span, exit))) : internalEffect.makeSpanScoped(name, options), span => withParentSpan(self, span, options)));\n};\n/**\n * Wraps a layer so spans created during its construction use the supplied span\n * as their parent.\n *\n * **Details**\n *\n * Use this to attach layer construction to an existing trace hierarchy. This API\n * does not create or end the supplied parent span.\n *\n * When the supplied span is a native `Span`, layer construction also receives\n * diagnostic information that helps associate failures with the layer call site.\n * External spans are only installed as the parent span and do not add this\n * diagnostic call-site information.\n *\n * **Example** (Attaching layers to an existing parent span)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer, Tracer } from \"effect\"\n *\n * class Database extends Context.Service<Database, {\n * readonly query: (sql: string) => Effect.Effect<string>\n * }>()(\"Database\") {}\n *\n * class Cache extends Context.Service<Cache, {\n * readonly get: (key: string) => Effect.Effect<string | null>\n * }>()(\"Cache\") {}\n *\n * // Create layers\n * const DatabaseLayer = Layer.effect(Database, Effect.gen(function*() {\n * return {\n * query: Effect.fn(\"Database.query\")((sql: string) => Effect.succeed(`DB: ${sql}`))\n * }\n * }))\n *\n * const CacheLayer = Layer.effect(Cache, Effect.gen(function*() {\n * return {\n * get: Effect.fn(\"Cache.get\")((key: string) => Effect.succeed(`Cache: ${key}`))\n * }\n * }))\n *\n * // Use with an existing parent span from Effect.withSpan\n * const program = Effect.withSpan(\"application-startup\")(\n * Effect.gen(function*() {\n * const parentSpan = yield* Tracer.ParentSpan\n *\n * // Both layers will be children of \"application-startup\" span\n * const AppLayer = Layer.mergeAll(DatabaseLayer, CacheLayer).pipe(\n * Layer.withParentSpan(parentSpan)\n * )\n *\n * const context = yield* Layer.build(AppLayer)\n * const database = Context.get(context, Database)\n * const cache = Context.get(context, Cache)\n *\n * const dbResult = yield* database.query(\"SELECT * FROM users\")\n * const cacheResult = yield* cache.get(\"user:123\")\n *\n * return { dbResult, cacheResult }\n * })\n * )\n * Effect.runSync(Effect.scoped(program)) // => { dbResult: \"DB: SELECT * FROM users\", cacheResult: \"Cache: user:123\" }\n * ```\n *\n * @category tracing\n * @since 2.0.0\n */\nexport const withParentSpan = function () {\n const dataFirst = isLayer(arguments[0]);\n const span = dataFirst ? arguments[1] : arguments[0];\n let options = dataFirst ? arguments[2] : arguments[1];\n let provideStackFrame = identity;\n if (span._tag === \"Span\") {\n options = internalTracer.addSpanStackTrace(options);\n provideStackFrame = provideSpanStackFrame(span.name, options?.captureStackTrace);\n }\n const parentSpanLayer = parentSpan(span);\n if (dataFirst) {\n return provide(provideStackFrame(arguments[0]), parentSpanLayer);\n }\n return self => provide(provideStackFrame(self), parentSpanLayer);\n};\nconst provideSpanStackFrame = (name, stack) => {\n stack = typeof stack === \"function\" ? stack : constUndefined;\n return updateService(CurrentStackFrame, parent => ({\n name,\n stack,\n parent\n }));\n};\n//# sourceMappingURL=Layer.js.map","/**\n * Records the full reason an `Effect` failed.\n *\n * A `Cause<E>` can contain typed failures, unexpected defects, interruptions,\n * and annotations. Keeping those details together lets code inspect or format\n * failures without first collapsing them to a single error value. This module\n * includes the `Cause` and `Reason` data types, helpers for building and\n * checking causes, and small error types used by several Effect APIs.\n *\n * @since 2.0.0\n */\nimport * as Context from \"./Context.js\";\nimport * as core from \"./internal/core.js\";\nimport * as effect from \"./internal/effect.js\";\n/**\n * Unique brand for `Cause` values, used for runtime type checks via {@link isCause}.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const TypeId = core.CauseTypeId;\n/**\n * Unique brand for `Reason` values, used for runtime type checks via {@link isReason}.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const ReasonTypeId = core.CauseReasonTypeId;\n/**\n * Checks whether an arbitrary value is a `Cause`.\n *\n * **Example** (Checking the runtime type)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * Cause.isCause(Cause.fail(\"error\")) // => true\n * Cause.isCause(\"not a cause\") // => false\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isCause = core.isCause;\n/**\n * Checks whether an arbitrary value is a `Reason` (`Fail`, `Die`, or `Interrupt`).\n *\n * **Example** (Checking the runtime type)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * const reason = Cause.fail(\"error\").reasons[0]\n * Cause.isReason(reason) // => true\n * Cause.isReason(\"not a reason\") // => false\n * ```\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isReason = core.isCauseReason;\n/**\n * Narrows a `Reason` to `Fail`.\n *\n * **When to use**\n *\n * Use as a predicate for `Array.filter` to pick out typed `Fail` reasons when\n * iterating over `cause.reasons`.\n *\n * **Example** (Filtering fail reasons)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * const cause = Cause.fail(\"error\")\n * const fails = cause.reasons.filter(Cause.isFailReason)\n * fails[0].error // => \"error\"\n * ```\n *\n * @see {@link isDieReason} — narrow to `Die`\n * @see {@link isInterruptReason} — narrow to `Interrupt`\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isFailReason = core.isFailReason;\n/**\n * Narrows a `Reason` to `Die`.\n *\n * **When to use**\n *\n * Use as a predicate for `Array.filter` to pick out `Die` (defect) reasons when\n * iterating over `cause.reasons`.\n *\n * **Example** (Filtering die reasons)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * const cause = Cause.die(\"defect\")\n * const dies = cause.reasons.filter(Cause.isDieReason)\n * dies[0].defect // => \"defect\"\n * ```\n *\n * @see {@link isFailReason} — narrow to `Fail`\n * @see {@link isInterruptReason} — narrow to `Interrupt`\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isDieReason = core.isDieReason;\n/**\n * Narrows a `Reason` to `Interrupt`.\n *\n * **When to use**\n *\n * Use as a predicate for `Array.filter` to pick out `Interrupt` reasons when\n * iterating over `cause.reasons`.\n *\n * **Example** (Filtering interrupt reasons)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * const cause = Cause.interrupt(123)\n * const interrupts = cause.reasons.filter(Cause.isInterruptReason)\n * interrupts[0].fiberId // => 123\n * ```\n *\n * @see {@link isFailReason} — narrow to `Fail`\n * @see {@link isDieReason} — narrow to `Die`\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isInterruptReason = core.isInterruptReason;\n/**\n * Creates a `Cause` from an array of `Reason` values.\n *\n * **When to use**\n *\n * Use when you already have individual reasons (e.g. from filtering or\n * transforming another cause's `reasons` array) and need to wrap them back\n * into a `Cause`.\n *\n * **Details**\n *\n * - Returns a new `Cause`.\n * - An empty array produces a cause equivalent to `empty`.\n *\n * **Gotchas**\n *\n * The `reasons` array is stored as provided. Treat the array as immutable\n * after passing it to this function.\n *\n * **Example** (Building a cause from reasons)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * const reasons = [\n * Cause.makeFailReason(\"err1\"),\n * Cause.makeFailReason(\"err2\")\n * ]\n * Cause.fromReasons(reasons) // => Cause.combine(Cause.fail(\"err1\"), Cause.fail(\"err2\"))\n * ```\n *\n * @see {@link combine} — merge two existing causes\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromReasons = core.causeFromReasons;\n/**\n * Represents a `Cause` with an empty `reasons` array.\n *\n * **When to use**\n *\n * Use to represent the absence of failure when constructing or combining\n * causes.\n *\n * **Details**\n *\n * Represents the absence of failure. Combining any cause with `empty` via\n * {@link combine} returns the original cause unchanged.\n *\n * **Example** (Combining with the empty cause)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * Cause.combine(Cause.empty, Cause.fail(\"boom\")) // => Cause.fail(\"boom\")\n * ```\n *\n * @see {@link combine} for merging causes where `empty` acts as the identity\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const empty = core.causeEmpty;\n/**\n * Creates a `Cause` containing a single `Fail` reason with the\n * given typed error.\n *\n * **When to use**\n *\n * Use to construct a cause from an expected typed error.\n *\n * **Example** (Creating a fail cause)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * Cause.fail(\"Something went wrong\") // => Cause.fromReasons([Cause.makeFailReason(\"Something went wrong\")])\n * ```\n *\n * @see {@link die} — for untyped defects\n * @see {@link interrupt} — for fiber interruptions\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fail = core.causeFail;\n/**\n * Creates a `Cause` containing a single `Die` reason with the\n * given defect.\n *\n * **When to use**\n *\n * Use to construct a cause from an untyped defect or unexpected thrown value.\n *\n * **Example** (Creating a die cause)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * Cause.die(\"Unexpected\") // => Cause.fromReasons([Cause.makeDieReason(\"Unexpected\")])\n * ```\n *\n * @see {@link fail} — for typed errors\n * @see {@link interrupt} — for fiber interruptions\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const die = core.causeDie;\n/**\n * Creates a `Cause` containing a single `Interrupt` reason,\n * optionally carrying the interrupting fiber's ID.\n *\n * **Example** (Creating an interrupt cause)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * Cause.interrupt(123) // => Cause.fromReasons([Cause.makeInterruptReason(123)])\n * ```\n *\n * @see {@link fail} — for typed errors\n * @see {@link die} — for untyped defects\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const interrupt = effect.causeInterrupt;\n/**\n * Creates a standalone `Fail` reason (not wrapped in a `Cause`).\n *\n * **When to use**\n *\n * Use when constructing a standalone typed failure reason for\n * {@link fromReasons} or direct comparison.\n *\n * **Example** (Creating a Fail reason)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * Cause.makeFailReason(\"error\") // => Cause.fail(\"error\").reasons[0]\n * ```\n *\n * @see {@link makeDieReason} — create a `Die` reason\n * @see {@link makeInterruptReason} — create an `Interrupt` reason\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeFailReason = error => new core.Fail(error);\n/**\n * Creates a standalone `Die` reason (not wrapped in a `Cause`).\n *\n * **When to use**\n *\n * Use when constructing a standalone defect reason for {@link fromReasons} or\n * direct comparison.\n *\n * **Example** (Creating a Die reason)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * Cause.makeDieReason(\"bug\") // => Cause.die(\"bug\").reasons[0]\n * ```\n *\n * @see {@link makeFailReason} — create a `Fail` reason\n * @see {@link makeInterruptReason} — create an `Interrupt` reason\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeDieReason = defect => new core.Die(defect);\n/**\n * Creates a standalone `Interrupt` reason (not wrapped in a `Cause`),\n * optionally carrying the interrupting fiber's ID.\n *\n * **When to use**\n *\n * Use when constructing a standalone interrupt reason for {@link fromReasons}\n * or direct comparison.\n *\n * **Example** (Creating an Interrupt reason)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * Cause.makeInterruptReason(42) // => Cause.interrupt(42).reasons[0]\n * ```\n *\n * @see {@link makeFailReason} — create a `Fail` reason\n * @see {@link makeDieReason} — create a `Die` reason\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeInterruptReason = effect.makeInterruptReason;\n/**\n * Returns `true` if every reason in the cause is an `Interrupt` (and\n * there is at least one reason).\n *\n * **When to use**\n *\n * Use when you need to detect failures caused only by interruption.\n *\n * **Example** (Checking interrupt-only causes)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * Cause.hasInterruptsOnly(Cause.interrupt(123)) // => true\n * Cause.hasInterruptsOnly(Cause.fail(\"error\")) // => false\n * Cause.hasInterruptsOnly(Cause.empty) // => false\n * ```\n *\n * @see {@link hasInterrupts} — `true` if the cause contains *any* interrupts\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const hasInterruptsOnly = effect.hasInterruptsOnly;\n/**\n * Transforms the typed error values inside a `Cause` using the\n * provided function. Only `Fail` reasons are affected; `Die` and `Interrupt`\n * reasons pass through unchanged.\n *\n * **When to use**\n *\n * Use to transform expected typed failures while preserving defects and\n * interruptions unchanged.\n *\n * **Details**\n *\n * If at least one `Fail` reason exists, this returns a new `Cause`\n * containing the mapped failures. If the cause has no `Fail` reasons, the\n * original cause is returned unchanged.\n *\n * **Example** (Mapping errors to uppercase)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * const cause = Cause.fail(\"error\")\n * const mapped = Cause.map(cause, (e) => e.toUpperCase())\n * const reason = mapped.reasons[0]\n * if (Cause.isFailReason(reason)) {\n * reason.error // => \"ERROR\"\n * }\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const map = effect.causeMap;\n/**\n * Merges two causes into a single cause whose `reasons` array is the union\n * of both inputs (de-duplicated by value equality).\n *\n * **When to use**\n *\n * Use to merge independent causes into one structured failure value.\n *\n * **Details**\n *\n * - Combining with `empty` returns the other cause unchanged.\n * - If the result is structurally equal to `self`, `self` is returned\n * (referential shortcut).\n *\n * **Example** (Combining two causes)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * const combined = Cause.combine(Cause.fail(\"error1\"), Cause.fail(\"error2\"))\n * combined // => Cause.fromReasons([Cause.makeFailReason(\"error1\"), Cause.makeFailReason(\"error2\")])\n * ```\n *\n * @see {@link fromReasons} — build a cause from an array of reasons\n * @see {@link empty} for the identity cause used when combining\n *\n * @category combining\n * @since 4.0.0\n */\nexport const combine = effect.causeCombine;\n/**\n * Collapses a `Cause` into a single `unknown` value, picking the \"most\n * important\" failure in this order:\n *\n * **When to use**\n *\n * Use to collapse a structured cause to the single value that synchronous and\n * promise runners would throw.\n *\n * **Details**\n *\n * 1. First `Fail` error (the `E` value)\n * 2. First `Die` defect\n * 3. A generic `Error(\"All fibers interrupted without error\")` for interrupt-only causes\n * 4. A generic `Error(\"Empty cause\")` for `empty`\n *\n * This is the function used by `Effect.runPromise` and `Effect.runSync` to\n * decide what to throw.\n *\n * **Gotchas**\n *\n * This function is lossy. Use {@link prettyErrors} or iterate `cause.reasons`\n * when you need all failures.\n *\n * **Example** (Squashing a cause)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * Cause.squash(Cause.fail(\"error\")) // => \"error\"\n * Cause.squash(Cause.die(\"defect\")) // => \"defect\"\n * ```\n *\n * @see {@link prettyErrors} — non-lossy conversion to `Array<Error>`\n * @see {@link pretty} — human-readable string rendering\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const squash = effect.causeSquash;\n/**\n * Returns `true` if the cause contains at least one `Fail` reason.\n *\n * **When to use**\n *\n * Use to check whether a cause includes typed failures before extracting,\n * mapping, or rendering them.\n *\n * **Example** (Checking for typed errors)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * Cause.hasFails(Cause.fail(\"error\")) // => true\n * Cause.hasFails(Cause.die(\"defect\")) // => false\n * ```\n *\n * @see {@link hasDies} — check for defects\n * @see {@link hasInterrupts} — check for interruptions\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const hasFails = effect.hasFails;\n/**\n * Returns a `Result` whose success value is the first `Fail` reason in\n * the cause, including its annotations. If the cause has no `Fail` reason, the\n * failure value is the original cause narrowed to `Cause<never>`, because it\n * contains no typed error reasons.\n *\n * **When to use**\n *\n * Use when you need the full `Fail` reason from a `Cause`, including\n * annotations.\n *\n * **Example** (Extracting the first Fail reason)\n *\n * ```ts import.meta.vitest\n * import { Cause, Result } from \"effect\"\n *\n * Cause.findFail(Cause.fail(\"error\")) // => Result.succeed(Cause.makeFailReason(\"error\"))\n * ```\n *\n * @see {@link findError} — extract the unwrapped `E` value\n * @see {@link findDie} — extract the first `Die` reason\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const findFail = effect.findFail;\n/**\n * Returns a `Result` whose success value is the first typed error value `E`\n * from a `Fail` reason in the cause. If the cause has no `Fail` reason,\n * the failure value is the original cause narrowed to `Cause<never>`, because\n * it contains no typed error reasons.\n *\n * **When to use**\n *\n * Use when you need the first typed error value from a `Cause` as a `Result`\n * that preserves the original cause when no match is found.\n *\n * **Example** (Extracting the first error value)\n *\n * ```ts import.meta.vitest\n * import { Cause, Result } from \"effect\"\n *\n * Cause.findError(Cause.fail(\"error\")) // => Result.succeed(\"error\")\n * ```\n *\n * @see {@link findFail} — extract the full `Fail` reason\n * @see {@link findErrorOption} — `Option`-based variant\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const findError = effect.findError;\n/**\n * Returns the first typed error value `E` from a cause wrapped in\n * `Option.some`, or `Option.none` if no `Fail` reason exists.\n *\n * **When to use**\n *\n * Use when you need the first typed error value from a `Cause` as an `Option`,\n * discarding the original cause.\n *\n * **Example** (Extracting an error as Option)\n *\n * ```ts import.meta.vitest\n * import { Cause, Option } from \"effect\"\n *\n * Cause.findErrorOption(Cause.fail(\"error\")) // => Option.some(\"error\")\n * Cause.findErrorOption(Cause.die(\"defect\")) // => Option.none()\n * ```\n *\n * @see {@link findError} — `Result`-based variant\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const findErrorOption = effect.findErrorOption;\n/**\n * Returns `true` if the cause contains at least one `Die` reason.\n *\n * **When to use**\n *\n * Use to check whether a cause includes defects before extracting or rendering\n * them.\n *\n * **Example** (Checking for defects)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * Cause.hasDies(Cause.die(\"defect\")) // => true\n * Cause.hasDies(Cause.fail(\"error\")) // => false\n * ```\n *\n * @see {@link hasFails} — check for typed errors\n * @see {@link hasInterrupts} — check for interruptions\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const hasDies = effect.hasDies;\n/**\n * Returns a `Result` whose success value is the first `Die` reason in\n * the cause, including its annotations. If the cause has no `Die` reason, the\n * failure value is the original cause.\n *\n * **When to use**\n *\n * Use when you need the full `Die` reason from a `Cause`, including\n * annotations.\n *\n * **Example** (Extracting the first Die reason)\n *\n * ```ts import.meta.vitest\n * import { Cause, Result } from \"effect\"\n *\n * Cause.findDie(Cause.die(\"defect\")) // => Result.succeed(Cause.makeDieReason(\"defect\"))\n * ```\n *\n * @see {@link findDefect} — extract the unwrapped defect value\n * @see {@link findFail} — extract the first `Fail` reason\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const findDie = effect.findDie;\n/**\n * Returns a `Result` whose success value is the first defect value from a\n * `Die` reason in the cause. If the cause has no `Die` reason, the\n * failure value is the original cause.\n *\n * **When to use**\n *\n * Use when you need the first defect value from a `Cause` as a `Result`,\n * without the full `Die` reason.\n *\n * **Example** (Extracting the first defect)\n *\n * ```ts import.meta.vitest\n * import { Cause, Result } from \"effect\"\n *\n * Cause.findDefect(Cause.die(\"defect\")) // => Result.succeed(\"defect\")\n * ```\n *\n * @see {@link findDie} — extract the full `Die` reason\n * @see {@link findError} — extract the first typed error\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const findDefect = effect.findDefect;\n/**\n * Returns `true` if the cause contains at least one `Interrupt` reason.\n *\n * **Example** (Checking for interruptions)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * Cause.hasInterrupts(Cause.interrupt(123)) // => true\n * Cause.hasInterrupts(Cause.fail(\"error\")) // => false\n * ```\n *\n * @see {@link hasInterruptsOnly} — `true` only when *all* reasons are interrupts\n * @see {@link hasFails} — check for typed errors\n * @see {@link hasDies} — check for defects\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const hasInterrupts = effect.hasInterrupts;\n/**\n * Returns a `Result` whose success value is the first `Interrupt` reason\n * in the cause, including its annotations. If the cause has no `Interrupt`\n * reason, the failure value is the original cause.\n *\n * **When to use**\n *\n * Use when you need the first `Interrupt` reason from a `Cause`, including the\n * fiber ID and annotations.\n *\n * **Example** (Extracting the first interrupt)\n *\n * ```ts import.meta.vitest\n * import { Cause, Result } from \"effect\"\n *\n * Cause.findInterrupt(Cause.interrupt(42)) // => Result.succeed(Cause.makeInterruptReason(42))\n * ```\n *\n * @see {@link interruptors} — collect all interrupting fiber IDs as a `Set`\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const findInterrupt = effect.findInterrupt;\n/**\n * Collects the defined fiber IDs from all `Interrupt` reasons in the\n * cause into a `ReadonlySet`. Interrupt reasons without a `fiberId` are\n * ignored. Returns an empty set when the cause has no interrupting fiber IDs.\n *\n * **When to use**\n *\n * Use when you need interrupting fiber IDs as a set, with absence represented\n * as an empty set.\n *\n * **Example** (Collecting interruptors)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * const cause = Cause.combine(\n * Cause.interrupt(1),\n * Cause.interrupt(2)\n * )\n *\n * Cause.interruptors(cause) // => new Set([1, 2])\n * ```\n *\n * @see {@link filterInterruptors} — `Result`-based variant\n *\n * @category getters\n * @since 2.0.0\n */\nexport const interruptors = effect.causeInterruptors;\n/**\n * Returns a `Result` whose success value is the set of defined fiber IDs from\n * the cause's `Interrupt` reasons. If the cause has no `Interrupt`\n * reason, the failure value is the original cause.\n *\n * **When to use**\n *\n * Use when you need absence of interrupt reasons to fail with the original\n * cause.\n *\n * **Gotchas**\n *\n * Interrupt reasons without a `fiberId` still count as interrupts, so the\n * function succeeds with an empty `Set` when every interrupt reason has an\n * undefined fiber ID.\n *\n * **Example** (Extracting interruptors with Result)\n *\n * ```ts import.meta.vitest\n * import { Cause, Result } from \"effect\"\n *\n * Cause.filterInterruptors(Cause.interrupt(1)) // => Result.succeed(new Set([1]))\n * ```\n *\n * @see {@link interruptors} — always-succeeding variant\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterInterruptors = effect.causeFilterInterruptors;\n/**\n * Converts a `Cause` into an `Array<Error>` suitable for logging or\n * rethrowing.\n *\n * **When to use**\n *\n * Use to convert every renderable failure in a cause into individual `Error`\n * values before logging or rethrowing.\n *\n * **Details**\n *\n * Each `Fail` and `Die` reason is converted into a standard\n * `Error`:\n *\n * - **Objects / Error instances** — `message`, `name`, `stack`, and `cause`\n * are preserved. Extra enumerable properties are copied. Stack traces are\n * cleaned up and enriched with span annotations when available.\n * - **Strings** — used directly as the `Error` message.\n * - **Other primitives** (`null`, `undefined`, numbers, …) — wrapped in an\n * `Error` with message `\"Unknown error: <value>\"`.\n *\n * `Interrupt` reasons are collected separately. If the cause contains\n * **only** interrupts (no `Fail` or `Die`), a single `InterruptError` is\n * returned whose `cause` lists the interrupting fiber IDs.\n *\n * An empty cause returns an empty array.\n *\n * **Example** (Converting a cause to errors)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * Cause.prettyErrors(Cause.fail(new Error(\"boom\")))[0].message // => \"boom\"\n * ```\n *\n * @see {@link pretty} — renders the cause as a single string\n * @see {@link squash} — lossy collapse to a single thrown value\n *\n * @category formatting\n * @since 3.2.0\n */\nexport const prettyErrors = effect.causePrettyErrors;\n/**\n * Formats a `Cause` as a human-readable string for logging or debugging.\n *\n * **When to use**\n *\n * Use to render a whole cause as one human-readable string for logs or\n * diagnostics.\n *\n * **Details**\n *\n * Delegates to {@link prettyErrors} to convert each reason to an `Error`,\n * then joins their stack traces with newlines. Nested `Error.cause` chains\n * are rendered inline with indentation:\n *\n * ```text\n * ErrorName: message\n * at ...\n * at ... {\n * [cause]: NestedError: message\n * at ...\n * }\n * ```\n *\n * Span annotations are appended to the relevant stack frames when available.\n *\n * **Gotchas**\n *\n * Rendering an empty cause produces an empty string because there are no\n * errors to render.\n *\n * **Example** (Rendering a cause)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * Cause.pretty(Cause.fail(\"something went wrong\")).includes(\"something went wrong\") // => true\n * ```\n *\n * @see {@link prettyErrors} — get the individual `Error` instances\n *\n * @category formatting\n * @since 2.0.0\n */\nexport const pretty = effect.causePretty;\n/**\n * Checks whether an arbitrary value is a `NoSuchElementError`.\n *\n * **Example** (Checking the runtime type)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * Cause.isNoSuchElementError(new Cause.NoSuchElementError()) // => true\n * Cause.isNoSuchElementError(\"nope\") // => false\n * ```\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isNoSuchElementError = core.isNoSuchElementError;\n/**\n * Unique brand for `NoSuchElementError`.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const NoSuchElementErrorTypeId = core.NoSuchElementErrorTypeId;\n/**\n * Constructs a `NoSuchElementError` with an optional message.\n *\n * **When to use**\n *\n * Use to create the error value for APIs that intentionally fail when an\n * expected element is absent.\n *\n * **Example** (Creating a NoSuchElementError)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * new Cause.NoSuchElementError(\"Element not found\").message // => \"Element not found\"\n * ```\n *\n * @see {@link isNoSuchElementError} for checking unknown values\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const NoSuchElementError = core.NoSuchElementError;\n/**\n * Checks whether an arbitrary value is a `Done` signal.\n *\n * **Example** (Checking the runtime type)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * Cause.isDone(Cause.Done()) // => true\n * Cause.isDone(\"not done\") // => false\n * ```\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isDone = core.isDone;\n/**\n * Unique brand for `Done` values.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const DoneTypeId = core.DoneTypeId;\n/**\n * Creates a `Done` signal with an optional value.\n *\n * **When to use**\n *\n * Use when you need to construct a low-level pull completion signal directly.\n *\n * @see {@link done} — create a failing `Effect` with `Done`\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Done = core.Done;\n/**\n * Creates an Effect that fails with a `Done` error. Shorthand for\n * `Effect.fail(Cause.Done(value))`.\n *\n * **When to use**\n *\n * Use when you model stream or queue completion through the error channel.\n *\n * **Example** (Failing with Done)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Exit } from \"effect\"\n *\n * const program = Cause.done(\"finished\")\n *\n * await Effect.runPromiseExit(program) // => Exit.fail(Cause.Done(\"finished\"))\n * ```\n *\n * @see {@link Done} — create the signal value without an Effect\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const done = core.done;\n/**\n * Unique brand for `TimeoutError`.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const TimeoutErrorTypeId = effect.TimeoutErrorTypeId;\n/**\n * Checks whether an arbitrary value is a `TimeoutError`.\n *\n * **Example** (Checking the runtime type)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * Cause.isTimeoutError(new Cause.TimeoutError()) // => true\n * Cause.isTimeoutError(\"nope\") // => false\n * ```\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isTimeoutError = effect.isTimeoutError;\n/**\n * Constructs a `TimeoutError` with an optional message.\n *\n * **Example** (Creating a TimeoutError)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * new Cause.TimeoutError(\"Operation timed out\").message // => \"Operation timed out\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const TimeoutError = effect.TimeoutError;\n/**\n * Unique brand for `IllegalArgumentError`.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const IllegalArgumentErrorTypeId = effect.IllegalArgumentErrorTypeId;\n/**\n * Checks whether an arbitrary value is an `IllegalArgumentError`.\n *\n * **Example** (Checking the runtime type)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * Cause.isIllegalArgumentError(new Cause.IllegalArgumentError()) // => true\n * Cause.isIllegalArgumentError(\"nope\") // => false\n * ```\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isIllegalArgumentError = effect.isIllegalArgumentError;\n/**\n * Constructs an `IllegalArgumentError` with an optional message.\n *\n * **Example** (Creating an IllegalArgumentError)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * new Cause.IllegalArgumentError(\"Invalid argument\").message // => \"Invalid argument\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const IllegalArgumentError = effect.IllegalArgumentError;\n/**\n * Checks whether an arbitrary value is an `ExceededCapacityError`.\n *\n * **Example** (Checking the runtime type)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * Cause.isExceededCapacityError(new Cause.ExceededCapacityError()) // => true\n * Cause.isExceededCapacityError(\"nope\") // => false\n * ```\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isExceededCapacityError = effect.isExceededCapacityError;\n/**\n * Unique brand for `ExceededCapacityError`.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const ExceededCapacityErrorTypeId = effect.ExceededCapacityErrorTypeId;\n/**\n * Constructs an `ExceededCapacityError` with an optional message.\n *\n * **When to use**\n *\n * Use to create the error value for bounded-resource capacity failures.\n *\n * **Example** (Creating an ExceededCapacityError)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * new Cause.ExceededCapacityError(\"Queue full\").message // => \"Queue full\"\n * ```\n *\n * @see {@link isExceededCapacityError} for checking unknown values\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const ExceededCapacityError = effect.ExceededCapacityError;\n/**\n * Unique brand present on `AsyncFiberError` values and used by\n * `isAsyncFiberError` for runtime checks.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const AsyncFiberErrorTypeId = effect.AsyncFiberErrorTypeId;\n/**\n * Checks whether an arbitrary value is an `AsyncFiberError`.\n *\n * **Example** (Checking the runtime type)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect } from \"effect\"\n *\n * const fiber = Effect.runFork(Effect.void)\n *\n * const error = new Cause.AsyncFiberError(fiber)\n * Cause.isAsyncFiberError(error) // => true\n * Cause.isAsyncFiberError(\"nope\") // => false\n * ```\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isAsyncFiberError = effect.isAsyncFiberError;\n/**\n * Constructs an `AsyncFiberError` for a fiber that could not be resolved\n * synchronously.\n *\n * **When to use**\n *\n * Use to create the error value for a fiber that could not be completed by a\n * synchronous runner.\n *\n * **Example** (Creating an AsyncFiberError)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect } from \"effect\"\n *\n * const fiber = Effect.runFork(Effect.void)\n *\n * new Cause.AsyncFiberError(fiber).message // => \"An asynchronous Effect was executed with Effect.runSync\"\n * ```\n *\n * @see {@link isAsyncFiberError} for checking unknown values\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const AsyncFiberError = effect.AsyncFiberError;\n/**\n * Unique brand for `UnknownError`.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const UnknownErrorTypeId = effect.UnknownErrorTypeId;\n/**\n * Checks whether an arbitrary value is an `UnknownError`.\n *\n * **Example** (Checking the runtime type)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * Cause.isUnknownError(new Cause.UnknownError(\"x\")) // => true\n * Cause.isUnknownError(\"nope\") // => false\n * ```\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isUnknownError = effect.isUnknownError;\n/**\n * Constructs an `UnknownError`. The first argument is the original\n * cause (stored in `Error.cause`); the second is an optional human-readable\n * message.\n *\n * **Example** (Creating an UnknownError)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n *\n * new Cause.UnknownError({ raw: true }, \"Unexpected value\").message // => \"Unexpected value\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const UnknownError = effect.UnknownError;\n/**\n * Attaches metadata to every reason in a `Cause`.\n *\n * **When to use**\n *\n * Use to attach diagnostic metadata to every reason in a cause.\n *\n * **Details**\n *\n * Annotations are stored as a `Context` on each reason and can be\n * retrieved later via {@link reasonAnnotations} or {@link annotations}.\n * The runtime uses this to attach stack traces and spans.\n *\n * - Returns a new `Cause`.\n * - By default, existing keys are preserved. Pass `{ overwrite: true }` to\n * replace them.\n *\n * **Example** (Annotating a cause)\n *\n * ```ts import.meta.vitest\n * import { Cause, Context } from \"effect\"\n *\n * class RequestId extends Context.Service<RequestId, string>()(\"RequestId\") {}\n *\n * const annotated = Cause.annotate(Cause.fail(\"error\"), Context.make(RequestId, \"req-1\"))\n * Context.getOrUndefined(Cause.annotations(annotated), RequestId) // => \"req-1\"\n * ```\n *\n * @see {@link annotations} for reading merged annotations from a cause\n * @see {@link reasonAnnotations} for reading annotations from a single reason\n *\n * @category annotations\n * @since 4.0.0\n */\nexport const annotate = core.causeAnnotate;\n/**\n * Reads the annotations from a single `Reason` as a `Context`.\n *\n * **When to use**\n *\n * Use when you need tracing metadata (e.g. `StackTrace`) from\n * a specific reason rather than the whole cause.\n *\n * **Example** (Reading reason annotations)\n *\n * ```ts import.meta.vitest\n * import { Cause, Context } from \"effect\"\n *\n * class RequestId extends Context.Service<RequestId, string>()(\"RequestId\") {}\n *\n * const reason = Cause.makeFailReason(\"error\")\n * const annotated = reason.annotate(Context.make(RequestId, \"req-1\"))\n *\n * Context.getOrUndefined(Cause.reasonAnnotations(annotated), RequestId) // => \"req-1\"\n * ```\n *\n * @see {@link annotations} — merged annotations from all reasons in a cause\n *\n * @category annotations\n * @since 4.0.0\n */\nexport const reasonAnnotations = effect.reasonAnnotations;\n/**\n * Reads the merged annotations from all reasons in a `Cause`.\n *\n * **When to use**\n *\n * Use to read diagnostic metadata merged from the whole cause.\n *\n * **Gotchas**\n *\n * When multiple reasons contain the same annotation key, the value from the\n * later reason wins.\n *\n * **Example** (Reading merged annotations)\n *\n * ```ts import.meta.vitest\n * import { Cause, Context } from \"effect\"\n *\n * class RequestId extends Context.Service<RequestId, string>()(\"RequestId\") {}\n *\n * const cause = Cause.annotate(\n * Cause.fail(\"error\"),\n * Context.make(RequestId, \"req-1\")\n * )\n *\n * Context.getOrUndefined(Cause.annotations(cause), RequestId) // => \"req-1\"\n * ```\n *\n * @see {@link reasonAnnotations} — annotations from a single reason\n *\n * @category annotations\n * @since 4.0.0\n */\nexport const annotations = effect.causeAnnotations;\n/**\n * Context annotation used to store the stack frame captured at the point of failure.\n *\n * **When to use**\n *\n * Use to read the failure stack-frame annotation from a `Reason` when building\n * diagnostics, logging, or custom cause renderers.\n *\n * **Details**\n *\n * The runtime annotates every reason with this when a stack frame is\n * available. Retrieve it via\n * `Context.get(Cause.reasonAnnotations(reason), Cause.StackTrace)`.\n *\n * @see {@link reasonAnnotations} for reading annotations from a single reason\n * @see {@link annotations} for reading merged annotations from a cause\n * @see {@link InterruptorStackTrace} for the interrupt-specific stack-frame annotation\n *\n * @category services\n * @since 4.0.0\n */\nexport class StackTrace extends /*#__PURE__*/Context.Service()(\"effect/Cause/StackTrace\") {}\n/**\n * Context annotation used to store the stack frame captured at the point of\n * interruption.\n *\n * **When to use**\n *\n * Use when you need the stack-frame annotation used by interrupt-only cause\n * rendering.\n *\n * **Details**\n *\n * Similar to `StackTrace` but specific to `Interrupt` reasons.\n *\n * @see {@link StackTrace} for stack frames attached to failures\n * @see {@link reasonAnnotations} for reading annotations from a single reason\n * @see {@link annotate} for attaching annotations to a cause\n *\n * @category services\n * @since 4.0.0\n */\nexport class InterruptorStackTrace extends /*#__PURE__*/Context.Service()(\"effect/Cause/InterruptorStackTrace\") {}\n//# sourceMappingURL=Cause.js.map","import * as Context from \"../Context.js\";\n/** @internal */\nexport const Random = /*#__PURE__*/Context.Reference(\"effect/Random\", {\n defaultValue: () => ({\n nextIntUnsafe() {\n return Math.floor(Math.random() * (Number.MAX_SAFE_INTEGER - Number.MIN_SAFE_INTEGER + 1)) + Number.MIN_SAFE_INTEGER;\n },\n nextDoubleUnsafe() {\n return Math.random();\n }\n })\n});\n/** @internal */\nexport const nextBetween = (min, max, draw) => {\n const value = draw * (max - min) + min;\n if (value !== max || min >= max || !Number.isFinite(max)) {\n return value;\n }\n // Rounding can reach the excluded endpoint even for a draw below 1.\n // Return its immediate predecessor, which is at least min for finite min < max.\n if (max === 0) {\n return -Number.MIN_VALUE;\n }\n const view = new DataView(new ArrayBuffer(8));\n view.setFloat64(0, max);\n const bits = view.getBigUint64(0);\n view.setBigUint64(0, max > 0 ? bits - BigInt(1) : bits + BigInt(1));\n return view.getFloat64(0);\n};\n//# sourceMappingURL=random.js.map","/**\n * Models one low-level pull step for stream-like consumers.\n *\n * A `Pull<A, E, Done, R>` is an `Effect` that can produce one `A`, fail with an\n * ordinary error `E`, or signal end-of-input with `Cause.Done<Done>`. The\n * separate done signal lets low-level consumers distinguish normal completion\n * from failure. This module includes type extractors and helpers for detecting,\n * filtering, catching, converting, and matching done signals separately from\n * ordinary failures.\n *\n * @since 4.0.0\n */\nimport * as Cause from \"./Cause.js\";\nimport * as Exit from \"./Exit.js\";\nimport * as Filter from \"./Filter.js\";\nimport { dual } from \"./Function.js\";\nimport * as internalEffect from \"./internal/effect.js\";\nimport * as Result from \"./Result.js\";\n// -----------------------------------------------------------------------------\n// Done\n// -----------------------------------------------------------------------------\n/**\n * Handles `Cause.Done` failures in an effect while leaving ordinary failures\n * in the error channel.\n *\n * **When to use**\n *\n * Use to recover from a `Cause.Done` completion signal in an effect, such as\n * turning a pull leftover value into a successful recovery effect while\n * preserving ordinary failures.\n *\n * **Details**\n *\n * The handler receives the done leftover value and may recover with a new\n * effect. Non-done errors are preserved.\n *\n * @see {@link matchEffect} for handling success, ordinary failure, and done outcomes explicitly\n * @see {@link filterDoneLeftover} for extracting a done leftover from an existing `Cause`\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchDone = /*#__PURE__*/dual(2, (effect, f) => internalEffect.catchCauseFilter(effect, filterDoneLeftover, l => f(l)));\n/**\n * Checks whether a Cause contains any done errors.\n *\n * **When to use**\n *\n * Use when you need to test whether a pull failure cause represents normal\n * completion and only need a boolean result.\n *\n * @see {@link isDoneFailure} for checking a single `Cause.Reason`\n * @see {@link filterDone} for extracting the `Cause.Done` value from a `Cause`\n * @see {@link filterNoDone} for selecting causes with no done failures\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isDoneCause = cause => cause.reasons.some(isDoneFailure);\n/**\n * Checks whether a `Cause.Reason` is a `Fail` reason whose error is a\n * `Cause.Done` signal.\n *\n * **When to use**\n *\n * Use when you need to identify done completion reasons while traversing\n * `cause.reasons`, before handling ordinary failures.\n *\n * @see {@link isDoneCause} for checking an entire `Cause` for any done reason\n * @see {@link filterDone} for extracting the `Cause.Done` value from a `Cause`\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isDoneFailure = failure => failure._tag === \"Fail\" && Cause.isDone(failure.error);\n/**\n * Finds a `Cause.Done` failure in a `Cause`.\n *\n * **When to use**\n *\n * Use to separate `Cause.Done` completion from ordinary causes while preserving\n * the typed done value.\n *\n * **Details**\n *\n * Returns a successful `Result` with the `Cause.Done` value when the cause\n * contains a done signal and no other failures besides interruptions. When the\n * done signal was merged with a real failure (for example a failing\n * finalizer), the `Result` fails with the remaining cause, stripped of the\n * done signal. Without a done signal the `Result` fails with the original\n * cause.\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterDone = cause => {\n let done;\n let hasFailure = false;\n for (const reason of cause.reasons) {\n if (isDoneFailure(reason)) {\n done ??= reason.error;\n } else if (reason._tag !== \"Interrupt\") {\n hasFailure = true;\n }\n }\n if (done === undefined) return Result.fail(cause);\n return hasFailure ? Result.fail(Cause.fromReasons(cause.reasons.filter(reason => !isDoneFailure(reason)))) : Result.succeed(done);\n};\n/**\n * Finds a `Cause.Done` failure in a cause whose done value is not used.\n *\n * **When to use**\n *\n * Use to detect `Cause.Done` completion in a `Cause` when the completion value\n * is not part of the downstream logic.\n *\n * **Details**\n *\n * Returns a successful `Result` with the done marker when it is the only\n * failure, otherwise returns a failed `Result` with the non-done cause.\n *\n * @see {@link filterDone} for preserving the typed `Cause.Done` value when the done payload matters\n * @see {@link filterDoneLeftover} for extracting only the done leftover value\n * @see {@link filterNoDone} for the inverse filter that succeeds only when no done failure is present\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterDoneVoid = filterDone;\n/**\n * Keeps a `Cause` only when it contains no `Cause.Done` failures.\n *\n * **When to use**\n *\n * Use to select ordinary failure causes for handling while leaving `Cause.Done`\n * completion causes outside that handler.\n *\n * **Details**\n *\n * Returns a successful `Result` with the cause when every failure is non-done;\n * otherwise returns a failed `Result` with the original cause.\n *\n * @see {@link filterDone} for the inverse typed done filter\n * @see {@link filterDoneVoid} for done detection when the payload is not needed\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterNoDone = /*#__PURE__*/Filter.fromPredicate(cause => cause.reasons.every(failure => !isDoneFailure(failure)));\n/**\n * Filters a Cause to extract the leftover value from done errors.\n *\n * **When to use**\n *\n * Use to extract only the leftover value carried by a `Cause.Done` completion\n * signal.\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterDoneLeftover = cause => {\n const done = filterDone(cause);\n return Result.isFailure(done) ? done : Result.succeed(done.success.value);\n};\n/**\n * Converts a `Cause` into an `Exit`, treating `Cause.Done` as successful\n * completion.\n *\n * **When to use**\n *\n * Use to produce an `Exit` for finalizing a low-level pull workflow when a\n * `Cause.Done` signal should be treated as success and any remaining cause\n * should fail.\n *\n * **Details**\n *\n * If the done signal is the only failure in the cause, its leftover becomes\n * the successful value. Otherwise the non-done cause becomes the failure\n * cause.\n *\n * @see {@link filterDone} for extracting the done signal without converting the cause to an `Exit`\n * @see {@link matchEffect} for handling `Pull` success, failure, and done outcomes directly\n *\n * @category converting\n * @since 4.0.0\n */\nexport const doneExitFromCause = cause => {\n const halt = filterDone(cause);\n return !Result.isFailure(halt) ? Exit.succeed(halt.success.value) : Exit.failCause(halt.failure);\n};\n/**\n * Pattern matches on a Pull, handling success, failure, and done cases.\n *\n * **When to use**\n *\n * Use to handle all three `Pull` outcomes with effectful handlers.\n *\n * **Example** (Matching Pull outcomes)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Pull } from \"effect\"\n *\n * const pull = Cause.done(\"stream ended\")\n *\n * const result = Pull.matchEffect(pull, {\n * onSuccess: (value) => Effect.succeed(`Got value: ${value}`),\n * onFailure: (cause) => Effect.succeed(`Got error: ${cause}`),\n * onDone: (leftover) => Effect.succeed(`Stream halted with: ${leftover}`)\n * })\n *\n * await Effect.runPromise(result) // => \"Stream halted with: stream ended\"\n * ```\n *\n * @category pattern matching\n * @since 4.0.0\n */\nexport const matchEffect = /*#__PURE__*/dual(2, (self, options) => internalEffect.matchCauseEffect(self, {\n onSuccess: options.onSuccess,\n onFailure: cause => {\n const halt = filterDone(cause);\n return !Result.isFailure(halt) ? options.onDone(halt.success.value) : options.onFailure(halt.failure);\n }\n}));\n//# sourceMappingURL=Pull.js.map","import * as Cause from \"./Cause.js\";\nimport * as Context from \"./Context.js\";\nimport * as Cron from \"./Cron.js\";\nimport * as Duration from \"./Duration.js\";\nimport { constant, dual, identity } from \"./Function.js\";\nimport { isEffect } from \"./internal/core.js\";\nimport * as effect from \"./internal/effect.js\";\nimport * as random from \"./internal/random.js\";\nimport { pipeArguments } from \"./Pipeable.js\";\nimport { hasProperty } from \"./Predicate.js\";\nimport * as Pull from \"./Pull.js\";\nimport * as Result from \"./Result.js\";\nconst TypeId = \"~effect/Schedule\";\nconst randomNext = /*#__PURE__*/random.Random.useSync(random => random.nextDoubleUnsafe());\n/**\n * Context reference containing metadata for the currently running schedule step.\n *\n * **Details**\n *\n * Repeat, retry, stream, and channel scheduling operations provide this service\n * to effects run between schedule steps. The default value contains undefined\n * input and output values, zero duration, and zeroed timing fields before any\n * schedule step has produced metadata.\n *\n * @category services\n * @since 4.0.0\n */\nexport const CurrentMetadata = /*#__PURE__*/Context.Reference(\"effect/Schedule/CurrentMetadata\", {\n defaultValue: /*#__PURE__*/constant({\n input: undefined,\n output: undefined,\n duration: Duration.zero,\n attempt: 0,\n start: 0,\n now: 0,\n elapsed: 0,\n elapsedSincePrevious: 0\n })\n});\nconst ScheduleProto = {\n [TypeId]: {\n _Out: identity,\n _In: identity,\n _Env: identity\n },\n pipe() {\n return pipeArguments(this, arguments);\n }\n};\n/**\n * Type guard that checks if a value is a Schedule.\n *\n * **Example** (Checking for schedules)\n *\n * ```ts import.meta.vitest\n * import { Schedule } from \"effect\"\n *\n * const schedule = Schedule.exponential(\"100 millis\")\n * const notSchedule = { foo: \"bar\" }\n *\n * Schedule.isSchedule(schedule) // => true\n * Schedule.isSchedule(notSchedule) // => false\n * Schedule.isSchedule(null) // => false\n * Schedule.isSchedule(undefined) // => false\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isSchedule = u => hasProperty(u, TypeId);\n/**\n * Creates a Schedule from a step function that returns a Pull.\n *\n * **Example** (Creating a custom schedule from a step function)\n *\n * ```ts import.meta.vitest\n * import { Cause, Duration, Effect, Schedule } from \"effect\"\n *\n * const schedule = Schedule.fromStep(Effect.sync(() => {\n * let count = 0\n *\n * return (_now: number, _input: string) => {\n * if (count >= 3) {\n * return Cause.done(count)\n * }\n * return Effect.succeed([count++, Duration.millis(100)] as [number, Duration.Duration])\n * }\n * }))\n *\n * const program = Effect.gen(function*() {\n * const step = yield* Schedule.toStep(schedule)\n * const [output] = yield* step(0, \"input\")\n * return output\n * })\n *\n * await Effect.runPromise(program) // => 0\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromStep = step => {\n const self = Object.create(ScheduleProto);\n self.step = step;\n return self;\n};\nconst metadataFn = () => {\n let n = 0;\n let previous;\n let start;\n return (now, input) => {\n if (start === undefined) start = now;\n const elapsed = now - start;\n const elapsedSincePrevious = previous === undefined ? 0 : now - previous;\n previous = now;\n return {\n input,\n attempt: ++n,\n start,\n now,\n elapsed,\n elapsedSincePrevious\n };\n };\n};\n/**\n * Creates a Schedule from a step function that receives metadata about the schedule's execution.\n *\n * **Example** (Creating a metadata-aware schedule)\n *\n * ```ts import.meta.vitest\n * import { Cause, Duration, Effect, Schedule } from \"effect\"\n *\n * const firstThreeInputs = Schedule.fromStepWithMetadata(Effect.succeed((metadata: Schedule.InputMetadata<string>) => {\n * if (metadata.attempt > 3) {\n * return Cause.done(\"finished\")\n * }\n *\n * return Effect.succeed([\n * `attempt ${metadata.attempt}: ${metadata.input}`,\n * Duration.millis(250)\n * ] as [string, Duration.Duration])\n * }))\n *\n * const program = Effect.gen(function*() {\n * const step = yield* Schedule.toStep(firstThreeInputs)\n * const [output] = yield* step(0, \"input\")\n * return output\n * })\n *\n * await Effect.runPromise(program) // => \"attempt 1: input\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromStepWithMetadata = step => fromStep(effect.map(step, f => {\n const meta = metadataFn();\n return (now, input) => f(meta(now, input));\n}));\n/**\n * Extracts the step function from a Schedule.\n *\n * **Example** (Extracting a schedule step function)\n *\n * ```ts import.meta.vitest\n * import { Duration, Effect, Schedule } from \"effect\"\n *\n * // Extract step function from an existing schedule\n * const schedule = Schedule.exponential(\"100 millis\").pipe(Schedule.upTo({ times: 3 }))\n *\n * const program = Effect.gen(function*() {\n * const stepFn = yield* Schedule.toStep(schedule)\n *\n * // Use the step function directly for custom logic. The timestamp is\n * // supplied by the caller, so tests can pass a deterministic value.\n * const now = 0\n * return yield* stepFn(now, \"input\")\n * })\n *\n * await Effect.runPromise(program) // => [Duration.millis(100), Duration.millis(100)]\n * ```\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const toStep = schedule => effect.catchCause(schedule.step, cause => effect.succeed(() => effect.failCause(cause)));\n/**\n * Extracts a step function from a `Schedule` that sleeps for each computed\n * delay and returns metadata for the completed step.\n *\n * **When to use**\n *\n * Use to drive a schedule manually while preserving the computed output,\n * delay, input, attempt, and elapsed timing metadata for each step.\n *\n * **Details**\n *\n * The returned step reads the current time from `Clock` when invoked, calls the\n * schedule step with that timestamp and input, sleeps for the returned\n * duration, and then yields `Metadata`.\n *\n * @see {@link toStep} for manually supplying the timestamp and handling the returned delay yourself\n * @see {@link toStepWithSleep} for the same automatic sleeping behavior when only the schedule output is needed\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const toStepWithMetadata = schedule => effect.clockWith(clock => effect.map(toStep(schedule), step => {\n const metaFn = metadataFn();\n return input => effect.suspend(() => {\n const now = clock.currentTimeMillisUnsafe();\n return effect.flatMap(step(now, input), ([output, duration]) => {\n const meta = metaFn(now, input);\n meta.output = output;\n meta.duration = duration;\n return effect.as(effect.sleep(duration), meta);\n });\n });\n}));\n/**\n * Extracts a step function from a Schedule that automatically handles sleep delays.\n *\n * **Example** (Extracting a sleeping step function)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schedule } from \"effect\"\n * import { TestClock } from \"effect/testing\"\n *\n * const schedule = Schedule.recurs(3)\n *\n * const program = Effect.gen(function*() {\n * const stepWithSleep = yield* Schedule.toStepWithSleep(schedule)\n *\n * return [yield* stepWithSleep(\"first\"), yield* stepWithSleep(\"second\")]\n * })\n *\n * await Effect.runPromise(Effect.provide(program, TestClock.layer())) // => [0, 1]\n * ```\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const toStepWithSleep = schedule => effect.map(toStepWithMetadata(schedule), step => input => effect.map(step(input), meta => meta.output));\n/**\n * Returns a new `Schedule` that adds the delay computed by the specified\n * effectful function to the next recurrence of the schedule.\n *\n * **Example** (Adding extra delay to a schedule)\n *\n * ```ts import.meta.vitest\n * import { Duration, Effect, Schedule } from \"effect\"\n *\n * const schedule = Schedule.recurs(1).pipe(\n * Schedule.addDelay(() => Effect.succeed(\"25 millis\"))\n * )\n * const program = Effect.gen(function*() {\n * const step = yield* Schedule.toStep(schedule)\n * const [, delay] = yield* step(0, undefined)\n * return delay\n * })\n *\n * await Effect.runPromise(program) // => Duration.millis(25)\n * ```\n *\n * @category delays & timeouts\n * @since 2.0.0\n */\nexport const addDelay = /*#__PURE__*/dual(2, (self, f) => modifyDelay(self, metadata => effect.map(f(metadata), d => Duration.sum(Duration.fromInputUnsafe(d), metadata.duration))));\n/**\n * Returns a schedule that runs `self` to completion, then runs `other`, and\n * merges their outputs.\n *\n * **Example** (Sequencing quick and slow retries)\n *\n * ```ts import.meta.vitest\n * import { Schedule } from \"effect\"\n *\n * const schedule = Schedule.concat(Schedule.recurs(1), Schedule.recurs(2))\n * Schedule.isSchedule(schedule) // => true\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const concat = /*#__PURE__*/dual(2, (self, other) => map(concatResult(self, other), ({\n output\n}) => effect.succeed(Result.merge(output))));\n/**\n * Returns a schedule that runs `self` to completion, then runs `other`, and\n * preserves which schedule produced each output.\n *\n * **Details**\n *\n * The resulting schedule emits a `Result` to indicate which phase produced\n * each output: outputs from `self` are emitted as `Failure`, and outputs from\n * `other` are emitted as `Success`.\n *\n * **Example** (Tracking sequential schedule phases)\n *\n * ```ts import.meta.vitest\n * import { Schedule } from \"effect\"\n *\n * const schedule = Schedule.concatResult(Schedule.recurs(1), Schedule.recurs(2))\n * Schedule.isSchedule(schedule) // => true\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const concatResult = /*#__PURE__*/dual(2, (self, other) => fromStep(effect.sync(() => {\n let currentSide = 0;\n let currentStep;\n const left = map(self, ({\n output\n }) => Result.fail(output));\n const right = map(other, ({\n output\n }) => Result.succeed(output));\n return function recur(now, input) {\n if (currentStep) return currentStep(now, input);\n return toStep(currentSide === 0 ? left : right).pipe(effect.flatMap(step => {\n currentSide++;\n if (currentSide === 1) {\n currentStep = (now, input) => Pull.catchDone(step(now, input), _ => {\n currentStep = undefined;\n return recur(now, input);\n });\n return currentStep(now, input);\n }\n currentStep = step;\n return currentStep(now, input);\n }));\n };\n})));\n/**\n * Combines schedules by recurring while all schedules want to recur, using the\n * maximum delay between recurrences and outputting that maximum delay.\n *\n * **When to use**\n *\n * Use when a combined policy should continue only while every schedule still\n * recurs, and should wait for the slowest schedule between recurrences.\n *\n * **Example** (Combining retry schedules by their maximum delay)\n *\n * ```ts import.meta.vitest\n * import { Schedule } from \"effect\"\n *\n * const schedule = Schedule.max([Schedule.fixed(\"5 seconds\"), Schedule.spaced(\"10 seconds\")])\n * Schedule.isSchedule(schedule) // => true\n * ```\n *\n * @category combining\n * @since 4.0.0\n */\nexport const max = schedules => fromStep(effect.map(effect.all(schedules.map(toStep)), steps => (now, input) => effect.flatMap(effect.forEach(steps, step => Pull.matchEffect(step(now, input), {\n onSuccess: result => effect.succeed(result[1]),\n onDone: () => effect.undefined,\n onFailure: effect.failCause\n})), results => {\n const duration = maxDuration(results);\n if (duration === undefined) {\n return Cause.done(Duration.zero);\n }\n return effect.succeed([duration, duration]);\n})));\nconst maxDuration = results => {\n let max = results[0];\n for (let i = 1; i < results.length; i++) {\n max = results[i] && max && Duration.max(max, results[i]);\n if (max === undefined) break;\n }\n return max;\n};\n/**\n * Returns a new `Schedule` that recurs on the specified `Cron` schedule and\n * outputs the duration between recurrences.\n *\n * **Example** (Scheduling work with cron expressions)\n *\n * ```ts import.meta.vitest\n * import { Schedule } from \"effect\"\n *\n * const everyMinute = Schedule.cron(\"* * * * *\")\n * Schedule.isSchedule(everyMinute) // => true\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const cron = (expression, tz) => {\n const parsed = Cron.isCron(expression) ? Result.succeed(expression) : Cron.parse(expression, tz);\n return fromStep(effect.map(effect.fromResult(parsed), cron => (now, _) => {\n if (now === Number.POSITIVE_INFINITY) {\n return Cause.done(Duration.zero);\n }\n return effect.sync(() => {\n const next = Cron.next(cron, now).getTime();\n const duration = Duration.millis(next - now);\n return [duration, duration];\n });\n }));\n};\n/**\n * Returns a schedule that recurs once after the specified duration.\n *\n * **When to use**\n *\n * Use when you need a schedule that recurs once after a fixed delay.\n *\n * **Details**\n *\n * The schedule outputs the configured duration for its first recurrence and\n * then completes.\n *\n * **Example** (Recurring once after a duration)\n *\n * ```ts import.meta.vitest\n * import { Schedule } from \"effect\"\n *\n * Schedule.isSchedule(Schedule.duration(\"1 second\")) // => true\n * ```\n *\n * @see {@link during} for recurring until a duration has elapsed\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const duration = durationInput => {\n const duration = Duration.fromInputUnsafe(durationInput);\n return fromStepWithMetadata(effect.succeed(meta => meta.attempt === 1 ? effect.succeed([duration, duration]) : Cause.done(Duration.zero)));\n};\n/**\n * Returns a new `Schedule` that will always recur, but only during the\n * specified `duration` of time.\n *\n * **When to use**\n *\n * Use to bound a repeating or retrying schedule by elapsed time.\n *\n * **Example** (Repeating work during a duration)\n *\n * ```ts import.meta.vitest\n * import { Schedule } from \"effect\"\n *\n * Schedule.isSchedule(Schedule.during(\"5 seconds\")) // => true\n * ```\n *\n * @see {@link duration} for one delayed recurrence\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const during = duration => {\n const durationMillis = Duration.toMillis(duration);\n return fromStepWithMetadata(effect.succeed(meta => {\n const elapsed = Duration.millis(meta.elapsed);\n return meta.elapsed > durationMillis ? Cause.done(elapsed) : effect.succeed([elapsed, Duration.zero]);\n }));\n};\n/**\n * Combines schedules by recurring while at least one schedule wants to recur,\n * using the minimum delay between recurrences and outputting that minimum delay.\n *\n * **When to use**\n *\n * Use when a combined policy should continue while any schedule still recurs,\n * and should wait for the fastest schedule between recurrences.\n *\n * **Example** (Combining retry schedules by their minimum delay)\n *\n * ```ts import.meta.vitest\n * import { Schedule } from \"effect\"\n *\n * const schedule = Schedule.min([Schedule.fixed(\"5 seconds\"), Schedule.spaced(\"10 seconds\")])\n * Schedule.isSchedule(schedule) // => true\n * ```\n *\n * @category combining\n * @since 4.0.0\n */\nexport const min = schedules => fromStep(effect.map(effect.all(schedules.map(toStep)), steps => (now, input) => effect.flatMap(effect.forEach(steps, step => Pull.matchEffect(step(now, input), {\n onSuccess: result => effect.succeed(result[1]),\n onDone: () => effect.undefined,\n onFailure: effect.failCause\n})), results => {\n const duration = minDuration(results);\n if (duration === undefined) {\n return Cause.done(Duration.zero);\n }\n return effect.succeed([duration, duration]);\n})));\nconst minDuration = results => {\n let min = undefined;\n for (let i = 0; i < results.length; i++) {\n const duration = results[i];\n if (duration !== undefined) {\n min = min === undefined ? duration : Duration.min(min, duration);\n }\n }\n return min;\n};\n/**\n * Schedule that always recurs, but will wait a certain amount between\n * repetitions, given by `base * factor.pow(n)`, where `n` is the number of\n * repetitions so far. Returns the current duration between recurrences.\n *\n * **Example** (Retrying with exponential backoff)\n *\n * ```ts import.meta.vitest\n * import { Duration, Effect, Schedule } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const step = yield* Schedule.toStep(Schedule.exponential(\"100 millis\"))\n * return yield* step(0, undefined)\n * })\n *\n * await Effect.runPromise(program) // => [Duration.millis(100), Duration.millis(100)]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const exponential = (base, factor = 2) => {\n const baseMillis = Duration.toMillis(Duration.fromInputUnsafe(base));\n return fromStepWithMetadata(effect.succeed(meta => {\n const duration = Duration.millis(baseMillis * Math.pow(factor, meta.attempt - 1));\n return effect.succeed([duration, duration]);\n }));\n};\n/**\n * Schedule that always recurs, increasing delays by summing the preceding\n * two delays (similar to the Fibonacci sequence). Returns the current\n * duration between recurrences.\n *\n * **Example** (Retrying with Fibonacci backoff)\n *\n * ```ts import.meta.vitest\n * import { Duration, Effect, Schedule } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const step = yield* Schedule.toStep(Schedule.fibonacci(\"100 millis\"))\n * return yield* step(0, undefined)\n * })\n *\n * await Effect.runPromise(program) // => [Duration.millis(100), Duration.millis(100)]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fibonacci = one => {\n const oneMillis = Duration.toMillis(Duration.fromInputUnsafe(one));\n return fromStep(effect.sync(() => {\n let a = 0;\n let b = oneMillis;\n return constant(effect.sync(() => {\n const next = a + b;\n a = b;\n b = next;\n const duration = Duration.millis(next);\n return [duration, duration];\n }));\n }));\n};\n/**\n * Returns a `Schedule` that recurs on the specified fixed `interval` and\n * outputs the number of repetitions of the schedule so far.\n *\n * **When to use**\n *\n * Use when recurrences should stay aligned to a regular cadence.\n *\n * **Gotchas**\n *\n * If the action run between recurrences takes longer than the interval, the\n * next recurrence happens immediately, but missed intervals are not replayed.\n *\n * ```text\n * |-----interval-----|-----interval-----|-----interval-----|\n * |---------action--------||action|-----|action|-----------|\n * ```\n *\n * **Example** (Repeating on fixed intervals)\n *\n * ```ts import.meta.vitest\n * import { Duration, Effect, Schedule } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const step = yield* Schedule.toStep(Schedule.fixed(\"1 second\"))\n * return yield* step(0, undefined)\n * })\n *\n * await Effect.runPromise(program) // => [0, Duration.seconds(1)]\n * ```\n *\n * @see {@link spaced} for delaying after each action completes\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fixed = interval => {\n const window = Duration.toMillis(Duration.fromInputUnsafe(interval));\n return fromStepWithMetadata(effect.sync(() => {\n let start = 0;\n let lastRun = 0;\n return meta => effect.sync(() => {\n if (window === 0) {\n return [meta.attempt - 1, Duration.zero];\n }\n if (meta.attempt === 1) {\n start = meta.now;\n lastRun = meta.now + window;\n return [0, Duration.millis(window)];\n }\n const runningBehind = meta.now > lastRun + window;\n const boundary = window - (meta.now - start) % window;\n const delay = runningBehind ? 0 : boundary === 0 ? window : boundary;\n lastRun = runningBehind ? meta.now : meta.now + delay;\n return [meta.attempt - 1, Duration.millis(delay)];\n });\n }));\n};\n/**\n * Returns a new `Schedule` that maps each schedule decision to a new output\n * using the full schedule metadata.\n *\n * **Details**\n *\n * The callback receives the schedule input, output, selected delay duration,\n * current attempt, and elapsed timing information. Return either a plain value\n * or an `Effect` that produces the new output.\n *\n * **Example** (Mapping schedule outputs)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schedule } from \"effect\"\n *\n * const countSchedule = Schedule.recurs(5).pipe(\n * Schedule.map(({ output: count }) => Effect.succeed(`Execution #${count + 1}`))\n * )\n * const program = Effect.gen(function*() {\n * const step = yield* Schedule.toStep(countSchedule)\n * const [output] = yield* step(0, undefined)\n * return output\n * })\n *\n * await Effect.runPromise(program) // => \"Execution #1\"\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => fromStep(effect.map(toStep(self), step => {\n const meta = metadataFn();\n return (now, input) => Pull.matchEffect(step(now, input), {\n onSuccess: ([output, duration]) => {\n const result = f({\n ...meta(now, input),\n output,\n duration\n });\n if (!isEffect(result)) return effect.succeed([result, duration]);\n return effect.map(result, output => [output, duration]);\n },\n onFailure: effect.failCause,\n onDone: output => {\n const result = f({\n ...meta(now, input),\n output,\n duration: Duration.zero\n });\n if (!isEffect(result)) return Cause.done(result);\n return effect.flatMap(result, Cause.done);\n }\n });\n})));\n/**\n * Returns a new `Schedule` that modifies the delay of the next recurrence\n * of the schedule using the specified effectful function.\n *\n * **Example** (Modifying delays from schedule metadata)\n *\n * ```ts import.meta.vitest\n * import { Duration, Effect, Schedule } from \"effect\"\n *\n * const schedule = Schedule.spaced(\"10 millis\").pipe(\n * Schedule.modifyDelay(({ duration }) => Effect.succeed(Duration.times(duration, 2)))\n * )\n * const program = Effect.gen(function*() {\n * const step = yield* Schedule.toStep(schedule)\n * const [, delay] = yield* step(0, undefined)\n * return delay\n * })\n *\n * await Effect.runPromise(program) // => Duration.millis(20)\n * ```\n *\n * @category delays & timeouts\n * @since 2.0.0\n */\nexport const modifyDelay = /*#__PURE__*/dual(2, (self, f) => fromStep(effect.map(toStep(self), step => {\n const meta = metadataFn();\n return (now, input) => effect.flatMap(step(now, input), ([output, duration]) => effect.map(f({\n ...meta(now, input),\n output,\n duration\n }), replacement => [output, Duration.fromInputUnsafe(replacement)]));\n})));\n/**\n * Returns a new `Schedule` that randomly adjusts each recurrence delay.\n *\n * **When to use**\n *\n * Use to add random variation to an existing schedule's recurrence delays while\n * preserving its output and completion behavior.\n *\n * **Details**\n *\n * Each recurrence delay is scaled by a random factor between `0.8` and `1.2`.\n *\n * @see {@link modifyDelay} for replacing recurrence delays with a custom effectful transformation\n *\n * @category delays & timeouts\n * @since 2.0.0\n */\nexport const jittered = self => modifyDelay(self, ({\n duration\n}) => effect.map(randomNext, random => {\n const millis = Duration.toMillis(duration);\n return Duration.millis(millis * 0.8 * (1 - random) + millis * 1.2 * random);\n}));\n/**\n * Returns a new `Schedule` that outputs the inputs of the specified schedule.\n *\n * **Example** (Passing inputs through as outputs)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schedule } from \"effect\"\n *\n * const inputSchedule = Schedule.passthrough(\n * Schedule.exponential(\"100 millis\").pipe(Schedule.upTo({ times: 3 }))\n * )\n * const program = Effect.gen(function*() {\n * const step = yield* Schedule.toStep(inputSchedule)\n * const [output] = yield* step(0, \"input\")\n * return output\n * })\n *\n * await Effect.runPromise(program) // => \"input\"\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const passthrough = self => fromStep(effect.map(toStep(self), step => (now, input) => Pull.matchEffect(step(now, input), {\n onSuccess: result => effect.succeed([input, result[1]]),\n onFailure: effect.failCause,\n onDone: () => Cause.done(input)\n})));\n/**\n * Returns a `Schedule` which can only be stepped the specified number of\n * `times` before it terminates.\n *\n * **When to use**\n *\n * Use when you need a counter schedule with no additional delay.\n *\n * **Gotchas**\n *\n * `recurs(n)` counts schedule recurrences, not the first evaluation of the\n * effect being repeated or retried. For retrying, this means one initial\n * attempt plus at most `n` retries.\n *\n * **Example** (Limiting recurrences)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schedule } from \"effect\"\n * import { TestClock } from \"effect/testing\"\n *\n * const executions: Array<number> = []\n * const program = Effect.sync(() => executions.push(executions.length + 1)).pipe(\n * Effect.repeat(Schedule.recurs(3)),\n * Effect.as(executions)\n * )\n *\n * await Effect.runPromise(Effect.provide(program, TestClock.layer())) // => [1, 2, 3, 4]\n * ```\n *\n * @see {@link upTo} for limiting an existing schedule\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const recurs = times => while_(forever, ({\n attempt\n}) => effect.succeed(attempt <= times));\n/**\n * Returns a schedule that recurs continuously, each repetition spaced the\n * specified duration from the last run.\n *\n * **When to use**\n *\n * Use when each delay should start after the previous action completes.\n *\n * **Example** (Repeating with fixed spacing)\n *\n * ```ts import.meta.vitest\n * import { Duration, Effect, Schedule } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const step = yield* Schedule.toStep(Schedule.spaced(\"2 seconds\"))\n * return yield* step(0, undefined)\n * })\n *\n * await Effect.runPromise(program) // => [0, Duration.seconds(2)]\n * ```\n *\n * @see {@link fixed} for recurrence aligned to a regular cadence\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const spaced = duration => {\n const decoded = Duration.fromInputUnsafe(duration);\n return fromStepWithMetadata(effect.succeed(meta => effect.succeed([meta.attempt - 1, decoded])));\n};\n/**\n * Returns a new `Schedule` that allows execution of an effectful function for\n * every decision of the schedule, but does not alter the inputs and outputs of\n * the schedule.\n *\n * **Details**\n *\n * The callback receives the full schedule metadata, including the input, output,\n * computed delay duration, current attempt, and elapsed timing information.\n *\n * **Example** (Tapping schedule metadata)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schedule } from \"effect\"\n *\n * const attempts: Array<number> = []\n * const monitoredSchedule = Schedule.recurs(2).pipe(\n * Schedule.tap((metadata) => Effect.sync(() => attempts.push(metadata.attempt)))\n * )\n * const program = Effect.gen(function*() {\n * const step = yield* Schedule.toStep(monitoredSchedule)\n * const [output] = yield* step(0, undefined)\n * return { attempts, output }\n * })\n *\n * await Effect.runPromise(program) // => { attempts: [1], output: 0 }\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const tap = /*#__PURE__*/dual(2, (self, f) => fromStep(effect.map(toStep(self), step => {\n const meta = metadataFn();\n return (now, input) => effect.tap(step(now, input), ([output, duration]) => f({\n ...meta(now, input),\n output,\n duration\n }));\n})));\n/**\n * Returns a new `Schedule` that limits an existing schedule by elapsed\n * duration, number of outputs, or both.\n *\n * **When to use**\n *\n * Use to bound an existing schedule while preserving its output and delay\n * behavior. When both `duration` and `times` are specified, the schedule\n * stops as soon as either limit is reached.\n *\n * **Gotchas**\n *\n * The `times` option limits schedule outputs. When used with repeat or retry,\n * the effect is evaluated once before the schedule is stepped, so the total\n * number of evaluations can be one greater than the configured number of\n * outputs.\n *\n * The `duration` option is based on the elapsed time observed by the schedule\n * step. Long-running effects can cause the duration limit to be detected on the\n * following schedule step.\n *\n * **Example** (Limiting by duration and recurrence count)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schedule } from \"effect\"\n * import { TestClock } from \"effect/testing\"\n *\n * const executions: Array<number> = []\n * const schedule = Schedule.forever.pipe(Schedule.upTo({ times: 2 }))\n * const program = Effect.sync(() => executions.push(executions.length + 1)).pipe(\n * Effect.repeat(schedule),\n * Effect.as(executions)\n * )\n *\n * await Effect.runPromise(Effect.provide(program, TestClock.layer())) // => [1, 2, 3]\n * ```\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const upTo = /*#__PURE__*/dual(2, (self, options) => {\n const duration = options.duration === undefined ? undefined : Duration.fromInputUnsafe(options.duration);\n return while_(self, ({\n attempt,\n elapsed\n }) => effect.succeed((options.times === undefined || attempt <= options.times) && (duration === undefined || Duration.isLessThanOrEqualTo(Duration.millis(elapsed), duration))));\n});\nconst while_ = /*#__PURE__*/dual(2, (self, predicate) => fromStep(effect.map(toStep(self), step => {\n const meta = metadataFn();\n return (now, input) => effect.flatMap(step(now, input), result => {\n const [output, duration] = result;\n const eff = predicate({\n ...meta(now, input),\n output,\n duration\n });\n return effect.flatMap(isEffect(eff) ? eff : effect.succeed(eff), check => check ? effect.succeed(result) : Cause.done(output));\n });\n})));\nexport {\n/**\n * Returns a new schedule that continues while the predicate returns `true`.\n *\n * **When to use**\n *\n * Use to stop an existing schedule based on its full metadata, such as the\n * current input, output, attempt, delay, or elapsed time.\n *\n * **Details**\n *\n * The predicate receives `Metadata`, may return `boolean` or an\n * `Effect<boolean, ...>`, preserves the output and delay when it returns\n * `true`, and stops the schedule when it returns `false`.\n *\n * @see {@link upTo} for stopping after a fixed number of schedule outputs\n *\n * @category filtering\n * @since 4.0.0\n */\nwhile_ as while };\n/**\n * Schedule that divides the timeline to `interval`-long windows, and sleeps\n * until the nearest window boundary every time it recurs.\n *\n * **Details**\n *\n * For example, `Schedule.windowed(\"10 seconds\")` would produce a schedule as\n * follows:\n *\n * ```text\n * 10s 10s 10s 10s\n * |----------|----------|----------|----------|\n * |action------|sleep---|act|-sleep|action----|\n * ```\n *\n * **Example** (Repeating on aligned windows)\n *\n * ```ts import.meta.vitest\n * import { Duration, Effect, Schedule } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const step = yield* Schedule.toStep(Schedule.windowed(\"5 seconds\"))\n * return yield* step(0, undefined)\n * })\n *\n * await Effect.runPromise(program) // => [0, Duration.seconds(5)]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const windowed = interval => {\n const window = Duration.toMillis(Duration.fromInputUnsafe(interval));\n return fromStepWithMetadata(effect.succeed(meta => effect.sync(() => [meta.attempt - 1, window === 0 ? Duration.zero : Duration.millis(window - meta.elapsed % window)])));\n};\n/**\n * Returns a new `Schedule` that will recur forever.\n *\n * **Details**\n *\n * The output of the schedule is the current count of its repetitions thus far\n * (i.e. `0, 1, 2, ...`).\n *\n * **Example** (Repeating forever)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schedule } from \"effect\"\n * import { TestClock } from \"effect/testing\"\n *\n * const executions: Array<number> = []\n * const schedule = Schedule.forever.pipe(Schedule.upTo({ times: 2 }))\n * const program = Effect.sync(() => executions.push(executions.length + 1)).pipe(\n * Effect.repeat(schedule),\n * Effect.as(executions)\n * )\n *\n * await Effect.runPromise(Effect.provide(program, TestClock.layer())) // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const forever = /*#__PURE__*/spaced(Duration.zero);\nconst constIdentity = /*#__PURE__*/fromStep(/*#__PURE__*/effect.succeed((_now, input) => effect.succeed([input, Duration.zero])));\nconst identity_ = () => constIdentity;\nexport {\n/**\n * Creates a schedule that always recurs, passing inputs directly as outputs.\n *\n * **When to use**\n *\n * Use when you need an infinite schedule that preserves input values as\n * outputs.\n *\n * **Details**\n *\n * This schedule runs indefinitely, returning each input value as its output\n * without modification. It effectively acts as a pass-through that simply\n * echoes its input values at each step.\n *\n * @see {@link forever} for an infinite schedule that returns incrementing step counts\n * @category constructors\n * @since 2.0.0\n */\nidentity_ as identity };\n/**\n * Sets the input type of the provided schedule without altering its behavior.\n *\n * **When to use**\n *\n * Use to adapt a schedule that does not depend on its input values.\n *\n * **Details**\n *\n * This helper is checked at compile time and does not change the schedule's\n * runtime behavior.\n *\n * **Example** (Setting a schedule input type)\n *\n * ```ts import.meta.vitest\n * import { Schedule } from \"effect\"\n *\n * const schedule = Schedule.recurs(3).pipe(\n * Schedule.setInputType<string>()\n * )\n * Schedule.isSchedule(schedule) // => true\n * ```\n *\n * @category utility types\n * @since 4.0.0\n */\nexport const setInputType = () => self => self;\n//# sourceMappingURL=Schedule.js.map","import * as Context from \"../Context.js\";\nimport { dual } from \"../Function.js\";\nimport * as Layer from \"../Layer.js\";\nimport { isEffect } from \"./core.js\";\nimport * as effect from \"./effect.js\";\nconst provideLayer = (self, layer, options) => effect.scopedWith(scope => effect.flatMap(options?.local ? Layer.buildWithMemoMap(layer, Layer.makeMemoMapUnsafe(), scope) : Layer.buildWithScope(layer, scope), context => effect.provideContext(self, context)));\n/** @internal */\nexport const provide = /*#__PURE__*/dual(args => isEffect(args[0]), (self, source, options) => Context.isContext(source) ? effect.provideContext(self, source) : provideLayer(self, Array.isArray(source) ? Layer.mergeAll(...source) : source, options));\n//# sourceMappingURL=layer.js.map","import { constant, constTrue, dual, identity } from \"../Function.js\";\nimport * as Option from \"../Option.js\";\nimport * as Pull from \"../Pull.js\";\nimport * as Schedule from \"../Schedule.js\";\nimport { internalCall } from \"../Utils.js\";\nimport * as core from \"./core.js\";\nimport * as effect from \"./effect.js\";\n/** @internal */\nexport const repeatOrElse = /*#__PURE__*/dual(3, (self, schedule, orElse) => effect.flatMap(Schedule.toStepWithMetadata(schedule), step => {\n let meta = Schedule.CurrentMetadata.defaultValue();\n return effect.catch_(effect.forever(effect.tap(effect.flatMap(effect.suspend(() => effect.provideService(self, Schedule.CurrentMetadata, meta)), step), meta_ => effect.sync(() => {\n meta = meta_;\n })), {\n disableYield: true\n }), error => core.isDone(error) ? effect.succeed(error.value) : orElse(error, meta.attempt === 0 ? Option.none() : Option.some(meta)));\n}));\n/** @internal */\nexport const retryOrElse = /*#__PURE__*/dual(3, (self, policy, orElse) => effect.flatMap(Schedule.toStepWithMetadata(policy), step => {\n let meta = Schedule.CurrentMetadata.defaultValue();\n let lastError;\n const loop = effect.catch_(effect.suspend(() => effect.provideService(self, Schedule.CurrentMetadata, meta)), error => {\n lastError = error;\n return effect.flatMap(step(error), meta_ => {\n meta = meta_;\n return loop;\n });\n });\n return Pull.catchDone(loop, out => internalCall(() => orElse(lastError, out)));\n}));\n/** @internal */\nexport const repeat = /*#__PURE__*/dual(2, (self, options) => {\n const schedule = typeof options === \"function\" ? options(identity) : Schedule.isSchedule(options) ? options : buildFromOptions(options);\n return repeatOrElse(self, schedule, effect.fail);\n});\n/** @internal */\nexport const retry = /*#__PURE__*/dual(2, (self, options) => {\n const schedule = typeof options === \"function\" ? options(identity) : Schedule.isSchedule(options) ? options : buildFromOptions(options);\n return retryOrElse(self, schedule, effect.fail);\n});\n/** @internal */\nexport const scheduleFrom = /*#__PURE__*/dual(3, (self, initial, schedule) => effect.flatMap(Schedule.toStepWithMetadata(schedule), step => {\n let meta = Schedule.CurrentMetadata.defaultValue();\n const selfWithMeta = effect.suspend(() => effect.provideService(self, Schedule.CurrentMetadata, meta));\n return effect.catch_(effect.flatMap(step(initial), meta_ => {\n meta = meta_;\n const body = constant(effect.flatMap(selfWithMeta, step));\n return effect.whileLoop({\n while: constTrue,\n body,\n step(meta_) {\n meta = meta_;\n }\n });\n }), error => core.isDone(error) ? effect.succeed(error.value) : effect.fail(error));\n}));\nconst passthroughForever = /*#__PURE__*/Schedule.passthrough(Schedule.forever);\n/** @internal */\nexport const buildFromOptions = options => {\n let schedule = options.schedule ? Schedule.passthrough(options.schedule) : passthroughForever;\n if (options.while) {\n schedule = Schedule.while(schedule, ({\n input\n }) => {\n const applied = options.while(input);\n return core.isEffect(applied) ? applied : effect.succeed(applied);\n });\n }\n if (options.until) {\n schedule = Schedule.while(schedule, ({\n input\n }) => {\n const applied = options.until(input);\n return core.isEffect(applied) ? effect.map(applied, b => !b) : effect.succeed(!applied);\n });\n }\n if (options.times !== undefined) {\n schedule = Schedule.while(schedule, ({\n attempt\n }) => effect.succeed(attempt <= options.times));\n }\n return schedule;\n};\n//# sourceMappingURL=schedule.js.map","import * as Equal from \"./Equal.js\";\nimport { dual } from \"./Function.js\";\nimport * as core from \"./internal/core.js\";\nimport * as internalEffect from \"./internal/effect.js\";\nimport * as InternalRecord from \"./internal/record.js\";\nimport { hasProperty } from \"./Predicate.js\";\nconst TypeId = \"~effect/Request\";\nconst requestVariance = /*#__PURE__*/Equal.byReferenceUnsafe({\n /* c8 ignore next */\n _E: _ => _,\n /* c8 ignore next */\n _A: _ => _,\n /* c8 ignore next */\n _R: _ => _\n});\n/**\n * Prototype used by Effect's request constructors.\n *\n * **Details**\n *\n * This low-level value provides the structural request marker for values\n * created by `Request.of`, `Request.tagged`, `Request.Class`, and\n * `Request.TaggedClass`. Most users should use those constructors instead of\n * interacting with the prototype directly.\n *\n * @category prototypes\n * @since 4.0.0\n */\nexport const RequestPrototype = {\n ...core.StructuralProto,\n [TypeId]: requestVariance\n};\n/**\n * Checks whether a value is a `Request`.\n *\n * **Example** (Checking request values)\n *\n * ```ts import.meta.vitest\n * import { Request } from \"effect\"\n *\n * declare const User: unique symbol\n * declare const UserNotFound: unique symbol\n * type User = typeof User\n * type UserNotFound = typeof UserNotFound\n *\n * interface GetUser extends Request.Request<User, UserNotFound> {\n * readonly _tag: \"GetUser\"\n * readonly id: string\n * }\n * const GetUser = Request.tagged<GetUser>(\"GetUser\")\n *\n * const request = GetUser({ id: \"123\" })\n * Request.isRequest(request) // => true\n * Request.isRequest(\"not a request\") // => false\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isRequest = u => hasProperty(u, TypeId);\n/**\n * Creates a constructor function for a specific Request type.\n *\n * **Example** (Creating untagged request constructors)\n *\n * ```ts import.meta.vitest\n * import { Request } from \"effect\"\n *\n * declare const UserProfile: unique symbol\n * declare const ProfileError: unique symbol\n * type UserProfile = typeof UserProfile\n * type ProfileError = typeof ProfileError\n *\n * interface GetUserProfile extends Request.Request<UserProfile, ProfileError> {\n * readonly id: string\n * readonly includeSettings: boolean\n * }\n *\n * const GetUserProfile = Request.of<GetUserProfile>()\n *\n * const request = GetUserProfile({\n * id: \"user-123\",\n * includeSettings: true\n * })\n *\n * request.id // => \"user-123\"\n * request.includeSettings // => true\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const of = () => args => Object.setPrototypeOf({\n ...args\n}, RequestPrototype);\n/**\n * Creates a constructor function for a tagged Request type. The tag is automatically\n * added to the request, making it useful for discriminated unions.\n *\n * **Example** (Creating tagged request constructors)\n *\n * ```ts import.meta.vitest\n * import { Request } from \"effect\"\n *\n * declare const User: unique symbol\n * declare const UserNotFound: unique symbol\n * declare const Post: unique symbol\n * declare const PostNotFound: unique symbol\n * type User = typeof User\n * type UserNotFound = typeof UserNotFound\n * type Post = typeof Post\n * type PostNotFound = typeof PostNotFound\n *\n * interface GetUser extends Request.Request<User, UserNotFound> {\n * readonly _tag: \"GetUser\"\n * readonly id: string\n * }\n *\n * interface GetPost extends Request.Request<Post, PostNotFound> {\n * readonly _tag: \"GetPost\"\n * readonly id: string\n * }\n *\n * const GetUser = Request.tagged<GetUser>(\"GetUser\")\n * const GetPost = Request.tagged<GetPost>(\"GetPost\")\n *\n * const userRequest = GetUser({ id: \"user-123\" })\n * const postRequest = GetPost({ id: \"post-456\" })\n *\n * // _tag is automatically set\n * Array.of(userRequest._tag, postRequest._tag) // => [\"GetUser\", \"GetPost\"]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const tagged = tag => args => {\n return Object.setPrototypeOf({\n ...args,\n _tag: tag\n }, RequestPrototype);\n};\n/**\n * Defines request types with TypeScript classes.\n *\n * **Details**\n *\n * Subclasses pass their data fields to `super`, and instances are marked as\n * `Request` values while retaining the provided readonly fields.\n *\n * **Example** (Defining request classes)\n *\n * ```ts import.meta.vitest\n * import { Request } from \"effect\"\n *\n * class GetUser extends Request.Class<{ id: number }, string, Error> {\n * constructor(readonly id: number) {\n * super({ id })\n * }\n * }\n *\n * const getUserRequest = new GetUser(123)\n * getUserRequest.id // => 123\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const Class = /*#__PURE__*/function () {\n function Class(args) {\n if (args) {\n InternalRecord.assignProperties(this, args);\n }\n }\n Class.prototype = RequestPrototype;\n return Class;\n}();\n/**\n * Creates a class constructor for requests with a fixed `_tag` field.\n *\n * **Details**\n *\n * Use this when defining class-based request types that should participate in\n * tagged unions or tag-based request resolvers.\n *\n * **Example** (Defining tagged request classes)\n *\n * ```ts import.meta.vitest\n * import { Request } from \"effect\"\n *\n * class GetUserById\n * extends Request.TaggedClass(\"GetUserById\")<{ id: number }, string, Error>\n * {}\n *\n * const request = new GetUserById({ id: 123 })\n *\n * request._tag // => \"GetUserById\"\n * request.id // => 123\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const TaggedClass = tag => {\n return class TaggedClass extends Class {\n _tag = tag;\n };\n};\n/**\n * Completes a request entry with the provided result.\n *\n * **When to use**\n *\n * Use when you need to finish a `Request.Entry` with a prebuilt final `Exit`\n * result.\n *\n * @see {@link completeEffect} for completing an entry from an effect that may succeed or fail\n * @see {@link succeed} for completing an entry with a successful value\n * @see {@link fail} for completing an entry with a typed failure\n * @see {@link failCause} for completing an entry with a failure `Cause`\n *\n * @category completion\n * @since 2.0.0\n */\nexport const complete = /*#__PURE__*/dual(2, (self, result) => internalEffect.sync(() => self.completeUnsafe(result)));\n/**\n * Completes a request entry with the result of an effect.\n *\n * **When to use**\n *\n * Use to finish a `Request.Entry` by running an effect whose success or typed\n * failure should become the request result.\n *\n * **Details**\n *\n * If the effect succeeds, the entry is completed successfully with its value.\n * If the effect fails, the entry is completed with that failure.\n *\n * **Gotchas**\n *\n * The returned effect itself does not fail with the request error.\n *\n * @see {@link complete} for completing an entry with a prebuilt `Exit`\n * @see {@link succeed} for completing an entry with a successful value\n * @see {@link fail} for completing an entry with a typed failure\n * @see {@link failCause} for completing an entry with a failure `Cause`\n *\n * @category completion\n * @since 2.0.0\n */\nexport const completeEffect = /*#__PURE__*/dual(2, (self, effect) => internalEffect.matchEffect(effect, {\n onFailure: error => complete(self, core.exitFail(error)),\n onSuccess: value => complete(self, core.exitSucceed(value))\n}));\n/**\n * Completes a request entry with a typed failure.\n *\n * **When to use**\n *\n * Use to report a request-specific typed error while implementing a\n * `RequestResolver`.\n *\n * @see {@link failCause} for completing an entry with a full `Cause`\n * @see {@link complete} for completing an entry with an existing `Exit`\n * @see {@link completeEffect} for completing an entry from an effect result\n * @see {@link succeed} for completing an entry successfully\n *\n * @category completion\n * @since 2.0.0\n */\nexport const fail = /*#__PURE__*/dual(2, (self, error) => complete(self, core.exitFail(error)));\n/**\n * Completes a request entry with a failure `Cause`.\n *\n * **When to use**\n *\n * Use when you need a `RequestResolver` to complete an entry with structured\n * cause information rather than only the request's typed error value.\n *\n * @see {@link fail} for completing an entry with a typed error value\n * @see {@link complete} for completing an entry with an existing `Exit`\n * @see {@link completeEffect} for completing an entry from an effect result\n * @see {@link succeed} for completing an entry successfully\n *\n * @category completion\n * @since 2.0.0\n */\nexport const failCause = /*#__PURE__*/dual(2, (self, cause) => complete(self, core.exitFailCause(cause)));\n/**\n * Completes a request entry successfully with the supplied value.\n *\n * **When to use**\n *\n * Use when you need to finish a `Request.Entry` with a successful request\n * value.\n *\n * @see {@link complete} for completing an entry with a prebuilt `Exit`\n * @see {@link completeEffect} for completing an entry from an effect result\n * @see {@link fail} for completing an entry with a typed failure\n * @see {@link failCause} for completing an entry with a failure `Cause`\n *\n * @category completion\n * @since 2.0.0\n */\nexport const succeed = /*#__PURE__*/dual(2, (self, value) => complete(self, core.exitSucceed(value)));\n/**\n * Creates a `Request.Entry` from its component fields.\n *\n * **Details**\n *\n * This is a low-level helper for request runtime and resolver infrastructure;\n * most application code receives entries from a `RequestResolver` instead of\n * constructing them directly.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const makeEntry = options => options;\n//# sourceMappingURL=Request.js.map","import * as Context from \"../Context.js\";\nimport { dual } from \"../Function.js\";\nimport { makeEntry } from \"../Request.js\";\nimport { Scheduler } from \"../Scheduler.js\";\nimport { exitDie, isEffect } from \"./core.js\";\nimport * as effect from \"./effect.js\";\n/** @internal */\nexport const request = /*#__PURE__*/dual(2, (self, resolver) => {\n const withResolver = resolver => effect.callback(resume => {\n const entry = addEntry(resolver, self, resume, effect.getCurrentFiber());\n return maybeRemoveEntry(resolver, entry);\n });\n return isEffect(resolver) ? effect.flatMap(resolver, withResolver) : withResolver(resolver);\n});\n/** @internal */\nexport const requestUnsafe = (self, options) => {\n const entry = addEntry(options.resolver, self, options.onExit, {\n context: options.context,\n cache: {\n scheduler: Context.get(options.context, Scheduler)\n }\n });\n return () => removeEntryUnsafe(options.resolver, entry);\n};\nconst batchPool = [];\nconst pendingBatches = /*#__PURE__*/new WeakMap();\nconst addEntry = (resolver, request, resume, fiber) => {\n let batchMap = pendingBatches.get(resolver);\n if (!batchMap) {\n batchMap = new Map();\n pendingBatches.set(resolver, batchMap);\n }\n let batch;\n let completed = false;\n const entry = makeEntry({\n request,\n context: fiber.context,\n uninterruptible: false,\n completeUnsafe(effect) {\n if (completed) return;\n completed = true;\n // Removed entries still notify resolver hooks, but not their cancelled callers.\n if (batch && !batch.entrySet.delete(entry)) return;\n resume(effect);\n }\n });\n if (resolver.preCheck !== undefined && !resolver.preCheck(entry)) {\n return entry;\n }\n const key = resolver.batchKey(entry);\n batch = batchMap.get(key);\n if (!batch) {\n if (batchPool.length > 0) {\n batch = batchPool.pop();\n batch.key = key;\n batch.resolver = resolver;\n batch.map = batchMap;\n } else {\n const newBatch = {\n key,\n resolver,\n map: batchMap,\n entrySet: new Set(),\n entries: new Set(),\n delayEffect: effect.flatMap(effect.suspend(() => newBatch.resolver.delay), _ => runBatch(newBatch)),\n run: effect.onExit(effect.suspend(() => newBatch.resolver.runAll(Array.from(newBatch.entries), newBatch.key)), exit => {\n for (const entry of newBatch.entrySet) {\n entry.completeUnsafe(exit._tag === \"Success\" ? exitDie(new Error(\"Effect.request: RequestResolver did not complete request\", {\n cause: entry.request\n })) : exit);\n }\n newBatch.entries.clear();\n if (batchPool.length < 128) {\n newBatch.entrySet.clear();\n newBatch.key = undefined;\n newBatch.fiber = undefined;\n newBatch.resolver = undefined;\n newBatch.map = undefined;\n batchPool.push(newBatch);\n }\n return effect.void;\n })\n };\n batch = newBatch;\n }\n batchMap.set(key, batch);\n batch.fiber = effect.runForkWith(fiber.context)(batch.delayEffect, {\n scheduler: fiber.cache.scheduler\n });\n }\n batch.entrySet.add(entry);\n batch.entries.add(entry);\n if (batch.resolver.collectWhile(batch.entries)) return entry;\n batch.fiber.interruptUnsafe(fiber.id);\n batch.fiber = effect.runForkWith(fiber.context)(runBatch(batch), {\n scheduler: fiber.cache.scheduler\n });\n return entry;\n};\nconst removeEntryUnsafe = (resolver, entry) => {\n if (entry.uninterruptible) return;\n const batchMap = pendingBatches.get(resolver);\n if (!batchMap) return;\n const key = resolver.batchKey(entry);\n const batch = batchMap.get(key);\n if (!batch) return;\n if (!batch.entries.delete(entry)) return;\n batch.entrySet.delete(entry);\n let fiber;\n if (batch.entries.size === 0) {\n batchMap.delete(key);\n fiber = batch.fiber;\n }\n // Delay finalizers may enqueue new requests, so complete the removed entry first.\n entry.completeUnsafe(effect.exitInterrupt());\n fiber?.interruptUnsafe();\n};\nconst maybeRemoveEntry = (resolver, entry) => effect.sync(() => removeEntryUnsafe(resolver, entry));\nfunction runBatch(batch) {\n if (!batch.map.has(batch.key)) return effect.void;\n batch.map.delete(batch.key);\n return batch.run;\n}\n//# sourceMappingURL=request.js.map","import * as Context from \"./Context.js\";\nimport * as Duration from \"./Duration.js\";\nimport * as Exit from \"./Exit.js\";\nimport { constant, dual } from \"./Function.js\";\nimport * as core from \"./internal/core.js\";\nimport * as internal from \"./internal/effect.js\";\nimport * as internalExecutionPlan from \"./internal/executionPlan.js\";\nimport * as internalLayer from \"./internal/layer.js\";\nimport * as InternalRecord from \"./internal/record.js\";\nimport * as internalRequest from \"./internal/request.js\";\nimport * as internalSchedule from \"./internal/schedule.js\";\nimport * as Metric from \"./Metric.js\";\nimport { CurrentLogAnnotations, CurrentLogSpans } from \"./References.js\";\nimport { internalCall } from \"./Utils.js\";\n/**\n * Runtime identifier used to recognize `Effect` values.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const TypeId = core.EffectTypeId;\n/**\n * Checks whether a value is an `Effect`.\n *\n * **Example** (Checking whether a value is an Effect)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * Effect.isEffect(Effect.succeed(1)) // => true\n * Effect.isEffect(\"hello\") // => false\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isEffect = core.isEffect;\n/**\n * Combines an iterable or record of effects into one effect whose success shape\n * follows the input.\n *\n * **When to use**\n *\n * Use to run a known collection of effects and collect results in the same\n * tuple, iterable, or record shape.\n *\n * **Details**\n *\n * Tuple and iterable inputs collect results in order. Record inputs collect\n * results under the same keys. By default, the combined effect fails on the\n * first failure; with concurrent execution, effects that have already started\n * may be interrupted, while effects not yet started are skipped.\n *\n * Options:\n *\n * Use `concurrency` to control sequential or concurrent execution. Use\n * `mode: \"result\"` to run every effect and collect each success or failure as a\n * `Result` in the same output shape. Use `discard: true` to ignore successful\n * values and return `void`.\n *\n * **Example** (Collecting tuple results in order)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const tupleOfEffects = [\n * Effect.succeed(42),\n * Effect.succeed(\"Hello\")\n * ] as const\n *\n * // ┌─── Effect<[number, string], never, never>\n * // ▼\n * const resultsAsTuple = Effect.all(tupleOfEffects)\n *\n * await Effect.runPromise(resultsAsTuple) // => [42, \"Hello\"]\n * ```\n *\n * **Example** (Collecting iterable results in order)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const iterableOfEffects: Iterable<Effect.Effect<number>> = [1, 2, 3].map(\n * Effect.succeed\n * )\n *\n * // ┌─── Effect<number[], never, never>\n * // ▼\n * const resultsAsArray = Effect.all(iterableOfEffects)\n *\n * await Effect.runPromise(resultsAsArray) // => [1, 2, 3]\n * ```\n *\n * **Example** (Collecting struct results by key)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const structOfEffects = {\n * a: Effect.succeed(42),\n * b: Effect.succeed(\"Hello\")\n * }\n *\n * // ┌─── Effect<{ a: number; b: string; }, never, never>\n * // ▼\n * const resultsAsStruct = Effect.all(structOfEffects)\n *\n * await Effect.runPromise(resultsAsStruct) // => { a: 42, b: \"Hello\" }\n * ```\n *\n * **Example** (Collecting record results by key)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const recordOfEffects: Record<string, Effect.Effect<number>> = {\n * key1: Effect.succeed(1),\n * key2: Effect.succeed(2)\n * }\n *\n * // ┌─── Effect<{ [x: string]: number; }, never, never>\n * // ▼\n * const resultsAsRecord = Effect.all(recordOfEffects)\n *\n * await Effect.runPromise(resultsAsRecord) // => { key1: 1, key2: 2 }\n * ```\n *\n * **Example** (Stopping on the first failure)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit } from \"effect\"\n * const output: Array<unknown> = []\n * const record = (value: unknown) => Effect.sync(() => { output.push(value) })\n *\n * const program = Effect.all([\n * Effect.succeed(\"Task1\").pipe(Effect.tap(record)),\n * Effect.fail(\"Task2: Oh no!\").pipe(Effect.tap(record)),\n * // Won't execute due to earlier failure\n * Effect.succeed(\"Task3\").pipe(Effect.tap(record))\n * ])\n *\n * const outcome = await Effect.runPromiseExit(program)\n * const observation = [output, outcome] // => [[\"Task1\"], Exit.fail(\"Task2: Oh no!\")]\n * ```\n *\n * @see {@link forEach} for iterating over elements and applying an effect.\n * @category combining\n * @since 2.0.0\n */\nexport const all = internal.all;\n/**\n * Applies an effectful function to each element and partitions failures and\n * successes.\n *\n * **Details**\n *\n * The returned tuple is `[excluded, satisfying]`, where `excluded` contains\n * all failures and `satisfying` contains all successes.\n *\n * This function runs every effect and never fails. Use `concurrency` to control\n * parallelism.\n *\n * **Example** (Separating successes and failures)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const program = Effect.partition([0, 1, 2, 3], (n) =>\n * n % 2 === 0 ? Effect.fail(`${n} is even`) : Effect.succeed(n)\n * )\n *\n * await Effect.runPromise(program) // => [['0 is even', '2 is even'], [1, 3]]\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const partition = internal.partition;\n/**\n * Reduces elements from left to right with an effectful accumulator function.\n *\n * **When to use**\n *\n * Use when each accumulation step is effectful and must run sequentially in\n * iteration order.\n *\n * **Details**\n *\n * The accumulator function receives the current accumulator, the current\n * element, and its zero-based index. The `zero` function is evaluated each\n * time the effect runs. An empty iterable succeeds with its result. If a step\n * fails, remaining elements are not processed.\n *\n * **Example** (Summing values sequentially)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.reduce(\n * [1, 2, 3],\n * () => 0,\n * (total, value, index) =>\n * Effect.sync(() => { output.push(`Adding ${value} at index ${index}`) }).pipe(\n * Effect.as(total + value)\n * )\n * )\n *\n * void output.push(await Effect.runPromise(program))\n * output // => [\"Adding 1 at index 0\", \"Adding 2 at index 1\", \"Adding 3 at index 2\", 6]\n * ```\n *\n * @category folding\n * @since 2.0.0\n */\nexport const reduce = internal.reduce;\n/**\n * Applies an effectful function to each element and accumulates all failures.\n *\n * **Details**\n *\n * This function always evaluates every element. If at least one effect fails,\n * all failures are returned as a non-empty array and successes are discarded.\n * If all effects succeed, it returns all collected successes.\n *\n * Use `discard: true` to ignore successful values while still validating all\n * elements.\n *\n * **Example** (Validating every element)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit } from \"effect\"\n *\n * const program = Effect.validate([0, 1, 2, 3], (n) =>\n * n % 2 === 0 ? Effect.fail(`${n} is even`) : Effect.succeed(n)\n * )\n *\n * await Effect.runPromiseExit(program) // => Exit.fail([\"0 is even\", \"2 is even\"])\n * ```\n *\n * @category validation\n * @since 2.0.0\n */\nexport const validate = internal.validate;\n/**\n * Returns the first element that satisfies an effectful predicate.\n *\n * **Details**\n *\n * The predicate receives the element and its index. Evaluation short-circuits\n * as soon as an element matches.\n *\n * **Example** (Finding the first successful match)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option } from \"effect\"\n *\n * const program = Effect.findFirst([1, 2, 3, 4], (n) => Effect.succeed(n > 2))\n *\n * await Effect.runPromise(program) // => Option.some(3)\n * ```\n *\n * @category searching\n * @since 2.0.0\n */\nexport const findFirst = internal.findFirst;\n/**\n * Returns the first value that passes an effectful `FilterEffect`.\n *\n * **When to use**\n *\n * Use when you need to find the first element that satisfies an effectful\n * filter returning a `Result`, which also transforms the matching element.\n *\n * **Details**\n *\n * The filter receives the element and index. Evaluation short-circuits on the\n * first `Result.succeed` and returns the transformed value in `Option.some`.\n *\n * @see {@link findFirst} for the simpler effectful predicate-based variant\n *\n * @category searching\n * @since 4.0.0\n */\nexport const findFirstFilter = internal.findFirstFilter;\n/**\n * Executes an effectful operation for each element in an `Iterable`.\n *\n * **When to use**\n *\n * Use to traverse an iterable with an effectful function while preserving\n * element order in the collected results.\n *\n * **Details**\n *\n * The `forEach` function applies a provided operation to each element in the\n * iterable, producing a new effect that returns an array of results.\n *\n * If any effect fails, the iteration stops immediately (short-circuiting), and\n * the error is propagated.\n *\n * Concurrency:\n *\n * The `concurrency` option controls how many operations are performed\n * concurrently. By default, the operations are performed sequentially.\n *\n * Discarding Results:\n *\n * If the `discard` option is set to `true`, the intermediate results are not\n * collected, and the final result of the operation is `void`.\n *\n * **Example** (Mapping over an iterable with effects)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const result = Effect.forEach(\n * [1, 2, 3, 4, 5],\n * (n, index) =>\n * Effect.sync(() => { output.push(`Currently at index ${index}`) }).pipe(Effect.as(n * 2))\n * )\n *\n * void output.push(await Effect.runPromise(result))\n * output // => [\"Currently at index 0\", \"Currently at index 1\", \"Currently at index 2\", \"Currently at index 3\", \"Currently at index 4\", [2, 4, 6, 8, 10]]\n * ```\n *\n * **Example** (Running effects without collecting results)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * // Apply effects but discard the results\n * const result = Effect.forEach(\n * [1, 2, 3, 4, 5],\n * (n, index) =>\n * Effect.sync(() => { output.push(`Currently at index ${index}`) }).pipe(Effect.as(n * 2)),\n * { discard: true }\n * )\n *\n * void output.push(await Effect.runPromise(result))\n * output // => [\"Currently at index 0\", \"Currently at index 1\", \"Currently at index 2\", \"Currently at index 3\", \"Currently at index 4\", undefined]\n * ```\n *\n * @see {@link all} for combining multiple effects into one.\n * @category sequencing\n * @since 2.0.0\n */\nexport const forEach = internal.forEach;\n/**\n * Returns the first element of the iterable produced by an effect, or fails\n * with `NoSuchElementError` if the iterable is empty.\n *\n * **When to use**\n *\n * Use when an effect produces a collection that must contain at least one\n * element and absence should be represented in the typed error channel.\n *\n * **Example** (Getting the first element)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option } from \"effect\"\n *\n * const first = await Effect.runPromise(Effect.head(Effect.succeed([1, 2, 3])))\n * first // => 1\n *\n * const empty = Effect.head(Effect.succeed([] as Array<number>)).pipe(Effect.catchNoSuchElement)\n * await Effect.runPromise(empty) // => Option.none()\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const head = internal.head;\n/**\n * Executes a body effect repeatedly while a condition holds true.\n *\n * **Example** (Repeating an effectful loop)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * let counter = 0\n *\n * const program = Effect.whileLoop({\n * while: () => counter < 5,\n * body: () => Effect.sync(() => ++counter),\n * step: (n) => void output.push(`Current count: ${n}`)\n * })\n *\n * await Effect.runPromise(program)\n * output // => [\"Current count: 1\", \"Current count: 2\", \"Current count: 3\", \"Current count: 4\", \"Current count: 5\"]\n * ```\n *\n * @category repetition\n * @since 2.0.0\n */\nexport const whileLoop = internal.whileLoop;\n// -----------------------------------------------------------------------------\n// Creating Effects\n// -----------------------------------------------------------------------------\n/**\n * Creates an `Effect` that represents an asynchronous computation guaranteed to\n * succeed.\n *\n * **When to use**\n *\n * Use to convert a `Promise` into an `Effect` when the async operation is\n * guaranteed to succeed and will not reject.\n *\n * **Details**\n *\n * An optional `AbortSignal` can be provided to allow for interruption of the\n * wrapped `Promise` API.\n *\n * **Gotchas**\n *\n * The `Promise` must not reject. If it rejects, the rejection is treated as a\n * defect, not as a typed failure. Use `tryPromise` when rejection is expected.\n *\n * Interruption aborts the provided `AbortSignal`, but the underlying\n * asynchronous operation only stops if it observes that signal.\n *\n * **Example** (Wrapping a non-rejecting Promise)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const succeedAsync = (message: string) =>\n * Effect.promise<string>(() => Promise.resolve(message))\n *\n * // ┌─── Effect<string, never, never>\n * // ▼\n * const program = succeedAsync(\"Async operation completed successfully!\")\n * await Effect.runPromise(program) // => \"Async operation completed successfully!\"\n * ```\n *\n * @see {@link tryPromise} for a version that can handle failures.\n * @category constructors\n * @since 2.0.0\n */\nexport const promise = internal.promise;\n/**\n * Creates an `Effect` from an asynchronous computation that may throw or\n * reject, mapping failures into the error channel.\n *\n * **When to use**\n *\n * Use when you need to perform asynchronous operations that might fail, such\n * as fetching data from an API, and want thrown exceptions or rejected promises\n * captured as Effect errors.\n *\n * **Details**\n *\n * The promise thunk is evaluated when the effect runs. If it returns a promise\n * that resolves, the resolved value becomes the success value. If the thunk\n * throws before returning a promise, or if the returned promise rejects, the\n * thrown or rejected value is mapped into the error channel.\n *\n * Passing the thunk directly maps failures to {@link Cause.UnknownError}.\n * Passing `{ try, catch }` uses `catch` to map failures to an error of type\n * `E`.\n *\n * The thunk receives an `AbortSignal` that is aborted if the effect is\n * interrupted. The underlying asynchronous operation only stops if it observes\n * that signal.\n *\n * **Gotchas**\n *\n * If `catch` throws while mapping the error, that thrown value is treated as a\n * defect. Return the error value you want in the error channel instead of\n * throwing it.\n *\n * **Example** (Wrapping a fetch request that may fail)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const getTodo = (id: number) =>\n * Effect.tryPromise(() => Promise.resolve({ id, completed: false }))\n *\n * // ┌─── Effect<{ id: number; completed: boolean }, UnknownError, never>\n * // ▼\n * const program = getTodo(1)\n * await Effect.runPromise(program) // => { id: 1, completed: false }\n * ```\n *\n * **Example** (Mapping Promise rejections to a tagged error)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect } from \"effect\"\n *\n * class TodoFetchError extends Data.TaggedError(\"TodoFetchError\")<{ readonly cause: unknown }> {}\n *\n * const getTodo = (id: number) =>\n * Effect.tryPromise({\n * try: () => Promise.reject(`Todo ${id} is unavailable`),\n * // remap the error\n * catch: (cause) => new TodoFetchError({ cause })\n * })\n *\n * // ┌─── Effect<never, TodoFetchError, never>\n * // ▼\n * const program = Effect.flip(getTodo(1))\n * const error = await Effect.runPromise(program)\n * error._tag // => \"TodoFetchError\"\n * ```\n *\n * @see {@link promise} if the effectful computation is asynchronous and does not throw errors.\n * @category constructors\n * @since 2.0.0\n */\nexport const tryPromise = internal.tryPromise;\n/**\n * Creates an `Effect` that always succeeds with a given value.\n *\n * **When to use**\n *\n * Use when an effect should complete successfully with a specific value without any errors\n * or external dependencies.\n *\n * **Example** (Creating a successful effect)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * // Creating an effect that represents a successful scenario\n * //\n * // ┌─── Effect<number, never, never>\n * // ▼\n * const success = Effect.succeed(42)\n * Effect.runSync(success) // => 42\n * ```\n *\n * @see {@link fail} to create an effect that represents a failure.\n * @category constructors\n * @since 2.0.0\n */\nexport const succeed = internal.succeed;\n/**\n * Returns an effect which succeeds with `None`.\n *\n * **Example** (Succeeding with Option.none)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option } from \"effect\"\n *\n * const program = Effect.succeedNone\n *\n * Effect.runSync(program) // => Option.none()\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const succeedNone = internal.succeedNone;\n/**\n * Returns an effect which succeeds with the value wrapped in a `Some`.\n *\n * **Example** (Succeeding with Option.some)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option } from \"effect\"\n *\n * const program = Effect.succeedSome(42)\n *\n * Effect.runSync(program) // => Option.some(42)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const succeedSome = internal.succeedSome;\n/**\n * Creates an `Effect` lazily, delaying construction until it is needed.\n *\n * **When to use**\n *\n * Use when you need to defer the evaluation of an effect until it is required.\n *\n * **Details**\n *\n * `suspend` takes a thunk that represents an effect and delays creating it\n * until the suspended effect is evaluated. This is useful for optimizing\n * expensive computations, managing circular dependencies such as recursive\n * functions, and helping TypeScript unify return types when branches construct\n * different effects. Any side effects or scoped captures inside the thunk are\n * re-executed on each invocation.\n *\n * **Example** (Lazily evaluating side effects)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * let i = 0\n *\n * const bad = Effect.succeed(i++)\n *\n * const good = Effect.suspend(() => Effect.succeed(i++))\n *\n * Effect.runSync(bad) // => 0\n * Effect.runSync(bad) // => 0\n *\n * Effect.runSync(good) // => 1\n * Effect.runSync(good) // => 2\n * ```\n *\n * **Example** (Suspending recursive Fibonacci evaluation)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const blowsUp = (n: number): Effect.Effect<number> =>\n * n < 2\n * ? Effect.succeed(1)\n * : Effect.zipWith(blowsUp(n - 1), blowsUp(n - 2), (a, b) => a + b)\n *\n * // console.log(Effect.runSync(blowsUp(32)))\n * // crash: JavaScript heap out of memory\n *\n * const allGood = (n: number): Effect.Effect<number> =>\n * n < 2\n * ? Effect.succeed(1)\n * : Effect.zipWith(\n * Effect.suspend(() => allGood(n - 1)),\n * Effect.suspend(() => allGood(n - 2)),\n * (a, b) => a + b\n * )\n *\n * Effect.runSync(allGood(16)) // => 1597\n * ```\n *\n * **Example** (Helping TypeScript infer recursive effect types)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * // Without suspend, TypeScript may struggle with type inference.\n * // Inferred type:\n * // (a: number, b: number) =>\n * // Effect<never, Error, never> | Effect<number, never, never>\n * const withoutSuspend = (a: number, b: number) =>\n * b === 0\n * ? Effect.fail(new Error(\"Cannot divide by zero\"))\n * : Effect.succeed(a / b)\n *\n * // Using suspend to unify return types.\n * // Inferred type:\n * // (a: number, b: number) => Effect<number, Error, never>\n * const withSuspend = (a: number, b: number) =>\n * Effect.suspend(() =>\n * b === 0\n * ? Effect.fail(new Error(\"Cannot divide by zero\"))\n * : Effect.succeed(a / b)\n * )\n *\n * Effect.runSync(withSuspend(6, 2)) // => 3\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const suspend = internal.suspend;\n/**\n * Creates an `Effect` that represents a synchronous side-effectful computation.\n *\n * **When to use**\n *\n * Use when you need to wrap a synchronous side-effectful operation that is not\n * expected to throw.\n *\n * **Details**\n *\n * The provided function is evaluated lazily when the effect runs.\n *\n * **Gotchas**\n *\n * The function must not throw. If it throws, the thrown value is treated as a\n * defect, not as a typed failure. Use `try` when throwing is expected.\n *\n * **Example** (Capturing synchronous logging in an Effect)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const log = (message: string) =>\n * Effect.sync(() => {\n * void output.push(message) // side effect\n * })\n *\n * // ┌─── Effect<void, never, never>\n * // ▼\n * const program = log(\"Hello, World!\")\n * Effect.runSync(program)\n * output // => [\"Hello, World!\"]\n * ```\n *\n * @see {@link try_ | try} for a version that can handle failures.\n * @category constructors\n * @since 2.0.0\n */\nexport const sync = internal.sync;\nconst void_ = internal.void;\nexport {\n/**\n * Returns an effect that succeeds with `void`.\n *\n * @category constructors\n * @since 2.0.0\n */\nvoid_ as void };\nconst undefined_ = internal.undefined;\nexport {\n/**\n * Returns an effect that succeeds with `undefined`.\n *\n * @category constructors\n * @since 4.0.0\n */\nundefined_ as undefined };\n/**\n * Creates an `Effect` from a callback-based asynchronous API.\n *\n * **When to use**\n *\n * Use when you need to integrate APIs that complete through callbacks instead\n * of returning a `Promise`.\n *\n * **Details**\n *\n * The registration function receives a `resume` callback and, when requested,\n * an `AbortSignal`. Call `resume` at most once with the effect that should\n * complete the fiber; later calls are ignored. Return an optional cleanup\n * effect from the registration function to run if the fiber is interrupted.\n *\n * **Example** (Integrating callback APIs)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const fromCallback = (message: string) =>\n * Effect.callback<void>((resume) => {\n * queueMicrotask(() => {\n * void output.push(message)\n * resume(Effect.void)\n * })\n * })\n *\n * await Effect.runPromise(fromCallback(\"callback completed\"))\n * output // => [\"callback completed\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const callback = internal.callback;\n/**\n * Returns an effect that will never produce anything. The moral equivalent of\n * `while(true) {}`, only without the wasted CPU cycles.\n *\n * **Example** (Creating a never-ending effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option } from \"effect\"\n *\n * const program = Effect.timeoutOption(Effect.never, 0)\n * await Effect.runPromise(program) // => Option.none()\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const never = internal.never;\n/**\n * Effect that succeeds with an empty record `{}`, used as the starting point\n * for do notation chains.\n *\n * **Example** (Starting do notation)\n *\n * ```ts import.meta.vitest\n * import { Effect, pipe } from \"effect\"\n *\n * const program = pipe(\n * Effect.Do,\n * Effect.bind(\"x\", () => Effect.succeed(2)),\n * Effect.bind(\"y\", ({ x }) => Effect.succeed(x + 1)),\n * Effect.let(\"sum\", ({ x, y }) => x + y)\n * )\n *\n * Effect.runSync(program) // => { x: 2, y: 3, sum: 5 }\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const Do = internal.Do;\n/**\n * Gives a name to the success value of an `Effect`, creating a single-key\n * record used in do notation pipelines.\n *\n * **When to use**\n *\n * Use to start a do-notation pipeline from an existing `Effect` when its\n * success value should become the first named field in the accumulated record.\n *\n * @see {@link Do} for starting from an empty accumulated record\n * @see {@link bind} for adding fields produced by effects\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const bindTo = internal.bindTo;\nconst let_ = internal.let;\nexport {\n/**\n * Adds a computed plain value to the do notation record.\n *\n * **When to use**\n *\n * Use to add a derived, synchronous value to a do-notation pipeline when it\n * depends on fields already accumulated in the record and does not need to run\n * another `Effect`.\n *\n * **Details**\n *\n * The new field is added with object spreading. If the name already exists in\n * the record, the computed value replaces it in the returned type.\n *\n * @see {@link bind} for adding fields produced by effects\n * @see {@link bindTo} for naming an existing success value\n * @see {@link Do} for starting from an empty accumulated record\n * @see {@link gen} for sequencing without accumulating a record\n *\n * @category mapping\n * @since 2.0.0\n */\nlet_ as let };\n/**\n * Adds an `Effect` value to the do notation record under a given name.\n *\n * **When to use**\n *\n * Use to sequence an effectful step in a do-notation pipeline when that step\n * depends on fields already accumulated in the record and its success value\n * should be stored under a name.\n *\n * **Details**\n *\n * The function receives the current record, runs the returned effect after the\n * input effect succeeds, and inserts its success value under `name`. The\n * resulting effect combines the error and service requirements of both steps.\n *\n * **Gotchas**\n *\n * Binding a name that already exists replaces that field in the resulting\n * record.\n *\n * @see {@link Do} for starting from an empty do-notation record\n * @see {@link bindTo} for naming the success value of an existing effect\n * @see {@link gen} for generator-based sequencing without accumulating a record\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const bind = internal.bind;\n/**\n * Provides a way to write effectful code using generator functions, simplifying\n * control flow and error handling.\n *\n * **When to use**\n *\n * Use when you want to write effectful code that looks and behaves like\n * synchronous code, while still handling asynchronous tasks, errors, and complex\n * control flow such as loops and conditions.\n *\n * Generator functions work similarly to `async/await` but keep errors,\n * requirements, and interruption in the Effect type. You can `yield*` values\n * from effects and return the final result at the end.\n *\n * **Example** (Sequencing effects with generators)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect } from \"effect\"\n *\n * class DiscountRateError extends Data.TaggedError(\"DiscountRateError\")<{}> {}\n *\n * const addServiceCharge = (amount: number) => amount + 1\n *\n * const applyDiscount = (\n * total: number,\n * discountRate: number\n * ): Effect.Effect<number, DiscountRateError> =>\n * discountRate === 0\n * ? Effect.fail(new DiscountRateError())\n * : Effect.succeed(total - (total * discountRate) / 100)\n *\n * const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))\n *\n * const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))\n *\n * export const program = Effect.gen(function*() {\n * const transactionAmount = yield* fetchTransactionAmount\n * const discountRate = yield* fetchDiscountRate\n * const discountedAmount = yield* applyDiscount(\n * transactionAmount,\n * discountRate\n * )\n * const finalAmount = addServiceCharge(discountedAmount)\n * return `Final amount to charge: ${finalAmount}`\n * })\n *\n * await Effect.runPromise(program) // => \"Final amount to charge: 96\"\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const gen = internal.gen;\n/**\n * Creates an `Effect` that represents a recoverable error.\n *\n * **When to use**\n *\n * Use to explicitly signal a recoverable error in an `Effect`.\n *\n * **Details**\n *\n * The error keeps propagating unless it is handled. You can handle tagged\n * errors with functions like {@link catchTag} or {@link catchTags}.\n *\n * **Example** (Creating a failed effect)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect } from \"effect\"\n *\n * class OperationFailedError extends Data.TaggedError(\"OperationFailedError\")<{}> {}\n *\n * // ┌─── Effect<never, OperationFailedError, never>\n * // ▼\n * const failure = Effect.fail(\n * new OperationFailedError()\n * )\n * Effect.runSync(Effect.flip(failure))._tag // => \"OperationFailedError\"\n * ```\n *\n * @see {@link succeed} to create an effect that represents a successful value.\n * @category constructors\n * @since 2.0.0\n */\nexport const fail = internal.fail;\n/**\n * Creates an `Effect` that represents a recoverable error using a lazy evaluation.\n *\n * **When to use**\n *\n * Use to defer computing a recoverable error value until the effect is run.\n *\n * **Details**\n *\n * The error-producing function is evaluated each time the effect is executed.\n *\n * **Example** (Lazily creating failures)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect } from \"effect\"\n *\n * class ProgramError extends Data.TaggedError(\"ProgramError\")<{ readonly operation: string }> {}\n *\n * const program = Effect.failSync(() => new ProgramError({ operation: \"sync\" }))\n *\n * Effect.runSync(Effect.flip(program)).operation // => \"sync\"\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const failSync = internal.failSync;\n/**\n * Creates an `Effect` that represents a failure with a specific `Cause`.\n *\n * **When to use**\n *\n * Use when you already have a full `Cause` and need to preserve defects,\n * interruptions, annotations, or combined failures in the effect's failure\n * channel.\n *\n * **Details**\n *\n * This function allows you to create effects that fail with complex error\n * structures, including multiple errors, defects, interruptions, and more.\n *\n * **Example** (Failing with a full Cause)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect } from \"effect\"\n *\n * const program = Effect.failCause(\n * Cause.fail(\"Network error\")\n * )\n *\n * Effect.runSync(Effect.flip(program)) // => \"Network error\"\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const failCause = internal.failCause;\n/**\n * Creates an `Effect` that represents a failure with a `Cause` computed lazily.\n *\n * **When to use**\n *\n * Use to defer computing a full `Cause` until the effect is run.\n *\n * **Details**\n *\n * The cause-producing function is evaluated each time the effect is executed.\n *\n * **Example** (Lazily creating a Cause)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect } from \"effect\"\n *\n * const program = Effect.failCauseSync(() =>\n * Cause.fail(\"Error computed at runtime\")\n * )\n *\n * Effect.runSync(Effect.flip(program)) // => \"Error computed at runtime\"\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const failCauseSync = internal.failCauseSync;\n/**\n * Creates an effect that terminates a fiber with a specified error.\n *\n * **When to use**\n *\n * Use when you need an `Effect` to report an unrecoverable defect instead of a\n * typed error.\n *\n * **Details**\n *\n * The `die` function is used to signal a defect, which represents a critical\n * and unexpected error in the code. When invoked, it produces an effect that\n * does not handle the error and instead terminates the fiber.\n *\n * The error channel of the resulting effect is of type `never`, indicating that\n * it cannot recover from this failure.\n *\n * **Example** (Failing on division by zero)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit } from \"effect\"\n *\n * const defect = new Error(\"Cannot divide by zero\")\n * const divide = (a: number, b: number) =>\n * b === 0\n * ? Effect.die(defect)\n * : Effect.succeed(a / b)\n *\n * // ┌─── Effect<number, never, never>\n * // ▼\n * const program = divide(1, 0)\n *\n * Effect.runSyncExit(program) // => Exit.die(defect)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const die = internal.die;\nconst try_ = internal.try;\nexport {\n/**\n * Creates an `Effect` from a synchronous computation that may throw, mapping\n * thrown values into the error channel.\n *\n * **When to use**\n *\n * Use when you need to perform synchronous operations that might throw, such\n * as parsing JSON, and want thrown exceptions captured as Effect errors.\n *\n * **Details**\n *\n * The thunk is evaluated when the effect runs. If it returns normally, the\n * returned value becomes the success value. If it throws, the thrown value is\n * mapped into the error channel.\n *\n * Passing the thunk directly maps failures to {@link Cause.UnknownError}.\n * Passing `{ try, catch }` uses `catch` to map failures to an error of type\n * `E`.\n *\n * **Gotchas**\n *\n * If `catch` throws while mapping the error, that thrown value is treated as\n * a defect. Return the error value you want in the error channel instead of\n * throwing it.\n *\n * **Example** (Parsing JSON)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const parseJSON = (input: string) =>\n * Effect.try(() => JSON.parse(input))\n *\n * // Success case\n * await Effect.runPromise(parseJSON(\"{\\\"name\\\": \\\"Alice\\\"}\")) // => { name: 'Alice' }\n *\n * // Failure case maps the thrown value to UnknownError\n * const exit = await Effect.runPromiseExit(parseJSON(\"invalid json\"))\n * exit._tag // => \"Failure\"\n * ```\n *\n * **Example** (Mapping exceptions to a tagged error)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect } from \"effect\"\n *\n * class JsonParsingError extends Data.TaggedError(\"JsonParsingError\")<{ readonly cause: unknown }> {}\n *\n * const parseJSON = (input: string) =>\n * Effect.try({\n * try: () => JSON.parse(input),\n * catch: (cause) => new JsonParsingError({ cause })\n * })\n *\n * const error = await Effect.runPromise(Effect.flip(parseJSON(\"invalid json\")))\n * error._tag // => \"JsonParsingError\"\n * ```\n *\n * @see {@link sync} if the effectful computation is synchronous and does not\n * throw errors.\n * @category constructors\n * @since 2.0.0\n */\ntry_ as try };\n/**\n * Yields control back to the Effect runtime, allowing other fibers to execute.\n *\n * **Example** (Yielding to other fibers)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.gen(function*() {\n * void output.push(\"Before yield\")\n * yield* Effect.yieldNow\n * void output.push(\"After yield\")\n * })\n *\n * await Effect.runPromise(program)\n * output // => [\"Before yield\", \"After yield\"]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const yieldNow = internal.yieldNow;\n/**\n * Yields control back to the Effect runtime with a specified priority, allowing other fibers to execute.\n *\n * **Example** (Yielding with priority)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.gen(function*() {\n * void output.push(\"High priority task\")\n * yield* Effect.yieldNowWith(10) // Higher priority\n * void output.push(\"Continued after yield\")\n * })\n *\n * await Effect.runPromise(program)\n * output // => [\"High priority task\", \"Continued after yield\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const yieldNowWith = internal.yieldNowWith;\n/**\n * Provides access to the current fiber within an effect computation.\n *\n * **Example** (Reading the current fiber)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const program = Effect.withFiber((fiber) => Effect.succeed(typeof fiber.id))\n *\n * Effect.runSync(program) // => \"number\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const withFiber = core.withFiber;\n/**\n * Accesses the current fiber to compute a successful value.\n *\n * **Example** (Computing a value from the current fiber)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const program = Effect.withFiberSucceed((fiber) => typeof fiber.id)\n *\n * Effect.runSync(program) // => \"number\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const withFiberSucceed = core.withFiberSucceed;\n// -----------------------------------------------------------------------------\n// Conversions\n// -----------------------------------------------------------------------------\n/**\n * Converts a `Result` to an `Effect`.\n *\n * **Example** (Converting a Result into an Effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Result } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const success = Result.succeed(42)\n * const failure = Result.fail(\"Something went wrong\")\n *\n * const effect1 = Effect.fromResult(success)\n * const effect2 = Effect.fromResult(failure)\n *\n * void output.push(Effect.runSync(effect1))\n * void output.push(Effect.runSync(Effect.flip(effect2)))\n * output // => [42, \"Something went wrong\"]\n * ```\n *\n * @category converting\n * @since 4.0.0\n */\nexport const fromResult = internal.fromResult;\n/**\n * Converts an `Option` into an `Effect`.\n *\n * **When to use**\n *\n * Use when absence should become a typed `NoSuchElementError` in the effect error\n * channel.\n *\n * **Details**\n *\n * `Option.some` becomes a successful effect with the contained value, while\n * `Option.none` becomes a failed effect. By default the failure is a\n * `NoSuchElementError`, but you can provide an `onNone` callback to customize\n * the error value.\n *\n * **Example** (Converting an Option into an Effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const some = Option.some(42)\n * const none = Option.none()\n *\n * const effect1 = Effect.fromOption(some)\n * const effect2 = Effect.fromOption(none)\n * const effect3 = Effect.fromOption(none, () => new Error(\"missing\"))\n *\n * void output.push(Effect.runSync(effect1))\n * void output.push(Effect.runSync(Effect.flip(effect2))._tag)\n * void output.push(Effect.runSync(Effect.flip(effect3)).message)\n * output // => [42, \"NoSuchElementError\", \"missing\"]\n * ```\n *\n * @category converting\n * @since 4.0.0\n */\nexport const fromOption = internal.fromOption;\n/**\n * Converts an `Option` of an `Effect` into an `Effect` of an `Option`.\n *\n * **When to use**\n *\n * Use when an effect should run only when an optional value is present, while\n * preserving absence as a successful `None`.\n *\n * **Details**\n *\n * - `None` becomes an effect that succeeds with `None`\n * - `Some(effect)` runs the inner effect and wraps its success value in `Some`\n * - Inner failures are preserved in the resulting effect\n *\n * **Example** (Transposing an Option of an Effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option } from \"effect\"\n *\n * const some = Option.some(Effect.succeed(42))\n *\n * // ┌─── Effect<Option<number>, never, never>\n * // ▼\n * const program = Effect.transposeOption(some)\n *\n * Effect.runSync(program) // => Option.some(42)\n * ```\n *\n * @category converting\n * @since 3.13.0\n */\nexport const transposeOption = internal.transposeOption;\n/**\n * Converts a nullable value to an `Effect`, failing with a `NoSuchElementError`\n * when the value is `null` or `undefined`.\n *\n * **Example** (Failing on nullish values)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.fn(function*(input: string | null) {\n * const value = yield* Effect.fromNullishOr(input)\n * yield* Effect.sync(() => { output.push(value) })\n * },\n * Effect.catch(() => Effect.sync(() => { output.push(\"missing\") }))\n * )\n *\n * await Effect.runPromise(program(null))\n * await Effect.runPromise(program(\"hello\"))\n * output // => [\"missing\", \"hello\"]\n * ```\n *\n * @category converting\n * @since 4.0.0\n */\nexport const fromNullishOr = internal.fromNullishOr;\n// -----------------------------------------------------------------------------\n// Mapping\n// -----------------------------------------------------------------------------\n/**\n * Chains effects to produce new `Effect` instances, useful for combining\n * operations that depend on previous results.\n *\n * **When to use**\n *\n * Use when you need to chain multiple effects, ensuring that each\n * step produces a new `Effect` while flattening any nested effects that may\n * occur.\n *\n * **Details**\n *\n * `flatMap` lets you sequence effects so that the result of one effect can be\n * used in the next step. It is similar to `flatMap` used with arrays but works\n * specifically with `Effect` instances, allowing you to avoid deeply nested\n * effect structures.\n *\n * Since effects are immutable, `flatMap` always returns a new effect instead of\n * changing the original one.\n *\n * **Example** (Choosing flatMap syntax variants)\n *\n * ```ts import.meta.vitest\n * import { Effect, pipe } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const myEffect = Effect.succeed(1)\n * const transformation = (n: number) => Effect.succeed(n + 1)\n *\n * const flatMappedWithPipe = pipe(myEffect, Effect.flatMap(transformation))\n * const flatMappedWithDataFirst = Effect.flatMap(myEffect, transformation)\n * const flatMappedWithMethod = myEffect.pipe(Effect.flatMap(transformation))\n *\n * void output.push(Effect.runSync(Effect.all([\n * flatMappedWithPipe,\n * flatMappedWithDataFirst,\n * flatMappedWithMethod\n * ])))\n * output // => [[2, 2, 2]]\n * ```\n *\n * **Example** (Sequencing dependent effects)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect, pipe } from \"effect\"\n *\n * class DiscountRateError extends Data.TaggedError(\"DiscountRateError\")<{}> {}\n *\n * // Function to apply a discount safely to a transaction amount\n * const applyDiscount = (\n * total: number,\n * discountRate: number\n * ): Effect.Effect<number, DiscountRateError> =>\n * discountRate === 0\n * ? Effect.fail(new DiscountRateError())\n * : Effect.succeed(total - (total * discountRate) / 100)\n *\n * // Simulated asynchronous task to fetch a transaction amount from database\n * const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))\n *\n * // Chaining the fetch and discount application using `flatMap`\n * const finalAmount = pipe(\n * fetchTransactionAmount,\n * Effect.flatMap((amount) => applyDiscount(amount, 5))\n * )\n *\n * await Effect.runPromise(finalAmount) // => 95\n * ```\n *\n * @see {@link tap} for a version that ignores the result of the effect.\n * @category sequencing\n * @since 2.0.0\n */\nexport const flatMap = internal.flatMap;\n/**\n * Flattens an `Effect` that produces another `Effect` into a single effect.\n *\n * **Example** (Flattening nested effects)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const nested = Effect.succeed(Effect.succeed(\"hello\"))\n *\n * const program = Effect.gen(function*() {\n * const value = yield* Effect.flatten(nested)\n * yield* Effect.sync(() => { output.push(value) })\n * })\n *\n * Effect.runSync(program)\n * output // => [\"hello\"]\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const flatten = internal.flatten;\n/**\n * Runs this effect and then runs another effect, optionally using the first\n * effect's success value to choose the next effect.\n *\n * **When to use**\n *\n * Use when you need one effect to run after another and the second effect may\n * depend on the first effect's success value.\n *\n * **Details**\n *\n * When the second argument is an `Effect`, the first success value is discarded\n * and the returned effect produces the second effect's value. When the second\n * argument is a function, it receives the first success value and must return\n * the next `Effect`.\n *\n * Failures or requirements from either effect are preserved in the returned\n * effect.\n *\n * **Example** (Choosing andThen syntax variants)\n *\n * ```ts import.meta.vitest\n * import { Effect, pipe } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const myEffect = Effect.succeed(1)\n * const anotherEffect = Effect.succeed(\"done\")\n *\n * const transformedWithPipe = pipe(myEffect, Effect.andThen(anotherEffect))\n * const transformedWithDataFirst = Effect.andThen(myEffect, anotherEffect)\n * const transformedWithMethod = myEffect.pipe(Effect.andThen(anotherEffect))\n *\n * void output.push(Effect.runSync(Effect.all([\n * transformedWithPipe,\n * transformedWithDataFirst,\n * transformedWithMethod\n * ])))\n * output // => [['done', 'done', 'done']]\n * ```\n *\n * **Example** (Sequencing a discount calculation after fetching a total)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect, pipe } from \"effect\"\n *\n * class DiscountRateError extends Data.TaggedError(\"DiscountRateError\")<{}> {}\n *\n * // Function to apply a discount safely to a transaction amount\n * const applyDiscount = (\n * total: number,\n * discountRate: number\n * ): Effect.Effect<number, DiscountRateError> =>\n * discountRate === 0\n * ? Effect.fail(new DiscountRateError())\n * : Effect.succeed(total - (total * discountRate) / 100)\n *\n * // Simulated asynchronous task to fetch a transaction amount from database\n * const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))\n *\n * // Using Effect.map and Effect.flatMap\n * const result1 = pipe(\n * fetchTransactionAmount,\n * Effect.map((amount) => amount * 2),\n * Effect.flatMap((amount) => applyDiscount(amount, 5))\n * )\n *\n * await Effect.runPromise(result1) // => 190\n *\n * // Using Effect.andThen\n * const result2 = pipe(\n * fetchTransactionAmount,\n * Effect.andThen((amount) => Effect.succeed(amount * 2)),\n * Effect.andThen((amount) => applyDiscount(amount, 5))\n * )\n *\n * await Effect.runPromise(result2) // => 190\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const andThen = internal.andThen;\n/**\n * Runs a side effect with the result of an effect without changing the original\n * value.\n *\n * **When to use**\n *\n * Use when you need to run an effectful observation, such as logging or\n * tracking, while passing the original success value to the next step.\n *\n * **Details**\n *\n * `tap` works similarly to `flatMap`, but it ignores the result of the function\n * passed to it. The value from the previous effect remains available for the\n * next part of the chain. Note that if the side effect fails, the entire chain\n * will fail too.\n *\n * **Example** (Logging a step in a pipeline)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect, pipe } from \"effect\"\n * const output: Array<unknown> = []\n *\n * class DiscountRateError extends Data.TaggedError(\"DiscountRateError\")<{}> {}\n *\n * // Function to apply a discount safely to a transaction amount\n * const applyDiscount = (\n * total: number,\n * discountRate: number\n * ): Effect.Effect<number, DiscountRateError> =>\n * discountRate === 0\n * ? Effect.fail(new DiscountRateError())\n * : Effect.succeed(total - (total * discountRate) / 100)\n *\n * // Simulated asynchronous task to fetch a transaction amount from database\n * const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))\n *\n * const finalAmount = pipe(\n * fetchTransactionAmount,\n * // Log the fetched transaction amount\n * Effect.tap((amount) => Effect.sync(() => { output.push(`Apply a discount to: ${amount}`) })),\n * // `amount` is still available!\n * Effect.flatMap((amount) => applyDiscount(amount, 5))\n * )\n *\n * void output.push(await Effect.runPromise(finalAmount))\n * output // => [\"Apply a discount to: 100\", 95]\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const tap = internal.tap;\n/**\n * Converts both success and failure of an `Effect` into a `Result` type.\n *\n * **When to use**\n *\n * Use when you want an `Effect`'s typed failures to be handled as `Result`\n * data while preserving the original error value.\n *\n * **Details**\n *\n * This function converts an effect that may fail into an effect that always\n * succeeds, wrapping the outcome in a `Result` type. The result will be\n * `Result.Failure` if the effect fails, containing the recoverable error, or\n * `Result.Success` if it succeeds, containing the result.\n *\n * Using this function, you can handle recoverable errors explicitly without\n * causing the effect to fail. This is particularly useful in scenarios where\n * you want to chain effects and manage both success and failure in the same\n * logical flow.\n *\n * The resulting effect cannot fail directly because all recoverable failures\n * are represented inside the `Result` type.\n *\n * **Gotchas**\n *\n * `result` only captures typed, recoverable failures. Defects and\n * interruptions are not captured inside the `Result` and still fail the\n * effect.\n *\n * **Example** (Capturing success or failure as Result)\n *\n * ```ts import.meta.vitest\n * import { Effect, Result } from \"effect\"\n *\n * const success = Effect.succeed(42)\n * const failure = Effect.fail(\"Something went wrong\")\n *\n * const program1 = Effect.result(success)\n * const program2 = Effect.result(failure)\n *\n * Effect.runSync(program1) // => Result.succeed(42)\n *\n * Effect.runSync(program2) // => Result.fail(\"Something went wrong\")\n * ```\n *\n * @see {@link option} for a version that uses `Option` instead.\n * @see {@link exit} for a version that encapsulates both recoverable errors and defects in an `Exit`.\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const result = internal.result;\n/**\n * Converts success to `Option.some` and failure to `Option.none`.\n *\n * **When to use**\n *\n * Use when you only care whether an effect succeeds and want recoverable\n * failures represented as `Option.none`.\n *\n * **Details**\n *\n * Success values become `Option.some`, recoverable failures become\n * `Option.none`, and defects still fail the effect.\n *\n * **Gotchas**\n *\n * `option` only captures typed, recoverable failures as `Option.none`.\n * Defects and interruptions are not captured inside the `Option` and still\n * fail the effect.\n *\n * `option` also discards typed failure values. Use `result` if the failure\n * value matters.\n *\n * **Example** (Capturing success or failure as Option)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option } from \"effect\"\n *\n * const program = Effect.all([\n * Effect.option(Effect.succeed(1)),\n * Effect.option(Effect.fail(\"missing\"))\n * ])\n *\n * Effect.runSync(program) // => [Option.some(1), Option.none()]\n * ```\n *\n * @see {@link result} for a version that uses `Result` instead.\n * @see {@link exit} for a version that encapsulates both recoverable errors and defects in an `Exit`.\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const option = internal.option;\n/**\n * Transforms an effect to encapsulate both failure and success using the `Exit`\n * data type.\n *\n * **When to use**\n *\n * Use when you need to inspect the full outcome, including typed failures, defects,\n * and interruptions.\n *\n * **Details**\n *\n * `exit` wraps an effect's success or failure inside an `Exit` type, allowing\n * you to handle both cases explicitly.\n *\n * The resulting effect cannot fail because the failure is encapsulated within\n * the `Exit.Failure` type. The error type is set to `never`, indicating that\n * the effect is structured to never fail directly.\n *\n * **Example** (Capturing completion as Exit)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit } from \"effect\"\n *\n * const success = Effect.succeed(42)\n * const failure = Effect.fail(\"Something went wrong\")\n *\n * const program1 = Effect.exit(success)\n * const program2 = Effect.exit(failure)\n *\n * Effect.runSync(program1) // => Exit.succeed(42)\n *\n * Effect.runSync(program2) // => Exit.fail(\"Something went wrong\")\n * ```\n *\n * @see {@link option} for a version that uses `Option` instead.\n * @see {@link result} for a version that uses `Result` instead.\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const exit = internal.exit;\n/**\n * Transforms the value inside an effect by applying a function to it.\n *\n * **When to use**\n *\n * Use to transform an effect's success value with a function that returns a\n * plain value, producing a new effect without changing the original effect's\n * typed error or context requirements.\n *\n * **Details**\n *\n * `map` takes a function and applies it to the value contained within an\n * effect, creating a new effect with the transformed value.\n *\n * It's important to note that effects are immutable, meaning that the original\n * effect is not modified. Instead, a new effect is returned with the updated\n * value.\n *\n * **Example** (Choosing map syntax variants)\n *\n * ```ts import.meta.vitest\n * import { Effect, pipe } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const myEffect = Effect.succeed(1)\n * const transformation = (n: number) => n + 1\n *\n * const mappedWithPipe = pipe(myEffect, Effect.map(transformation))\n * const mappedWithDataFirst = Effect.map(myEffect, transformation)\n * const mappedWithMethod = myEffect.pipe(Effect.map(transformation))\n *\n * void output.push(Effect.runSync(Effect.all([\n * mappedWithPipe,\n * mappedWithDataFirst,\n * mappedWithMethod\n * ])))\n * output // => [[2, 2, 2]]\n * ```\n *\n * **Example** (Adding a service charge)\n *\n * ```ts import.meta.vitest\n * import { Effect, pipe } from \"effect\"\n *\n * const addServiceCharge = (amount: number) => amount + 1\n *\n * const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))\n *\n * const finalAmount = pipe(\n * fetchTransactionAmount,\n * Effect.map(addServiceCharge)\n * )\n *\n * await Effect.runPromise(finalAmount) // => 101\n * ```\n *\n * @see {@link mapError} for a version that operates on the error channel.\n * @see {@link mapBoth} for a version that operates on both channels.\n * @see {@link flatMap} or {@link andThen} for a version that can return a new effect.\n * @category mapping\n * @since 2.0.0\n */\nexport const map = internal.map;\n/**\n * Replaces the value inside an effect with a constant value.\n *\n * **When to use**\n *\n * Use to replace a successful value with a constant while preserving failures\n * and requirements.\n *\n * **Details**\n *\n * `as` allows you to ignore the original value inside an effect and\n * replace it with a new constant value.\n *\n * **Example** (Replacing a success value)\n *\n * ```ts import.meta.vitest\n * import { Effect, pipe } from \"effect\"\n *\n * // Replaces the value 5 with the constant \"new value\"\n * const program = pipe(Effect.succeed(5), Effect.as(\"new value\"))\n *\n * Effect.runSync(program) // => \"new value\"\n * ```\n *\n * @see {@link map} for deriving the replacement value from the success value\n * @see {@link asVoid} for replacing the success value with `void`\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const as = internal.as;\n/**\n * Maps the success value of an `Effect` to `Some`, preserving failures.\n *\n * **Example** (Wrapping success in Option.some)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option } from \"effect\"\n *\n * const program = Effect.asSome(Effect.succeed(42))\n *\n * Effect.runSync(program) // => Option.some(42)\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const asSome = internal.asSome;\n/**\n * Maps the success value of an `Effect` to `void`, preserving failures.\n *\n * **Example** (Discarding success values)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const program = Effect.asVoid(Effect.succeed(42))\n *\n * Effect.runSync(program) // => undefined\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const asVoid = internal.asVoid;\n/**\n * Swaps an effect's success and failure channels.\n *\n * **When to use**\n *\n * Use to swap an `Effect`'s success and failure channels.\n *\n * **Details**\n *\n * For an `Effect<A, E, R>`, the returned effect has type `Effect<E, A, R>`.\n *\n * **Example** (Swapping success and failure channels)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * // ┌─── Effect<number, string, never>\n * // ▼\n * const program = Effect.fail(\"Oh uh!\").pipe(Effect.as(2))\n *\n * // ┌─── Effect<string, number, never>\n * // ▼\n * const flipped = Effect.flip(program)\n * Effect.runSync(flipped) // => \"Oh uh!\"\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const flip = internal.flip;\n// -----------------------------------------------------------------------------\n// Zipping\n// -----------------------------------------------------------------------------\n/**\n * Combines two effects into a single effect, producing a tuple with the results of both effects.\n *\n * **When to use**\n *\n * Use to combine exactly two effects into a tuple.\n *\n * **Details**\n *\n * The `zip` function executes the first effect (left) and then the second effect (right).\n * Once both effects succeed, their results are combined into a tuple.\n *\n * Concurrency:\n *\n * By default, `zip` processes the effects sequentially. To execute the effects concurrently,\n * use the `{ concurrent: true }` option.\n *\n * **Example** (Combining two effects sequentially)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const task1 = Effect.succeed(1)\n * const task2 = Effect.succeed(\"hello\")\n *\n * // Combine the two effects together\n * //\n * // ┌─── Effect<[number, string], never, never>\n * // ▼\n * const program = Effect.zip(task1, task2)\n *\n * Effect.runSync(program) // => [1, 'hello']\n * ```\n *\n * **Example** (Combining two effects concurrently)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const task1 = Effect.succeed(1)\n * const task2 = Effect.succeed(\"hello\")\n *\n * // Run both effects concurrently using the concurrent option\n * const program = Effect.zip(task1, task2, { concurrent: true })\n *\n * await Effect.runPromise(program) // => [1, 'hello']\n * ```\n *\n * @see {@link zipWith} for a version that combines the results with a custom function.\n * @see {@link all} for collecting a larger structure of effects.\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zip = internal.zip;\n/**\n * Combines two effects sequentially and applies a function to their results to\n * produce a single value.\n *\n * **When to use**\n *\n * Use when you need to run two effects sequentially and combine their results\n * with a function instead of keeping the results as a tuple.\n *\n * **Details**\n *\n * Concurrency:\n *\n * By default, the effects are run sequentially. To execute them concurrently,\n * use the `{ concurrent: true }` option.\n *\n * **Example** (Combining two success values with a function)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const task1 = Effect.succeed(1)\n * const task2 = Effect.succeed(\"hello\")\n *\n * const task3 = Effect.zipWith(\n * task1,\n * task2,\n * // Combines results into a single value\n * (number, string) => number + string.length\n * )\n *\n * Effect.runSync(task3) // => 6\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipWith = internal.zipWith;\n// -----------------------------------------------------------------------------\n// Error handling\n// -----------------------------------------------------------------------------\nconst catch_ = internal.catch_;\nexport {\n/**\n * Handles all errors in an effect by providing a fallback effect.\n *\n * **When to use**\n *\n * Use when every recoverable error from an effect should be handled by the same\n * fallback function while unrecoverable defects remain defects.\n *\n * **Details**\n *\n * The `catch` function catches any errors that may occur during the\n * execution of an effect and allows you to handle them by specifying a fallback\n * effect. This ensures that the program continues without failing by recovering\n * from errors using the provided fallback logic.\n *\n * **Gotchas**\n *\n * `catch` only handles recoverable errors. It will not recover from\n * unrecoverable defects.\n *\n * @see {@link catchCause} for a version that can recover from both recoverable and unrecoverable errors.\n *\n * @category error handling\n * @since 4.0.0\n */\ncatch_ as catch };\n/**\n * Catches and handles specific errors by their `_tag` field, which is used as a\n * discriminator.\n *\n * **When to use**\n *\n * Use when you need to recover from one specific tagged error in an effect\n * error channel.\n *\n * **Details**\n *\n * The error type must have a readonly `_tag` field. `catchTag` matches that\n * field and only handles errors with the requested tag.\n *\n * **Example** (Handling a tagged error)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * class NetworkError {\n * readonly _tag = \"NetworkError\"\n * constructor(readonly message: string) {}\n * }\n *\n * class ValidationError {\n * readonly _tag = \"ValidationError\"\n * constructor(readonly message: string) {}\n * }\n *\n * const task: Effect.Effect<string, NetworkError | ValidationError> =\n * Effect.fail(new NetworkError(\"offline\"))\n *\n * const program = Effect.catchTag(\n * task,\n * \"NetworkError\",\n * (error) => Effect.succeed(`Recovered from network error: ${error.message}`)\n * )\n *\n * Effect.runSync(program) // => \"Recovered from network error: offline\"\n * ```\n *\n * @see {@link catchTags} for handling multiple tagged errors in one call\n * @see {@link catchIf} for recovering from errors that match a predicate\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const catchTag = internal.catchTag;\n/**\n * Handles multiple errors in a single block of code using their `_tag` field.\n *\n * **When to use**\n *\n * Use when one recovery step should handle several tagged error types by\n * matching their readonly `_tag` fields.\n *\n * **Details**\n *\n * Pass a handler table whose keys are tags, plus an optional fallback for\n * unmatched errors.\n *\n * The error type must have a readonly `_tag` field to use `catchTags`. This\n * field is used to identify and match errors.\n *\n * **Example** (Handling multiple tagged errors)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect } from \"effect\"\n *\n * // Define tagged error types\n * class ValidationError extends Data.TaggedError(\"ValidationError\")<{\n * message: string\n * }> {}\n *\n * class NetworkError extends Data.TaggedError(\"NetworkError\")<{\n * statusCode: number\n * }> {}\n *\n * // An effect that might fail with multiple error types\n * const program: Effect.Effect<string, ValidationError | NetworkError> =\n * Effect.fail(new NetworkError({ statusCode: 503 }))\n *\n * // Handle multiple error types at once\n * const handled = Effect.catchTags(program, {\n * ValidationError: (error) =>\n * Effect.succeed(`Validation failed: ${error.message}`),\n * NetworkError: (error) => Effect.succeed(`Network error: ${error.statusCode}`)\n * })\n *\n * Effect.runSync(handled) // => \"Network error: 503\"\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const catchTags = internal.catchTags;\n/**\n * Catches a specific reason within a tagged error.\n *\n * **When to use**\n *\n * Use to handle one nested reason inside an `Effect`'s tagged error while\n * preserving the parent error shape for unmatched reasons.\n *\n * **Details**\n *\n * Use this to handle nested error causes without removing the parent error\n * from the error channel. The handler receives the unwrapped reason.\n *\n * **Example** (Handling an error reason)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect } from \"effect\"\n *\n * class RateLimitError extends Data.TaggedError(\"RateLimitError\")<{\n * retryAfter: number\n * }> {}\n *\n * class QuotaExceededError extends Data.TaggedError(\"QuotaExceededError\")<{\n * limit: number\n * }> {}\n *\n * class AiError extends Data.TaggedError(\"AiError\")<{\n * reason: RateLimitError | QuotaExceededError\n * }> {}\n *\n * const program: Effect.Effect<string, AiError> = Effect.fail(\n * new AiError({ reason: new RateLimitError({ retryAfter: 30 }) })\n * )\n *\n * // Handle rate limits specifically\n * const handled = program.pipe(\n * Effect.catchReason(\"AiError\", \"RateLimitError\", (reason) =>\n * Effect.succeed(`Retry after ${reason.retryAfter}s`)\n * )\n * )\n *\n * Effect.runSync(handled) // => \"Retry after 30s\"\n * ```\n *\n * @see {@link catchReasons} for handling several nested reason tags\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchReason = internal.catchReason;\n/**\n * Catches multiple reasons within a tagged error using an object of handlers.\n *\n * **Example** (Handling multiple error reasons)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect } from \"effect\"\n *\n * class RateLimitError extends Data.TaggedError(\"RateLimitError\")<{\n * retryAfter: number\n * }> {}\n *\n * class QuotaExceededError extends Data.TaggedError(\"QuotaExceededError\")<{\n * limit: number\n * }> {}\n *\n * class AiError extends Data.TaggedError(\"AiError\")<{\n * reason: RateLimitError | QuotaExceededError\n * }> {}\n *\n * const program: Effect.Effect<string, AiError> = Effect.fail(\n * new AiError({ reason: new QuotaExceededError({ limit: 100 }) })\n * )\n *\n * const handled = program.pipe(\n * Effect.catchReasons(\"AiError\", {\n * RateLimitError: (reason) =>\n * Effect.succeed(`Retry after ${reason.retryAfter}s`),\n * QuotaExceededError: (reason) =>\n * Effect.succeed(`Quota exceeded: ${reason.limit}`)\n * })\n * )\n *\n * Effect.runSync(handled) // => \"Quota exceeded: 100\"\n * ```\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchReasons = internal.catchReasons;\n/**\n * Promotes nested reason errors into the Effect error channel, replacing\n * the parent error.\n *\n * **Example** (Extracting the reason from a tagged error)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect } from \"effect\"\n *\n * class RateLimitError extends Data.TaggedError(\"RateLimitError\")<{\n * retryAfter: number\n * }> {}\n *\n * class QuotaExceededError extends Data.TaggedError(\"QuotaExceededError\")<{\n * limit: number\n * }> {}\n *\n * class AiError extends Data.TaggedError(\"AiError\")<{\n * reason: RateLimitError | QuotaExceededError\n * }> {}\n *\n * const program: Effect.Effect<string, AiError> = Effect.fail(\n * new AiError({ reason: new RateLimitError({ retryAfter: 30 }) })\n * )\n *\n * // Before: Effect<string, AiError>\n * // After: Effect<string, RateLimitError | QuotaExceededError>\n * const unwrapped = program.pipe(Effect.unwrapReason(\"AiError\"))\n * Effect.runSync(Effect.flip(unwrapped))._tag // => \"RateLimitError\"\n * ```\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const unwrapReason = internal.unwrapReason;\n/**\n * Handles both recoverable and unrecoverable errors by providing a recovery\n * effect.\n *\n * **When to use**\n *\n * Use when you need to recover from an `Effect` by inspecting the full `Cause`,\n * including recoverable failures, defects, and interruptions, instead of only\n * the typed error value.\n *\n * **Details**\n *\n * When to Recover from Defects:\n *\n * Defects are unexpected errors that typically shouldn't be recovered from, as\n * they often indicate serious issues. However, in some cases, such as\n * dynamically loaded plugins, controlled recovery might be needed.\n *\n * **Example** (Recovering from full failure causes)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * // An effect that might fail in different ways\n * const program = Effect.die(\"Something went wrong\")\n *\n * // Recover from any cause (including defects)\n * const recovered = Effect.catchCause(program, (cause) => {\n * if (Cause.hasDies(cause)) {\n * return Effect.sync(() => { output.push(\"Caught defect\") }).pipe(\n * Effect.as(\"Recovered from defect\")\n * )\n * }\n * return Effect.succeed(\"Unknown error\")\n * })\n *\n * void output.push(Effect.runSync(recovered))\n * output // => [\"Caught defect\", \"Recovered from defect\"]\n * ```\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchCause = internal.catchCause;\n/**\n * Recovers from defects using a provided recovery function.\n *\n * **When to use**\n *\n * Use when you need to report or translate defects at integration boundaries.\n *\n * **Details**\n *\n * `catchDefect` handles unexpected defects, such as thrown exceptions or\n * values passed to `die`, without catching typed failures or interruptions.\n *\n * When to Recover from Defects:\n *\n * Defects are unexpected errors that typically should not be recovered from, as\n * they often indicate serious issues. In some cases, such as dynamically loaded\n * plugins, controlled recovery may be needed.\n *\n * **Example** (Recovering from defects)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * // An effect that might throw an unexpected error (defect)\n * const program = Effect.sync(() => {\n * throw new Error(\"Unexpected error\")\n * })\n *\n * // Recover from defects only\n * const recovered = Effect.catchDefect(program, (defect) => {\n * return Effect.sync(() => { output.push(`Caught defect: ${(defect as Error).message}`) }).pipe(\n * Effect.as(\"Recovered from defect\")\n * )\n * })\n *\n * void output.push(Effect.runSync(recovered))\n * output // => [\"Caught defect: Unexpected error\", \"Recovered from defect\"]\n * ```\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchDefect = internal.catchDefect;\n/**\n * Recovers from specific errors using a `Predicate` or `Refinement`.\n *\n * **When to use**\n *\n * Use when you need to recover from errors that match a condition.\n *\n * **Details**\n *\n * Use a `Refinement` for type narrowing or a `Predicate` for simple boolean\n * matching. Non-matching errors re-fail with the original cause. Defects and\n * interrupts are not caught.\n *\n * **Example** (Recovering when a predicate matches)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect, Filter } from \"effect\"\n *\n * class NotFound extends Data.TaggedError(\"NotFound\")<{ id: string }> {}\n *\n * const program = Effect.fail(new NotFound({ id: \"user-1\" }))\n *\n * // With a refinement\n * const recovered = program.pipe(\n * Effect.catchIf(\n * (error): error is NotFound => error._tag === \"NotFound\",\n * (error) => Effect.succeed(`missing:${error.id}`)\n * )\n * )\n *\n * // With a Filter\n * const recovered2 = program.pipe(\n * Effect.catchFilter(\n * Filter.tagged(\"NotFound\"),\n * (error) => Effect.succeed(`missing:${error.id}`)\n * )\n * )\n *\n * Effect.runSync(Effect.all([recovered, recovered2])) // => ['missing:user-1', 'missing:user-1']\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const catchIf = internal.catchIf;\n/**\n * Recovers from specific errors using a `Filter`.\n *\n * **When to use**\n *\n * Use to recover from typed `Effect` errors with a reusable `Filter` when\n * matching can also narrow or transform the error before choosing the recovery\n * effect.\n *\n * **Details**\n *\n * The filter runs on typed failures extracted from the `Cause`. Successful\n * filter results are passed to `f`; failed filter results are passed to\n * `orElse` when provided. Without `orElse`, the original failure cause is\n * preserved.\n *\n * @see {@link catchIf} for predicate-based recovery from typed errors\n * @see {@link catchTag} for recovering from a single tagged error\n * @see {@link catchTags} for recovering from several tagged errors\n * @see {@link catchCauseFilter} for filtering full causes instead of typed errors\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchFilter = internal.catchFilter;\n/**\n * Catches `NoSuchElementError` failures and converts them to `Option.none`.\n *\n * **When to use**\n *\n * Use when you expect missing-value failures and want them to become an\n * optional success while all other failures keep failing.\n *\n * **Details**\n *\n * Success values become `Option.some`, `NoSuchElementError` becomes\n * `Option.none`, and all other errors are preserved.\n *\n * **Example** (Recovering from missing Option values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const some = Effect.fromNullishOr(1).pipe(Effect.catchNoSuchElement)\n * const none = Effect.fromNullishOr(null).pipe(Effect.catchNoSuchElement)\n *\n * void output.push(Effect.runSync(some))\n * void output.push(Effect.runSync(none))\n * output // => [Option.some(1), Option.none()]\n * ```\n *\n * @see {@link fromOption} for converting `Option.none` into `NoSuchElementError`\n * @see {@link fromNullishOr} for converting nullish values into `NoSuchElementError`\n * @see {@link option} for converting any failure into `Option.none`\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchNoSuchElement = internal.catchNoSuchElement;\n/**\n * Recovers from specific failures based on a predicate.\n *\n * **When to use**\n *\n * Use to recover an `Effect` from full causes selected by a predicate.\n *\n * **Details**\n *\n * This function allows you to conditionally catch and recover from failures\n * that match a specific predicate. This is useful when you want to handle\n * only certain types of errors while letting others propagate.\n *\n * **Example** (Recovering from selected causes)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const httpRequest = Effect.fail(\"Network Error\")\n *\n * // Only catch network-related failures\n * const program = Effect.catchCauseIf(\n * httpRequest,\n * Cause.hasFails,\n * (cause) =>\n * Effect.gen(function*() {\n * yield* Effect.sync(() => { output.push(`Caught network error: ${Cause.squash(cause)}`) })\n * return \"Fallback response\"\n * })\n * )\n *\n * void output.push(Effect.runSync(program))\n * output // => [\"Caught network error: Network Error\", \"Fallback response\"]\n * ```\n *\n * @see {@link catchCause} for recovering from every cause\n * @see {@link catchCauseFilter} for selecting full causes with a `Filter`\n * @see {@link catchIf} for predicate-based recovery from typed errors\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchCauseIf = internal.catchCauseIf;\n/**\n * Recovers from specific failures based on a `Filter`.\n *\n * **When to use**\n *\n * Use when you need to recover an `Effect` only from causes selected by a\n * `Filter`, while giving the recovery both the selected value and the original\n * `Cause`.\n *\n * **Details**\n *\n * The filter is applied to the full `Cause`. When it succeeds, the handler\n * receives the selected value and the original cause. When it fails, the effect\n * re-fails with the residual cause returned by the filter.\n *\n * @see {@link catchCauseIf} for predicate-based cause selection\n * @see {@link catchFilter} for filtering typed error values instead of full causes\n * @see {@link catchCause} for recovering from every cause without filtering\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchCauseFilter = internal.catchCauseFilter;\n/**\n * Transforms the failure value of an effect without changing its success value.\n *\n * **When to use**\n *\n * Use to translate an `Effect`'s typed failures while leaving successful values\n * unchanged.\n *\n * **Details**\n *\n * Only the failure channel is transformed. The success channel and requirements\n * are preserved.\n *\n * **Example** (Transforming the error channel)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect } from \"effect\"\n *\n * class TaskError extends Data.TaggedError(\"TaskError\")<{ readonly message: string }> {}\n *\n * // ┌─── Effect<number, string, never>\n * // ▼\n * const simulatedTask = Effect.fail(\"Oh no!\").pipe(Effect.as(1))\n *\n * // ┌─── Effect<number, TaskError, never>\n * // ▼\n * const mapped = Effect.mapError(\n * simulatedTask,\n * (message) => new TaskError({ message })\n * )\n * Effect.runSync(Effect.flip(mapped)).message // => \"Oh no!\"\n * ```\n *\n * @see {@link map} for a version that operates on the success channel.\n * @see {@link mapBoth} for a version that operates on both channels.\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const mapError = internal.mapError;\n/**\n * Applies transformations to both the success and error channels of an effect.\n *\n * **When to use**\n *\n * Use to transform both success and failure channels of an `Effect` without\n * changing whether it succeeds or fails.\n *\n * **Details**\n *\n * This function takes two map functions as arguments: one for the error channel\n * and one for the success channel. You can use it when you want to modify both\n * the error and the success values without altering the overall success or\n * failure status of the effect.\n *\n * **Example** (Transforming success and failure channels)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect } from \"effect\"\n *\n * class TaskError extends Data.TaggedError(\"TaskError\")<{ readonly message: string }> {}\n *\n * // ┌─── Effect<number, string, never>\n * // ▼\n * const simulatedTask = Effect.fail(\"Oh no!\").pipe(Effect.as(1))\n *\n * // ┌─── Effect<boolean, TaskError, never>\n * // ▼\n * const modified = Effect.mapBoth(simulatedTask, {\n * onFailure: (message) => new TaskError({ message }),\n * onSuccess: (n) => n > 0\n * })\n * Effect.runSync(Effect.flip(modified)).message // => \"Oh no!\"\n * ```\n *\n * @see {@link map} for a version that operates on the success channel.\n * @see {@link mapError} for a version that operates on the error channel.\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const mapBoth = internal.mapBoth;\n/**\n * Converts typed failures from the error channel into defects, removing the\n * error type from the returned effect.\n *\n * **When to use**\n *\n * Use when you need to turn an `Effect` typed failure that represents an\n * unrecoverable bug or invalid state into a defect.\n *\n * **Example** (Converting typed failures into defects)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect, Exit } from \"effect\"\n *\n * class DivideByZeroError extends Data.TaggedError(\"DivideByZeroError\")<{}> {}\n *\n * const divide = (a: number, b: number) =>\n * b === 0\n * ? Effect.fail(new DivideByZeroError())\n * : Effect.succeed(a / b)\n *\n * // ┌─── Effect<number, never, never>\n * // ▼\n * const program = Effect.orDie(divide(1, 0))\n *\n * Effect.runSyncExit(program) // => Exit.die(new DivideByZeroError())\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const orDie = internal.orDie;\n/**\n * Runs an effectful operation when the source effect fails, while preserving\n * the original failure when the operation succeeds.\n *\n * **Details**\n *\n * Use this for logging, metrics, or other failure-side observations. If the\n * operation passed to `tapError` fails, that error is also represented in the\n * returned effect's error channel.\n *\n * **Example** (Running effects on failure)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit } from \"effect\"\n * const output: Array<unknown> = []\n *\n * // Simulate a task that fails with an error\n * const task: Effect.Effect<number, string> = Effect.fail(\"NetworkError\")\n *\n * // Use tapError to log the error message when the task fails\n * const tapping = Effect.tapError(\n * task,\n * (error) => Effect.sync(() => { output.push(`expected error: ${error}`) })\n * )\n *\n * void output.push(Effect.runSyncExit(tapping))\n * output // => [\"expected error: NetworkError\", Exit.fail(\"NetworkError\")]\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const tapError = internal.tapError;\n/**\n * Runs an effectful handler when a failure's `_tag` matches.\n *\n * **Details**\n *\n * Use this with tagged-union errors to perform side effects for one tag or a\n * list of tags. When the handler succeeds, the original failure is preserved;\n * if the handler fails, its error is also included in the returned effect.\n *\n * **Example** (Running effects for tagged failures)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect, Exit } from \"effect\"\n * const output: Array<unknown> = []\n *\n * class NetworkError extends Data.TaggedError(\"NetworkError\")<{\n * statusCode: number\n * }> {}\n *\n * class ValidationError extends Data.TaggedError(\"ValidationError\")<{\n * field: string\n * }> {}\n *\n * const task: Effect.Effect<number, NetworkError | ValidationError> =\n * Effect.fail(new NetworkError({ statusCode: 504 }))\n *\n * const program = Effect.tapErrorTag(task, \"NetworkError\", (error) =>\n * Effect.sync(() => { output.push(`expected error: ${error.statusCode}`) })\n * )\n *\n * void output.push(Effect.runSyncExit(program))\n * output // => [\"expected error: 504\", Exit.fail(new NetworkError({ statusCode: 504 }))]\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const tapErrorTag = internal.tapErrorTag;\n/**\n * Runs an effectful operation with the full `Cause` when the source effect\n * fails.\n *\n * **When to use**\n *\n * Use when failure observation needs typed failures, defects, and interruptions\n * rather than only the typed error value.\n *\n * **Details**\n *\n * Use this to log or inspect typed failures, defects, and interruptions. When\n * the operation succeeds, the original cause is preserved. If the operation\n * fails, its error is also represented in the returned effect.\n *\n * **Example** (Observing full failure causes)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Exit } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const task = Effect.fail(\"Something went wrong\")\n *\n * const program = Effect.tapCause(\n * task,\n * (cause) => Effect.sync(() => { output.push(`Logging cause: ${Cause.squash(cause)}`) })\n * )\n *\n * void output.push(Effect.runSyncExit(program))\n * output // => [\"Logging cause: Something went wrong\", Exit.fail(\"Something went wrong\")]\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const tapCause = internal.tapCause;\n/**\n * Executes a side effect conditionally when a failed effect's cause matches a predicate.\n *\n * **Details**\n *\n * This function allows you to tap into the cause of an effect's failure only when\n * the cause matches a specific predicate. This is useful for conditional logging,\n * monitoring, or other side effects based on the type of failure.\n *\n * **Example** (Observing selected failure causes)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Exit } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const task = Effect.fail(\"Network timeout\")\n *\n * // Only log causes that contain failures (not interrupts or defects)\n * const program = Effect.tapCauseIf(\n * task,\n * Cause.hasFails,\n * (cause) => Effect.sync(() => { output.push(`Logging failure cause: ${Cause.squash(cause)}`) })\n * )\n *\n * void output.push(Effect.runSyncExit(program))\n * output // => [\"Logging failure cause: Network timeout\", Exit.fail(\"Network timeout\")]\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const tapCauseIf = internal.tapCauseIf;\n/**\n * Executes a side effect conditionally when a failed effect's cause passes a filter.\n *\n * **When to use**\n *\n * Use when you need to observe only failure causes selected by a `Filter`,\n * while giving the side effect both the selected value and the original\n * `Cause`.\n *\n * **Details**\n *\n * A successful filter result runs the side effect with the selected value and\n * original cause. A failed filter result skips the side effect and preserves the\n * original cause.\n *\n * @see {@link tapCauseIf} for selecting causes with a boolean predicate\n * @see {@link tapCause} for observing every failure cause\n * @see {@link catchCauseFilter} for recovering from selected causes instead of only observing them\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const tapCauseFilter = internal.tapCauseFilter;\n/**\n * Runs an effectful operation when the source effect dies with a defect.\n *\n * **Details**\n *\n * Use this for diagnostics such as logging unexpected thrown exceptions or\n * values passed to `die`. Recoverable failures are not handled. When the\n * operation succeeds, the original defect is preserved; if the operation fails,\n * its error is also represented in the returned effect.\n *\n * **Example** (Observing defects)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit } from \"effect\"\n * const output: Array<unknown> = []\n *\n * // Simulate a severe failure in the system\n * const task2: Effect.Effect<number> = Effect.die(\n * \"Something went wrong\"\n * )\n *\n * // Log the defect using tapDefect\n * const tapping2 = Effect.tapDefect(\n * task2,\n * (defect) => Effect.sync(() => { output.push(`defect: ${defect}`) })\n * )\n *\n * void output.push(Effect.runSyncExit(tapping2))\n * output // => [\"defect: Something went wrong\", Exit.die(\"Something went wrong\")]\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const tapDefect = internal.tapDefect;\n/**\n * Retries an effect until it succeeds, discarding failures.\n *\n * **Details**\n *\n * Yields between attempts so other fibers can run.\n *\n * **Example** (Retrying until success)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * let attempts = 0\n *\n * const flaky = Effect.gen(function*() {\n * attempts++\n * yield* Effect.sync(() => { output.push(`Attempt ${attempts}`) })\n * if (attempts < 3) {\n * return yield* Effect.fail(\"Not ready\")\n * }\n * return \"Ready\"\n * })\n *\n * const program = Effect.eventually(flaky)\n *\n * void output.push(await Effect.runPromise(program))\n * output // => [\"Attempt 1\", \"Attempt 2\", \"Attempt 3\", \"Ready\"]\n * ```\n *\n * @category repetition\n * @since 2.0.0\n */\nexport const eventually = internal.eventually;\n/**\n * Retries typed failures from an effect according to a retry policy.\n *\n * **When to use**\n *\n * Use when you need to rerun an effect after transient typed failures, such as\n * network issues or temporary resource unavailability.\n *\n * **Details**\n *\n * The policy can be a `Schedule`, a schedule builder, or a `Retry.Options`\n * object using `schedule`, `times`, `while`, or `until`. If a retry eventually\n * succeeds, the returned effect succeeds with that value. If the policy stops\n * while the effect is still failing, the last failure is propagated.\n *\n * **Gotchas**\n *\n * The source effect is always evaluated once before any retry policy is\n * applied. For example, `Schedule.recurs(3)` allows up to three retries after\n * the initial attempt.\n *\n * Defects and interruptions are not retried.\n *\n * **Example** (Retrying with a schedule)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect, Schedule } from \"effect\"\n *\n * class AttemptError extends Data.TaggedError(\"AttemptError\")<{ readonly attempt: number }> {}\n *\n * let attempt = 0\n * const task = Effect.callback<string, AttemptError>((resume) => {\n * attempt++\n * if (attempt <= 2) {\n * resume(Effect.fail(new AttemptError({ attempt })))\n * } else {\n * resume(Effect.succeed(\"Success!\"))\n * }\n * })\n *\n * const policy = Schedule.recurs(5)\n * const program = Effect.retry(task, policy)\n *\n * await Effect.runPromise(program) // => \"Success!\"\n * ```\n *\n * @see {@link retryOrElse} for a version that allows you to run a fallback.\n * @see {@link repeat} if your retry condition is based on successful outcomes rather than errors.\n * @category error handling\n * @since 2.0.0\n */\nexport const retry = internalSchedule.retry;\n/**\n * Retries a failing effect and runs a fallback effect if retries are exhausted.\n *\n * **When to use**\n *\n * Use when you want to handle failures gracefully by specifying an alternative\n * action after repeated failures.\n *\n * **Details**\n *\n * The `Effect.retryOrElse` function attempts to retry a failing effect multiple\n * times according to a defined {@link Schedule} policy.\n *\n * If the retries are exhausted and the effect still fails, it runs a fallback\n * effect instead.\n *\n * **Example** (Falling back after retries are exhausted)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect, Schedule } from \"effect\"\n * const output: Array<unknown> = []\n *\n * class NetworkTimeoutError extends Data.TaggedError(\"NetworkTimeoutError\")<{}> {}\n *\n * let attempt = 0\n * const networkRequest = Effect.gen(function*() {\n * attempt++\n * yield* Effect.sync(() => { output.push(`Network attempt ${attempt}`) })\n * if (attempt < 3) {\n * return yield* Effect.fail(new NetworkTimeoutError())\n * }\n * return \"Network data\"\n * })\n *\n * // Retry up to 2 times, then fall back to cached data\n * const program = Effect.retryOrElse(\n * networkRequest,\n * Schedule.recurs(2),\n * (error, retryCount) =>\n * Effect.gen(function*() {\n * yield* Effect.sync(() => { output.push(`All ${retryCount} retries failed, using cache`) })\n * return \"Cached data\"\n * })\n * )\n *\n * void output.push(await Effect.runPromise(program))\n * output // => [\"Network attempt 1\", \"Network attempt 2\", \"Network attempt 3\", \"Network data\"]\n * ```\n *\n * @see {@link retry} for a version that does not run a fallback effect.\n * @category error handling\n * @since 2.0.0\n */\nexport const retryOrElse = internalSchedule.retryOrElse;\n/**\n * Exposes an effect's full failure cause in the error channel as `Cause<E>`.\n *\n * **Details**\n *\n * Use `sandbox` when downstream error handling needs to distinguish typed\n * failures, defects, and interruptions. Use `unsandbox` to restore the original\n * typed error channel after cause-level handling.\n *\n * **Example** (Exposing failures as causes)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect } from \"effect\"\n *\n * const task = Effect.fail(\"Something went wrong\")\n *\n * // Sandbox exposes the full cause as the error type\n * const program = Effect.gen(function*() {\n * const result = yield* Effect.flip(Effect.sandbox(task))\n * return `Caught cause: ${Cause.squash(result)}`\n * })\n *\n * Effect.runSync(program) // => \"Caught cause: Something went wrong\"\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const sandbox = internal.sandbox;\n/**\n * Discards both the success and failure values of an effect.\n *\n * **When to use**\n *\n * Use when an effect should run for its side effects while both success and\n * failure values are discarded.\n *\n * **Details**\n *\n * Use the `log` option to emit the full {@link Cause} when the effect fails,\n * and `message` to prepend a custom log message.\n *\n * **Example** (Discarding success and failure values)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * // ┌─── Effect<number, string, never>\n * // ▼\n * const task = Effect.fail(\"Uh oh!\").pipe(Effect.as(5))\n *\n * // ┌─── Effect<void, never, never>\n * // ▼\n * const program = task.pipe(Effect.ignore)\n * Effect.runSync(program) // => undefined\n * ```\n *\n * **Example** (Logging failures while ignoring results)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const task = Effect.fail(\"Uh oh!\")\n *\n * const program = task.pipe(Effect.ignore)\n * Effect.runSync(program) // => undefined\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const ignore = internal.ignore;\n/**\n * Ignores the effect's failure cause, including defects and interruptions.\n *\n * **When to use**\n *\n * Use when a best-effort effect should never fail, even from defects or\n * interruption, and optional cause logging is enough.\n *\n * **Details**\n *\n * Use the `log` option to emit the full {@link Cause} when the effect fails,\n * and `message` to prepend a custom log message.\n *\n * **Example** (Ignoring failures and logging causes)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const task = Effect.fail(\"boom\")\n *\n * const program = task.pipe(Effect.ignoreCause)\n * Effect.runSync(program) // => undefined\n * ```\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const ignoreCause = internal.ignoreCause;\n/**\n * Applies an `ExecutionPlan` to an effect, retrying with step-provided resources\n * until it succeeds or the plan is exhausted.\n *\n * **Details**\n *\n * Each attempt updates `ExecutionPlan.CurrentMetadata` (attempt and step index),\n * and retry timing is derived per step (the first attempt uses the remaining\n * attempts schedule; later retries apply the step schedule at least once).\n *\n * Attempts can be observed from outside the effect by passing\n * `options.onEvent`, which receives an `ExecutionPlan.Event` before each\n * attempt and after it settles. The handler is awaited inline before and after\n * every attempt, so events are strictly ordered; keep it cheap. It cannot\n * fail, which keeps observation from changing the plan's outcome, and its\n * requirements are added to the resulting effect. Terminal events run like\n * finalizers, so they are emitted even when the attempt is interrupted.\n *\n * **Example** (Retrying with an execution plan)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, ExecutionPlan, Layer } from \"effect\"\n *\n * const Endpoint = Context.Service<{ url: string }>(\"Endpoint\")\n *\n * const fetchUrl = Effect.gen(function*() {\n * const endpoint = yield* Effect.service(Endpoint)\n * if (endpoint.url === \"bad\") {\n * return yield* Effect.fail(\"Unavailable\")\n * }\n * return endpoint.url\n * })\n *\n * const plan = ExecutionPlan.make(\n * { provide: Layer.succeed(Endpoint, { url: \"bad\" }), attempts: 2 },\n * { provide: Layer.succeed(Endpoint, { url: \"good\" }) }\n * )\n *\n * const program = Effect.withExecutionPlan(fetchUrl, plan)\n * Effect.runSync(program) // => \"good\"\n * ```\n *\n * **Example** (Observing execution-plan attempts)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, ExecutionPlan, Layer } from \"effect\"\n *\n * const Endpoint = Context.Service<{ url: string }>(\"Endpoint\")\n *\n * const fetchUrl = Effect.gen(function*() {\n * const endpoint = yield* Effect.service(Endpoint)\n * if (endpoint.url === \"bad\") {\n * return yield* Effect.fail(\"Unavailable\")\n * }\n * return endpoint.url\n * })\n *\n * const plan = ExecutionPlan.make(\n * { provide: Layer.succeed(Endpoint, { url: \"bad\" }) },\n * { provide: Layer.succeed(Endpoint, { url: \"good\" }) }\n * )\n *\n * const events: Array<string> = []\n * const program = Effect.withExecutionPlan(fetchUrl, plan, {\n * onEvent: (event) => Effect.sync(() => events.push(`${event._tag}:${event.stepIndex}`))\n * })\n *\n * await Effect.runPromise(program) // => \"good\"\n *\n * events // => [\"AttemptStart:0\", \"AttemptFailure:0\", \"AttemptStart:1\", \"AttemptSuccess:1\"]\n * ```\n *\n * @category error handling\n * @since 3.16.0\n */\nexport const withExecutionPlan = internalExecutionPlan.withExecutionPlan;\n/**\n * Runs an effect and reports any errors to the configured `ErrorReporter`s.\n *\n * **Details**\n *\n * If the `defectsOnly` option is set to `true`, only defects (unrecoverable\n * errors) will be reported, while regular failures will be ignored.\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const withErrorReporting = internal.withErrorReporting;\n// -----------------------------------------------------------------------------\n// Fallback\n// -----------------------------------------------------------------------------\n/**\n * Recovers from a typed failure by producing a fallback success value.\n *\n * **Details**\n *\n * If the source effect succeeds, its value is preserved. If it fails in the\n * error channel, `orElseSucceed` evaluates the fallback and succeeds with that\n * value, removing the typed error from the returned effect.\n *\n * Defects and interruptions are not recovered by this operator.\n *\n * **Example** (Replacing failures with a value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit } from \"effect\"\n *\n * const validate = (age: number): Effect.Effect<number, string> => {\n * if (age < 0) {\n * return Effect.fail(\"NegativeAgeError\")\n * } else if (age < 18) {\n * return Effect.fail(\"IllegalAgeError\")\n * } else {\n * return Effect.succeed(age)\n * }\n * }\n *\n * const program = Effect.orElseSucceed(validate(-1), () => 18)\n *\n * Effect.runSyncExit(program) // => Exit.succeed(18)\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const orElseSucceed = internal.orElseSucceed;\n/**\n * Runs a sequence of effects and returns the result of the first successful\n * one.\n *\n * **When to use**\n *\n * Use when you have prioritized fallback `Effect`s, such as attempting\n * multiple APIs, reading configuration from several sources, or trying\n * alternative resource locations in order.\n *\n * **Details**\n *\n * This function executes the provided effects in sequence, stopping at the\n * first success. If an effect succeeds, its result is returned immediately and\n * no further effects in the sequence are executed.\n *\n * If all effects fail, the returned effect fails with the error from the last\n * effect. If the collection is empty, the returned effect defects with an\n * `Error` whose message is `\"Received an empty collection of effects\"`.\n *\n * **Example** (Trying alternatives until one succeeds)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const primary = Effect.fail(\"primary unavailable\")\n * const secondary = Effect.succeed(\"secondary result\")\n * const tertiary = Effect.sync(() => {\n * throw new Error(\"not evaluated\")\n * })\n *\n * const program = Effect.firstSuccessOf([\n * primary,\n * secondary,\n * tertiary\n * ])\n *\n * Effect.runSync(program) // => \"secondary result\"\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const firstSuccessOf = internal.firstSuccessOf;\n// -----------------------------------------------------------------------------\n// Delays & timeouts\n// -----------------------------------------------------------------------------\n/**\n * Adds a time limit to an effect, triggering a timeout if the effect exceeds\n * the duration.\n *\n * **When to use**\n *\n * Use when you need a timeout of an `Effect` to be represented as a typed\n * failure.\n *\n * **Details**\n *\n * The `timeout` function allows you to specify a time limit for an\n * effect's execution. If the effect does not complete within the given time, a\n * `TimeoutError` is raised. This can be useful for controlling how long your\n * program waits for a task to finish, ensuring that it doesn't hang\n * indefinitely if the task takes too long.\n *\n * **Gotchas**\n *\n * If the timeout wins, the source effect is interrupted.\n *\n * **Example** (Failing when work takes too long)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const timedEffect = Effect.never.pipe(Effect.timeout(0))\n * const error = await Effect.runPromise(Effect.flip(timedEffect))\n * error._tag // => \"TimeoutError\"\n * ```\n *\n * @see {@link timeoutOption} for returning `Option.none` on timeout.\n * @see {@link timeoutOrElse} for a version that allows specifying both success and timeout handlers.\n *\n * @category delays & timeouts\n * @since 2.0.0\n */\nexport const timeout = internal.timeout;\n/**\n * Runs an effect with a time limit and represents only the timeout case as\n * `Option.none`.\n *\n * **When to use**\n *\n * Use when a timeout of an `Effect` should be handled as `Option.none`.\n *\n * **Details**\n *\n * If the source effect succeeds before the timeout, the returned effect\n * succeeds with `Option.some(value)`. If the timeout wins, the source effect is\n * interrupted and the returned effect succeeds with `Option.none`. If the\n * source effect fails before the timeout, that failure is preserved.\n *\n * **Example** (Returning None on timeout)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option } from \"effect\"\n *\n * const timedOutEffect = Effect.never.pipe(Effect.timeoutOption(0))\n * await Effect.runPromise(timedOutEffect) // => Option.none()\n * ```\n *\n * @see {@link timeout} for a version that raises a `TimeoutError`.\n * @see {@link timeoutOrElse} for a version that allows specifying both success and timeout handlers.\n *\n * @category delays & timeouts\n * @since 3.1.0\n */\nexport const timeoutOption = internal.timeoutOption;\n/**\n * Applies a timeout to an effect, lazily evaluating `orElse` after interrupting\n * the source if the timeout is reached.\n *\n * **Example** (Falling back on timeout)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.timeoutOrElse(Effect.never, {\n * duration: 0,\n * orElse: () => Effect.sync(() => { output.push(\"Query timed out, using cached data\") }).pipe(\n * Effect.as(\"Cached result\")\n * )\n * })\n *\n * void output.push(await Effect.runPromise(program))\n * output // => [\"Query timed out, using cached data\", \"Cached result\"]\n * ```\n *\n * @see {@link timeout} for failing with a `TimeoutError`.\n * @see {@link timeoutOption} for returning `Option.none` on timeout.\n *\n * @category delays & timeouts\n * @since 4.0.0\n */\nexport const timeoutOrElse = internal.timeoutOrElse;\n/**\n * Returns an effect that is delayed from this effect by the specified\n * `Duration`.\n *\n * **Example** (Delaying an effect)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.delay(Effect.sync(() => { output.push(\"Delayed message\") }), 0)\n *\n * await Effect.runPromise(program)\n * output // => [\"Delayed message\"]\n * ```\n *\n * @category delays & timeouts\n * @since 2.0.0\n */\nexport const delay = internal.delay;\n/**\n * Returns an effect that suspends the current fiber for the specified duration\n * without blocking a JavaScript thread.\n *\n * **Example** (Pausing without blocking)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.gen(function*() {\n * yield* Effect.sync(() => { output.push(\"Start\") })\n * yield* Effect.sleep(0)\n * yield* Effect.sync(() => { output.push(\"End\") })\n * })\n *\n * await Effect.runPromise(program)\n * output // => [\"Start\", \"End\"]\n * ```\n *\n * @category delays & timeouts\n * @since 2.0.0\n */\nexport const sleep = internal.sleep;\n/**\n * Returns the runtime duration of an effect together with its result.\n *\n * **Details**\n *\n * The original success, failure, or interruption is preserved; only the success\n * value is paired with the duration.\n *\n * **Example** (Measuring execution time)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const [, value] = yield* Effect.timed(Effect.succeed(\"ok\"))\n * return value\n * })\n *\n * Effect.runSync(program) // => \"ok\"\n * ```\n *\n * @category delays & timeouts\n * @since 2.0.0\n */\nexport const timed = internal.timed;\n// -----------------------------------------------------------------------------\n// Racing\n// -----------------------------------------------------------------------------\n/**\n * Runs multiple effects concurrently and returns the first successful result.\n *\n * **When to use**\n *\n * Use when early failures should be ignored until a success occurs\n * or all effects fail.\n *\n * **Details**\n *\n * Early failures do not finish the race; `raceAll` keeps waiting until one\n * effect succeeds or every effect has failed. When one effect succeeds, the\n * remaining effects are interrupted. If every effect fails, the returned effect\n * fails with a cause containing the collected failure reasons.\n *\n * **Example** (Racing many effects)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const raced = Effect.raceAll([\n * Effect.succeed(\"Fast\"),\n * Effect.never\n * ])\n * await Effect.runPromise(raced) // => \"Fast\"\n * ```\n *\n * @see {@link race} for a version that handles only two effects.\n * @category racing\n * @since 2.0.0\n */\nexport const raceAll = internal.raceAll;\n/**\n * Runs multiple effects concurrently and completes with the first effect to\n * finish, whether it succeeds or fails.\n *\n * **Details**\n *\n * After the first effect completes, all remaining effects are interrupted. Use\n * `raceAll` when early failures should be ignored until a success occurs or\n * all effects fail.\n *\n * **Example** (Taking the first settled result)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const raced = Effect.raceAllFirst([\n * Effect.fail(\"First failed\"),\n * Effect.never\n * ])\n * await Effect.runPromise(Effect.flip(raced)) // => \"First failed\"\n * ```\n *\n * @category racing\n * @since 4.0.0\n */\nexport const raceAllFirst = internal.raceAllFirst;\n/**\n * Races two effects and returns the first successful result.\n *\n * **Details**\n *\n * If one effect succeeds, the other is interrupted and `onWinner` can observe the\n * winning fiber. If both fail, the race fails.\n *\n * **Example** (Racing two effects)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const fastFail = Effect.fail(\"fast-fail\")\n * const slowSuccess = Effect.succeed(\"slow-success\")\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Effect.race(fastFail, slowSuccess)\n * yield* Effect.sync(() => { output.push(`winner: ${result}`) })\n * })\n *\n * await Effect.runPromise(program)\n * output // => [\"winner: slow-success\"]\n * ```\n *\n * @category racing\n * @since 2.0.0\n */\nexport const race = internal.race;\n/**\n * Races two effects and returns the result of the first one to complete, whether\n * it succeeds or fails.\n *\n * **When to use**\n *\n * Use when any completion, including failure, should decide the race and\n * interrupt the losing effect.\n *\n * **Details**\n *\n * The losing effect is interrupted, and `onWinner` can observe the winning fiber.\n *\n * **Example** (Observing the winning fiber)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const fastFail = Effect.fail(\"fast-fail\")\n * const slowSuccess = Effect.never\n *\n * const program = Effect.gen(function*() {\n * const message = yield* Effect.match(Effect.raceFirst(fastFail, slowSuccess), {\n * onFailure: (error) => `failed: ${error}`,\n * onSuccess: (value) => `succeeded: ${value}`\n * })\n * yield* Effect.sync(() => { output.push(message) })\n * })\n *\n * await Effect.runPromise(program)\n * output // => [\"failed: fast-fail\"]\n * ```\n *\n * @category racing\n * @since 2.0.0\n */\nexport const raceFirst = internal.raceFirst;\n// -----------------------------------------------------------------------------\n// Filtering\n// -----------------------------------------------------------------------------\n/**\n * Filters elements of an iterable using a predicate, refinement, or effectful\n * predicate.\n *\n * **Example** (Filtering success values)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * // Sync predicate\n * const evens = Effect.filter([1, 2, 3, 4], (n) => n % 2 === 0)\n *\n * // Effectful predicate\n * const checked = Effect.filter([1, 2, 3], (n) => Effect.succeed(n > 1))\n *\n * void output.push(Effect.runSync(evens))\n * void output.push(Effect.runSync(checked))\n * output // => [[2, 4], [2, 3]]\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const filter = internal.filter;\n/**\n * Filters and maps elements of an iterable with a `Filter`.\n *\n * **When to use**\n *\n * Use when you need to filter an iterable with a `Filter` inside an `Effect`,\n * collecting each filter success value.\n *\n * **Details**\n *\n * `Result.succeed` values are collected in the returned array, and\n * `Result.fail` values are skipped.\n *\n * @see {@link filter} for keeping original elements with a boolean predicate, refinement, or effectful predicate\n * @see {@link filterMapEffect} for using an effectful `Filter`\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const filterMap = internal.filterMap;\n/**\n * Filters and maps elements of an iterable effectfully with a `FilterEffect`.\n *\n * **When to use**\n *\n * Use when you need to filter each iterable element effectfully and transform\n * accepted elements into successful output values.\n *\n * **Details**\n *\n * `Result.succeed` values are collected in the returned array, and\n * `Result.fail` values are skipped.\n *\n * **Gotchas**\n *\n * With concurrent execution, successful values are collected in completion\n * order, not input order.\n *\n * @see {@link filterMap} for using a synchronous `Filter`\n * @see {@link filter} for keeping original elements with a predicate\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterMapEffect = internal.filterMapEffect;\n/**\n * Filters an effect, providing an alternative effect if the predicate fails.\n *\n * **When to use**\n *\n * Use when a successful value that fails a predicate should continue with an\n * effectful fallback instead of failing the effect.\n *\n * **Details**\n *\n * This function applies a predicate to the result of an effect. If the\n * predicate evaluates to `false`, it executes the `orElse` effect instead. The\n * `orElse` effect can produce an alternative value or perform additional\n * computations.\n *\n * **Example** (Filtering with a fallback effect)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * // An effect that produces a number\n * const program = Effect.succeed(5)\n *\n * // Filter for even numbers, provide alternative for odd numbers\n * const filtered = Effect.filterOrElse(\n * program,\n * (n) => n % 2 === 0,\n * (n) => Effect.succeed(`Number ${n} is odd`)\n * )\n *\n * Effect.runSync(filtered) // => \"Number 5 is odd\"\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const filterOrElse = internal.filterOrElse;\n/**\n * Filters an effect with a `Filter`, providing an alternative effect on failure.\n *\n * **When to use**\n *\n * Use when a successful effect value should be accepted and transformed by a\n * `Filter`, while rejected values should continue with an alternative effect\n * built from the filter failure.\n *\n * **Details**\n *\n * `Result.succeed` becomes the returned success value, and `Result.fail` is\n * passed to `orElse`.\n *\n * @see {@link filterOrElse} for using a predicate and fallback effect\n * @see {@link filterMapOrFail} for failing the effect when the filter fails\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterMapOrElse = internal.filterMapOrElse;\n/**\n * Filters an effect, failing with a custom error if the predicate fails.\n *\n * **Details**\n *\n * This function applies a predicate to the result of an effect. If the\n * predicate evaluates to `false`, the effect fails with either a custom\n * error (if `orFailWith` is provided) or a `NoSuchElementError`.\n *\n * **Example** (Filtering with a custom failure)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * // An effect that produces a number\n * const program = Effect.succeed(5)\n *\n * // Filter for even numbers, fail for odd numbers\n * const filtered = Effect.filterOrFail(\n * program,\n * (n) => n % 2 === 0,\n * (n) => `Expected even number, got ${n}`\n * )\n *\n * Effect.runSync(Effect.flip(filtered)) // => \"Expected even number, got 5\"\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const filterOrFail = internal.filterOrFail;\n/**\n * Filters and maps an effect with a `Filter`, failing when the filter fails.\n *\n * **When to use**\n *\n * Use when validating and transforming one effect success with a synchronous\n * `Filter`, while rejected values should fail the effect.\n *\n * **Details**\n *\n * `Result.succeed` becomes the returned success value. `Result.fail` is mapped\n * with `orFailWith` when provided, or fails with `NoSuchElementError`.\n *\n * @see {@link filterMapOrElse} for continuing with a fallback effect when the filter fails\n * @see {@link filterOrFail} for validating with a predicate instead of a `Filter`\n * @see {@link filterMap} for filtering and mapping iterable elements\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterMapOrFail = internal.filterMapOrFail;\n// -----------------------------------------------------------------------------\n// Conditional Operators\n// -----------------------------------------------------------------------------\n/**\n * Runs an effect conditionally based on the result of an effectful boolean\n * condition.\n *\n * **When to use**\n *\n * Use when you need an effectful check to decide whether another effect should\n * run while representing the skipped case explicitly.\n *\n * **Details**\n *\n * The condition effect is evaluated first. If it succeeds with `true`, the\n * source effect is run and its success value is wrapped in `Option.some`. If it\n * succeeds with `false`, the source effect is skipped and the result is\n * `Option.none`. If the condition effect fails, that failure is preserved.\n *\n * **Example** (Conditionally running an effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const shouldLog = true\n *\n * const program = Effect.when(\n * Effect.sync(() => { output.push(\"Condition is true!\") }),\n * Effect.succeed(shouldLog)\n * )\n *\n * void output.push(Effect.runSync(program))\n * output // => [\"Condition is true!\", Option.some(undefined)]\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const when = internal.when;\n// -----------------------------------------------------------------------------\n// Pattern matching\n// -----------------------------------------------------------------------------\n/**\n * Handles both success and failure cases of an effect without performing side\n * effects.\n *\n * **When to use**\n *\n * Use when you need to fold an `Effect` into a value by handling success and\n * failure differently without triggering side effects.\n *\n * **Details**\n *\n * `match` lets you define custom handlers for both success and failure\n * scenarios. You provide separate functions to handle each case, allowing you\n * to process the result if the effect succeeds, or handle the error if the\n * effect fails.\n *\n * **Example** (Matching success and failure values)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect } from \"effect\"\n *\n * class ExampleError extends Data.TaggedError(\"ExampleError\")<{ readonly message: string }> {}\n *\n * const success: Effect.Effect<number, ExampleError> = Effect.succeed(42)\n *\n * const program1 = Effect.match(success, {\n * onFailure: (error) => `failure: ${error.message}`,\n * onSuccess: (value) => `success: ${value}`\n * })\n *\n * // Run and log the result of the successful effect\n * Effect.runSync(program1) // => \"success: 42\"\n *\n * const failure: Effect.Effect<number, ExampleError> = Effect.fail(\n * new ExampleError({ message: \"Uh oh!\" })\n * )\n *\n * const program2 = Effect.match(failure, {\n * onFailure: (error) => `failure: ${error.message}`,\n * onSuccess: (value) => `success: ${value}`\n * })\n *\n * // Run and log the result of the failed effect\n * Effect.runSync(program2) // => \"failure: Uh oh!\"\n * ```\n *\n * @see {@link matchEffect} if you need to perform side effects in the handlers.\n * @category pattern matching\n * @since 2.0.0\n */\nexport const match = internal.match;\n/**\n * Handles both success and failure cases of an effect without performing side\n * effects, with eager evaluation for resolved effects.\n *\n * **When to use**\n *\n * Use when you need to handle both success and failure cases of an\n * already-resolved `Effect` with optimized handling.\n *\n * **Details**\n *\n * `matchEager` works like `match` but provides better performance for resolved\n * effects (Success or Failure). When the effect is already resolved, it applies\n * the handlers immediately without fiber scheduling. For unresolved effects,\n * it falls back to the regular `match` behavior.\n *\n * **Example** (Pattern matching eagerly when possible)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.gen(function*() {\n * const result = yield* Effect.matchEager(Effect.succeed(42), {\n * onFailure: (error) => `Failed: ${error}`,\n * onSuccess: (value) => `Success: ${value}`\n * })\n * void output.push(result)\n * })\n *\n * Effect.runSync(program)\n * output // => [\"Success: 42\"]\n * ```\n *\n * @see {@link match} for the non-eager version.\n * @see {@link matchEffect} if you need to perform side effects in the handlers.\n * @category pattern matching\n * @since 4.0.0\n */\nexport const matchEager = internal.matchEager;\n/**\n * Handles failures by matching the cause of failure.\n *\n * **When to use**\n *\n * Use when you need to fold an `Effect` while the failure handler inspects the\n * full `Cause`.\n *\n * **Details**\n *\n * The `matchCause` function allows you to handle failures with access to the\n * full cause of the failure within a fiber.\n *\n * **Example** (Matching on success or failure causes)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect } from \"effect\"\n *\n * const task = Effect.fail(\"Something went wrong\")\n *\n * const program = Effect.matchCause(task, {\n * onFailure: (cause) => `Failed: ${Cause.squash(cause)}`,\n * onSuccess: (value) => `Success: ${value}`\n * })\n *\n * Effect.runSync(program) // => \"Failed: Something went wrong\"\n * ```\n *\n * @see {@link matchCauseEffect} if you need to perform side effects in the\n * handlers.\n * @see {@link match} if you don't need to handle the cause of the failure.\n * @category pattern matching\n * @since 2.0.0\n */\nexport const matchCause = internal.matchCause;\n/**\n * Handles failures by matching the cause of failure with eager evaluation.\n *\n * **When to use**\n *\n * Use when you expect an `Effect` to already be resolved and want to match the\n * `Cause` without regular effect pipeline overhead.\n *\n * **Details**\n *\n * `matchCauseEager` works like `matchCause` but provides better performance for resolved\n * effects by immediately applying the matching function instead of deferring it\n * through the effect pipeline.\n *\n * **Example** (Eagerly matching already completed effects)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const handleResult = Effect.matchCauseEager(Effect.succeed(42), {\n * onSuccess: (value) => `Success: ${value}`,\n * onFailure: (cause) => `Failed: ${cause}`\n * })\n * Effect.runSync(handleResult) // => \"Success: 42\"\n * ```\n *\n * @category pattern matching\n * @since 4.0.0\n */\nexport const matchCauseEager = internal.matchCauseEager;\n/**\n * Handles success or failure eagerly with effectful handlers when the effect is already resolved.\n *\n * **When to use**\n *\n * Use when you need effectful success and cause-aware failure handlers for\n * `Effect` inputs that may already be resolved.\n *\n * **Details**\n *\n * If the effect is an `Exit`, the matching handler runs immediately; otherwise it behaves like\n * {@link matchCauseEffect}.\n *\n * @see {@link matchCauseEffect} for the non-eager effectful variant\n * @see {@link matchCauseEager} for eager cause matching with pure handlers\n * @see {@link matchEffect} for effectful matching on typed failures instead of full causes\n *\n * @category pattern matching\n * @since 4.0.0\n */\nexport const matchCauseEffectEager = internal.matchCauseEffectEager;\n/**\n * Handles failures with access to the cause and allows performing side effects.\n *\n * **When to use**\n *\n * Use when you need to fold an `Effect` with effectful success handlers and\n * `Cause`-aware failure handlers.\n *\n * **Details**\n *\n * The `matchCauseEffect` function works similarly to {@link matchCause}, but it\n * also allows you to perform additional side effects based on the failure\n * cause. This function provides access to the complete cause of the failure,\n * making it possible to differentiate between various failure types, and allows\n * you to respond accordingly while performing side effects (like logging or\n * other operations).\n *\n * **Example** (Effectfully matching on causes)\n *\n * ```ts import.meta.vitest\n * import { Cause, Data, Effect, Result } from \"effect\"\n * const output: Array<unknown> = []\n *\n * class TaskError extends Data.TaggedError(\"TaskError\")<{ readonly message: string }> {}\n *\n * const task = Effect.fail(new TaskError({ message: \"Task failed\" }))\n *\n * const program = Effect.matchCauseEffect(task, {\n * onFailure: (cause) =>\n * Effect.gen(function*() {\n * if (Cause.hasFails(cause)) {\n * const error = Cause.findError(cause)\n * if (Result.isSuccess(error)) {\n * yield* Effect.sync(() => { output.push(`Handling error: ${error.success.message}`) })\n * }\n * return \"recovered from error\"\n * } else {\n * yield* Effect.sync(() => { output.push(\"Handling interruption or defect\") })\n * return \"recovered from interruption/defect\"\n * }\n * }),\n * onSuccess: (value) =>\n * Effect.gen(function*() {\n * yield* Effect.sync(() => { output.push(`Success: ${value}`) })\n * return `processed ${value}`\n * })\n * })\n *\n * void output.push(Effect.runSync(program))\n * output // => [\"Handling error: Task failed\", \"recovered from error\"]\n * ```\n *\n * @see {@link matchCause} if you don't need side effects and only want to handle the result or failure.\n * @see {@link matchEffect} if you don't need to handle the cause of the failure.\n *\n * @category pattern matching\n * @since 2.0.0\n */\nexport const matchCauseEffect = internal.matchCauseEffect;\n/**\n * Handles both success and failure by running effectful handlers.\n *\n * **When to use**\n *\n * Use when you need to handle an `Effect`'s failure or success with handlers\n * that return effects.\n *\n * **Details**\n *\n * Use `matchEffect` when either branch needs to return an `Effect`, such as\n * performing logging, recovery, notification, or other effectful work. The\n * returned effect succeeds or fails according to the handler that is run.\n *\n * **Example** (Matching success and failure with effectful handlers)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect } from \"effect\"\n *\n * class ExampleError extends Data.TaggedError(\"ExampleError\")<{ readonly message: string }> {}\n *\n * const success: Effect.Effect<number, ExampleError> = Effect.succeed(42)\n * const failure: Effect.Effect<number, ExampleError> = Effect.fail(\n * new ExampleError({ message: \"Uh oh!\" })\n * )\n *\n * const program1 = Effect.matchEffect(success, {\n * onFailure: (error) =>\n * Effect.succeed(`failure: ${error.message}`),\n * onSuccess: (value) =>\n * Effect.succeed(`success: ${value}`)\n * })\n *\n * Effect.runSync(program1) // => \"success: 42\"\n *\n * const program2 = Effect.matchEffect(failure, {\n * onFailure: (error) =>\n * Effect.succeed(`failure: ${error.message}`),\n * onSuccess: (value) =>\n * Effect.succeed(`success: ${value}`)\n * })\n *\n * Effect.runSync(program2) // => \"failure: Uh oh!\"\n * ```\n *\n * @see {@link match} if you don't need side effects and only want to handle the\n * result or failure.\n * @category pattern matching\n * @since 2.0.0\n */\nexport const matchEffect = internal.matchEffect;\n// -----------------------------------------------------------------------------\n// Condition checking\n// -----------------------------------------------------------------------------\n/**\n * Determines whether an effect fails.\n *\n * **Details**\n *\n * Defects are not converted; if the effect dies, the resulting effect dies too.\n *\n * **Example** (Checking whether an effect fails)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.gen(function*() {\n * const failed = yield* Effect.isFailure(Effect.fail(\"Uh oh!\"))\n * yield* Effect.sync(() => { output.push(failed) })\n * })\n *\n * Effect.runSync(program)\n * output // => [true]\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const isFailure = internal.isFailure;\n/**\n * Returns whether an effect completes successfully.\n *\n * **Details**\n *\n * Returns `false` for failures in the error channel, but defects still fail the\n * effect.\n *\n * **Example** (Checking whether an effect succeeds)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.gen(function*() {\n * const ok = yield* Effect.isSuccess(Effect.succeed(\"done\"))\n * const failed = yield* Effect.isSuccess(Effect.fail(\"Uh oh\"))\n * yield* Effect.sync(() => { output.push(`ok: ${ok}`) })\n * yield* Effect.sync(() => { output.push(`failed: ${failed}`) })\n * })\n *\n * Effect.runSync(program)\n * output // => [\"ok: true\", \"failed: false\"]\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const isSuccess = internal.isSuccess;\n// -----------------------------------------------------------------------------\n// Environment\n// -----------------------------------------------------------------------------\n/**\n * Returns the complete context.\n *\n * **When to use**\n *\n * Use to read the complete `Context` available to the current effect.\n *\n * **Details**\n *\n * This function allows you to access all services that are currently available\n * in the effect's environment. This can be useful for debugging, introspection,\n * or when you need to pass the entire context to another function.\n *\n * **Example** (Reading the full context)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Option } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const Logger = Context.Service<{\n * log: (msg: string) => void\n * }>(\"Logger\")\n * const Database = Context.Service<{\n * query: (sql: string) => string\n * }>(\"Database\")\n *\n * const program = Effect.gen(function*() {\n * const allServices = yield* Effect.context()\n *\n * // Check if specific services are available\n * const loggerOption = Context.getOption(allServices, Logger)\n * const databaseOption = Context.getOption(allServices, Database)\n *\n * yield* Effect.sync(() => { output.push(`Logger available: ${Option.isSome(loggerOption)}`) })\n * yield* Effect.sync(() => { output.push(`Database available: ${Option.isSome(databaseOption)}`) })\n * })\n *\n * const context = Context.make(Logger, { log: () => {} })\n * .pipe(Context.add(Database, { query: () => \"result\" }))\n *\n * const provided = Effect.provideContext(program, context)\n * Effect.runSync(provided)\n * output // => [\"Logger available: true\", \"Database available: true\"]\n * ```\n *\n * @see {@link contextWith} for deriving an effect from the complete context\n * @see {@link service} for reading one service from the context\n *\n * @category accessors\n * @since 2.0.0\n */\nexport const context = internal.context;\n/**\n * Transforms the current context using the provided function.\n *\n * **When to use**\n *\n * Use to derive an effect from the complete `Context`.\n *\n * **Details**\n *\n * This function allows you to access the complete context and perform\n * computations based on all available services. This is useful when you need\n * to conditionally execute logic based on what services are available.\n *\n * **Example** (Deriving values from the context)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Option } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const Logger = Context.Service<{\n * log: (msg: string) => void\n * }>(\"Logger\")\n * const Cache = Context.Service<{\n * get: (key: string) => string | null\n * }>(\"Cache\")\n *\n * const program = Effect.contextWith((services: Context.Context<Context.Service.Identifier<typeof Cache>>) => {\n * const cacheOption = Context.getOption(services, Cache)\n * const hasCache = Option.isSome(cacheOption)\n *\n * if (hasCache) {\n * return Effect.gen(function*() {\n * const cache = yield* Effect.service(Cache)\n * yield* Effect.sync(() => { output.push(\"Using cached data\") })\n * return cache.get(\"user:123\") || \"default\"\n * })\n * } else {\n * return Effect.gen(function*() {\n * yield* Effect.sync(() => { output.push(\"No cache available, using fallback\") })\n * return \"fallback data\"\n * })\n * }\n * })\n *\n * const withCache = Effect.provideService(program, Cache, {\n * get: () => \"cached_value\"\n * })\n * void output.push(Effect.runSync(withCache))\n * output // => [\"Using cached data\", \"cached_value\"]\n * ```\n *\n * @see {@link context} for reading the complete context as a value\n * @see {@link service} for reading one service from the context\n *\n * @category accessors\n * @since 2.0.0\n */\nexport const contextWith = internal.contextWith;\n/**\n * Provides dependencies to an effect using layers or a context. Use `options.local`\n * to build the layer every time; by default, layers are shared between provide\n * calls.\n *\n * **Example** (Providing dependencies with a layer)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer } from \"effect\"\n *\n * interface Database {\n * readonly query: (sql: string) => Effect.Effect<string>\n * }\n *\n * const Database = Context.Service<Database>(\"Database\")\n *\n * const DatabaseLayer = Layer.succeed(Database)({\n * query: Effect.fn(\"Database.query\")((sql: string) => Effect.succeed(`Result for: ${sql}`))\n * })\n *\n * const program = Effect.gen(function*() {\n * const db = yield* Database\n * return yield* db.query(\"SELECT * FROM users\")\n * })\n *\n * const provided = Effect.provide(program, DatabaseLayer)\n *\n * await Effect.runPromise(provided) // => \"Result for: SELECT * FROM users\"\n * ```\n *\n * @category providing services\n * @since 2.0.0\n */\nexport const provide = internalLayer.provide;\n/**\n * Provides a context to an effect, fulfilling its service requirements.\n *\n * **Details**\n *\n * This function provides multiple services at once by supplying a context\n * that contains all the required services. It removes the provided services\n * from the effect's requirements, making them available to the effect.\n *\n * **Example** (Providing a complete context)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * // Define service keys\n * const Logger = Context.Service<{\n * log: (msg: string) => void\n * }>(\"Logger\")\n * const Database = Context.Service<{\n * query: (sql: string) => string\n * }>(\"Database\")\n *\n * // Create a context with multiple services\n * const context = Context.make(Logger, { log: (message) => { output.push(message) } })\n * .pipe(Context.add(Database, { query: () => \"result\" }))\n *\n * // An effect that requires both services\n * const program = Effect.gen(function*() {\n * const logger = yield* Effect.service(Logger)\n * const db = yield* Effect.service(Database)\n * logger.log(\"Querying database\")\n * return db.query(\"SELECT * FROM users\")\n * })\n *\n * const provided = Effect.provideContext(program, context)\n * void output.push(Effect.runSync(provided))\n * output // => [\"Querying database\", \"result\"]\n * ```\n *\n * @category providing services\n * @since 4.0.0\n */\nexport const provideContext = internal.provideContext;\n/**\n * Runs an effect with the provided context as its complete environment.\n *\n * **When to use**\n *\n * Use when you already have a `Context` containing every service required by\n * the effect and want the wrapped effect to run with exactly that context.\n *\n * **Gotchas**\n *\n * `setContext` replaces the current context for the wrapped effect. Services\n * from an outer context are not inherited unless they are also present in the\n * context passed to `setContext`.\n *\n * **Example** (Running with a complete context)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect } from \"effect\"\n *\n * class Config extends Context.Service<Config, {\n * readonly greeting: string\n * }>()(\"Config\") {}\n *\n * const program = Effect.gen(function*() {\n * const config = yield* Effect.service(Config)\n * return `${config.greeting}, World!`\n * })\n *\n * const context = Context.make(Config, { greeting: \"Hello\" })\n *\n * const runnable = Effect.setContext(program, context)\n *\n * Effect.runSync(runnable) // => \"Hello, World!\"\n * ```\n *\n * @see {@link provideContext} for partially satisfying an effect's context requirements.\n * @see {@link updateContext} for deriving the required context from the current one.\n *\n * @category providing services\n * @since 4.0.0\n */\nexport const setContext = internal.setContext;\n/**\n * Accesses a service from the context.\n *\n * **Example** (Accessing a required service)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect } from \"effect\"\n *\n * interface Database {\n * readonly query: (sql: string) => Effect.Effect<string>\n * }\n *\n * const Database = Context.Service<Database>(\"Database\")\n *\n * const program = Effect.gen(function*() {\n * const db = yield* Effect.service(Database)\n * return yield* db.query(\"SELECT * FROM users\")\n * })\n *\n * const runnable = Effect.provideService(program, Database, {\n * query: (sql) => Effect.succeed(`Result for: ${sql}`)\n * })\n * Effect.runSync(runnable) // => \"Result for: SELECT * FROM users\"\n * ```\n *\n * @category accessors\n * @since 4.0.0\n */\nexport const service = internal.service;\n/**\n * Optionally accesses a service from the environment.\n *\n * **When to use**\n *\n * Use to read an optional dependency from the current context without making\n * that dependency part of the effect's required environment.\n *\n * **Details**\n *\n * This function attempts to access a service from the environment. If the\n * service is available, it returns `Some(service)`. If the service is not\n * available, it returns `None`. Unlike `service`, this function does not\n * require the service to be present in the environment.\n *\n * **Example** (Accessing an optional service)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Option } from \"effect\"\n * const output: Array<unknown> = []\n *\n * // Define a service key\n * const Logger = Context.Service<{\n * log: (msg: string) => void\n * }>(\"Logger\")\n *\n * // Use serviceOption to optionally access the logger\n * const program = Effect.gen(function*() {\n * const maybeLogger = yield* Effect.serviceOption(Logger)\n *\n * if (Option.isSome(maybeLogger)) {\n * maybeLogger.value.log(\"Service is available\")\n * } else {\n * void output.push(\"Service not available\")\n * }\n * })\n *\n * Effect.runSync(program)\n * output // => [\"Service not available\"]\n * ```\n *\n * @category accessors\n * @since 2.0.0\n */\nexport const serviceOption = internal.serviceOption;\n/**\n * Provides part of the required context while leaving the rest unchanged.\n *\n * **Details**\n *\n * This function allows you to transform the context required by an effect,\n * providing part of the context and leaving the rest to be fulfilled later.\n *\n * **Example** (Updating the context before running)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect } from \"effect\"\n *\n * // Define services\n * const Logger = Context.Service<{\n * log: (msg: string) => void\n * }>(\"Logger\")\n * const Config = Context.Service<{\n * name: string\n * }>(\"Config\")\n *\n * const program = Effect.service(Config).pipe(\n * Effect.map((config) => `Hello ${config.name}!`)\n * )\n *\n * // Transform services by providing Config while keeping Logger requirement\n * const configured = program.pipe(\n * Effect.updateContext((context: Context.Context<Context.Service.Identifier<typeof Logger>>) =>\n * Context.add(context, Config, { name: \"World\" })\n * )\n * )\n *\n * // The effect now requires only Logger service\n * const result = Effect.provideService(configured, Logger, {\n * log: () => {}\n * })\n * Effect.runSync(result) // => \"Hello World!\"\n * ```\n *\n * @category providing services\n * @since 4.0.0\n */\nexport const updateContext = internal.updateContext;\n/**\n * Runs an effect with a service implementation transformed by the provided\n * function.\n *\n * **Details**\n *\n * The service must be available in the effect's context; `updateService`\n * replaces it for the wrapped effect with the value returned by the updater.\n *\n * **Example** (Replacing a service for one effect)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * // Define a counter service\n * const Counter = Context.Service<{ count: number }>(\"Counter\")\n *\n * const program = Effect.gen(function*() {\n * const updatedCounter = yield* Effect.service(Counter)\n * yield* Effect.sync(() => { output.push(`Updated count: ${updatedCounter.count}`) })\n * return updatedCounter.count\n * }).pipe(\n * Effect.updateService(Counter, (counter) => ({ count: counter.count + 1 }))\n * )\n *\n * // Provide initial service and run\n * const result = Effect.provideService(program, Counter, { count: 0 })\n * void output.push(Effect.runSync(result))\n * output // => [\"Updated count: 1\", 1]\n * ```\n *\n * @category providing services\n * @since 2.0.0\n */\nexport const updateService = internal.updateService;\n/**\n * Updates a service for the lifetime of the current scope and restores its\n * previous value when the scope closes.\n *\n * **When to use**\n *\n * Use when you need a setup effect to change a service for subsequent effects\n * in the same scope.\n *\n * **Details**\n *\n * The updater receives the currently visible service value. A\n * `Context.Service` remains in the requirements, while a `Context.Reference`\n * uses its default when no override is present and adds no service requirement.\n * The returned effect always requires `Scope`. The optional `reset` function\n * receives the original, updated, and current values when the scope closes,\n * allowing changes to be merged during restoration. It defaults to returning\n * the original value.\n *\n * **Example** (Updating a reference within a scope)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const CurrentNumber = Context.Reference<number>(\"CurrentNumber\", {\n * defaultValue: () => 1\n * })\n *\n * const program = Effect.gen(function*() {\n * const before = yield* CurrentNumber\n * const during = yield* Effect.scoped(\n * Effect.gen(function*() {\n * yield* Effect.updateServiceScoped(\n * CurrentNumber,\n * (value) => value + 1,\n * {\n * // Optional: when omitted, the original value is restored\n * reset: (original, updated, current) =>\n * Math.max(original, updated, current) + 1\n * }\n * )\n * return yield* CurrentNumber\n * })\n * )\n * const after = yield* CurrentNumber\n *\n * void output.push([before, during, after])\n * })\n *\n * await Effect.runPromise(program)\n * output // => [[1, 2, 3]]\n * ```\n *\n * @see {@link updateService} for updating a service only within a wrapped effect\n *\n * @category providing services\n * @since 4.0.0\n */\nexport const updateServiceScoped = internal.updateServiceScoped;\n/**\n * Provides one concrete service implementation to an effect.\n *\n * **When to use**\n *\n * Use to satisfy one service requirement with an already-built implementation.\n *\n * **Details**\n *\n * The service requirement identified by the `Context.Key` is removed from the\n * effect requirements after the implementation is provided.\n *\n * **Example** (Providing a service value)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * // Define a service for configuration\n * const Config = Context.Service<{\n * apiUrl: string\n * timeout: number\n * }>(\"Config\")\n *\n * const fetchData = Effect.gen(function*() {\n * const config = yield* Effect.service(Config)\n * yield* Effect.sync(() => { output.push(`Fetching from: ${config.apiUrl}`) })\n * yield* Effect.sync(() => { output.push(`Timeout: ${config.timeout}ms`) })\n * return \"data\"\n * })\n *\n * // Provide the service implementation\n * const program = Effect.provideService(fetchData, Config, {\n * apiUrl: \"https://api.example.com\",\n * timeout: 5000\n * })\n *\n * void output.push(Effect.runSync(program))\n * output // => [\"Fetching from: https://api.example.com\", \"Timeout: 5000ms\", \"data\"]\n * ```\n *\n * @see {@link provide} for providing multiple layers to an effect.\n * @see {@link provideServiceEffect} for acquiring the service implementation effectfully.\n * @see {@link provideContext} for providing a complete context.\n * @category providing services\n * @since 2.0.0\n */\nexport const provideService = internal.provideService;\n/**\n * Provides one service to an effect using an effectful acquisition.\n *\n * **When to use**\n *\n * Use when the service implementation must be created by an effect and its\n * acquisition failure should remain in the returned effect.\n *\n * **Details**\n *\n * `provideServiceEffect` runs the acquisition effect to produce the service\n * implementation, removes that service from the wrapped effect's requirements,\n * and leaves any other requirements to be provided later. Acquisition failures\n * are included in the returned effect's error channel.\n *\n * **Example** (Providing a service with an effect)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * // Define a database connection service\n * interface DatabaseConnection {\n * readonly query: (sql: string) => Effect.Effect<string>\n * }\n * const Database = Context.Service<DatabaseConnection>(\"Database\")\n *\n * // Effect that creates a database connection\n * const createConnection = Effect.gen(function*() {\n * yield* Effect.sync(() => { output.push(\"Establishing database connection...\") })\n * yield* Effect.sync(() => { output.push(\"Database connected!\") })\n * return {\n * query: (sql: string) => Effect.succeed(`Result for: ${sql}`)\n * }\n * })\n *\n * const program = Effect.gen(function*() {\n * const db = yield* Effect.service(Database)\n * return yield* db.query(\"SELECT * FROM users\")\n * })\n *\n * // Provide the service through an effect\n * const withDatabase = Effect.provideServiceEffect(\n * program,\n * Database,\n * createConnection\n * )\n *\n * void output.push(await Effect.runPromise(withDatabase))\n * output // => [\"Establishing database connection...\", \"Database connected!\", \"Result for: SELECT * FROM users\"]\n * ```\n *\n * @category providing services\n * @since 2.0.0\n */\nexport const provideServiceEffect = internal.provideServiceEffect;\n// -----------------------------------------------------------------------------\n// Resource management & finalization\n// -----------------------------------------------------------------------------\n/**\n * Returns the current scope for resource management.\n *\n * **Example** (Accessing the current scope)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.gen(function*() {\n * const currentScope = yield* Effect.scope\n * yield* Effect.sync(() => { output.push(\"Got scope for resource management\") })\n *\n * // Use the scope to manually manage resources if needed\n * const resource = yield* Effect.acquireRelease(\n * Effect.sync(() => { output.push(\"Acquiring resource\") }).pipe(Effect.as(\"resource\")),\n * () => Effect.sync(() => { output.push(\"Releasing resource\") })\n * )\n *\n * return resource\n * })\n *\n * void output.push(Effect.runSync(Effect.scoped(program)))\n * output // => [\"Got scope for resource management\", \"Acquiring resource\", \"Releasing resource\", \"resource\"]\n * ```\n *\n * @category resource management\n * @since 2.0.0\n */\nexport const scope = internal.scope;\n/**\n * Runs an effect with a scope that closes when the effect completes.\n *\n * **When to use**\n *\n * Use to acquire scoped resources for the duration of a single workflow.\n *\n * **Details**\n *\n * Finalizers for resources acquired inside the workflow run as soon as the\n * workflow completes, whether by success, failure, or interruption.\n *\n * **Example** (Running a scoped acquisition)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const resource = Effect.acquireRelease(\n * Effect.sync(() => { output.push(\"Acquiring resource\") }).pipe(Effect.as(\"resource\")),\n * () => Effect.sync(() => { output.push(\"Releasing resource\") })\n * )\n *\n * const program = Effect.scoped(\n * Effect.gen(function*() {\n * const res = yield* resource\n * yield* Effect.sync(() => { output.push(`Using ${res}`) })\n * return res\n * })\n * )\n *\n * Effect.runSync(program)\n * output // => [\"Acquiring resource\", \"Using resource\", \"Releasing resource\"]\n * ```\n *\n * @category resource management\n * @since 2.0.0\n */\nexport const scoped = internal.scoped;\n/**\n * Creates a scoped effect by providing access to the scope.\n *\n * **When to use**\n *\n * Use when resource acquisition needs direct access to the scope being created,\n * for example to register finalizers manually.\n *\n * **Example** (Working with an explicit scope)\n *\n * ```ts import.meta.vitest\n * import { Effect, Scope } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.scopedWith((scope) =>\n * Effect.gen(function*() {\n * yield* Effect.sync(() => { output.push(\"Inside scoped context\") })\n *\n * // Manually add a finalizer to the scope\n * yield* Scope.addFinalizer(scope, Effect.sync(() => { output.push(\"Manual finalizer\") }))\n *\n * // Create a scoped resource\n * const resource = yield* Effect.scoped(\n * Effect.acquireRelease(\n * Effect.sync(() => { output.push(\"Acquiring resource\") }).pipe(Effect.as(\"resource\")),\n * () => Effect.sync(() => { output.push(\"Releasing resource\") })\n * )\n * )\n *\n * return resource\n * })\n * )\n *\n * void output.push(Effect.runSync(program))\n * output // => [\"Inside scoped context\", \"Acquiring resource\", \"Releasing resource\", \"Manual finalizer\", \"resource\"]\n * ```\n *\n * @category resource management\n * @since 3.11.0\n */\nexport const scopedWith = internal.scopedWith;\n/**\n * Constructs a scoped resource from an acquisition effect and a release\n * finalizer.\n *\n * **When to use**\n *\n * Use to acquire a scoped resource with an explicit release finalizer.\n *\n * **Details**\n *\n * If acquisition succeeds, the release finalizer is added to the current scope\n * and is guaranteed to run when that scope closes. The finalizer receives the\n * `Exit` value used to close the scope.\n *\n * By default, acquisition is protected by an uninterruptible region. Pass\n * `{ interruptible: true }` to allow the acquisition effect to be interrupted.\n *\n * **Example** (Acquiring and releasing a resource)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit } from \"effect\"\n * const output: Array<unknown> = []\n *\n * // Simulate a resource that needs cleanup\n * interface FileHandle {\n * readonly path: string\n * readonly content: string\n * }\n *\n * // Acquire a file handle\n * const acquire = Effect.gen(function*() {\n * yield* Effect.sync(() => { output.push(\"Opening file\") })\n * return { path: \"/tmp/file.txt\", content: \"file content\" }\n * })\n *\n * // Release the file handle\n * const release = (handle: FileHandle, exit: Exit.Exit<unknown, unknown>) =>\n * Effect.sync(() => { output.push(\n * `Closing file ${handle.path} with exit: ${\n * Exit.isSuccess(exit) ? \"success\" : \"failure\"\n * }`\n * ) })\n *\n * // Create a scoped resource\n * const resource = Effect.acquireRelease(acquire, release)\n *\n * // Use the resource within a scope\n * const program = Effect.scoped(\n * Effect.gen(function*() {\n * const handle = yield* resource\n * yield* Effect.sync(() => { output.push(`Using file: ${handle.path}`) })\n * return handle.content\n * })\n * )\n *\n * void output.push(Effect.runSync(program))\n * output // => [\"Opening file\", \"Using file: /tmp/file.txt\", \"Closing file /tmp/file.txt with exit: success\", \"file content\"]\n * ```\n *\n * @see {@link acquireDisposable} for resources that implement JavaScript disposal protocols\n * @see {@link acquireUseRelease} for bracketing acquire, use, and release in one effect\n *\n * @category resource management\n * @since 2.0.0\n */\nexport const acquireRelease = internal.acquireRelease;\n/**\n * Acquires a scoped resource that implements JavaScript disposal protocols.\n *\n * **When to use**\n *\n * Use when you work with JavaScript `Disposable` or `AsyncDisposable` resources\n * that should be closed with the surrounding scope.\n *\n * **Details**\n *\n * The resource is automatically disposed when the surrounding\n * {@link Scope} is closed, using {@link Symbol.dispose} for\n * synchronous disposables or {@link Symbol.asyncDispose} for asynchronous\n * disposables.\n *\n * This is similar to {@link acquireRelease}, but uses the standard\n * JavaScript disposal protocol instead of requiring an explicit release\n * function. It works with JavaScript `Disposable` and `AsyncDisposable`\n * resources.\n *\n * **Example** (Acquiring a disposable resource)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * class Resource implements Disposable {\n * [Symbol.dispose]() {\n * void output.push(\"disposed\")\n * }\n * }\n *\n * const program = Effect.scoped(\n * Effect.gen(function*() {\n * yield* Effect.acquireDisposable(Effect.succeed(new Resource()))\n * void output.push(\"acquired\")\n * })\n * )\n *\n * Effect.runSync(program)\n * output // => [\"acquired\", \"disposed\"]\n * ```\n *\n * @see {@link acquireRelease} for resources that need an explicit finalizer\n *\n * @category resource management\n * @since 4.0.0\n */\nexport const acquireDisposable = internal.acquireDisposable;\n/**\n * Runs resource acquisition, usage, and release as one bracketed effect.\n *\n * **When to use**\n *\n * Use to bracket acquire, use, and release logic in one effect.\n *\n * **Details**\n *\n * `acquireUseRelease` does the following:\n *\n * 1. Ensures that the `Effect` value that acquires the resource will not be\n * interrupted. Note that acquisition may still fail due to internal\n * reasons (such as an uncaught exception).\n * 2. Ensures that the `release` `Effect` value will not be interrupted,\n * and will be executed as long as the acquisition `Effect` value\n * successfully acquires the resource.\n *\n * During the time period between the acquisition and release of the resource,\n * the `use` `Effect` value will be executed.\n *\n * If the `release` `Effect` value fails, then the entire `Effect` value will\n * fail, even if the `use` `Effect` value succeeds. If this fail-fast behavior\n * is not desired, errors produced by the `release` `Effect` value can be caught\n * and ignored.\n *\n * **Example** (Acquiring resources with cleanup)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit } from \"effect\"\n * const output: Array<unknown> = []\n *\n * interface Database {\n * readonly connection: string\n * readonly query: (sql: string) => Effect.Effect<string>\n * }\n *\n * const program = Effect.acquireUseRelease(\n * // Acquire - connect to database\n * Effect.gen(function*() {\n * yield* Effect.sync(() => { output.push(\"Connecting to database...\") })\n * return {\n * connection: \"db://localhost:5432\",\n * query: (sql: string) => Effect.succeed(`Result for: ${sql}`)\n * }\n * }),\n * // Use - perform database operations\n * (db) =>\n * Effect.gen(function*() {\n * yield* Effect.sync(() => { output.push(`Connected to ${db.connection}`) })\n * const result = yield* db.query(\"SELECT * FROM users\")\n * yield* Effect.sync(() => { output.push(`Query result: ${result}`) })\n * return result\n * }),\n * // Release - close database connection\n * (db, exit) =>\n * Effect.gen(function*() {\n * if (Exit.isSuccess(exit)) {\n * yield* Effect.sync(() => { output.push(`Closing connection to ${db.connection} (success)`) })\n * } else {\n * yield* Effect.sync(() => { output.push(`Closing connection to ${db.connection} (failure)`) })\n * }\n * })\n * )\n *\n * await Effect.runPromise(program)\n * output // => [\"Connecting to database...\", \"Connected to db://localhost:5432\", \"Query result: Result for: SELECT * FROM users\", \"Closing connection to db://localhost:5432 (success)\"]\n * ```\n *\n * @see {@link acquireRelease} for scoped resources whose use happens later\n *\n * @category resource management\n * @since 2.0.0\n */\nexport const acquireUseRelease = internal.acquireUseRelease;\n/**\n * Adds a finalizer to the current scope.\n *\n * **When to use**\n *\n * Use to register low-level cleanup in the current scope.\n *\n * **Details**\n *\n * The finalizer runs when the surrounding scope is closed and receives the\n * `Exit` value used to close the scope.\n *\n * **Example** (Registering scope finalizers)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.scoped(\n * Effect.gen(function*() {\n * // Add a finalizer that runs when the scope closes\n * yield* Effect.addFinalizer((exit) =>\n * Effect.sync(() => { output.push(\n * Exit.isSuccess(exit)\n * ? \"Cleanup: Operation completed successfully\"\n * : \"Cleanup: Operation failed, cleaning up resources\"\n * ) })\n * )\n *\n * yield* Effect.sync(() => { output.push(\"Performing main operation...\") })\n *\n * // This could succeed or fail\n * return \"operation result\"\n * })\n * )\n *\n * void output.push(Effect.runSync(program))\n * output // => [\"Performing main operation...\", \"Cleanup: Operation completed successfully\", \"operation result\"]\n * ```\n *\n * @see {@link acquireRelease} for resource acquisition with a release finalizer\n * @see {@link ensuring} for attaching a finalizer to one effect\n *\n * @category resource management\n * @since 2.0.0\n */\nexport const addFinalizer = internal.addFinalizer;\n/**\n * Returns an effect that, if this effect _starts_ execution, then the\n * specified `finalizer` is guaranteed to be executed, whether this effect\n * succeeds, fails, or is interrupted.\n *\n * **Details**\n *\n * For use cases that need access to the effect's result, see `onExit`.\n *\n * Finalizers offer very powerful guarantees, but they are low-level, and\n * should generally not be used for releasing resources. For higher-level\n * logic built on `ensuring`, see the `acquireRelease` family of methods.\n *\n * **Example** (Always running cleanup)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const task = Effect.gen(function*() {\n * yield* Effect.sync(() => { output.push(\"Task started\") })\n * yield* Effect.sync(() => { output.push(\"Task completed\") })\n * return 42\n * })\n *\n * // Ensure cleanup always runs, regardless of success or failure\n * const program = Effect.ensuring(\n * task,\n * Effect.sync(() => { output.push(\"Cleanup: This always runs!\") })\n * )\n *\n * void output.push(Effect.runSync(program))\n * output // => [\"Task started\", \"Task completed\", \"Cleanup: This always runs!\", 42]\n * ```\n *\n * @category resource management\n * @since 2.0.0\n */\nexport const ensuring = internal.ensuring;\n/**\n * Runs the specified effect if this effect fails, providing the error to the\n * effect if it exists. The provided effect will not be interrupted.\n *\n * **Example** (Running cleanup on failure)\n *\n * ```ts import.meta.vitest\n * import { Cause, Data, Effect, Exit } from \"effect\"\n * const output: Array<unknown> = []\n *\n * class TaskError extends Data.TaggedError(\"TaskError\")<{ readonly message: string }> {}\n *\n * const error = new TaskError({ message: \"Something went wrong\" })\n * const task = Effect.fail(error)\n *\n * const program = Effect.onError(\n * task,\n * (cause) => Effect.sync(() => { output.push(`Cleanup on error: ${Cause.squash(cause)}`) })\n * )\n *\n * void output.push(Effect.runSyncExit(program))\n * output // => [\"Cleanup on error: TaskError: Something went wrong\", Exit.fail(error)]\n * ```\n *\n * @category resource management\n * @since 2.0.0\n */\nexport const onError = internal.onError;\n/**\n * Runs the finalizer only when this effect fails and the `Cause` matches the\n * provided predicate.\n *\n * **Example** (Running cleanup for selected failures)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Exit } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const task = Effect.fail(\"boom\")\n *\n * const program = Effect.onErrorIf(\n * task,\n * Cause.hasFails,\n * (cause) =>\n * Effect.gen(function*() {\n * yield* Effect.sync(() => { output.push(`Cause: ${Cause.squash(cause)}`) })\n * })\n * )\n *\n * void output.push(Effect.runSyncExit(program))\n * output // => [\"Cause: boom\", Exit.fail(\"boom\")]\n * ```\n *\n * @category resource management\n * @since 4.0.0\n */\nexport const onErrorIf = internal.onErrorIf;\n/**\n * Runs the finalizer only when this effect fails and the cause matches the provided `Filter`.\n *\n * **When to use**\n *\n * Use when cleanup or diagnostics should run only for failures whose full\n * `Cause` is accepted or transformed by a `Filter`, and the finalizer needs the\n * filter's pass value plus the original cause.\n *\n * @see {@link onError} for cleanup on every failure\n * @see {@link onErrorIf} for selecting failures with a boolean predicate\n * @see {@link onExitFilter} for selecting from every exit instead of only failures\n *\n * @category resource management\n * @since 4.0.0\n */\nexport const onErrorFilter = internal.onErrorFilter;\n/**\n * Runs an optional finalizer with the effect's `Exit` value when the effect\n * completes.\n *\n * **When to use**\n *\n * Use when you are building a low-level `Effect` operator that must inspect the\n * source effect's `Exit`, may skip finalization by returning `undefined`, or\n * must choose whether finalization is forced into an uninterruptible region.\n *\n * **Details**\n *\n * This low-level operator preserves the source effect's result unless the\n * finalizer fails. If both the source effect and the finalizer fail, the two\n * causes are merged. Prefer `onExit` for normal cleanup logic.\n *\n * @see {@link onExit} for ordinary exit-aware cleanup whose finalizer always returns an effect\n *\n * @category resource management\n * @since 4.0.0\n */\nexport const onExitPrimitive = internal.onExitPrimitive;\n/**\n * Ensures that a cleanup function runs whether this effect succeeds, fails, or\n * is interrupted.\n *\n * **Details**\n *\n * If both the effect and the cleanup function fail, the two causes are merged.\n *\n * **Example** (Observing every exit)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const task = Effect.succeed(42)\n *\n * const program = Effect.onExit(task, (exit) =>\n * Effect.sync(() => { output.push(\n * Exit.isSuccess(exit)\n * ? `Task succeeded with: ${exit.value}`\n * : `Task failed: ${Exit.isFailure(exit) ? exit.cause : \"interrupted\"}`\n * ) }))\n *\n * void output.push(Effect.runSync(program))\n * output // => [\"Task succeeded with: 42\", 42]\n * ```\n *\n * @category resource management\n * @since 2.0.0\n */\nexport const onExit = internal.onExit;\n/**\n * Runs the cleanup effect only when the `Exit` satisfies the provided\n * predicate.\n *\n * **Example** (Observing selected exits)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.onExitIf(\n * Effect.succeed(42),\n * Exit.isSuccess,\n * (exit) =>\n * Exit.isSuccess(exit)\n * ? Effect.sync(() => { output.push(`Succeeded with: ${exit.value}`) })\n * : Effect.void\n * )\n *\n * void output.push(Effect.runSync(program))\n * output // => [\"Succeeded with: 42\", 42]\n * ```\n *\n * @category resource management\n * @since 4.0.0\n */\nexport const onExitIf = internal.onExitIf;\n/**\n * Runs the cleanup effect only when the `Exit` matches the provided `Filter`.\n *\n * **When to use**\n *\n * Use when cleanup should run only for `Exit` values selected by a `Filter`,\n * and the cleanup needs the extracted pass value together with the original\n * `Exit`.\n *\n * **Details**\n *\n * `Result.fail` skips cleanup, and `Result.succeed` runs cleanup with the\n * selected value and the original `Exit`.\n *\n * @see {@link onExit} for cleanup on every exit\n * @see {@link onExitIf} for selecting exits with a boolean predicate\n * @see {@link onErrorFilter} for selecting only failure causes\n *\n * @category resource management\n * @since 4.0.0\n */\nexport const onExitFilter = internal.onExitFilter;\n// -----------------------------------------------------------------------------\n// Caching\n// -----------------------------------------------------------------------------\n/**\n * Returns an effect that lazily computes a result and caches it for subsequent\n * evaluations.\n *\n * **When to use**\n *\n * Use when you need an expensive or time-consuming operation to be evaluated\n * once and reused by later callers.\n *\n * **Details**\n *\n * This function wraps an effect and ensures that its result is computed only\n * once. Once the result is computed, it is cached, meaning that subsequent\n * evaluations of the same effect will return the cached result without\n * re-executing the logic.\n *\n * **Example** (Memoizing an effect until invalidated)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n * const record = (value: unknown) => Effect.sync(() => { output.push(value) })\n *\n * let i = 1\n * const expensiveTask = Effect.sync(() => {\n * void output.push(\"expensive task...\")\n * return `result ${i++}`\n * })\n *\n * const program = Effect.gen(function*() {\n * void output.push(\"non-cached version:\")\n * yield* expensiveTask.pipe(Effect.andThen(record))\n * yield* expensiveTask.pipe(Effect.andThen(record))\n * void output.push(\"cached version:\")\n * const cached = yield* Effect.cached(expensiveTask)\n * yield* cached.pipe(Effect.andThen(record))\n * yield* cached.pipe(Effect.andThen(record))\n * })\n *\n * await Effect.runPromise(program)\n * output // => [\"non-cached version:\", \"expensive task...\", \"result 1\", \"expensive task...\", \"result 2\", \"cached version:\", \"expensive task...\", \"result 3\", \"result 3\"]\n * ```\n *\n * @see {@link cachedWithTTL} for a similar function that includes a\n * time-to-live duration for the cached value.\n * @see {@link cachedInvalidateWithTTL} for a similar function that includes an\n * additional effect for manually invalidating the cached value.\n * @category caching\n * @since 2.0.0\n */\nexport const cached = internal.cached;\n/**\n * Returns an effect that caches its result for a fixed duration or a duration\n * computed from its `Exit`, known as \"timeToLive\" (TTL).\n *\n * **When to use**\n *\n * Use when you need a costly effect result to be reused for a bounded duration\n * before being recomputed.\n *\n * **Details**\n *\n * This function is used to cache the result of an effect for a specified amount\n * of time. This means that the first time the effect is evaluated, its result\n * is computed and stored.\n *\n * If the effect is evaluated again within the specified `timeToLive`, the\n * cached result will be used, avoiding recomputation.\n *\n * After the specified duration has passed, the cache expires, and the effect\n * will be recomputed upon the next evaluation.\n *\n * `timeToLive` accepts a `Duration.Input` or a function from `Exit<A, E>` to\n * `Duration.Input`. The function runs once after each fresh computation,\n * including failures, so successes and failures can have different TTLs. It\n * does not run when the cache is created or when a cached result is reused.\n * The callback also receives interruption exits, which are cached for the\n * returned duration.\n *\n * The TTL starts when the computation completes. Concurrent callers share the\n * pending computation. A zero TTL expires immediately, and an infinite TTL\n * keeps the result indefinitely.\n *\n * **Example** (Memoizing an effect with TTL)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n * const record = (value: unknown) => Effect.sync(() => { output.push(value) })\n *\n * let i = 1\n * const expensiveTask = Effect.sync(() => {\n * void output.push(\"expensive task...\")\n * return `result ${i++}`\n * })\n *\n * const program = Effect.gen(function*() {\n * const cached = yield* Effect.cachedWithTTL(expensiveTask, \"1 hour\")\n * yield* cached.pipe(Effect.andThen(record))\n * yield* cached.pipe(Effect.andThen(record))\n * yield* cached.pipe(Effect.andThen(record))\n * })\n *\n * Effect.runSync(program)\n * output // => [\"expensive task...\", \"result 1\", \"result 1\", \"result 1\"]\n * ```\n *\n * **Example** (Caching successes while retrying failures)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit } from \"effect\"\n *\n * let attempts = 0\n * const task = Effect.suspend(() =>\n * ++attempts === 1 ? Effect.fail(\"temporary failure\") : Effect.succeed(42)\n * )\n * const program = Effect.gen(function*() {\n * const cached = yield* task.pipe(\n * Effect.cachedWithTTL((exit) => Exit.isSuccess(exit) ? \"1 hour\" : 0)\n * )\n * yield* Effect.exit(cached)\n * return yield* cached\n * })\n *\n * Effect.runSync(program) // => 42\n * ```\n *\n * @see {@link cached} for a similar function that caches the result\n * indefinitely.\n * @see {@link cachedInvalidateWithTTL} for a similar function that includes an\n * additional effect for manually invalidating the cached value.\n * @category caching\n * @since 2.0.0\n */\nexport const cachedWithTTL = internal.cachedWithTTL;\n/**\n * Creates a cached effect result for a specified duration and allows manual\n * invalidation before expiration.\n *\n * **When to use**\n *\n * Use when an effect result should be cached for a bounded time and callers\n * also need a manual invalidation effect to force recomputation before\n * expiration.\n *\n * **Details**\n *\n * This function behaves similarly to {@link cachedWithTTL} by caching the\n * result of an effect for a specified period of time. However, it introduces an\n * additional feature: it provides an effect that allows you to manually\n * invalidate the cached result before it naturally expires.\n *\n * This gives you more control over the cache, allowing you to refresh the\n * result when needed, even if the original cache has not yet expired.\n *\n * Once the cache is invalidated, the next time the effect is evaluated, the\n * result will be recomputed, and the cache will be refreshed.\n *\n * **Example** (Memoizing with TTL and invalidation)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n * const record = (value: unknown) => Effect.sync(() => { output.push(value) })\n *\n * let i = 1\n * const expensiveTask = Effect.sync(() => {\n * void output.push(\"expensive task...\")\n * return `result ${i++}`\n * })\n *\n * const program = Effect.gen(function*() {\n * const [cached, invalidate] = yield* Effect.cachedInvalidateWithTTL(\n * expensiveTask,\n * \"1 hour\"\n * )\n * yield* cached.pipe(Effect.andThen(record))\n * yield* cached.pipe(Effect.andThen(record))\n * yield* invalidate\n * yield* cached.pipe(Effect.andThen(record))\n * })\n *\n * Effect.runSync(program)\n * output // => [\"expensive task...\", \"result 1\", \"result 1\", \"expensive task...\", \"result 2\"]\n * ```\n *\n * @see {@link cached} for a similar function that caches the result\n * indefinitely.\n * @see {@link cachedWithTTL} for a similar function that caches the result for\n * a specified duration but does not include an effect for manual invalidation.\n * @category caching\n * @since 2.0.0\n */\nexport const cachedInvalidateWithTTL = internal.cachedInvalidateWithTTL;\n// -----------------------------------------------------------------------------\n// Interruption\n// -----------------------------------------------------------------------------\n/**\n * Returns an effect that is immediately interrupted.\n *\n * **Example** (Creating an interrupted effect)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * return yield* Effect.interrupt\n * yield* Effect.succeed(\"This won't execute and is unreachable\")\n * })\n *\n * Effect.runSyncExit(program)._tag // => \"Failure\"\n * ```\n *\n * @category interruption\n * @since 2.0.0\n */\nexport const interrupt = internal.interrupt;\n/**\n * Returns a new effect that allows the effect to be interruptible.\n *\n * **Example** (Allowing interruption)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option } from \"effect\"\n *\n * const program = Effect.interruptible(Effect.never).pipe(\n * Effect.timeoutOption(0)\n * )\n * await Effect.runPromise(program) // => Option.none()\n * ```\n *\n * @category interruption\n * @since 2.0.0\n */\nexport const interruptible = internal.interruptible;\n/**\n * Runs the specified finalizer effect if this effect is interrupted.\n *\n * **Example** (Running cleanup on interruption)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const task = Effect.forever(Effect.succeed(\"working...\"))\n *\n * const program = Effect.onInterrupt(\n * task,\n * () => Effect.sync(() => { output.push(\"Task was interrupted, cleaning up...\") })\n * )\n *\n * const fiber = Effect.runFork(program)\n * await Effect.runPromise(Fiber.interrupt(fiber))\n * output // => [\"Task was interrupted, cleaning up...\"]\n * ```\n *\n * @category interruption\n * @since 2.0.0\n */\nexport const onInterrupt = internal.onInterrupt;\n/**\n * Returns a new effect that disables interruption for the given effect.\n *\n * **Example** (Preventing interruption)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const criticalTask = Effect.gen(function*() {\n * yield* Effect.sync(() => { output.push(\"Starting critical section...\") })\n * yield* Effect.sync(() => { output.push(\"Critical section completed\") })\n * })\n *\n * const program = Effect.uninterruptible(criticalTask)\n *\n * Effect.runSync(program)\n * output // => [\"Starting critical section...\", \"Critical section completed\"]\n * ```\n *\n * @category interruption\n * @since 2.0.0\n */\nexport const uninterruptible = internal.uninterruptible;\n/**\n * Disables interruption and provides a restore function to restore the\n * interruptible state within the effect.\n *\n * **Example** (Restoring interruption in protected regions)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.uninterruptibleMask((restore) =>\n * Effect.gen(function*() {\n * yield* Effect.sync(() => { output.push(\"Uninterruptible phase...\") })\n * // Restore interruptibility for this part\n * yield* restore(\n * Effect.gen(function*() {\n * yield* Effect.sync(() => { output.push(\"Interruptible phase...\") })\n * })\n * )\n *\n * yield* Effect.sync(() => { output.push(\"Back to uninterruptible\") })\n * })\n * )\n *\n * Effect.runSync(program)\n * output // => [\"Uninterruptible phase...\", \"Interruptible phase...\", \"Back to uninterruptible\"]\n * ```\n *\n * @category interruption\n * @since 2.0.0\n */\nexport const uninterruptibleMask = internal.uninterruptibleMask;\n/**\n * Runs an effect in an interruptible region while providing `restore` for\n * locally restoring the previous interruptibility.\n *\n * **Example** (Controlling interruptibility locally)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.interruptibleMask((restore) =>\n * Effect.gen(function*() {\n * yield* Effect.sync(() => { output.push(\"Interruptible phase...\") })\n * // Make this part uninterruptible\n * yield* restore(\n * Effect.gen(function*() {\n * yield* Effect.sync(() => { output.push(\"Uninterruptible phase...\") })\n * })\n * )\n *\n * yield* Effect.sync(() => { output.push(\"Back to interruptible\") })\n * })\n * )\n *\n * Effect.runSync(program)\n * output // => [\"Interruptible phase...\", \"Uninterruptible phase...\", \"Back to interruptible\"]\n * ```\n *\n * @category interruption\n * @since 2.0.0\n */\nexport const interruptibleMask = internal.interruptibleMask;\n/**\n * Creates an AbortSignal that is managed by the provided scope.\n *\n * **When to use**\n *\n * Use to obtain a scope-managed `AbortSignal` for APIs that accept cancellation\n * through a signal.\n *\n * **Details**\n *\n * Each acquisition creates a fresh `AbortController`. Closing the owning scope\n * runs a finalizer that aborts the controller and the effect succeeds with the\n * controller's signal.\n *\n * **Gotchas**\n *\n * The signal is aborted when its owning scope closes, so avoid keeping it for\n * work that outlives that scope.\n *\n * @see {@link scoped} for binding resource lifetime to a scope\n *\n * @category interruption\n * @since 4.0.0\n */\nexport const abortSignal = internal.abortSignal;\n/**\n * Repeats this effect forever (until the first error).\n *\n * **Example** (Repeating forever)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option } from \"effect\"\n *\n * const program = Effect.forever(Effect.never).pipe(Effect.timeoutOption(0))\n * await Effect.runPromise(program) // => Option.none()\n * ```\n *\n * @category repetition\n * @since 2.0.0\n */\nexport const forever = internal.forever;\n/**\n * Repeats an effect based on a specified schedule or until the first failure.\n *\n * **When to use**\n *\n * Use to rerun an effect after successful executions.\n *\n * **Details**\n *\n * This function executes an effect repeatedly according to the given schedule.\n * Each repetition occurs after the initial execution of the effect, meaning\n * that the schedule determines the number of additional repetitions. For\n * example, using `Schedule.once` will result in the effect being executed twice\n * (once initially and once as part of the repetition).\n *\n * If the effect succeeds, it is repeated according to the schedule. If it\n * fails, the repetition stops immediately, and the failure is returned.\n *\n * The schedule can also specify delays between repetitions, making it useful\n * for tasks like retrying operations with backoff, periodic execution, or\n * performing a series of dependent actions.\n *\n * You can combine schedules for more advanced repetition logic, such as adding\n * delays, limiting recursions, or dynamically adjusting based on the outcome of\n * each execution.\n *\n * **Gotchas**\n *\n * The source effect is always evaluated once before the schedule is stepped.\n * The schedule controls additional repetitions, not the initial execution.\n *\n * **Example** (Repeating successful effects with a schedule)\n *\n * ```ts import.meta.vitest\n * // Success Example\n * import { Effect, Schedule } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const action = Effect.sync(() => { output.push(\"success\") })\n * const policy = Schedule.recurs(2)\n * const program = Effect.repeat(action, policy)\n *\n * void output.push(Effect.runSync(program))\n * output // => [\"success\", \"success\", \"success\", 2]\n * ```\n *\n * **Example** (Stopping repetition on failure)\n *\n * ```ts import.meta.vitest\n * // Failure Example\n * import { Effect, Schedule } from \"effect\"\n * const output: Array<unknown> = []\n *\n * let count = 0\n *\n * // Define a callback effect that simulates an action with possible failures\n * const action = Effect.callback<string, string>((resume) => {\n * if (count > 1) {\n * void output.push(\"failure\")\n * resume(Effect.fail(\"Uh oh!\"))\n * } else {\n * count++\n * void output.push(\"success\")\n * resume(Effect.succeed(\"yay!\"))\n * }\n * })\n *\n * const policy = Schedule.recurs(2)\n * const program = Effect.repeat(action, policy)\n *\n * void output.push((await Effect.runPromiseExit(program))._tag)\n * output // => [\"success\", \"success\", \"failure\", \"Failure\"]\n * ```\n *\n * @see {@link retry} for failure-based repetition\n * @see {@link repeatOrElse} for fallback handling when repetition fails\n *\n * @category repetition\n * @since 2.0.0\n */\nexport const repeat = internalSchedule.repeat;\n/**\n * Repeats an effect according to a schedule and runs a fallback effect if\n * repetition fails before the schedule completes.\n *\n * **When to use**\n *\n * Use when successful repetitions should follow a schedule, but failures from\n * the repeated effect or schedule need an effectful fallback.\n *\n * **Details**\n *\n * If the repeated effect or schedule step fails, `orElse` receives the failure\n * and the latest schedule metadata when at least one schedule step has run;\n * otherwise it receives `None`. If the schedule completes normally, the\n * returned effect succeeds with the schedule's output.\n *\n * **Example** (Recovering after repetition stops)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, Schedule } from \"effect\"\n * const output: Array<unknown> = []\n *\n * let attempt = 0\n * const task = Effect.gen(function*() {\n * attempt++\n * if (attempt <= 2) {\n * yield* Effect.sync(() => { output.push(`Attempt ${attempt} failed`) })\n * return yield* Effect.fail(`Error ${attempt}`)\n * }\n * yield* Effect.sync(() => { output.push(`Attempt ${attempt} succeeded`) })\n * return \"success\"\n * })\n *\n * const program = Effect.repeatOrElse(\n * task,\n * Schedule.recurs(3),\n * (error, previous) =>\n * Effect.sync(() => { output.push(\n * `Final failure: ${error}, after ${\n * Option.isSome(previous) ? previous.value.attempt : 0\n * } attempts`\n * ) }).pipe(Effect.map(() => 0))\n * )\n *\n * void output.push(Effect.runSync(program))\n * output // => [\"Attempt 1 failed\", \"Final failure: Error 1, after 0 attempts\", 0]\n * ```\n *\n * @category repetition\n * @since 2.0.0\n */\nexport const repeatOrElse = internalSchedule.repeatOrElse;\n/**\n * Returns an array of `n` identical effects.\n *\n * **When to use**\n *\n * Use when you need an array of identical effect values without running them\n * yet.\n *\n * **Details**\n *\n * This only creates the array of effects. It does not run or collect them.\n *\n * @see {@link all} for running the returned effects and collecting results\n * @see {@link replicateEffect} for repeating an effect and collecting results in one step with concurrency and discard options\n *\n * @category repetition\n * @since 2.0.0\n */\nexport const replicate = internal.replicate;\n/**\n * Performs this effect `n` times and collects results with `Effect.all` semantics.\n *\n * **When to use**\n *\n * Use when you want to run the repeated effects immediately, with optional\n * concurrency control or result discarding.\n *\n * **Details**\n *\n * Use `concurrency` to control parallelism and `discard: true` to ignore results.\n *\n * **Example** (Replicating an effect)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.gen(function*() {\n * const results = yield* Effect.replicateEffect(3)(Effect.succeed(1))\n * yield* Effect.sync(() => { output.push(results) })\n * })\n *\n * Effect.runSync(program)\n * output // => [[1, 1, 1]]\n * ```\n *\n * @category repetition\n * @since 2.0.0\n */\nexport const replicateEffect = internal.replicateEffect;\n/**\n * Runs an effect repeatedly according to a schedule and returns the schedule's\n * final output.\n *\n * **When to use**\n *\n * Use to rerun a successful effect according to a `Schedule` when the schedule\n * does not need a custom initial input.\n *\n * **Details**\n *\n * The schedule is first stepped with `undefined`. After each successful\n * execution, the effect's success value is fed to the schedule to decide\n * whether to run again. The returned effect fails if the effect or schedule\n * fails, and otherwise succeeds with the schedule output when the schedule\n * completes.\n *\n * **Example** (Scheduling repeated execution)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schedule } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const task = Effect.gen(function*() {\n * yield* Effect.sync(() => { output.push(\"Task executing...\") })\n * return 1\n * })\n *\n * const program = Effect.schedule(task, Schedule.recurs(2))\n *\n * void output.push(Effect.runSync(program))\n * output // => [\"Task executing...\", \"Task executing...\", 2]\n * ```\n *\n * @see {@link scheduleFrom} for a variant that allows the schedule's decision\n * to depend on the result of this effect.\n *\n * @category repetition\n * @since 2.0.0\n */\nexport const schedule = /*#__PURE__*/dual(2, (self, schedule) => scheduleFrom(self, undefined, schedule));\n/**\n * Runs an effect repeatedly according to a schedule that is initialized with a\n * specific schedule input.\n *\n * **Details**\n *\n * `initial` is passed to the schedule before the first execution, not to the\n * effect itself. After each successful execution, the effect's success value is\n * fed back into the schedule to decide whether to continue. The returned effect\n * succeeds with the schedule output when the schedule completes and fails if\n * the effect or schedule fails.\n *\n * **Example** (Scheduling from an initial value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schedule } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const task = (input: number) =>\n * Effect.gen(function*() {\n * yield* Effect.sync(() => { output.push(`Processing: ${input}`) })\n * return input + 1\n * })\n *\n * // Start with 0, repeat 3 times\n * const program = Effect.scheduleFrom(\n * task(0),\n * 0,\n * Schedule.recurs(2)\n * )\n *\n * void output.push(Effect.runSync(program))\n * output // => [\"Processing: 0\", \"Processing: 0\", 2]\n * ```\n *\n * @category repetition\n * @since 2.0.0\n */\nexport const scheduleFrom = internalSchedule.scheduleFrom;\n// -----------------------------------------------------------------------------\n// Tracing\n// -----------------------------------------------------------------------------\n/**\n * Returns the current tracer from the context.\n *\n * **Example** (Accessing the current tracer)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const currentTracer = yield* Effect.tracer\n * return typeof currentTracer.span\n * })\n *\n * Effect.runSync(program) // => \"function\"\n * ```\n *\n * @category tracing\n * @since 2.0.0\n */\nexport const tracer = internal.tracer;\n/**\n * Provides a tracer to an effect.\n *\n * **Example** (Providing a tracer)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const tracer = yield* Effect.tracer\n * return yield* Effect.withTracer(Effect.succeed(\"completed\"), tracer)\n * })\n *\n * Effect.runSync(program) // => \"completed\"\n * ```\n *\n * @category tracing\n * @since 2.0.0\n */\nexport const withTracer = internal.withTracer;\n/**\n * Enables or disables tracing for spans created by the given effect.\n *\n * **Details**\n *\n * When `enabled` is `false`, spans created inside the effect are not registered\n * with the current tracer and do not propagate as normal trace parents.\n *\n * **Example** (Enabling or disabling tracing)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const program = Effect.succeed(42).pipe(\n * Effect.withSpan(\"my-span\"),\n * // the span will not be registered with the tracer\n * Effect.withTracerEnabled(false)\n * )\n * Effect.runSync(program) // => 42\n * ```\n *\n * @category tracing\n * @since 2.0.0\n */\nexport const withTracerEnabled = internal.withTracerEnabled;\n/**\n * Enables or disables tracer timing for the given Effect.\n *\n * **Example** (Enabling or disabling tracing timing)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const program = Effect.succeed(42).pipe(\n * Effect.withSpan(\"my-span\"),\n * // the span will not have timing information\n * Effect.withTracerTiming(false)\n * )\n * Effect.runSync(program) // => 42\n * ```\n *\n * @category tracing\n * @since 2.0.0\n */\nexport const withTracerTiming = internal.withTracerTiming;\n/**\n * Adds an annotation to each span in this effect.\n *\n * **Example** (Annotating all spans)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const program = Effect.succeed(\"result\")\n *\n * // Add single annotation\n * const annotated1 = Effect.annotateSpans(program, \"user\", \"john\")\n *\n * // Add multiple annotations\n * const annotated2 = Effect.annotateSpans(program, {\n * operation: \"data-processing\",\n * version: \"1.0.0\",\n * environment: \"production\"\n * })\n *\n * Effect.runSync(Effect.all([annotated1, annotated2])) // => ['result', 'result']\n * ```\n *\n * @category tracing\n * @since 2.0.0\n */\nexport const annotateSpans = internal.annotateSpans;\n/**\n * Adds an annotation to the current span if available.\n *\n * **Example** (Annotating the current span)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * yield* Effect.annotateCurrentSpan(\"userId\", \"123\")\n * yield* Effect.annotateCurrentSpan({\n * operation: \"user-lookup\"\n * })\n * return \"success\"\n * })\n *\n * const traced = Effect.withSpan(program, \"user-operation\")\n * Effect.runSync(traced) // => \"success\"\n * ```\n *\n * @category tracing\n * @since 2.0.0\n */\nexport const annotateCurrentSpan = internal.annotateCurrentSpan;\n/**\n * Returns the currently active local tracing span.\n *\n * **Details**\n *\n * The effect fails with `NoSuchElementError` when there is no active local\n * `Span`.\n *\n * **Example** (Reading the current span)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const span = yield* Effect.currentSpan\n * return span.name\n * })\n *\n * const traced = Effect.withSpan(program, \"my-span\")\n * Effect.runSync(traced) // => \"my-span\"\n * ```\n *\n * @category tracing\n * @since 2.0.0\n */\nexport const currentSpan = internal.currentSpan;\n/**\n * Returns the current parent span from the effect context.\n *\n * **Details**\n *\n * The effect succeeds with either a local span or external span when one is\n * present, and fails with `NoSuchElementError` when no parent span is\n * available.\n *\n * **Example** (Reading the parent span)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const childOperation = Effect.gen(function*() {\n * const parentSpan = yield* Effect.currentParentSpan\n * return parentSpan._tag\n * })\n *\n * const program = Effect.withSpan(childOperation, \"child-span\")\n *\n * const traced = Effect.withSpan(program, \"parent-span\")\n * Effect.runSync(traced) // => \"Span\"\n * ```\n *\n * @category tracing\n * @since 2.0.0\n */\nexport const currentParentSpan = internal.currentParentSpan;\n/**\n * Returns the tracing span annotations currently carried in the effect context.\n *\n * **Details**\n *\n * These annotations are applied to spans created inside the context, such as\n * spans created by `withSpan`, `useSpan`, or `makeSpan`.\n *\n * **Example** (Providing span annotations)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const annotations = yield* Effect.spanAnnotations\n * return annotations\n * }).pipe(Effect.annotateSpans({ userId: \"123\", operation: \"data-processing\" }))\n *\n * Effect.runSync(program) // => { userId: '123', operation: 'data-processing' }\n * ```\n *\n * @category tracing\n * @since 2.0.0\n */\nexport const spanAnnotations = internal.spanAnnotations;\n/**\n * Returns the tracing span links currently carried in the effect context.\n *\n * **Details**\n *\n * These links are attached to spans created inside the context. Span links\n * connect related spans without making one span the parent of another.\n *\n * **Example** (Providing span links)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * // Get the current span links\n * const links = yield* Effect.spanLinks\n * return links\n * })\n *\n * Effect.runSync(program).length // => 0\n * ```\n *\n * @category tracing\n * @since 2.0.0\n */\nexport const spanLinks = internal.spanLinks;\n/**\n * Adds a link with the provided span to all spans in this effect.\n *\n * **Details**\n *\n * This is useful for connecting spans that are related but not in a direct\n * parent-child relationship. For example, you might want to link spans from\n * parallel operations or connect spans across different traces.\n *\n * **Example** (Linking one span to another span)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const program = Effect.withSpan(Effect.gen(function*() {\n * const parentSpan = yield* Effect.currentSpan\n * return yield* Effect.spanLinks.pipe(\n * Effect.linkSpans(parentSpan, { relationship: \"follows\" })\n * )\n * }), \"parent-operation\")\n *\n * Effect.runSync(program).length // => 1\n * ```\n *\n * **Example** (Linking multiple spans at once)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const span1 = yield* Effect.makeSpan(\"span-1\")\n * const span2 = yield* Effect.makeSpan(\"span-2\")\n *\n * return yield* Effect.spanLinks.pipe(\n * Effect.linkSpans([span1, span2], {\n * type: \"dependency\",\n * source: \"multiple-operations\"\n * })\n * )\n * })\n *\n * Effect.runSync(program).length // => 2\n * ```\n *\n * @category tracing\n * @since 2.0.0\n */\nexport const linkSpans = internal.linkSpans;\n/**\n * Creates a new tracing span and returns it without managing its lifetime.\n *\n * **Details**\n *\n * The span is not added to the current span stack and is not ended\n * automatically. Use `withSpan`, `useSpan`, or `makeSpanScoped` when the span\n * should be installed as context or closed automatically.\n *\n * **Example** (Creating a span manually)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const span = yield* Effect.makeSpan(\"my-operation\")\n * return span.name\n * })\n *\n * Effect.runSync(program) // => \"my-operation\"\n * ```\n *\n * @category tracing\n * @since 2.0.0\n */\nexport const makeSpan = internal.makeSpan;\n/**\n * Create a new span for tracing, and automatically close it when the Scope\n * finalizes.\n *\n * **Details**\n *\n * The span is not added to the current span stack, so no child spans will be\n * created for it.\n *\n * **Example** (Creating a scoped standalone span)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const program = Effect.scoped(\n * Effect.gen(function*() {\n * const span = yield* Effect.makeSpanScoped(\"scoped-operation\")\n * return span.name\n * // Span automatically closes when scope ends\n * })\n * )\n *\n * Effect.runSync(program) // => \"scoped-operation\"\n * ```\n *\n * @category tracing\n * @since 2.0.0\n */\nexport const makeSpanScoped = internal.makeSpanScoped;\n/**\n * Create a new span for tracing, and automatically close it when the effect\n * completes.\n *\n * **Details**\n *\n * The span is not added to the current span stack, so no child spans will be\n * created for it.\n *\n * **Example** (Running an effect with a standalone span)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const program = Effect.useSpan(\n * \"user-operation\",\n * (span) => Effect.succeed(`${span.name}: success`)\n * )\n * Effect.runSync(program) // => \"user-operation: success\"\n * ```\n *\n * @category tracing\n * @since 2.0.0\n */\nexport const useSpan = internal.useSpan;\n/**\n * Wraps the effect with a child span for tracing.\n *\n * **Example** (Wrapping an effect in a child span)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const task = Effect.succeed(\"result\")\n *\n * const traced = Effect.withSpan(task, \"my-task\", {\n * attributes: { version: \"1.0\" }\n * })\n * Effect.runSync(traced) // => \"result\"\n * ```\n *\n * @category tracing\n * @since 2.0.0\n */\nexport const withSpan = internal.withSpan;\n/**\n * Wraps the effect with a scoped child span for tracing.\n *\n * **Details**\n *\n * The span is ended when the Scope is finalized.\n *\n * **Example** (Creating a scoped child span)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const program = Effect.scoped(\n * Effect.gen(function*() {\n * const task = Effect.succeed(\"working\")\n * yield* Effect.withSpanScoped(task, \"scoped-task\")\n * return \"completed\"\n * })\n * )\n * Effect.runSync(program) // => \"completed\"\n * ```\n *\n * @category tracing\n * @since 2.0.0\n */\nexport const withSpanScoped = internal.withSpanScoped;\n/**\n * Adds the provided span to the current span stack.\n *\n * **Example** (Setting a parent span)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const span = yield* Effect.makeSpan(\"parent-span\")\n * const childTask = Effect.succeed(\"child operation\")\n * yield* Effect.withParentSpan(childTask, span)\n * return \"completed\"\n * })\n * Effect.runSync(program) // => \"completed\"\n * ```\n *\n * @category tracing\n * @since 2.0.0\n */\nexport const withParentSpan = internal.withParentSpan;\n// -----------------------------------------------------------------------------\n// Batching\n// -----------------------------------------------------------------------------\n/**\n * Executes a request using the provided resolver.\n *\n * **When to use**\n *\n * Use when you need resolver-driven batching for a typed `Request`.\n *\n * **Example** (Executing a request through a resolver)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Request, RequestResolver } from \"effect\"\n * const output: Array<unknown> = []\n *\n * interface GetUser extends Request.Request<string> {\n * readonly _tag: \"GetUser\"\n * readonly id: number\n * }\n * const GetUser = Request.tagged<GetUser>(\"GetUser\")\n *\n * const resolver = RequestResolver.make<GetUser>(\n * Effect.fnUntraced(function*(entries) {\n * for (const entry of entries) {\n * yield* Request.complete(entry, Exit.succeed(`user-${entry.request.id}`))\n * }\n * })\n * )\n *\n * const program = Effect.gen(function*() {\n * const name = yield* Effect.request(GetUser({ id: 1 }), resolver)\n * yield* Effect.sync(() => { output.push(name) })\n * })\n *\n * await Effect.runPromise(program)\n * output // => [\"user-1\"]\n * ```\n *\n * @see {@link requestUnsafe} for the low-level entry point when you already have a `Context` and need to enqueue outside an `Effect`\n *\n * @category running\n * @since 2.0.0\n */\nexport const request = internalRequest.request;\n/**\n * Registers a request with a resolver and delivers the exit value via `onExit`.\n *\n * **When to use**\n *\n * Use when you already have a `Context` and need to enqueue a request outside\n * an `Effect` while receiving completion through `onExit`.\n *\n * **Details**\n *\n * It returns a canceler that removes the pending request entry.\n *\n * @see {@link request} for the `Effect`-returning API used for normal request execution\n *\n * @category unsafe\n * @since 4.0.0\n */\nexport const requestUnsafe = internalRequest.requestUnsafe;\n// -----------------------------------------------------------------------------\n// Supervision & Fiber's\n// -----------------------------------------------------------------------------\n/**\n * Returns an effect that forks this effect into its own separate fiber,\n * returning the fiber immediately, without waiting for it to begin executing\n * the effect.\n *\n * **Details**\n *\n * You can use the `forkChild` method whenever you want to execute an effect in a\n * new fiber, concurrently and without \"blocking\" the fiber executing other\n * effects. Using fibers can be tricky, so instead of using this method\n * directly, consider other higher-level methods, such as `raceWith`,\n * `zipPar`, and so forth.\n *\n * The fiber returned by this method has methods to interrupt the fiber and to\n * wait for it to finish executing the effect. See `Fiber` for more\n * information.\n *\n * Whenever you use this method to launch a new fiber, the new fiber is\n * attached to the parent fiber's scope. This means when the parent fiber\n * terminates, the child fiber will be terminated as well, ensuring that no\n * fibers leak. This behavior is called \"auto supervision\", and if this\n * behavior is not desired, you may use the `forkDetach` or `forkIn` methods.\n *\n * **Example** (Forking a child fiber)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber } from \"effect\"\n *\n * const task = Effect.succeed(\"result\")\n *\n * const program = Effect.gen(function*() {\n * const fiber = yield* task.pipe(Effect.forkChild)\n * const result = yield* Fiber.join(fiber)\n * return result\n * })\n *\n * await Effect.runPromise(program) // => \"result\"\n * ```\n *\n * @category forking\n * @since 4.0.0\n */\nexport const forkChild = internal.forkChild;\n/**\n * Forks the effect in the specified scope. The fiber will be interrupted\n * when the scope is closed.\n *\n * **Example** (Forking into a supplied scope)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const task = Effect.never\n *\n * const program = Effect.scoped(\n * Effect.gen(function*() {\n * const scope = yield* Effect.scope\n * const fiber = yield* Effect.forkIn(task, scope)\n * // Fiber will be interrupted when scope closes\n * return \"done\"\n * })\n * )\n *\n * await Effect.runPromise(program) // => \"done\"\n * ```\n *\n * @category forking\n * @since 2.0.0\n */\nexport const forkIn = internal.forkIn;\n/**\n * Forks the fiber in a `Scope`, interrupting it when the scope is closed.\n *\n * **Example** (Forking into the current scope)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const backgroundTask = Effect.never\n *\n * const program = Effect.scoped(\n * Effect.gen(function*() {\n * yield* backgroundTask.pipe(Effect.forkScoped)\n *\n * // Fiber will be interrupted when scope closes\n * return \"scope completed\"\n * })\n * )\n *\n * await Effect.runPromise(program) // => \"scope completed\"\n * ```\n *\n * @category forking\n * @since 2.0.0\n */\nexport const forkScoped = internal.forkScoped;\n/**\n * Forks the effect into a new fiber attached to the global scope. Because the\n * new fiber is attached to the global scope, when the fiber executing the\n * returned effect terminates, the forked fiber will continue running.\n *\n * **Example** (Forking a detached fiber)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber } from \"effect\"\n *\n * const daemonTask = Effect.succeed(\"daemon result\")\n *\n * const program = Effect.gen(function*() {\n * const fiber = yield* daemonTask.pipe(Effect.forkDetach)\n * return yield* Fiber.join(fiber)\n * })\n *\n * await Effect.runPromise(program) // => \"daemon result\"\n * ```\n *\n * @category forking\n * @since 4.0.0\n */\nexport const forkDetach = internal.forkDetach;\n/**\n * Waits for all child fibers forked by this effect to complete before this\n * effect completes.\n *\n * **When to use**\n *\n * Use to let an effect start child work concurrently while still delaying its\n * own completion until that child work is done.\n *\n * **Gotchas**\n *\n * Child fibers that already exist before the wrapped effect starts are not\n * awaited.\n *\n * @see {@link forkChild} for forking child fibers that are awaited by this operator\n * @see {@link forkDetach} for forking fibers outside the child scope\n * @see {@link forkIn} for forking into an explicit scope\n * @see {@link forkScoped} for forking fibers tied to the current scope\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const awaitAllChildren = internal.awaitAllChildren;\n/**\n * Accesses the fiber currently executing the effect.\n *\n * **Example** (Accessing the current fiber)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.gen(function*() {\n * const fiber = yield* Effect.fiber\n * yield* Effect.sync(() => { output.push(typeof fiber.id) })\n * })\n *\n * Effect.runSync(program)\n * output // => [\"number\"]\n * ```\n *\n * @category accessors\n * @since 4.0.0\n */\nexport const fiber = internal.fiber;\n/**\n * Accesses the current fiber id executing the effect.\n *\n * **Example** (Accessing the current fiber id)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const program = Effect.fiberId.pipe(Effect.map((id) => typeof id))\n * Effect.runSync(program) // => \"number\"\n * ```\n *\n * @category accessors\n * @since 2.0.0\n */\nexport const fiberId = internal.fiberId;\n/**\n * Runs an effect in the background, returning a fiber that can\n * be observed or interrupted.\n *\n * **When to use**\n *\n * Use when you need to start an effect in the background and receive a fiber.\n *\n * **Example** (Running an effect in the background)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber } from \"effect\"\n * const output: Array<unknown> = []\n *\n * // ┌─── Effect<number, never, never>\n * // ▼\n * const program = Effect.sync(() => { output.push(\"running...\") }).pipe(Effect.as(\"done\"))\n *\n * // ┌─── RuntimeFiber<number, never>\n * // ▼\n * const fiber = Effect.runFork(program)\n *\n * void output.push(await Effect.runPromise(Fiber.join(fiber)))\n * output // => [\"running...\", \"done\"]\n * ```\n *\n * @category running\n * @since 2.0.0\n */\nexport const runFork = internal.runFork;\n/**\n * Runs an effect in the background with the provided services.\n *\n * **When to use**\n *\n * Use when an effect still requires services, you already have a `Context`, and\n * you want a background fiber.\n *\n * **Example** (Running with services in the background)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Fiber } from \"effect\"\n * const output: Array<unknown> = []\n *\n * interface Logger {\n * log: (message: string) => void\n * }\n *\n * const Logger = Context.Service<Logger>(\"Logger\")\n *\n * const services = Context.make(Logger, {\n * log: (message) => void output.push(message)\n * })\n *\n * const program = Effect.gen(function*() {\n * const logger = yield* Logger\n * logger.log(\"Hello from service!\")\n * return \"done\"\n * })\n *\n * const fiber = Effect.runForkWith(services)(program)\n * void output.push(await Effect.runPromise(Fiber.join(fiber)))\n * output // => [\"Hello from service!\", \"done\"]\n * ```\n *\n * @category running\n * @since 4.0.0\n */\nexport const runForkWith = internal.runForkWith;\n/**\n * Forks an effect with the provided services, registers `onExit` as a fiber observer, and returns an interruptor.\n *\n * **When to use**\n *\n * Use when embedding an effect into callback-style code with explicit services\n * and a synchronous interruptor.\n *\n * **Details**\n *\n * The returned interruptor calls `fiber.interruptUnsafe`, optionally with an interruptor id.\n *\n * **Example** (Running with services and a callback)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * interface Logger {\n * log: (message: string) => Effect.Effect<void>\n * }\n *\n * const Logger = Context.Service<Logger>(\"Logger\")\n *\n * const services = Context.make(Logger, {\n * log: (message) => Effect.sync(() => { output.push(message) })\n * })\n *\n * const program = Effect.gen(function*() {\n * const logger = yield* Logger\n * yield* logger.log(\"Started\")\n * return \"done\"\n * })\n *\n * await new Promise<void>((resolve) => {\n * Effect.runCallbackWith(services)(program, {\n * onExit: (exit) => {\n * void output.push(exit._tag)\n * resolve()\n * }\n * })\n * })\n * output // => [\"Started\", \"Success\"]\n * ```\n *\n * @category running\n * @since 4.0.0\n */\nexport const runCallbackWith = internal.runCallbackWith;\n/**\n * Runs an effect asynchronously, registering `onExit` as a fiber observer and\n * returning an interruptor.\n *\n * **Details**\n *\n * The interruptor calls `fiber.interruptUnsafe` with the optional interruptor\n * id.\n *\n * **Example** (Running with a callback)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.gen(function*() {\n * yield* Effect.sync(() => { output.push(\"working\") })\n * return \"done\"\n * })\n *\n * await new Promise<void>((resolve) => {\n * Effect.runCallback(program, {\n * onExit: (exit) => {\n * Effect.runSync(\n * Exit.match(exit, {\n * onFailure: () => Effect.sync(() => { output.push(\"failed\") }),\n * onSuccess: (value) => Effect.sync(() => { output.push(`success: ${value}`) })\n * })\n * )\n * resolve()\n * }\n * })\n * })\n *\n * output // => [\"working\", \"success: done\"]\n * ```\n *\n * @category running\n * @since 2.0.0\n */\nexport const runCallback = internal.runCallback;\n/**\n * Executes an effect and returns the result as a `Promise`.\n *\n * **When to use**\n *\n * Use when you need to execute an effect and work with the\n * result using `Promise` syntax, typically for compatibility with other\n * promise-based code.\n *\n * If the effect succeeds, the promise will resolve with the result. If the\n * effect fails, the promise will reject with an error.\n *\n * **Example** (Running a successful effect as a Promise)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * await Effect.runPromise(Effect.succeed(1)) // => 1\n * ```\n *\n * **Example** (Running effects as promises)\n *\n * ```ts import.meta.vitest\n * //Example: Handling a Failing Effect as a Rejected Promise\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * await Effect.runPromise(Effect.fail(\"my error\")).catch(() => {\n * void output.push(\"rejected\")\n * })\n * output // => [\"rejected\"]\n * ```\n *\n * @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting.\n * @category running\n * @since 2.0.0\n */\nexport const runPromise = internal.runPromise;\n/**\n * Executes an effect as a Promise with the provided services.\n *\n * **When to use**\n *\n * Use when you already have a `Context` and need Promise interop that rejects on\n * effect failure.\n *\n * **Example** (Running with services as a promise)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect } from \"effect\"\n *\n * interface Config {\n * apiUrl: string\n * }\n *\n * const Config = Context.Service<Config>(\"Config\")\n *\n * const context = Context.make(Config, {\n * apiUrl: \"https://api.example.com\"\n * })\n *\n * const program = Effect.gen(function*() {\n * const config = yield* Config\n * return `Connecting to ${config.apiUrl}`\n * })\n *\n * await Effect.runPromiseWith(context)(program) // => \"Connecting to https://api.example.com\"\n * ```\n *\n * @category running\n * @since 4.0.0\n */\nexport const runPromiseWith = internal.runPromiseWith;\n/**\n * Runs an effect and returns a `Promise` that resolves to an `Exit`, which\n * represents the outcome (success or failure) of the effect.\n *\n * **When to use**\n *\n * Use when you need to determine if an effect succeeded\n * or failed, including any defects, and you want to work with a `Promise`.\n *\n * **Details**\n *\n * The `Exit` type represents the result of the effect. Successful effects are\n * wrapped in `Success`, and failed effects are wrapped in `Failure` with a\n * `Cause`.\n *\n * **Example** (Observing promise results as Exit)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit } from \"effect\"\n *\n * // Execute a successful effect and get the Exit result as a Promise\n * await Effect.runPromiseExit(Effect.succeed(1)) // => Exit.succeed(1)\n *\n * // Execute a failing effect and get the Exit result as a Promise\n * await Effect.runPromiseExit(Effect.fail(\"my error\")) // => Exit.fail(\"my error\")\n * ```\n *\n * @see {@link runPromise} for a version that rejects on failure.\n *\n * @category running\n * @since 2.0.0\n */\nexport const runPromiseExit = internal.runPromiseExit;\n/**\n * Runs an effect and returns a Promise of Exit with provided services.\n *\n * **When to use**\n *\n * Use when you already have a `Context` and need Promise interop that preserves\n * success and failure as an `Exit`.\n *\n * **Example** (Running with services as an Exit promise)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Exit } from \"effect\"\n * const output: Array<unknown> = []\n *\n * interface Database {\n * query: (sql: string) => string\n * }\n *\n * const Database = Context.Service<Database>(\"Database\")\n *\n * const services = Context.make(Database, {\n * query: (sql) => `Result for: ${sql}`\n * })\n *\n * const program = Effect.gen(function*() {\n * const db = yield* Database\n * return db.query(\"SELECT * FROM users\")\n * })\n *\n * const exit = await Effect.runPromiseExitWith(services)(program)\n * if (Exit.isSuccess(exit)) {\n * void output.push(`Success: ${exit.value}`)\n * }\n * output // => [\"Success: Result for: SELECT * FROM users\"]\n * ```\n *\n * @category running\n * @since 4.0.0\n */\nexport const runPromiseExitWith = internal.runPromiseExitWith;\n/**\n * Executes an effect synchronously and returns its success value.\n *\n * **When to use**\n *\n * Use when you need to execute an effect that is guaranteed to complete\n * synchronously.\n *\n * **Details**\n *\n * If the effect fails, dies, is interrupted, or performs asynchronous work,\n * `runSync` throws a `FiberFailure` instead of returning a value. Use\n * `runSyncExit` when you want the failure captured as an `Exit`.\n *\n * **Example** (Running a synchronous effect)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.sync(() => {\n * void output.push(\"Hello, World!\")\n * return 1\n * })\n *\n * const result = Effect.runSync(program)\n * void output.push(result)\n * output // => [\"Hello, World!\", 1]\n * ```\n *\n * **Example** (Throwing for failed or async effects)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * try {\n * // Attempt to run an effect that fails\n * Effect.runSync(Effect.fail(\"my error\"))\n * } catch (e) {\n * void output.push(\"failed effect\")\n * }\n * try {\n * // Attempt to run an effect that involves async work\n * Effect.runSync(Effect.promise(() => Promise.resolve(1)))\n * } catch (e) {\n * void output.push(\"async effect\")\n * }\n * output // => [\"failed effect\", \"async effect\"]\n * ```\n *\n * @see {@link runSyncExit} for a version that returns an `Exit` type instead of\n * throwing an error.\n * @category running\n * @since 2.0.0\n */\nexport const runSync = internal.runSync;\n/**\n * Executes an effect synchronously with provided services.\n *\n * **When to use**\n *\n * Use when you already have a `Context`, the effect is known to complete\n * synchronously, and failures should throw.\n *\n * **Example** (Running synchronously with services)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect } from \"effect\"\n *\n * interface MathService {\n * add: (a: number, b: number) => number\n * }\n *\n * const MathService = Context.Service<MathService>(\"MathService\")\n *\n * const context = Context.make(MathService, {\n * add: (a, b) => a + b\n * })\n *\n * const program = Effect.gen(function*() {\n * const math = yield* MathService\n * return math.add(2, 3)\n * })\n *\n * const result = Effect.runSyncWith(context)(program)\n * result // => 5\n * ```\n *\n * @category running\n * @since 4.0.0\n */\nexport const runSyncWith = internal.runSyncWith;\n/**\n * Runs an effect synchronously and captures the outcome safely as an `Exit` type, which\n * represents the outcome (success or failure) of the effect.\n *\n * **When to use**\n *\n * Use to find out whether an effect succeeded or failed,\n * including any defects, without dealing with asynchronous operations.\n *\n * **Details**\n *\n * The `Exit` type represents the result of the effect. Successful effects are\n * wrapped in `Success`, and failed effects are wrapped in `Failure` with a\n * `Cause`.\n *\n * If the effect contains asynchronous operations, `runSyncExit` will\n * return an `Failure` with a `Die` cause, indicating that the effect cannot be\n * resolved synchronously.\n *\n * **Example** (Observing synchronous results as Exit)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit } from \"effect\"\n *\n * Effect.runSyncExit(Effect.succeed(1)) // => Exit.succeed(1)\n *\n * Effect.runSyncExit(Effect.fail(\"my error\")) // => Exit.fail(\"my error\")\n * ```\n *\n * **Example** (Capturing async work as a Die cause)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Exit } from \"effect\"\n *\n * const exit = Effect.runSyncExit(Effect.promise(() => Promise.resolve(1)))\n * const isAsyncDie = Exit.hasDies(exit) && exit.cause.reasons.some(\n * (reason) => Cause.isDieReason(reason) && Cause.isAsyncFiberError(reason.defect)\n * )\n *\n * isAsyncDie // => true\n * ```\n *\n * @see {@link runSync} for a version that throws on failure.\n *\n * @category running\n * @since 2.0.0\n */\nexport const runSyncExit = internal.runSyncExit;\n/**\n * Runs an effect synchronously with provided services, returning an Exit result safely.\n *\n * **When to use**\n *\n * Use when you already have a `Context` and need a synchronous `Exit` instead of\n * throwing on failure.\n *\n * **Example** (Running synchronously with services as Exit)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Exit } from \"effect\"\n * const output: Array<unknown> = []\n *\n * // Define a logger service\n * const Logger = Context.Service<{\n * log: (msg: string) => void\n * }>(\"Logger\")\n *\n * const program = Effect.gen(function*() {\n * const logger = yield* Effect.service(Logger)\n * logger.log(\"Computing result...\")\n * return 42\n * })\n *\n * // Prepare context\n * const context = Context.make(Logger, {\n * log: (msg) => void output.push(`[LOG] ${msg}`)\n * })\n *\n * const exit = Effect.runSyncExitWith(context)(program)\n *\n * if (Exit.isSuccess(exit)) {\n * void output.push(`Success: ${exit.value}`)\n * } else {\n * void output.push(`Failure: ${exit.cause}`)\n * }\n * output // => [\"[LOG] Computing result...\", \"Success: 42\"]\n * ```\n *\n * @category running\n * @since 4.0.0\n */\nexport const runSyncExitWith = internal.runSyncExitWith;\n/**\n * Creates an Effect-returning function without tracing.\n *\n * **When to use**\n *\n * Use when you are defining a reusable Effect function whose implementation\n * would otherwise be a normal function returning {@link gen}, especially when\n * tracing spans or stack-frame capture are not needed.\n *\n * **Details**\n *\n * Compared to a plain function that returns {@link gen}, `Effect.fnUntraced`\n * reuses the generator body instead of allocating a fresh generator closure\n * around the arguments on every call. It does not record an Effect stack-frame\n * boundary and does not create tracing spans. Use {@link fn} when you need\n * those stack frames or spans. Additional arguments after the generator body\n * act like `pipe` transforms: each transform receives the previous result and\n * the original function arguments. Annotate the generator return type with\n * `Effect.fn.Return<A, E, R>` when the produced `Effect` type needs to be\n * stated explicitly.\n *\n * **Example** (Defining untraced effect functions)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const f = Effect.fnUntraced(function*(\n * value: string\n * ) {\n * return yield* Effect.succeed(value.length)\n * })\n *\n * // ┌─── Effect.Effect<number>\n * // ▼\n * const program = f(\"hello\")\n * Effect.runSync(program) // => 5\n * ```\n *\n * **Example** (Transforming the returned Effect)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const f = Effect.fnUntraced(\n * function*(value: string) {\n * return yield* Effect.succeed(value.length)\n * },\n * (effect, value) =>\n * effect.pipe(Effect.map((length) => `${value}: ${length}`))\n * )\n *\n * // ┌─── Effect.Effect<string>\n * // ▼\n * const program = f(\"hello\")\n * Effect.runSync(program) // => \"hello: 5\"\n * ```\n *\n * **Example** (Annotating an untraced non-parametric function)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const f = Effect.fnUntraced(function*(\n * value: string\n * ): Effect.fn.Return<number> {\n * return yield* Effect.succeed(value.length)\n * })\n *\n * // ┌─── Effect.Effect<number>\n * // ▼\n * const program = f(\"hello\")\n * Effect.runSync(program) // => 5\n * ```\n *\n * **Example** (Annotating an untraced parametric function)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const f = Effect.fnUntraced(function*<A>(\n * value: A\n * ): Effect.fn.Return<A> {\n * return yield* Effect.succeed(value)\n * })\n *\n * // ┌─── Effect.Effect<string>\n * // ▼\n * const program = f(\"hello\")\n * Effect.runSync(program) // => \"hello\"\n * ```\n *\n * @category constructors\n * @since 3.12.0\n */\nexport const fnUntraced = internal.fnUntraced;\n/**\n * Creates a reusable traced function from an Effect body.\n *\n * **When to use**\n *\n * Use when you are defining a reusable Effect function whose implementation\n * would otherwise be a normal function returning {@link gen}, and you want\n * tracing spans or stack-frame capture.\n *\n * **Details**\n *\n * Compared to a plain function that returns {@link gen}, `Effect.fn` reuses the\n * generator body instead of allocating a fresh generator closure around the\n * arguments on every call. Call `Effect.fn(body, ...)` for a generic\n * stack-frame boundary without creating a span. Call\n * `Effect.fn(\"operationName\", options?)(body, ...)` when that boundary should\n * have a readable operation name and the returned `Effect` should create a\n * tracing span when run. {@link SpanOptionsNoTrace} configures span metadata\n * such as attributes, links, parent or root selection, kind, sampling, and log\n * level. Additional arguments after the generator body act like `pipe`\n * transforms: each transform receives the previous result and the original\n * function arguments. When those transforms return an `Effect`, the returned\n * effect includes stack-frame metadata and, for the named form, a tracing span.\n * Generator bodies may declare a `this` parameter; pass `{ self }` before the\n * body to bind `this` when the function is created.\n *\n * **Example** (Defining traced effect functions)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const f = Effect.fn(\"calculateLength\")(function*(value: string) {\n * return yield* Effect.succeed(value.length)\n * })\n *\n * // ┌─── Effect.Effect<number>\n * // ▼\n * const program = f(\"hello\")\n * Effect.runSync(program) // => 5\n * ```\n *\n * **Example** (Transforming the returned Effect)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const f = Effect.fn(\"formatLength\")(\n * function*(value: string) {\n * return yield* Effect.succeed(value.length)\n * },\n * (effect, value) =>\n * effect.pipe(Effect.map((length) => `${value}: ${length}`))\n * )\n *\n * // ┌─── Effect.Effect<string>\n * // ▼\n * const program = f(\"hello\")\n * Effect.runSync(program) // => \"hello: 5\"\n * ```\n *\n * **Example** (Binding this)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * class Counter {\n * count = 0\n *\n * increment = Effect.fn(\"Counter.increment\")(\n * { self: this },\n * function*(this: Counter, by: number) {\n * this.count += by\n * return yield* Effect.succeed(this.count)\n * }\n * )\n * }\n *\n * const counter = new Counter()\n *\n * // ┌─── Effect.Effect<number>\n * // ▼\n * const program = counter.increment(1)\n * Effect.runSync(program) // => 1\n * ```\n *\n * **Example** (Annotating a traced non-parametric function)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const f = Effect.fn(\"calculateLength\")(function*(\n * value: string\n * ): Effect.fn.Return<number> {\n * return yield* Effect.succeed(value.length)\n * })\n *\n * // ┌─── Effect.Effect<number>\n * // ▼\n * const program = f(\"hello\")\n * Effect.runSync(program) // => 5\n * ```\n *\n * **Example** (Annotating a traced parametric function)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const f = Effect.fn(\"succeed\")(function*<A>(\n * value: A\n * ): Effect.fn.Return<A> {\n * return yield* Effect.succeed(value)\n * })\n *\n * // ┌─── Effect.Effect<string>\n * // ▼\n * const program = f(\"hello\")\n * Effect.runSync(program) // => \"hello\"\n * ```\n *\n * @category constructors\n * @since 3.11.0\n */\nexport const fn = internal.fn;\n// ========================================================================\n// Clock\n// ========================================================================\n/**\n * Retrieves the `Clock` service from the context and provides it to the\n * specified effectful function.\n *\n * **Example** (Accessing the Clock service)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const program = Effect.clockWith((clock) =>\n * clock.currentTimeMillis.pipe(\n * Effect.map(() => \"Clock is available\")\n * )\n * )\n *\n * Effect.runSync(program) // => \"Clock is available\"\n * ```\n *\n * @category accessors\n * @since 2.0.0\n */\nexport const clockWith = internal.clockWith;\n// ========================================================================\n// Logging\n// ========================================================================\n/**\n * Creates a logger function that logs at the specified level.\n *\n * **Details**\n *\n * If no level is provided, the logger uses the fiber's current log level and\n * extracts any `Cause` values from the message list.\n *\n * **Example** (Logging at a dynamic level)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger, References } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const logWarn = Effect.logWithLevel(\"Warn\")\n *\n * const program = Effect.gen(function*() {\n * yield* logWarn(\"Cache miss\")\n * })\n * const logger = Logger.make<unknown, void>(({ logLevel, message }) => {\n * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(\" \") : String(message)}`)\n * })\n * const runnable = program.pipe(\n * Effect.provideService(References.MinimumLogLevel, \"Debug\"),\n * Effect.provide(Logger.layer([logger]))\n * )\n * Effect.runSync(runnable)\n * output // => [\"Warn: Cache miss\"]\n * ```\n *\n * @category logging\n * @since 2.0.0\n */\nexport const logWithLevel = internal.logWithLevel;\n/**\n * Logs one or more messages using the default log level.\n *\n * **Example** (Logging at the default level)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.gen(function*() {\n * const result = 2 + 2\n * yield* Effect.log(\"Result:\", result)\n * return result\n * })\n *\n * const logger = Logger.make<unknown, void>(({ logLevel, message }) => {\n * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(\" \") : String(message)}`)\n * })\n * const runnable = Effect.provide(program, Logger.layer([logger]))\n * void output.push(Effect.runSync(runnable))\n * output // => [\"Info: Result: 4\", 4]\n * ```\n *\n * @category logging\n * @since 2.0.0\n */\nexport const log = /*#__PURE__*/internal.logWithLevel();\n/**\n * Logs one or more messages at the FATAL level.\n *\n * **Example** (Logging fatal messages)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.gen(function*() {\n * yield* Effect.logFatal(\"Critical system failure\")\n * })\n *\n * const logger = Logger.make<unknown, void>(({ logLevel, message }) => {\n * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(\" \") : String(message)}`)\n * })\n * const runnable = Effect.provide(program, Logger.layer([logger]))\n * Effect.runSync(runnable)\n * output // => [\"Fatal: Critical system failure\"]\n * ```\n *\n * @category logging\n * @since 2.0.0\n */\nexport const logFatal = /*#__PURE__*/internal.logWithLevel(\"Fatal\");\n/**\n * Logs one or more messages at the WARNING level.\n *\n * **Example** (Logging warnings)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.gen(function*() {\n * yield* Effect.logWarning(\"API rate limit approaching\")\n * })\n *\n * const logger = Logger.make<unknown, void>(({ logLevel, message }) => {\n * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(\" \") : String(message)}`)\n * })\n * Effect.runSync(Effect.provide(program, Logger.layer([logger])))\n * output // => [\"Warn: API rate limit approaching\"]\n * ```\n *\n * @category logging\n * @since 2.0.0\n */\nexport const logWarning = /*#__PURE__*/internal.logWithLevel(\"Warn\");\n/**\n * Logs one or more messages at the ERROR level.\n *\n * **Example** (Logging errors)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.gen(function*() {\n * yield* Effect.logError(\"Database connection failed\")\n * })\n *\n * const logger = Logger.make<unknown, void>(({ logLevel, message }) => {\n * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(\" \") : String(message)}`)\n * })\n * Effect.runSync(Effect.provide(program, Logger.layer([logger])))\n * output // => [\"Error: Database connection failed\"]\n * ```\n *\n * @category logging\n * @since 2.0.0\n */\nexport const logError = /*#__PURE__*/internal.logWithLevel(\"Error\");\n/**\n * Logs one or more messages at the INFO level.\n *\n * **Example** (Logging information)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.gen(function*() {\n * yield* Effect.logInfo(\"Application starting up\")\n * })\n *\n * const logger = Logger.make<unknown, void>(({ logLevel, message }) => {\n * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(\" \") : String(message)}`)\n * })\n * Effect.runSync(Effect.provide(program, Logger.layer([logger])))\n * output // => [\"Info: Application starting up\"]\n * ```\n *\n * @category logging\n * @since 2.0.0\n */\nexport const logInfo = /*#__PURE__*/internal.logWithLevel(\"Info\");\n/**\n * Logs one or more messages at the DEBUG level.\n *\n * **Example** (Logging debug messages)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger, References } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.gen(function*() {\n * yield* Effect.logDebug(\"Debug mode enabled\")\n * })\n *\n * const logger = Logger.make<unknown, void>(({ logLevel, message }) => {\n * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(\" \") : String(message)}`)\n * })\n * const runnable = program.pipe(\n * Effect.provideService(References.MinimumLogLevel, \"Debug\"),\n * Effect.provide(Logger.layer([logger]))\n * )\n * Effect.runSync(runnable)\n * output // => [\"Debug: Debug mode enabled\"]\n * ```\n *\n * @category logging\n * @since 2.0.0\n */\nexport const logDebug = /*#__PURE__*/internal.logWithLevel(\"Debug\");\n/**\n * Logs one or more messages at the TRACE level.\n *\n * **Example** (Logging trace messages)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger, References } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.gen(function*() {\n * yield* Effect.logTrace(\"Entering function processData\")\n * })\n *\n * const logger = Logger.make<unknown, void>(({ logLevel, message }) => {\n * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(\" \") : String(message)}`)\n * })\n * const runnable = program.pipe(\n * Effect.provideService(References.MinimumLogLevel, \"Trace\"),\n * Effect.provide(Logger.layer([logger]))\n * )\n * Effect.runSync(runnable)\n * output // => [\"Trace: Entering function processData\"]\n * ```\n *\n * @category logging\n * @since 2.0.0\n */\nexport const logTrace = /*#__PURE__*/internal.logWithLevel(\"Trace\");\n/**\n * Adds a logger to the set of loggers which will output logs for this effect.\n *\n * **Example** (Adding a logger to an effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n * const output: Array<unknown> = []\n *\n * // Create a custom logger that logs to the console\n * const customLogger = Logger.make<unknown, void>(({ message }) =>\n * void output.push(`[CUSTOM]: ${Array.isArray(message) ? message.map(String).join(\" \") : String(message)}`)\n * )\n *\n * const program = Effect.gen(function*() {\n * yield* Effect.log(\"This will go to both default and custom logger\")\n * return \"completed\"\n * })\n *\n * // Add the custom logger to the effect\n * const programWithLogger = Effect.withLogger(program, customLogger)\n *\n * Effect.runSync(Effect.provide(programWithLogger, Logger.layer([])))\n * output // => [\"[CUSTOM]: This will go to both default and custom logger\"]\n * ```\n *\n * @category logging\n * @since 4.0.0\n */\nexport const withLogger = /*#__PURE__*/dual(2, (effect, logger) => internal.updateService(effect, internal.CurrentLoggers, loggers => new Set([...loggers, logger])));\n/**\n * Adds an annotation to each log line in this effect.\n *\n * **Example** (Adding log annotations)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.gen(function*() {\n * yield* Effect.log(\"Starting operation\")\n * })\n *\n * // Add annotations to all log messages\n * const annotatedProgram = Effect.annotateLogs(program, {\n * userId: \"user123\",\n * operation: \"data-processing\"\n * })\n *\n * // Also supports single key-value annotations\n * const singleAnnotated = Effect.annotateLogs(program, \"requestId\", \"req-456\")\n *\n * const logger = Logger.make<unknown, void>(({ message }) =>\n * void output.push(Array.isArray(message) ? message.join(\" \") : String(message))\n * )\n * const run = (effect: Effect.Effect<void>) =>\n * Effect.runSync(Effect.provide(effect, Logger.layer([logger])))\n * run(annotatedProgram)\n * run(singleAnnotated)\n * output // => [\"Starting operation\", \"Starting operation\"]\n * ```\n *\n * @category logging\n * @since 2.0.0\n */\nexport const annotateLogs = /*#__PURE__*/dual(args => isEffect(args[0]), (effect, ...args) => internal.updateService(effect, CurrentLogAnnotations, annotations => {\n const newAnnotations = args.length === 1 ? {\n ...annotations,\n ...args[0]\n } : {\n ...annotations\n };\n if (args.length === 1) {\n return newAnnotations;\n } else {\n InternalRecord.assignProperty(newAnnotations, args[0], args[1]);\n }\n return newAnnotations;\n}));\n/**\n * Adds log annotations to the current scope.\n *\n * **When to use**\n *\n * Use to attach log annotations that last until the current scope closes.\n *\n * **Details**\n *\n * This differs from `annotateLogs`, which only annotates a specific effect.\n * `annotateLogsScoped` updates annotations for the entire current `Scope` and\n * restores the previous annotations when the scope closes.\n *\n * **Example** (Adding scoped log annotations)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.scoped(\n * Effect.gen(function*() {\n * yield* Effect.log(\"before\")\n * yield* Effect.annotateLogsScoped({ requestId: \"req-123\" })\n * yield* Effect.log(\"inside scope\")\n * })\n * )\n *\n * const logger = Logger.make<unknown, void>(({ message }) =>\n * void output.push(Array.isArray(message) ? message.join(\" \") : String(message))\n * )\n * Effect.runSync(Effect.provide(program, Logger.layer([logger])))\n * output // => [\"before\", \"inside scope\"]\n * ```\n *\n * @see {@link annotateLogs} for annotating one effect\n *\n * @category logging\n * @since 3.1.0\n */\nexport const annotateLogsScoped = internal.annotateLogsScoped;\n/**\n * Adds a span to each log line in this effect.\n *\n * **Example** (Adding a log span)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const databaseOperation = Effect.gen(function*() {\n * yield* Effect.log(\"Connecting to database\")\n * yield* Effect.log(\"Executing query\")\n * yield* Effect.log(\"Processing results\")\n * return \"data\"\n * })\n *\n * const httpRequest = Effect.gen(function*() {\n * yield* Effect.log(\"Making HTTP request\")\n * const data = yield* Effect.withLogSpan(databaseOperation, \"db-operation\")\n * yield* Effect.log(\"Sending response\")\n * return data\n * })\n *\n * const program = Effect.withLogSpan(httpRequest, \"http-handler\")\n *\n * const logger = Logger.make<unknown, void>(({ message }) =>\n * void output.push(Array.isArray(message) ? message.join(\" \") : String(message))\n * )\n * void output.push(Effect.runSync(Effect.provide(program, Logger.layer([logger]))))\n * output // => [\"Making HTTP request\", \"Connecting to database\", \"Executing query\", \"Processing results\", \"Sending response\", \"data\"]\n * ```\n *\n * @category logging\n * @since 2.0.0\n */\nexport const withLogSpan = /*#__PURE__*/dual(2, (effect, label) => internal.flatMap(internal.currentTimeMillis, now => internal.updateService(effect, CurrentLogSpans, spans => {\n const span = [label, now];\n return [span, ...spans];\n})));\n// -----------------------------------------------------------------------------\n// Metrics\n// -----------------------------------------------------------------------------\n/**\n * Updates a metric after each effect execution, optionally mapping its `Exit` to\n * the metric's input.\n *\n * **Example** (Counting executions)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const counter = Metric.counter(\"effect_executions\", {\n * description: \"Counts effect executions\"\n * }).pipe(Metric.withConstantInput(1))\n *\n * const program = Effect.succeed(\"Hello\").pipe(\n * Effect.track(counter)\n * )\n *\n * Effect.runSync(program)\n * Effect.runSync(Metric.value(counter)).count // => 1\n * ```\n *\n * **Example** (Mapping exits)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Metric } from \"effect\"\n *\n * const exitTracker = Metric.frequency(\"exit_types\", {\n * description: \"Tracks success/failure/defect counts\"\n * })\n *\n * const mapExitToString = (exit: Exit.Exit<string, Error>) => {\n * if (Exit.isSuccess(exit)) return \"success\"\n * if (Exit.isFailure(exit)) return \"failure\"\n * return \"defect\"\n * }\n *\n * const effect = Effect.succeed(\"result\").pipe(\n * Effect.track(exitTracker, mapExitToString)\n * )\n * Effect.runSync(effect)\n * Effect.runSync(Metric.value(exitTracker)).occurrences.get(\"success\") // => 1\n * ```\n *\n * @category metrics\n * @since 4.0.0\n */\nexport const track = /*#__PURE__*/dual(args => isEffect(args[0]), (self, metric, f) => onExit(self, exit => {\n const input = f === undefined ? exit : internalCall(() => f(exit));\n return Metric.update(metric, input);\n}));\n/**\n * Updates the provided `Metric` every time the wrapped `Effect` succeeds with\n * a value.\n *\n * **Details**\n *\n * Also accepts an optional function which can be used to map the success value\n * of the `Effect` into a valid `Input` for the `Metric`.\n *\n * **Example** (Counting successful results)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const successCounter = Metric.counter(\"successes\").pipe(\n * Metric.withConstantInput(1)\n * )\n *\n * const program = Effect.succeed(42).pipe(\n * Effect.trackSuccesses(successCounter)\n * )\n *\n * Effect.runSync(program)\n * Effect.runSync(Metric.value(successCounter)).count // => 1\n * ```\n *\n * **Example** (Mapping successes before tracking)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * // Track successful request sizes\n * const requestSizeGauge = Metric.gauge(\"request_size_bytes\")\n *\n * const program = Effect.succeed(\"Hello World!\").pipe(\n * Effect.trackSuccesses(requestSizeGauge, (value: string) => value.length)\n * )\n *\n * Effect.runSync(program)\n * Effect.runSync(Metric.value(requestSizeGauge)).value // => 12\n * ```\n *\n * @category metrics\n * @since 4.0.0\n */\nexport const trackSuccesses = /*#__PURE__*/dual(args => isEffect(args[0]), (self, metric, f) => tap(self, value => {\n const input = f === undefined ? value : f(value);\n return Metric.update(metric, input);\n}));\n/**\n * Updates the provided `Metric` every time the wrapped `Effect` fails with an\n * **expected** error.\n *\n * **Details**\n *\n * Also accepts an optional function which can be used to map the error value\n * of the `Effect` into a valid `Input` for the `Metric`.\n *\n * **Example** (Counting expected failures)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const errorCounter = Metric.counter(\"errors\").pipe(\n * Metric.withConstantInput(1)\n * )\n *\n * const program = Effect.fail(\"Network timeout\").pipe(\n * Effect.trackErrors(errorCounter)\n * )\n *\n * Effect.runSyncExit(program)\n * Effect.runSync(Metric.value(errorCounter)).count // => 1\n * ```\n *\n * **Example** (Mapping errors before tracking)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect, Metric } from \"effect\"\n *\n * class ConnectionFailedError extends Data.TaggedError(\"ConnectionFailedError\")<{}> {}\n *\n * // Track error types using frequency metric\n * const errorTypeFrequency = Metric.frequency(\"error_types\")\n *\n * const program = Effect.fail(new ConnectionFailedError()).pipe(\n * Effect.trackErrors(errorTypeFrequency, (error: ConnectionFailedError) => error._tag)\n * )\n *\n * Effect.runSyncExit(program)\n * Effect.runSync(Metric.value(errorTypeFrequency)).occurrences.get(\"ConnectionFailedError\") // => 1\n * ```\n *\n * @category metrics\n * @since 4.0.0\n */\nexport const trackErrors = /*#__PURE__*/dual(args => isEffect(args[0]), (self, metric, f) => tapError(self, error => {\n const input = f === undefined ? error : internalCall(() => f(error));\n return Metric.update(metric, input);\n}));\n/**\n * Updates the provided `Metric` every time the wrapped `Effect` fails with an\n * **unexpected** error (i.e. a defect).\n *\n * **Details**\n *\n * Also accepts an optional function which can be used to map the defect value\n * of the `Effect` into a valid `Input` for the `Metric`.\n *\n * **Example** (Counting defects)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const defectCounter = Metric.counter(\"defects\").pipe(\n * Metric.withConstantInput(1)\n * )\n *\n * const program = Effect.die(\"Critical system failure\").pipe(\n * Effect.trackDefects(defectCounter)\n * )\n *\n * Effect.runSyncExit(program)\n * Effect.runSync(Metric.value(defectCounter)).count // => 1\n * ```\n *\n * **Example** (Mapping defects before tracking)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * // Track defect types using frequency metric\n * const defectTypeFrequency = Metric.frequency(\"defect_types\")\n *\n * const program = Effect.die(new Error(\"Null pointer exception\")).pipe(\n * Effect.trackDefects(defectTypeFrequency, (defect: unknown) => {\n * if (defect instanceof Error) return defect.constructor.name\n * return typeof defect\n * })\n * )\n *\n * Effect.runSyncExit(program)\n * Effect.runSync(Metric.value(defectTypeFrequency)).occurrences.get(\"Error\") // => 1\n * ```\n *\n * @category metrics\n * @since 4.0.0\n */\nexport const trackDefects = /*#__PURE__*/dual(args => isEffect(args[0]), (self, metric, f) => tapDefect(self, defect => {\n const input = f === undefined ? defect : internalCall(() => f(defect));\n return Metric.update(metric, input);\n}));\n/**\n * Updates the provided `Metric` with the `Duration` of time (in nanoseconds)\n * that the wrapped `Effect` took to complete.\n *\n * **Details**\n *\n * Also accepts an optional function which can be used to map the `Duration`\n * that the wrapped `Effect` took to complete into a valid `Input` for the\n * `Metric`.\n *\n * **Example** (Recording execution duration)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const executionTimer = Metric.timer(\"execution_time\")\n *\n * const program = Effect.succeed(\"done\").pipe(\n * Effect.trackDuration(executionTimer)\n * )\n *\n * Effect.runSync(program)\n * Effect.runSync(Metric.value(executionTimer)).count // => 1\n * ```\n *\n * **Example** (Mapping duration before tracking)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * // Track execution time in milliseconds using custom mapping\n * const durationGauge = Metric.gauge(\"execution_millis\")\n *\n * const program = Effect.succeed(\"done\").pipe(\n * Effect.trackDuration(durationGauge, () => 1)\n * )\n *\n * Effect.runSync(program)\n * Effect.runSync(Metric.value(durationGauge)).value // => 1\n * ```\n *\n * @category metrics\n * @since 4.0.0\n */\nexport const trackDuration = /*#__PURE__*/dual(args => isEffect(args[0]), (self, metric, f) => clockWith(clock => {\n const startTime = clock.monotonicTimeNanosUnsafe();\n return onExit(self, () => {\n const endTime = clock.monotonicTimeNanosUnsafe();\n const duration = Duration.subtract(Duration.fromInputUnsafe(endTime), Duration.fromInputUnsafe(startTime));\n const input = f === undefined ? duration : internalCall(() => f(duration));\n return Metric.update(metric, input);\n });\n}));\n// -----------------------------------------------------------------------------\n// Transactions\n// -----------------------------------------------------------------------------\n/**\n * Service that holds the current transaction state.\n *\n * **Details**\n *\n * It includes a journal that stores non-committed changes to `TxRef` values and\n * a retry flag that records whether the transaction should be retried.\n *\n * **Example** (Building transactions)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * // Transaction class for software transactional memory operations\n * const txEffect = Effect.gen(function*() {\n * const tx = yield* Effect.Transaction\n * // Use transaction for coordinated state changes\n * return \"Transaction complete\"\n * })\n *\n * const runnable = Effect.provideService(txEffect, Effect.Transaction, {\n * retry: false,\n * journal: new Map()\n * })\n * Effect.runSync(runnable) // => \"Transaction complete\"\n * ```\n *\n * @category services\n * @since 4.0.0\n */\nexport class Transaction extends /*#__PURE__*/Context.Service()(\"effect/Effect/Transaction\") {}\n/**\n * Defines a transaction boundary. Transactions are \"all or nothing\" with respect to changes\n * made to transactional values (i.e. TxRef) that occur within the transaction body.\n *\n * **Details**\n *\n * If called inside an active transaction, `tx` composes with the current transaction and reuses\n * its journal and retry state instead of creating a nested boundary.\n *\n * Effect transactions are optimistic with retry. A transaction is retried when\n * its body explicitly calls `Effect.txRetry` and any accessed transactional\n * value changes, or when any accessed transactional value changes because a\n * different transaction commits before the current one.\n *\n * The outermost `tx` call creates the transaction boundary and commits or rolls back the full\n * composed transaction.\n *\n * **Example** (Running a transaction)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxRef } from \"effect\"\n * const output: Array<unknown> = []\n *\n * const program = Effect.gen(function*() {\n * const ref1 = yield* TxRef.make(0)\n * const ref2 = yield* TxRef.make(0)\n *\n * // Nested tx calls compose into the same transaction\n * yield* Effect.tx(Effect.gen(function*() {\n * yield* TxRef.set(ref1, 10)\n * yield* Effect.tx(TxRef.set(ref2, 20))\n * const sum = (yield* TxRef.get(ref1)) + (yield* TxRef.get(ref2))\n * void output.push(`Transaction sum: ${sum}`)\n * }))\n *\n * void output.push(`Final ref1: ${yield* TxRef.get(ref1)}`)\n * void output.push(`Final ref2: ${yield* TxRef.get(ref2)}`)\n * })\n *\n * Effect.runSync(program)\n * output // => [\"Transaction sum: 30\", \"Final ref1: 10\", \"Final ref2: 20\"]\n * ```\n *\n * @category transactions\n * @since 4.0.0\n */\nexport const tx = effect => withFiber(fiber => {\n let state = Context.getOrUndefined(fiber.context, Transaction);\n if (state) {\n return effect;\n }\n // Create transaction state only at the outermost boundary\n state = {\n journal: new Map(),\n retry: false\n };\n let result;\n return uninterruptibleMask(restore => flatMap(whileLoop({\n while: () => !result,\n body: constant(restore(effect).pipe(provideService(Transaction, state), tapCause(() => {\n if (!state.retry) return void_;\n return restore(awaitPendingTransaction(state));\n }), exit)),\n step(exit) {\n if (state.retry || !isTransactionConsistent(state)) {\n return clearTransaction(state);\n }\n if (Exit.isSuccess(exit)) {\n commitTransaction(fiber, state);\n } else {\n clearTransaction(state);\n }\n result = exit;\n }\n }), () => result));\n});\nconst isTransactionConsistent = state => {\n for (const [ref, {\n version\n }] of state.journal) {\n if (ref.version !== version) {\n return false;\n }\n }\n return true;\n};\nconst awaitPendingTransaction = state => suspend(() => {\n const key = {};\n const refs = Array.from(state.journal.keys());\n const clearPending = () => {\n for (const clear of refs) {\n clear.pending.delete(key);\n }\n };\n return callback(resume => {\n const onCall = () => {\n clearPending();\n resume(void_);\n };\n for (const ref of refs) {\n ref.pending.set(key, onCall);\n }\n return sync(clearPending);\n });\n});\nfunction commitTransaction(fiber, state) {\n for (const [ref, {\n value\n }] of state.journal) {\n if (value !== ref.value) {\n ref.version = ref.version + 1;\n ref.value = value;\n }\n for (const pending of ref.pending.values()) {\n fiber.currentDispatcher.scheduleTask(pending, 0);\n }\n ref.pending.clear();\n }\n}\nfunction clearTransaction(state) {\n state.retry = false;\n state.journal.clear();\n}\n/**\n * Retries the current transaction by signaling that it must be retried.\n *\n * **Details**\n *\n * NOTE: the transaction retries on any change to transactional values (i.e. TxRef) accessed in its body.\n *\n * **Example** (Retrying transactions)\n *\n * ```ts import.meta.vitest\n * import { Deferred, Effect, TxRef } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const ref = yield* TxRef.make(0)\n * const update = yield* Deferred.make<void>()\n *\n * yield* Effect.forkChild(\n * Deferred.await(update).pipe(Effect.andThen(Effect.tx(TxRef.set(ref, 1))))\n * )\n *\n * return yield* Effect.tx(Effect.gen(function*() {\n * const value = yield* TxRef.get(ref)\n * if (value === 0) {\n * yield* Deferred.succeed(update, undefined)\n * return yield* Effect.txRetry\n * }\n * return value\n * }))\n * })\n *\n * await Effect.runPromise(program) // => 1\n * ```\n *\n * @category transactions\n * @since 4.0.0\n */\nexport const txRetry = /*#__PURE__*/flatMap(Transaction, state => {\n state.retry = true;\n return interrupt;\n});\n/**\n * Converts an error-first callback API into a function that returns an\n * `Effect`.\n *\n * **Details**\n *\n * The original function is called with the supplied arguments plus a final\n * callback. A non-null callback error fails the returned effect, while a\n * successful callback value becomes the effect success. Use `onError` to map\n * callback errors and `onSyncError` to turn synchronous throws into typed\n * failures; otherwise synchronous throws become defects.\n *\n * **Example** (Converting callbacks to effects)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const uppercase = (\n * input: string,\n * callback: (error: Error | null, value?: string) => void\n * ) => queueMicrotask(() => callback(null, input.toUpperCase()))\n *\n * const effectfulUppercase = Effect.effectify(uppercase)\n * const program = effectfulUppercase(\"hello\")\n *\n * await Effect.runPromise(program) // => \"HELLO\"\n * ```\n *\n * **Example** (Mapping callback errors to typed failures)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const fail = (\n * input: string,\n * callback: (error: Error | null, value?: string) => void\n * ) => queueMicrotask(() => callback(new Error(\"unavailable\")))\n *\n * const effectfulFail = Effect.effectify(\n * fail,\n * (error, args) => new Error(`Failed to process ${args[0]}: ${error.message}`)\n * )\n *\n * const program = Effect.flip(effectfulFail(\"hello\"))\n *\n * const error = await Effect.runPromise(program)\n * error.message // => \"Failed to process hello: unavailable\"\n * ```\n *\n * @category converting\n * @since 4.0.0\n */\nexport const effectify = (fn, onError, onSyncError) => (...args) => callback(resume => {\n try {\n fn(...args, (err, result) => {\n if (err) {\n resume(fail(onError ? onError(err, args) : err));\n } else {\n resume(succeed(result));\n }\n });\n } catch (err) {\n resume(onSyncError ? fail(onSyncError(err, args)) : die(err));\n }\n});\n// -----------------------------------------------------------------------------\n// Type constraints\n// -----------------------------------------------------------------------------\n/**\n * Ensures that an effect's success type extends a given type `A`.\n *\n * **Details**\n *\n * This helper is checked at compile time and does not change the effect's\n * runtime behavior.\n *\n * **Example** (Constraining the success type)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * // Define a constraint that the success type must be a number\n * const satisfiesNumber = Effect.satisfiesSuccessType<number>()\n *\n * // This works - Effect<42, never, never> extends Effect<number, never, never>\n * const validEffect = satisfiesNumber(Effect.succeed(42))\n * Effect.runSync(validEffect) // => 42\n *\n * // This would cause a TypeScript compilation error:\n * // const invalidEffect = satisfiesNumber(Effect.succeed(\"string\"))\n * // ^^^^^^^^^^^^^^^^^^^^^^\n * // Type 'string' is not assignable to type 'number'\n * ```\n *\n * @category utility types\n * @since 4.0.0\n */\nexport const satisfiesSuccessType = () => effect => effect;\n/**\n * Ensures that an effect's error type extends a given type `E`.\n *\n * **Details**\n *\n * This helper is checked at compile time and does not change the effect's\n * runtime behavior.\n *\n * **Example** (Constraining the error type)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect } from \"effect\"\n *\n * class ValidationError extends Data.TaggedError(\"ValidationError\")<{}> {}\n *\n * // Define a constraint that the error type must be a ValidationError\n * const satisfiesError = Effect.satisfiesErrorType<ValidationError>()\n *\n * // This works - Effect<number, ValidationError, never> extends the constrained type\n * const validEffect = satisfiesError(Effect.fail(new ValidationError()))\n * Effect.runSync(Effect.flip(validEffect))._tag // => \"ValidationError\"\n *\n * // This would cause a TypeScript compilation error:\n * // const invalidEffect = satisfiesError(Effect.fail(\"string error\"))\n * // ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n * // Type 'string' is not assignable to type 'ValidationError'\n * ```\n *\n * @category utility types\n * @since 4.0.0\n */\nexport const satisfiesErrorType = () => effect => effect;\n/**\n * Ensures that an effect's requirements type extends a given type `R`.\n *\n * **Details**\n *\n * This helper is checked at compile time and does not change the effect's\n * runtime behavior.\n *\n * **Example** (Constraining the services type)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * // Define a constraint that requires a string as the requirements type\n * const satisfiesStringServices = Effect.satisfiesServicesType<string>()\n *\n * // This works - effect requires string\n * const validEffect: Effect.Effect<number, never, \"config\"> = Effect.succeed(42)\n * const constrainedEffect = satisfiesStringServices(validEffect)\n *\n * // This would cause a TypeScript compilation error if uncommented:\n * // const invalidEffect: Effect.Effect<number, never, number> = Effect.succeed(42)\n * // const constrainedInvalid = satisfiesStringServices(invalidEffect)\n * ```\n *\n * @category utility types\n * @since 4.0.0\n */\nexport const satisfiesServicesType = () => effect => effect;\n/**\n * Applies `map` eagerly when an effect is already resolved.\n *\n * **When to use**\n *\n * Use when an already-resolved effect should apply a success transformation\n * immediately while pending effects still use regular mapping.\n *\n * **Details**\n *\n * Success effects apply the mapping function immediately. Failure effects pass\n * through unchanged, and pending effects fall back to regular `map` behavior.\n *\n * **Example** (Mapping already completed effects)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * // For resolved effects, the mapping is applied immediately\n * const resolved = Effect.succeed(5)\n * const mapped = Effect.mapEager(resolved, (n) => n * 2) // Applied eagerly\n *\n * // For pending effects, behaves like regular map\n * const pending = Effect.delay(Effect.succeed(5), 0)\n * const mappedPending = Effect.mapEager(pending, (n) => n * 2) // Uses regular map\n *\n * await Effect.runPromise(Effect.all([mapped, mappedPending])) // => [10, 10]\n * ```\n *\n * @category mapping\n * @since 4.0.0\n */\nexport const mapEager = internal.mapEager;\n/**\n * Applies `mapError` eagerly when an effect is already resolved.\n *\n * **When to use**\n *\n * Use when an already-resolved failed effect should apply an error\n * transformation immediately while pending effects still use regular error\n * mapping.\n *\n * **Details**\n *\n * Success effects pass through unchanged because there is no error to\n * transform. Failure effects apply the mapping function immediately, and\n * pending effects fall back to regular `mapError` behavior.\n *\n * **Example** (Mapping errors eagerly when possible)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * // For resolved failure effects, the error mapping is applied immediately\n * const failed = Effect.fail(\"original error\")\n * const mapped = Effect.mapErrorEager(failed, (err: string) => `mapped: ${err}`) // Applied eagerly\n *\n * // For pending effects, behaves like regular mapError\n * const pending = Effect.delay(Effect.fail(\"error\"), 0)\n * const mappedPending = Effect.mapErrorEager(\n * pending,\n * (err: string) => `mapped: ${err}`\n * ) // Uses regular mapError\n *\n * void output.push(await Effect.runPromise(Effect.all([\n * Effect.flip(mapped),\n * Effect.flip(mappedPending)\n * ])))\n * output // => [['mapped: original error', 'mapped: error']]\n * ```\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const mapErrorEager = internal.mapErrorEager;\n/**\n * Applies `mapBoth` eagerly when an effect is already resolved.\n *\n * **When to use**\n *\n * Use when an already-resolved effect should transform either success or\n * failure immediately while pending effects still use regular channel mapping.\n *\n * **Details**\n *\n * Success effects apply `onSuccess` immediately, and failure effects apply\n * `onFailure` immediately. Pending effects fall back to regular `mapBoth`\n * behavior.\n *\n * **Example** (Mapping both channels eagerly when possible)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * // For resolved effects, the appropriate mapping is applied immediately\n * const success = Effect.succeed(5)\n * const mapped = Effect.mapBothEager(success, {\n * onFailure: (err: string) => `Failed: ${err}`,\n * onSuccess: (n: number) => n * 2\n * }) // onSuccess applied eagerly\n *\n * const failure = Effect.fail(\"error\")\n * const mappedError = Effect.mapBothEager(failure, {\n * onFailure: (err: string) => `Failed: ${err}`,\n * onSuccess: (n: number) => n * 2\n * }) // onFailure applied eagerly\n *\n * void output.push(Effect.runSync(mapped))\n * void output.push(Effect.runSync(Effect.flip(mappedError)))\n * output // => [10, \"Failed: error\"]\n * ```\n *\n * @category mapping\n * @since 4.0.0\n */\nexport const mapBothEager = internal.mapBothEager;\n/**\n * Applies `flatMap` eagerly when an effect is already resolved.\n *\n * **When to use**\n *\n * Use when an already-resolved successful effect should bind immediately to the\n * next effect while pending effects still use regular flat mapping.\n *\n * **Details**\n *\n * Success effects apply the flatMap function immediately. Failure effects pass\n * through unchanged, and pending effects fall back to regular `flatMap`\n * behavior.\n *\n * **Example** (Flat mapping eagerly when possible)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * // For resolved effects, the flatMap is applied immediately\n * const resolved = Effect.succeed(5)\n * const flatMapped = Effect.flatMapEager(resolved, (n) => Effect.succeed(n * 2)) // Applied eagerly\n *\n * // For pending effects, behaves like regular flatMap\n * const pending = Effect.delay(Effect.succeed(5), 0)\n * const flatMappedPending = Effect.flatMapEager(\n * pending,\n * (n) => Effect.succeed(n * 2)\n * ) // Uses regular flatMap\n *\n * await Effect.runPromise(Effect.all([flatMapped, flatMappedPending])) // => [10, 10]\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const flatMapEager = internal.flatMapEager;\n/**\n * Applies `catch` eagerly when an effect is already resolved.\n *\n * **When to use**\n *\n * Use when an already-resolved failed effect should recover immediately while\n * pending effects still use regular error recovery.\n *\n * **Details**\n *\n * Success effects pass through unchanged because there is no error to catch.\n * Failure effects apply the catch function immediately, and pending effects\n * fall back to regular `catch` behavior.\n *\n * **Example** (Catching failures eagerly when possible)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * const output: Array<unknown> = []\n *\n * // For resolved failure effects, the catch function is applied immediately\n * const failed = Effect.fail(\"original error\")\n * const recovered = Effect.catchEager(\n * failed,\n * (err: string) => Effect.succeed(`recovered from: ${err}`)\n * ) // Applied eagerly\n *\n * // For success effects, returns success as-is\n * const success = Effect.succeed(42)\n * const unchanged = Effect.catchEager(\n * success,\n * (err: string) => Effect.succeed(`recovered from: ${err}`)\n * ) // Returns success as-is\n *\n * // For pending effects, behaves like regular catch\n * const pending = Effect.delay(Effect.fail(\"error\"), 0)\n * const recoveredPending = Effect.catchEager(\n * pending,\n * (err: string) => Effect.succeed(`recovered from: ${err}`)\n * ) // Uses regular catch\n *\n * void output.push(await Effect.runPromise(Effect.all([\n * recovered,\n * unchanged,\n * recoveredPending\n * ])))\n * output // => [['recovered from: original error', 42, 'recovered from: error']]\n * ```\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchEager = internal.catchEager;\n/**\n * Creates untraced function effects with eager evaluation optimization.\n *\n * **Details**\n *\n * Executes generator functions eagerly when all yielded effects are synchronous,\n * stopping at the first async effect and deferring to normal execution.\n *\n * **Example** (Defining eager untraced effect functions)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n *\n * const computation = Effect.fnUntracedEager(function*() {\n * yield* Effect.succeed(1)\n * yield* Effect.succeed(2)\n * return \"computed eagerly\"\n * })\n *\n * const effect = computation() // Executed immediately if all effects are sync\n * Effect.runSync(effect) // => \"computed eagerly\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fnUntracedEager = internal.fnUntracedEager;\n//# sourceMappingURL=Effect.js.map"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46],"mappings":";AAkDA,MAAa,iBAAiB,MAAM,SAAS;CAC3C,QAAQ,KAAK,QAAb;EACE,KAAK,GACH,OAAO;EACT,KAAK,GACH,OAAO,KAAK,EAAE,CAAC,IAAI;EACrB,KAAK,GACH,OAAO,KAAK,EAAE,CAAC,KAAK,EAAE,CAAC,IAAI,CAAC;EAC9B,KAAK,GACH,OAAO,KAAK,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,EAAE,CAAC,IAAI,CAAC,CAAC;EACvC,KAAK,GACH,OAAO,KAAK,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;EAChD,KAAK,GACH,OAAO,KAAK,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;EACzD,KAAK,GACH,OAAO,KAAK,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;EAClE,KAAK,GACH,OAAO,KAAK,EAAE,CAAC,KAAK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