{"version":3,"file":"index.mjs","names":["Prototype","Class","symbol","number","string","withVisitedTracking","equals","Hash.hash","emptyContext","format","Predicate.hasProperty","Predicate.hasProperty","Predicate.isFunction","format","format","Hash.symbol","Hash.structureKeys","Equal.symbol","Equal.equals","Hash.array","isFailReason","Hash.combine","Hash.string","Hash.hash","InterruptorStackTrace","withFiber","Error","TaggedError","isDone","Done","done","make","Tuple","TypeId","CommonProto","Equal.symbol","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","isLessThan","isGreaterThan","isLessThanOrEqualTo","isGreaterThanOrEqualTo","option.none","option.some","option.isNone","option.isSome","match","map","flatMap","get","make","withFiber","TypeId","Proto","makeUnsafe","Equal.symbol","Equal.equals","Hash.symbol","Hash.number","empty","Option.some","Option.none","merge","mergeAll","isArrayNonEmpty","normalize","succeed","result.succeed","fail","result.fail","isFailure","result.isFailure","isSuccess","result.isSuccess","match","makeEquivalence","Equivalence.Tuple","map","Array","fromIterable","append","internalArray.isArrayNonEmpty","empty","map","Equivalence.Array","TypeId","bigint0","bigint1","bigint10","fromInputUnsafe","invalid","zero","make","Hash.symbol","Hash.hash","Hash.number","Hash.structure","Equal.symbol","equals","isFinite","Equivalence","Result.fail","Result.succeed","Pipeable.Class","Error","core.Error","core.TaggedError","Data.TaggedError","encodeBase64","decodeBase64","Result.fail","Result.succeed","Context.Service","Equal.symbol","Hash.symbol","Hash.combine","Hash.string","Hash.random","isFailReason","Result.succeed","Result.fail","hasDies","hasInterruptsOnly","hash","Hash.hash","Equal.equals","CauseStackTrace","InterruptorStackTrace","Context.get","Context.make","failCause","flatMap","Context.empty","Context.hasSameCache","Context.getOrUndefinedUnsafe","Tracer.TracerKey","Scheduler.Scheduler","Tracer.ParentSpanKey","InternalMetric.FiberRuntimeMetricsKey","Scheduler.MaxOpsBeforeYield","Scheduler.PreventSchedulerYield","Context.makeUnsafe","succeed","callback","sync","withFiber","Context.merge","Arr.empty","fail","suspend","fromResult","succeedNone","failCauseSync","die","void_","try_","UnknownError","tryPromise","gen","fnUntraced","fnUntracedEager","as","map","Option.some","andThen","tap","uninterruptible","forkUnsafe","raceFirst","flatMapEager","mapEager","mapErrorEager","mapError","exitInterrupt","Result.isFailure","serviceOption","Context.getOption","provideContext","Context.add","forever","whileLoop","catchCause","catch_","catchTag","orDie","ignore","matchEffect","exit","scope","scoped","scopedWith","onExit","acquireRelease","uninterruptibleMask","addFinalizer","ensuring","onError","interrupt","forEach","Arr.fromIterable","forkIn","forkScoped","runForkWith","runFork","runPromiseExit","Scheduler.MixedScheduler","runSyncExit","Duration.toMillis","clockWith","sleep","Duration.fromInputUnsafe","TaggedError","IllegalArgumentError","Order.Number","TypeId","makeUnsafe","internalEffect.callback","internalEffect.sync","done","isDone","effect.scopeTag","makeUnsafe","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.Service","Context.getOrUndefined","internalEffect.provideService","internalEffect.map","Context.add","core.withFiber","succeed","Context.make","internalEffect.succeed","Scope.provide","internalEffect.forEach","Context.mergeAll","internalEffect.provideContext","Context.merge","succeed","core.exitSucceed","failCause","core.exitFailCause","fail","core.exitFail","void_","effect.exitVoid","effect.exitIsSuccess","effect.exitIsFailure","core.isFailReason","core.causeFromReasons","fail","core.causeFail","effect.hasInterruptsOnly","map","effect.causeMap","effect.hasDies","effect.causePretty","core.isDone","core.Done","core.done","effect.IllegalArgumentError","effect.UnknownError","Context.Service","TypeId","Proto","Inspectable.NodeInspectSymbol","toDateUtc","Hash.symbol","Hash.number","Equal.symbol","isDateTime","Hash.combine","Hash.hash","Equal.equals","Hash.string","Predicate.hasProperty","isUtc","makeUnsafe","make","toUtc","toEpochMillis","formatIso","internalEffect.catchCauseFilter","Cause.isDone","Result.fail","Cause.fromReasons","Result.succeed","Result.isFailure","Exit.succeed","Exit.failCause","matchEffect","internalEffect.matchCauseEffect","effect.scopedWith","effect.flatMap","Layer.buildWithMemoMap","Layer.makeMemoMapUnsafe","Layer.buildWithScope","effect.provideContext","provide","Context.isContext","Layer.mergeAll","forEach","internal.forEach","internal.whileLoop","internal.tryPromise","succeed","internal.succeed","internal.succeedNone","suspend","internal.suspend","internal.sync","internal.void","callback","internal.callback","internal.gen","fail","internal.fail","failCause","internal.failCause","internal.failCauseSync","internal.die","internal.try","core.withFiber","internal.fromResult","internal.flatMap","internal.andThen","internal.tap","internal.exit","map","internal.map","internal.as","internal.catch_","internal.catchTag","internal.catchCause","internal.mapError","internal.orDie","internal.ignore","internal.sleep","internal.raceFirst","internal.matchEffect","internalLayer.provide","internal.provideContext","internal.serviceOption","internal.scope","internal.scoped","internal.scopedWith","internal.acquireRelease","internal.addFinalizer","internal.ensuring","internal.onError","internal.onExit","interrupt","internal.interrupt","internal.uninterruptible","internal.uninterruptibleMask","internal.forever","internal.forkIn","internal.forkScoped","internal.runFork","internal.runForkWith","internal.runPromiseExit","internal.runSyncExit","internal.fnUntraced","internal.clockWith","Context.Service","internal.mapEager","internal.mapErrorEager","internal.flatMapEager","internal.fnUntracedEager","BigInt","Option.none","Option.some","bigint0","bigint1","make","TypeId","Data.TaggedError","Data.Error","effect.fiberJoin","effect.fiberInterrupt","effect.fiberRunIn","makeUnsafe","internal.makeLatchUnsafe","TypeId","make","make","Count.normalize","take","TypeId","variance","make","core.withFiber","MutableList.make","internalEffect.succeed","internalEffect.suspend","internalEffect.sync","core.exitFailCause","internalEffect.exitZipRight","core.causeFail","core.Done","core.exitSucceed","Count.normalize","internalEffect.andThen","Option.none","Option.some","MutableList.take","internalEffect.exitVoid","MutableList.takeN","internalEffect.callback","Pull.isDoneCause","makeUnsafe","internal.callback","internal.sync","internal.suspend","internal.succeed","core.withFiber","internal.void","internal.uninterruptibleMask","internal.flatMap","internal.onExitPrimitive","internal.getCurrentFiber","internal.succeedNone","internal.asSome","TypeId","identity_","fromTransform","Effect.catchCause","Effect.succeed","Effect.failCause","transformPull","Effect.flatMap","fromPull","Effect.fnUntraced","Scope.forkUnsafe","Scope.close","Pull.doneExitFromCause","Effect.onError","Queue.make","Effect.tap","Scope.addFinalizer","Queue.shutdown","Effect.forkIn","Scope.provide","Effect.map","Queue.takeAll","suspend","Effect.suspend","succeed","empty","Effect.sync","done","Cause.done","map","Pull.catchDone","Result.isSuccess","Arr.isReadonlyArrayNonEmpty","merge","Queue.bounded","Pull.isDoneCause","Queue.failCause","Effect.void","Queue.offer","Effect.forever","Effect.andThen","Queue.take","splitLines","Option.none","Pull.matchEffect","Option.some","unwrap","Scope.makeUnsafe","Effect.onExit","runFold","Effect.whileLoop","runFoldEffect","TypeId","fromChannel","TypeId","fromChannel","Channel.toTransform","Effect.flatMap","Effect.forever","Pull.catchDone","Effect.succeed","toChannel","Channel.fromTransform","Cause.done","Effect.forEach","unwrap","Channel.unwrap","Effect.map","TypeId","make","Effect.withFiber","Context.get","Scope.Scope","Duration.fromInputUnsafe","Effect.as","Scope.addFinalizerExit","close","Scope.close","Exit.void","Effect.void","Effect.uninterruptibleMask","Effect.interrupt","Fiber.interrupt","Effect.succeed","Scope.makeUnsafe","Effect.suspend","Effect.provideContext","Context.add","Effect.flatMap","Effect.onExit","Exit.isFailure","get","scope","Effect.scope","Duration.isFinite","Effect.sleep","Effect.ensuring","Effect.sync","Effect.runForkWith","Fiber.runIn","make","internal.make","internal.get","TypeId","internal.fromChannel","Channel.fromPull","Channel.fromTransform","Effect.flatMap","Channel.toPullScoped","Channel.callbackArray","Channel.empty","make","Channel.suspend","Arr.isReadonlyArrayNonEmpty","Channel.succeed","Channel.unwrap","Effect.map","Channel.map","Arr.map","Channel.merge","Channel.filterMapArray","Effect.sync","done","Effect.suspend","Effect.succeed","Effect.catch","Exit.fail","Cause.done","Arr.of","Channel.pipeTo","Channel.splitLines","run","Effect.scopedWith","Channel.runFold","Channel.runFoldEffect","Effect.whileLoop","TypeId","make","Effect.as","Effect.catchTag","Effect.succeed","Effect.fail","Effect.flatMap","Effect.try","Effect.fnUntraced","ByteSize.fromInputUnsafe","Stream.fromPull","Effect.suspend","Cause.done","Option.match","Arr.of","Stream.unwrap","Effect.map","Sink.forEach","Sink.unwrap","Context.Service","TypeId","Path","Exit.succeed","Option.none","Option.some","TypeId","InternalParser.missing","Filter","Arr.isReadonlyArrayNonEmpty","Arr.map","InternalAnnotations.getExpected","format","Cause.isFailReason","SchemaIssue.isIssue","Internal.isDateTime","Internal.isUtc","Internal.makeUnsafe","make","Internal.make","Internal.toUtc","Internal.toDateUtc","Internal.toEpochMillis","Context.Service","Internal.formatIso","Pipeable.Class","Effect.mapEager","Option.map","Effect.flatMapEager","Effect.fail","Option.isSome","SchemaIssue.Forbidden","passthrough_","Effect.succeed","passthrough","Option.isNone","Effect.succeedNone","transform","transformEffect","Option.some","Option.filter","Predicate.isNotUndefined","String","Number","BigInt","Date","Effect.try","SchemaIssue.InvalidValue","Encoding.encodeBase64","Effect.mapErrorEager","Effect.fromResult","Encoding.decodeBase64","TypeId","Hash.symbol","Hash.combine","Hash.hash","Hash.number","Equal.symbol","make","Equivalence","TypeId","Predicate.hasProperty","make","SchemaGetter.transformEffect","SchemaGetter.transform","Effect.succeed","Effect.fail","SchemaIssue.InvalidValue","fromJsonString","SchemaGetter.parseJson","SchemaGetter.stringifyJson","TypeId","InternalParser.missing","InternalParser.missingExit","Undefined","SchemaTransformation.Transformation","Predicate.isUnknown","Literal","format","SchemaGetter.transform","String","Predicate.isString","Number","Predicate.isNumber","Effect.fnUntracedEager","Effect.fail","SchemaIssue.InvalidType","SchemaIssue.UnexpectedKey","SchemaIssue.Pointer","SchemaIssue.Composite","InternalParser.sameExit","InternalParser.args","SchemaIssue.MissingKey","Exit.fail","InternalSchemaCause.getSchemaIssue","Exit.failCause","Cause.map","Predicate.isNotNullish","Exit.void","Effect.flatMap","Effect.exit","Arr.empty","InternalParser.succeed","Effect.flatMapEager","Effect.die","Union","InternalAnnotations.SENTINELS_ANNOTATION_KEY","Predicate.isObjectKeyword","SchemaIssue.AnyOf","Effect.catchCause","Effect.succeed","SchemaIssue.OneOf","Pipeable.Class","makeFilter","SchemaIssue.normalizeFilterOutput","isPattern","Arr.append","optional","withConstructorDefault","SchemaGetter.withDefault","SchemaGetter.passthrough","decodeTo","Predicate.isPropertyKey","Arr.isArrayNonEmpty","succeed","SchemaTransformation.numberFromString","SchemaTransformation.bigintFromString","SchemaIssue.Filter","InternalAnnotations.CONSTRUCTOR_ANNOTATION_KEY","Predicate.isFunction","Option.some","Result.succeed","Inspectable.BaseProto","make","Effect.map","Stream.decodeText","Stream.unwrap","Stream.splitLines","Effect.scoped","Effect.flatMap","Stream.runCollect","Stream.mkString","Context.Service","TypeId","Proto","Context.getUnsafe","make","PlatformError.systemError","Sink.fromChannel","Channel.mapDone","Channel.fromTransform","Effect.succeed","Effect.flatMap","Effect.callback","Effect.void","Effect.sync","Effect.forever","Pull.catchDone","Cause.done","Effect.raceFirst","Effect.fail","Stream.fromChannel","Channel.fromTransform","MutableRef.make","Latch.makeUnsafe","Exit.fail","Cause.Done","Effect.suspend","Effect.fail","Effect.flatMap","Arr.of","Effect.succeed","Effect.as","Scope.addFinalizer","Effect.sync","Cause.UnknownError","Deferred.isDoneUnsafe","make","FileSystem.FileSystem","Path.Path","Effect.fnUntraced","Predicate.isUndefined","Stream.isStream","Sink.isSink","ChildProcess.parseFdName","Predicate.isNotUndefined","Sink.drain","Stream.empty","NodeSink.fromWritable","Effect.forkScoped","Stream.run","NodeStream.fromReadable","Stream.transduce","Effect.suspend","Predicate.isNotNull","Effect.as","Effect.succeed","Stream.merge","Effect.callback","Deferred.makeUnsafe","Effect.fail","Exit.succeed","Effect.sync","Effect.void","Effect.try","Effect.catch","Duration.toMillis","Deferred.await","Effect.acquireRelease","Deferred.isDone","Effect.ignore","Effect.map","Effect.flatMap","Stream.unwrap","ChildProcess.make","fdName","ChildProcess.fdName","Effect.forEach","Effect.gen","makeSpawner","layer","TypeId","make","Effect.map","Effect.sync","random.nextBetween","Uuid.v4String","Effect.clockWith","Effect.succeed","Uuid.v7String","Effect.fail","PlatformError.badArgument","Effect.try","PlatformError.systemError","make","layer","EffectCrypto.Crypto","layer","NodeCrypto.layer","Error.badArgument","Option.flatMap","Option.fromNullishOr","BI.toNumber","Effect.try","link","Effect.suspend","Effect.acquireRelease","Effect.orDie","Effect.map","FileSystem.FileTypeId","Effect.flatMap","Effect.fail","Effect.succeed","Option.none","Option.some","Error.systemError","Effect.void","Effect.fnUntraced","Crypto","Effect.tryPromise","Effect.callback","ByteSize.bytes","Stream.callback","Effect.sync","Effect.matchEffect","Queue.offer","Cause.fail","Option.getOrElse","Stream.unwrap","FileSystem.WatchBackend","FileSystem.make","layer","FileSystem.FileSystem","layer","NodeFileSystem.layer","Effect.try","Path","TypeId","NodePath","layer","layer","NodePath.layer","TypeId","make","Effect.succeed","layer","Stdio.Stdio","layer","NodeStdio.layer","SchemaAST.toType","Effect.runSyncExit","Exit.isSuccess","Option.some","Option.none","make","InternalSchemaCause.getSchemaIssueOrThrow","decodeUnknownOption","InternalParser.missing","Effect.fail","SchemaIssue.InvalidValue","Effect.succeed","SchemaAST.defaultParseOptions","InternalParser.sameExit","Effect.flatMapEager","InternalParser.args","InternalParser.toOption","InternalParser.succeed","Effect.mapEager","InternalParser.fromOptionExit","InternalParser.missingExit","SchemaAST.getConstructorDescriptor","SchemaAST.collectIssues","SchemaIssue.Composite","Effect.flatMap","Effect.catchCause","Effect.failCauseSync","Cause.map","SchemaIssue.Encoding","TypeId","Pipeable.pipeArguments","SchemaAST.annotate","SchemaAST.annotateKey","SchemaAST.appendChecks","make","SchemaParser.makeEffect","SchemaParser.make","SchemaParser.makeOption","TypeId","Predicate.hasProperty","Data.Error","Data.TaggedError","Proto","Inspectable.BaseProto","Record.map","Duration.seconds","Result.fail","Result.succeed","Duration.isFinite","Duration.fromInputUnsafe","Result.getOrThrow","Duration.toSeconds","toRecord","TypeId","Equal.symbol","Hash.symbol","Hash.array","make","Arr.fromIterable","TypeId","InternalMake.TypeId","make","SchemaAST.Declaration","SchemaAST.getAST","Effect.succeed","Effect.fail","SchemaIssue.InvalidType","Data.TaggedError","SchemaIssue.defaultFormatter","SchemaParser.decodeUnknownOption","InternalMake.make","Predicate.hasProperty","SchemaAST.optional","SchemaAST.Literal","SchemaGetter.transform","SchemaAST.undefined","String","SchemaAST.string","Number","SchemaAST.number","SchemaAST.struct","SchemaAST.record","SchemaAST.tuple","SchemaAST.Arrays","SchemaAST.union","SchemaAST.decodeTo","SchemaTransformation.make","SchemaTransformation.passthrough","SchemaGetter.forbiddenEncoding","SchemaAST.withConstructorDefault","SchemaAST.Link","SchemaAST.makeFilter","format","SchemaAST.isPattern","Order.isGreaterThan","Order.isGreaterThanOrEqualTo","Order.isLessThan","Order.isLessThanOrEqualTo","Order.Number","Order.Date","Order.BigInt","RegExp","SchemaTransformation.transformEffect","Effect.try","SchemaIssue.InvalidValue","URL","SchemaTransformation.urlFromString","Date","SchemaTransformation.dateFromString","SchemaTransformation.fromJsonString","Result_.match","Encoding.decodeBase64","Effect.tryPromise","Encoding.encodeBase64","FormData","URLSearchParams","SchemaTransformation.transform","Uint8Array","SchemaTransformation.uint8ArrayFromBase64String","BigDecimal_.Order","BigDecimal_.format","SchemaGetter.transformEffect","Option_.match","DateTime.make","DateTime.toUtc","DateTime.formatIso","DateTime.isDateTime","DateTime.isUtc","DateTime.makeUnsafe","DateTime.toDateUtc","DateTime.toEpochMillis","Cookies_.isCookie","Cookies_.isCookies","Cookies_.fromSetCookie","Cookies_.toSetCookieHeaders","Cookies_.fromReadonlyRecord","Cookies_.toRecord","Cookies_.fromIterable","Cookies_.makeCookieUnsafe","UrlParams_.isUrlParams","UrlParams_.Equivalence","UrlParams_.make","UrlParams_.toReadonlyRecord","UrlParams_.fromInput","struct","internalOptions","Pipeable.pipeArguments","SchemaParser.make","SchemaParser.makeOption","SchemaAST.annotate","SchemaAST.annotateKey","SchemaAST.appendChecks","SchemaTransformation.Transformation","SchemaGetter.passthrough","InternalAnnotations.CONSTRUCTOR_ANNOTATION_KEY","InternalAnnotations.SENTINELS_ANNOTATION_KEY","SchemaAST.collectSentinels","Error","core.Error","Schema.Error","make","Queue.make","Effect.addFinalizer","Effect.sync","RcRef.make","Effect.acquireRelease","Queue.offerUnsafe","Effect.gen","Option.fromUndefinedOr","RcRef.get","Effect.suspend","Queue.poll","Effect.flatMap","Option.match","Effect.scoped","Effect.andThen","Queue.take","Effect.succeed","Effect.mapError","Terminal.QuitError","Effect.uninterruptible","Effect.callback","Predicate.isNullish","Effect.void","Effect.fail","Terminal.make","layer","Terminal.Terminal","layer","NodeTerminal.layer","NodeChildProcessSpawner.layer","NodeFileSystem.layer","NodeCrypto.layer","NodePath.layer","NodeStdio.layer","NodeTerminal.layer","Cause.hasInterruptsOnly","Cause.hasDies","Cause.pretty","Cause.isFailReason","Inspectable.toStringUnknown","Effect.runPromiseExit","Exit.isFailure","Data.TaggedError","Schema.Struct","Schema.Literal","Schema.String","Schema.Array","Schema.optional","Schema.Number","Schema.fromJsonString","Schema.Union","Effect.scoped","Effect.gen","path","fs","ChildProcess.make","Stream.make","Effect.forkScoped","Stream.decodeText","Stream.runFold","Stream.splitLines","Stream.filterMap","Filter.fromPredicateOption","Schema.decodeUnknownOption","Stream.runFoldEffect","Effect.sync","Fiber.join","path","Effect.map","Effect.catch","Effect.succeed","Effect.tap","Effect.sync","Effect.provide","NodeServices.layer"],"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/internal/array.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/internal/count.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/Tuple.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Record.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/Duration.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Filter.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/effect.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/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/Exit.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/dateTime.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/internal/layer.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Effect.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/BigInt.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/ByteSize.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/PlatformError.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Fiber.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Latch.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/MutableRef.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/MutableList.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Queue.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Semaphore.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Channel.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/internal/stream.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Sink.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/internal/rcRef.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/RcRef.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Stream.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/FileSystem.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Path.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/internal/schema/annotations.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/internal/schema/parser.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/SchemaIssue.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/internal/schema/cause.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/DateTime.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/SchemaGetter.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/BigDecimal.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/SchemaTransformation.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/SchemaAST.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Brand.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/unstable/process/ChildProcessSpawner.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/unstable/process/ChildProcess.js","../../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-rc.115_effect@4.0.0-rc.115/node_modules/@effect/platform-node-shared/dist/internal/nodeChildProcessSpawner.js","../../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-rc.115_effect@4.0.0-rc.115/node_modules/@effect/platform-node-shared/dist/internal/utils.js","../../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-rc.115_effect@4.0.0-rc.115/node_modules/@effect/platform-node-shared/dist/NodeSink.js","../../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-rc.115_effect@4.0.0-rc.115/node_modules/@effect/platform-node-shared/dist/NodeStream.js","../../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-rc.115_effect@4.0.0-rc.115/node_modules/@effect/platform-node-shared/dist/NodeChildProcessSpawner.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/internal/uuid.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Crypto.js","../../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-rc.115_effect@4.0.0-rc.115/node_modules/@effect/platform-node-shared/dist/NodeCrypto.js","../../../node_modules/.pnpm/@effect+platform-node@4.0.0-rc.115_effect@4.0.0-rc.115_redis@6.2.1_@opentelemetry+api@1.9.0_/node_modules/@effect/platform-node/dist/NodeCrypto.js","../../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-rc.115_effect@4.0.0-rc.115/node_modules/@effect/platform-node-shared/dist/NodeFileSystem.js","../../../node_modules/.pnpm/@effect+platform-node@4.0.0-rc.115_effect@4.0.0-rc.115_redis@6.2.1_@opentelemetry+api@1.9.0_/node_modules/@effect/platform-node/dist/NodeFileSystem.js","../../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-rc.115_effect@4.0.0-rc.115/node_modules/@effect/platform-node-shared/dist/NodePath.js","../../../node_modules/.pnpm/@effect+platform-node@4.0.0-rc.115_effect@4.0.0-rc.115_redis@6.2.1_@opentelemetry+api@1.9.0_/node_modules/@effect/platform-node/dist/NodePath.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Stdio.js","../../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-rc.115_effect@4.0.0-rc.115/node_modules/@effect/platform-node-shared/dist/NodeStdio.js","../../../node_modules/.pnpm/@effect+platform-node@4.0.0-rc.115_effect@4.0.0-rc.115_redis@6.2.1_@opentelemetry+api@1.9.0_/node_modules/@effect/platform-node/dist/NodeStdio.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/SchemaParser.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/internal/schema/make.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Struct.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/internal/schemaError.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/unstable/http/Cookies.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/unstable/http/UrlParams.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Schema.js","../../../node_modules/.pnpm/effect@4.0.0-rc.115/node_modules/effect/dist/Terminal.js","../../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-rc.115_effect@4.0.0-rc.115/node_modules/@effect/platform-node-shared/dist/NodeTerminal.js","../../../node_modules/.pnpm/@effect+platform-node@4.0.0-rc.115_effect@4.0.0-rc.115_redis@6.2.1_@opentelemetry+api@1.9.0_/node_modules/@effect/platform-node/dist/NodeTerminal.js","../../../node_modules/.pnpm/@effect+platform-node@4.0.0-rc.115_effect@4.0.0-rc.115_redis@6.2.1_@opentelemetry+api@1.9.0_/node_modules/@effect/platform-node/dist/NodeServices.js","../../../tooling/shared/src/run.ts","../../../tooling/shared/src/ui.ts","../src/runner.ts","../src/utils.ts","../src/index.ts"],"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 * @since 2.0.0\n */\n/** @internal */\nexport const isArrayNonEmpty = self => self.length > 0;\n//# sourceMappingURL=array.js.map","/**\n * Normalizes a collection count to a non-negative integer. `NaN` and\n * non-positive values become `0`; positive infinity is preserved.\n *\n * @internal\n */\nexport const normalize = n => n > 0 ? Math.floor(n) : 0;\n/**\n * Normalizes a collection count to an integer greater than or equal to `1`.\n *\n * @internal\n */\nexport const normalizeNonEmpty = n => Math.max(1, normalize(n));\n//# sourceMappingURL=count.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 fixed-length arrays, also called tuples.\n *\n * The runtime helpers in this module create new tuples instead of mutating\n * their inputs, and the types preserve element positions where possible. The\n * helpers cover tuple construction, indexed access, selecting or removing\n * positions, appending values, transforming elements, renaming indices, mapping\n * typed positions, and deriving comparison or combination helpers for tuple\n * shapes.\n *\n * @since 2.0.0\n */\nimport * as Combiner from \"./Combiner.js\";\nimport * as Equivalence from \"./Equivalence.js\";\nimport { dual } from \"./Function.js\";\nimport * as order from \"./Order.js\";\nimport * as Reducer from \"./Reducer.js\";\n/**\n * Creates a tuple from the provided arguments.\n *\n * **When to use**\n *\n * Use when you need a properly typed tuple without writing `[a, b, c] as const`\n * or another manual cast.\n *\n * **Details**\n *\n * The returned value has the exact tuple type, with each element's literal type\n * preserved.\n *\n * **Example** (Creating a tuple)\n *\n * ```ts import.meta.vitest\n * import { Tuple } from \"effect\"\n *\n * Tuple.make(10, 20, \"red\") // => [10, 20, \"red\"]\n * ```\n *\n * @see {@link get} – access a single element by index\n * @see {@link appendElement} – append an element to a tuple\n * @category constructors\n * @since 2.0.0\n */\nexport const make = (...elements) => elements;\n/**\n * Retrieves the element at the specified index from a tuple.\n *\n * **When to use**\n *\n * Use when a single tuple element should be extracted in a pipeline.\n *\n * **Details**\n *\n * The index is constrained to valid tuple positions at the type level.\n *\n * **Example** (Extracting an element by index)\n *\n * ```ts import.meta.vitest\n * import { pipe, Tuple } from \"effect\"\n *\n * pipe(Tuple.make(1, true, \"hello\"), Tuple.get(2)) // => \"hello\"\n * ```\n *\n * @see {@link make} – create a tuple\n * @see {@link pick} – extract multiple elements into a new tuple\n * @category getters\n * @since 4.0.0\n */\nexport const get = /*#__PURE__*/dual(2, (self, index) => self[index]);\n/**\n * Creates a new tuple containing only the elements at the specified indices.\n *\n * **When to use**\n *\n * Use to select a subset of elements from a tuple by position.\n *\n * **Details**\n *\n * The result order matches the order of the provided indices.\n *\n * **Example** (Selecting elements by index)\n *\n * ```ts import.meta.vitest\n * import { Tuple } from \"effect\"\n *\n * Tuple.pick([\"a\", \"b\", \"c\", \"d\"], [0, 2, 3]) // => [\"a\", \"c\", \"d\"]\n * ```\n *\n * @see {@link omit} – the inverse (exclude indices instead)\n * @see {@link get} – extract a single element\n * @category filtering\n * @since 4.0.0\n */\nexport const pick = /*#__PURE__*/dual(2, (self, indices) => {\n  return indices.map(i => self[i]);\n});\n/**\n * Creates a new tuple with the elements at the specified indices removed.\n *\n * **When to use**\n *\n * Use to drop elements from a tuple by position.\n *\n * **Details**\n *\n * Elements not at the specified indices are kept in their original order.\n *\n * **Example** (Removing elements by index)\n *\n * ```ts import.meta.vitest\n * import { Tuple } from \"effect\"\n *\n * Tuple.omit([\"a\", \"b\", \"c\", \"d\"], [1, 3]) // => [\"a\", \"c\"]\n * ```\n *\n * @see {@link pick} – the inverse (keep only specified indices)\n * @category filtering\n * @since 4.0.0\n */\nexport const omit = /*#__PURE__*/dual(2, (self, indices) => {\n  const toDrop = new Set(indices);\n  return self.filter((_, i) => !toDrop.has(i));\n});\n/**\n * Appends a single element to the end of a tuple.\n *\n * **When to use**\n *\n * Use when you need the appended value to remain part of the tuple's type-level\n * shape and preserve literal element positions.\n *\n * **Details**\n *\n * The result type is `[...T, E]`, preserving all existing element types.\n *\n * **Example** (Appending an element)\n *\n * ```ts import.meta.vitest\n * import { pipe, Tuple } from \"effect\"\n *\n * pipe(Tuple.make(1, 2), Tuple.appendElement(\"end\")) // => [1, 2, \"end\"]\n * ```\n *\n * @see {@link appendElements} – append multiple elements (another tuple)\n * @category combining\n * @since 2.0.0\n */\nexport const appendElement = /*#__PURE__*/dual(2, (self, element) => [...self, element]);\n/**\n * Concatenates two tuples into a single tuple.\n *\n * **When to use**\n *\n * Use to append all elements from one tuple to another tuple.\n *\n * **Details**\n *\n * The result type is `[...T1, ...T2]`, preserving all element types from both\n * tuples. Neither input tuple is mutated; a fresh tuple is returned.\n *\n * **Example** (Concatenating tuples)\n *\n * ```ts import.meta.vitest\n * import { pipe, Tuple } from \"effect\"\n *\n * pipe(Tuple.make(1, 2), Tuple.appendElements([\"a\", \"b\"] as const)) // => [1, 2, \"a\", \"b\"]\n * ```\n *\n * @see {@link appendElement} – append a single element\n * @category combining\n * @since 4.0.0\n */\nexport const appendElements = /*#__PURE__*/dual(2, (self, that) => [...self, ...that]);\n/**\n * Transforms elements of a tuple by providing an array of transform functions.\n * Each function applies to the element at the same position. Positions beyond\n * the array's length are copied unchanged.\n *\n * **When to use**\n *\n * Use when you want to update the first N elements while keeping the rest.\n *\n * **Details**\n *\n * Each transform function receives the current value and can return a different\n * type.\n *\n * **Example** (Transforming selected elements)\n *\n * ```ts import.meta.vitest\n * import { pipe, Tuple } from \"effect\"\n *\n * pipe(\n *   Tuple.make(\"hello\", 42, true),\n *   Tuple.evolve([\n *     (s) => s.toUpperCase(),\n *     (n) => n * 2\n *   ])\n * ) // => [\"HELLO\", 84, true]\n * ```\n *\n * @see {@link map} – apply the same transformation to all elements\n * @see {@link renameIndices} – swap element positions\n * @category mapping\n * @since 4.0.0\n */\nexport const evolve = /*#__PURE__*/dual(2, (self, evolver) => {\n  return self.map((e, i) => evolver[i] !== undefined ? evolver[i](e) : e);\n});\n/**\n * Renames tuple indices by providing an array of stringified source\n * indices. Each position in the array specifies which index to read from\n * (e.g., `[\"2\", \"1\", \"0\"]` reverses a 3-element tuple).\n *\n * **When to use**\n *\n * Use to reorder tuple elements while preserving index-specific types.\n *\n * **Details**\n *\n * The mapping returns a tuple in the requested index order.\n *\n * **Gotchas**\n *\n * The mapping uses stringified source indices, not arbitrary names.\n *\n * **Example** (Swapping elements)\n *\n * ```ts import.meta.vitest\n * import { pipe, Tuple } from \"effect\"\n *\n * pipe(\n *   Tuple.make(\"a\", \"b\", \"c\"),\n *   Tuple.renameIndices([\"2\", \"1\", \"0\"])\n * ) // => [\"c\", \"b\", \"a\"]\n * ```\n *\n * @see {@link evolve} – transform element values instead of positions\n * @category transforming\n * @since 4.0.0\n */\nexport const renameIndices = /*#__PURE__*/dual(2, (self, mapping) => {\n  return self.map((e, i) => mapping[i] !== undefined ? self[mapping[i]] : e);\n});\n/**\n * Applies a `Struct.Lambda` transformation to every element in a tuple.\n *\n * **When to use**\n *\n * Use when you want to apply the same transformation to every tuple element.\n *\n * **Details**\n *\n * The lambda lets the compiler track the output type for each element.\n *\n * **Gotchas**\n *\n * The lambda must be created with `Struct.lambda`; a plain function will not\n * type-check.\n *\n * **Example** (Wrapping every element in an array)\n *\n * ```ts import.meta.vitest\n * import { pipe, Struct, Tuple } from \"effect\"\n *\n * interface AsArray extends Struct.Lambda {\n *   <A>(self: A): Array<A>\n *   readonly \"~lambda.out\": Array<this[\"~lambda.in\"]>\n * }\n *\n * const asArray = Struct.lambda<AsArray>((a) => [a])\n * pipe(Tuple.make(1, \"hello\", true), Tuple.map(asArray)) // => [[1], [\"hello\"], [true]]\n * ```\n *\n * @see {@link mapPick} – apply a lambda only to selected indices\n * @see {@link mapOmit} – apply a lambda to all indices except selected ones\n * @see {@link evolve} – apply different functions to different indices\n * @category mapping\n * @since 3.9.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, lambda) => {\n  return self.map(e => lambda(e));\n});\n/**\n * Applies a `Struct.Lambda` transformation only to the elements at the\n * specified indices; all other elements are copied unchanged.\n *\n * **When to use**\n *\n * Use when you want to apply the same transformation to a subset of\n * positions.\n *\n * **Example** (Wrapping only selected elements in arrays)\n *\n * ```ts import.meta.vitest\n * import { pipe, Struct, Tuple } from \"effect\"\n *\n * interface AsArray extends Struct.Lambda {\n *   <A>(self: A): Array<A>\n *   readonly \"~lambda.out\": Array<this[\"~lambda.in\"]>\n * }\n *\n * const asArray = Struct.lambda<AsArray>((a) => [a])\n * pipe(\n *   Tuple.make(1, \"hello\", true),\n *   Tuple.mapPick([0, 2], asArray)\n * ) // => [[1], \"hello\", [true]]\n * ```\n *\n * @see {@link map} – apply a lambda to all elements\n * @see {@link mapOmit} – apply a lambda to all elements except selected ones\n * @category mapping\n * @since 4.0.0\n */\nexport const mapPick = /*#__PURE__*/dual(3, (self, indices, lambda) => {\n  const toPick = new Set(indices);\n  return self.map((e, i) => toPick.has(i) ? lambda(e) : e);\n});\n/**\n * Applies a `Struct.Lambda` transformation to all elements except those at the\n * specified indices; the excluded elements are copied unchanged.\n *\n * **When to use**\n *\n * Use when most elements should be transformed but a few should be\n * preserved.\n *\n * **Example** (Wrapping all elements except one in arrays)\n *\n * ```ts import.meta.vitest\n * import { pipe, Struct, Tuple } from \"effect\"\n *\n * interface AsArray extends Struct.Lambda {\n *   <A>(self: A): Array<A>\n *   readonly \"~lambda.out\": Array<this[\"~lambda.in\"]>\n * }\n *\n * const asArray = Struct.lambda<AsArray>((a) => [a])\n * pipe(\n *   Tuple.make(1, \"hello\", true),\n *   Tuple.mapOmit([1], asArray)\n * ) // => [[1], \"hello\", [true]]\n * ```\n *\n * @see {@link map} – apply a lambda to all elements\n * @see {@link mapPick} – apply a lambda only to selected indices\n * @category mapping\n * @since 4.0.0\n */\nexport const mapOmit = /*#__PURE__*/dual(3, (self, indices, lambda) => {\n  const toOmit = new Set(indices);\n  return self.map((e, i) => toOmit.has(i) ? e : lambda(e));\n});\n/**\n * Creates an `Equivalence` for tuples by comparing corresponding elements\n * using the provided per-position `Equivalence`s. Two tuples are equivalent\n * when all their corresponding elements are equivalent.\n *\n * **When to use**\n *\n * Use when you need an `Equivalence` to compare tuples element-by-element.\n *\n * **Details**\n *\n * This is an alias of `Equivalence.Tuple`.\n *\n * **Example** (Comparing tuples for equivalence)\n *\n * ```ts import.meta.vitest\n * import { Equivalence, Tuple } from \"effect\"\n *\n * const eq = Tuple.makeEquivalence([\n *   Equivalence.strictEqual<string>(),\n *   Equivalence.strictEqual<number>()\n * ])\n *\n * eq([\"Alice\", 30], [\"Alice\", 30]) // => true\n * eq([\"Alice\", 30], [\"Bob\", 30]) // => false\n * ```\n *\n * @see {@link makeOrder} – create an `Order` for tuples\n * @category instances\n * @since 4.0.0\n */\nexport const makeEquivalence = Equivalence.Tuple;\n/**\n * Creates an `Order` for tuples by comparing corresponding elements using the\n * provided per-position `Order`s. Elements are compared left-to-right; the\n * first non-zero comparison determines the result.\n *\n * **When to use**\n *\n * Use when you need to sort fixed-position arrays lexicographically, with each\n * position using its own ordering rule.\n *\n * **Details**\n *\n * This is an alias of `Order.Tuple`.\n *\n * **Example** (Ordering tuples)\n *\n * ```ts import.meta.vitest\n * import { Number, String, Tuple } from \"effect\"\n *\n * const ord = Tuple.makeOrder([String.Order, Number.Order])\n *\n * ord([\"Alice\", 30], [\"Bob\", 25]) // => -1\n * ord([\"Alice\", 30], [\"Alice\", 30]) // => 0\n * ```\n *\n * @see {@link makeEquivalence} – create an `Equivalence` for tuples\n * @category ordering\n * @since 4.0.0\n */\nexport const makeOrder = order.Tuple;\nexport {\n/**\n * Checks whether an array has exactly `N` elements, narrowing the type to a\n * fixed-length tuple.\n *\n * **When to use**\n *\n * Use to guard that an array has exactly the tuple length expected at\n * runtime.\n *\n * **Details**\n *\n * This is a re-export of `Predicate.isTupleOf`. It narrows the type to\n * `TupleOf<N, T>` in the truthy branch.\n *\n * **Gotchas**\n *\n * This only checks `.length`; it does not validate element types.\n *\n * **Example** (Checking exact length)\n *\n * ```ts import.meta.vitest\n * import { Tuple } from \"effect\"\n *\n * const arr: Array<number> = [1, 2, 3]\n * if (Tuple.isTupleOf(arr, 3)) {\n *   arr // => [1, 2, 3]\n * }\n * ```\n *\n * @see `isTupleOfAtLeast` – check for a minimum length\n * @category guards\n * @since 3.3.0\n */\nisTupleOf,\n/**\n * Checks whether an array has at least `N` elements, narrowing the type to a\n * tuple with a minimum length.\n *\n * **When to use**\n *\n * Use to guard that an array has at least the tuple length expected at\n * runtime.\n *\n * **Details**\n *\n * This is a re-export of `Predicate.isTupleOfAtLeast`. It narrows the type to\n * `TupleOfAtLeast<N, T>` in the truthy branch.\n *\n * **Gotchas**\n *\n * This only checks `.length`; it does not validate element types.\n *\n * **Example** (Checking minimum length)\n *\n * ```ts import.meta.vitest\n * import { Tuple } from \"effect\"\n *\n * const arr: Array<number> = [1, 2, 3, 4]\n * if (Tuple.isTupleOfAtLeast(arr, 3)) {\n *   arr // => [1, 2, 3, 4]\n * }\n * ```\n *\n * @see `isTupleOf` – check for an exact length\n * @category guards\n * @since 3.3.0\n */\nisTupleOfAtLeast } from \"./Predicate.js\";\n/**\n * Creates a `Combiner` for a tuple shape by providing a `Combiner` for each\n * position. When two tuples are combined, each element is merged using its\n * corresponding combiner.\n *\n * **When to use**\n *\n * Use when you need to merge two same-shape tuples by combining each position\n * independently, such as summing counters or concatenating strings.\n *\n * **Example** (Combining tuple elements)\n *\n * ```ts import.meta.vitest\n * import { Number, String, Tuple } from \"effect\"\n *\n * const C = Tuple.makeCombiner<readonly [number, string]>([\n *   Number.ReducerSum,\n *   String.ReducerConcat\n * ])\n *\n * C.combine([1, \"hello\"], [2, \" world\"]) // => [3, \"hello world\"]\n * ```\n *\n * @see {@link makeReducer} – like `makeCombiner` but with an initial value\n * @category combining\n * @since 4.0.0\n */\nexport function makeCombiner(combiners) {\n  return Combiner.make((self, that) => {\n    const out = [];\n    for (let i = 0; i < self.length; i++) {\n      out.push(combiners[i].combine(self[i], that[i]));\n    }\n    return out;\n  });\n}\n/**\n * Creates a `Reducer` for a tuple shape by providing a `Reducer` for each\n * position. The initial value is derived from each position's\n * `Reducer.initialValue`. When reducing a collection of tuples, each element\n * is combined independently.\n *\n * **When to use**\n *\n * Use when you need to fold same-shape tuples by accumulating each position\n * independently into one summary tuple.\n *\n * **Example** (Reducing a collection of tuples)\n *\n * ```ts import.meta.vitest\n * import { Number, String, Tuple } from \"effect\"\n *\n * const R = Tuple.makeReducer<readonly [number, string]>([\n *   Number.ReducerSum,\n *   String.ReducerConcat\n * ])\n *\n * R.combineAll([\n *   [1, \"a\"],\n *   [2, \"b\"],\n *   [3, \"c\"]\n * ]) // => [6, \"abc\"]\n * ```\n *\n * @see {@link makeCombiner} – like `makeReducer` but without an initial value\n * @category folding\n * @since 4.0.0\n */\nexport function makeReducer(reducers) {\n  const combine = makeCombiner(reducers).combine;\n  const initialValue = [];\n  for (let i = 0; i < reducers.length; i++) {\n    initialValue.push(reducers[i].initialValue);\n  }\n  return Reducer.make(combine, initialValue);\n}\n//# sourceMappingURL=Tuple.js.map","/**\n * Works with plain JavaScript records as immutable key/value dictionaries.\n *\n * A record is an object whose keys are strings or symbols. This module includes\n * helpers for construction, lookup, updates, mapping, filtering, folding,\n * set-like combination, and typed conversions between records and iterable\n * entries. Helpers that change values return new records instead of mutating the\n * input.\n *\n * @since 2.0.0\n */\nimport * as Equal from \"./Equal.js\";\nimport { dual, identity } from \"./Function.js\";\nimport * as InternalRecord from \"./internal/record.js\";\nimport * as Option from \"./Option.js\";\nimport * as Reducer from \"./Reducer.js\";\nimport * as R from \"./Result.js\";\n/**\n * Creates a new, empty record.\n *\n * **Example** (Creating an empty record)\n *\n * ```ts import.meta.vitest\n * import { Record } from \"effect\"\n *\n * // Create an empty record\n * const emptyRecord = Record.empty<string, number>()\n * emptyRecord // => {}\n *\n * // The type ensures type safety for future operations\n * Record.set(emptyRecord, \"count\", 42) // => { count: 42 }\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const empty = () => ({});\n/**\n * Determines if a mutable record is empty.\n *\n * **Example** (Checking for an empty record)\n *\n * ```ts import.meta.vitest\n * import { Record } from \"effect\"\n *\n * Record.isEmptyRecord({}) // => true\n * Record.isEmptyRecord({ a: 3 }) // => false\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isEmptyRecord = self => Object.keys(self).length === 0;\n/**\n * Determines if a readonly record is empty.\n *\n * **Example** (Checking for an empty readonly record)\n *\n * ```ts import.meta.vitest\n * import { Record } from \"effect\"\n *\n * Record.isEmptyReadonlyRecord({}) // => true\n * Record.isEmptyReadonlyRecord({ a: 3 }) // => false\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isEmptyReadonlyRecord = isEmptyRecord;\n/**\n * Takes an iterable and a projection function and returns a record.\n * The projection function maps each value of the iterable to a tuple of a key and a value, which is then added to the resulting record.\n *\n * **Example** (Building a record from mapped iterable values)\n *\n * ```ts import.meta.vitest\n * import { Record } from \"effect\"\n *\n * Record.fromIterableWith([1, 2, 3, 4], (a) => [String(a), a * 2]) // => { \"1\": 2, \"2\": 4, \"3\": 6, \"4\": 8 }\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromIterableWith = /*#__PURE__*/dual(2, (self, f) => {\n  const out = empty();\n  for (const a of self) {\n    const [k, b] = f(a);\n    InternalRecord.assignProperty(out, k, b);\n  }\n  return out;\n});\n/**\n * Creates a new record from an iterable, utilizing the provided function to determine the key for each element.\n *\n * **Example** (Building a record keyed by iterable values)\n *\n * ```ts import.meta.vitest\n * import { Record } from \"effect\"\n *\n * const users = [\n *   { id: \"2\", name: \"name2\" },\n *   { id: \"1\", name: \"name1\" }\n * ]\n *\n * Record.fromIterableBy(\n *   users,\n *   (user) => user.id\n * ) // => { \"1\": { id: \"1\", name: \"name1\" }, \"2\": { id: \"2\", name: \"name2\" } }\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromIterableBy = /*#__PURE__*/dual(2, (items, f) => fromIterableWith(items, a => [f(a), a]));\n/**\n * Builds a record from an iterable of key-value pairs.\n *\n * **Details**\n *\n * If there are conflicting keys when using `fromEntries`, the last occurrence of the key/value pair will overwrite the\n * previous ones. So the resulting record will only have the value of the last occurrence of each key.\n *\n * **Example** (Building a record from entries)\n *\n * ```ts import.meta.vitest\n * import { Record } from \"effect\"\n *\n * Record.fromEntries([[\"a\", 1], [\"b\", 2]]) // => { a: 1, b: 2 }\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromEntries = Object.fromEntries;\n/**\n * Transforms the values of a record into an `Array` with a custom mapping function.\n *\n * **Example** (Collecting mapped record values)\n *\n * ```ts import.meta.vitest\n * import { Record } from \"effect\"\n *\n * const x = { a: 1, b: 2, c: 3 }\n * Record.collect(x, (key, n) => [key, n]) // => [[\"a\", 1], [\"b\", 2], [\"c\", 3]]\n * ```\n *\n * @category converting\n * @since 2.0.0\n */\nexport const collect = /*#__PURE__*/dual(2, (self, f) => {\n  const out = [];\n  for (const key of keys(self)) {\n    out.push(f(key, self[key]));\n  }\n  return out;\n});\n/**\n * Takes a record and returns an array of tuples containing its keys and values.\n *\n * **Example** (Converting a record to entries)\n *\n * ```ts import.meta.vitest\n * import { Record } from \"effect\"\n *\n * const x = { a: 1, b: 2, c: 3 }\n * Record.toEntries(x) // => [[\"a\", 1], [\"b\", 2], [\"c\", 3]]\n * ```\n *\n * @category converting\n * @since 2.0.0\n */\nexport const toEntries = /*#__PURE__*/collect((key, value) => [key, value]);\n/**\n * Returns the number of key/value pairs in a record.\n *\n * **Example** (Getting the record size)\n *\n * ```ts import.meta.vitest\n * import { Record } from \"effect\"\n *\n * Record.size({ a: \"a\", b: 1, c: true }) // => 3\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const size = self => keys(self).length;\n/**\n * Checks whether a given `key` exists in a record.\n *\n * **Example** (Checking key membership)\n *\n * ```ts import.meta.vitest\n * import { Record } from \"effect\"\n *\n * Record.has({ a: 1, b: 2 }, \"a\") // => true\n * Record.has(Record.empty<string>(), \"c\") // => false\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const has = /*#__PURE__*/dual(2, (self, key) => Object.hasOwn(self, key));\n/**\n * Retrieves a value at a particular key from a record safely, returning it wrapped in an `Option`.\n *\n * **Example** (Getting a value as an Option)\n *\n * ```ts import.meta.vitest\n * import { Option, Record as R } from \"effect\"\n *\n * const person: Record<string, unknown> = { name: \"John Doe\", age: 35 }\n *\n * R.get(person, \"name\") // => Option.some(\"John Doe\")\n * R.get(person, \"email\") // => Option.none()\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const get = /*#__PURE__*/dual(2, (self, key) => Object.hasOwn(self, key) ? Option.some(self[key]) : Option.none());\n/**\n * Applies a function to the element at the specified key safely, creating a new record,\n * or return `Option.none()` if the key doesn't exist.\n *\n * **Example** (Modifying a value at a key)\n *\n * ```ts import.meta.vitest\n * import { Option, Record } from \"effect\"\n *\n * const f = (x: number) => x * 2\n *\n * const input: Record<string, number> = { a: 3 }\n *\n * Record.modify(input, \"a\", f) // => Option.some({ a: 6 })\n * Record.modify(input, \"b\", f) // => Option.none()\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const modify = /*#__PURE__*/dual(3, (self, key, f) => {\n  if (!has(self, key)) return Option.none();\n  return Option.some({\n    ...self,\n    [key]: f(self[key])\n  });\n});\n/**\n * Replaces the value at an existing key safely and returns the updated record in\n * `Option.some`.\n *\n * **Details**\n *\n * If the key is not present, returns `Option.none()` and leaves the record\n * unchanged.\n *\n * **Example** (Replacing a value at a key)\n *\n * ```ts import.meta.vitest\n * import { Option, Record } from \"effect\"\n *\n * Record.replace({ a: 1, b: 2, c: 3 }, \"a\", 10) // => Option.some({ a: 10, b: 2, c: 3 })\n * Record.replace(Record.empty<string>(), \"a\", 10) // => Option.none()\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const replace = /*#__PURE__*/dual(3, (self, key, b) => modify(self, key, () => b));\n/**\n * Removes a key from a record.\n *\n * **When to use**\n *\n * Use to create a shallow copy of a record without one property.\n *\n * **Details**\n *\n * If the key is not present, the result is still a shallow copy of the original\n * record.\n *\n * **Example** (Removing a key)\n *\n * ```ts import.meta.vitest\n * import { Record } from \"effect\"\n *\n * Record.remove({ a: 1, b: 2 }, \"a\") // => { b: 2 }\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const remove = /*#__PURE__*/dual(2, (self, key) => {\n  if (!has(self, key)) {\n    return {\n      ...self\n    };\n  }\n  const out = {\n    ...self\n  };\n  delete out[key];\n  return out;\n});\n/**\n * Retrieves the value of the property with the given `key` from a record safely and returns an `Option`\n * of a tuple with the value and the record with the removed property.\n * If the key is not present, returns `Option.none()`.\n *\n * **Example** (Popping a value and removing its key)\n *\n * ```ts import.meta.vitest\n * import { Option, Record } from \"effect\"\n *\n * const input: Record<string, number> = { a: 1, b: 2 }\n *\n * Record.pop(input, \"a\") // => Option.some([1, { b: 2 }])\n * Record.pop(input, \"c\") // => Option.none()\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const pop = /*#__PURE__*/dual(2, (self, key) => has(self, key) ? Option.some([self[key], remove(self, key)]) : Option.none());\n/**\n * Maps a record into another record by applying a transformation function to each of its values.\n *\n * **Example** (Mapping record values)\n *\n * ```ts import.meta.vitest\n * import { Record } from \"effect\"\n *\n * const f = (n: number) => `-${n}`\n *\n * Record.map({ a: 3, b: 5 }, f) // => { a: \"-3\", b: \"-5\" }\n *\n * const g = (n: number, key: string) => `${key.toUpperCase()}-${n}`\n *\n * Record.map({ a: 3, b: 5 }, g) // => { a: \"A-3\", b: \"B-5\" }\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => {\n  const out = {\n    ...self\n  };\n  for (const key of keys(self)) {\n    InternalRecord.assignProperty(out, key, f(self[key], key));\n  }\n  return out;\n});\n/**\n * Maps the keys of a `ReadonlyRecord` while preserving the corresponding values.\n *\n * **Example** (Mapping record keys)\n *\n * ```ts import.meta.vitest\n * import { Record } from \"effect\"\n *\n * Record.mapKeys({ a: 3, b: 5 }, (key) => key.toUpperCase()) // => { A: 3, B: 5 }\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const mapKeys = /*#__PURE__*/dual(2, (self, f) => {\n  const out = {};\n  for (const key of keys(self)) {\n    const a = self[key];\n    InternalRecord.assignProperty(out, f(key, a), a);\n  }\n  return out;\n});\n/**\n * Maps entries of a `ReadonlyRecord` using the provided function, allowing modification of both keys and corresponding values.\n *\n * **Example** (Mapping record entries)\n *\n * ```ts import.meta.vitest\n * import { Record } from \"effect\"\n *\n * Record.mapEntries({ a: 3, b: 5 }, (a, key) => [key.toUpperCase(), a + 1]) // => { A: 4, B: 6 }\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const mapEntries = /*#__PURE__*/dual(2, (self, f) => {\n  const out = {};\n  for (const key of keys(self)) {\n    const [k, b] = f(self[key], key);\n    InternalRecord.assignProperty(out, k, b);\n  }\n  return out;\n});\n/**\n * Transforms a record by applying the function `f` to each key and value in the original record.\n * If the function succeeds, the key-value pair is included in the output record.\n *\n * **Example** (Filtering and mapping with Result)\n *\n * ```ts import.meta.vitest\n * import { Record, Result } from \"effect\"\n *\n * const x = { a: 1, b: 2, c: 3 }\n * const f = (a: number, key: string) => a > 2 ? Result.succeed(a * 2) : Result.failVoid\n * Record.filterMap(x, f) // => { c: 6 }\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const filterMap = /*#__PURE__*/dual(2, (self, f) => {\n  const out = empty();\n  for (const key of keys(self)) {\n    const result = f(self[key], key);\n    if (R.isSuccess(result)) {\n      InternalRecord.assignProperty(out, key, result.success);\n    }\n  }\n  return out;\n});\n/**\n * Selects properties from a record whose values match the given predicate.\n *\n * **Example** (Filtering record values)\n *\n * ```ts import.meta.vitest\n * import { Record } from \"effect\"\n *\n * const x = { a: 1, b: 2, c: 3, d: 4 }\n * Record.filter(x, (n) => n > 2) // => { c: 3, d: 4 }\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const filter = /*#__PURE__*/dual(2, (self, predicate) => {\n  const out = empty();\n  for (const key of keys(self)) {\n    if (predicate(self[key], key)) {\n      InternalRecord.assignProperty(out, key, self[key]);\n    }\n  }\n  return out;\n});\n/**\n * Returns a new record containing only the `Some` values from a record of\n * `Option` values, preserving the original keys.\n *\n * **Example** (Extracting Some values)\n *\n * ```ts import.meta.vitest\n * import { Option, Record } from \"effect\"\n *\n * Record.getSomes({ a: Option.some(1), b: Option.none(), c: Option.some(2) }) // => { a: 1, c: 2 }\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const getSomes = self => {\n  const out = empty();\n  for (const key of keys(self)) {\n    const option = self[key];\n    if (Option.isSome(option)) {\n      InternalRecord.assignProperty(out, key, option.value);\n    }\n  }\n  return out;\n};\n/**\n * Returns a new record containing only the `Err` values from a record of\n * `Result` values, preserving the original keys.\n *\n * **Example** (Extracting Result failures)\n *\n * ```ts import.meta.vitest\n * import { Record, Result } from \"effect\"\n *\n * Record.getFailures({\n *     a: Result.succeed(1),\n *     b: Result.fail(\"err\"),\n *     c: Result.succeed(2)\n * }) // => { b: \"err\" }\n * ```\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const getFailures = self => {\n  const out = empty();\n  for (const key of keys(self)) {\n    const value = self[key];\n    if (R.isFailure(value)) {\n      InternalRecord.assignProperty(out, key, value.failure);\n    }\n  }\n  return out;\n};\n/**\n * Returns a new record containing only the `Ok` values from a record of\n * `Result` values, preserving the original keys.\n *\n * **Example** (Extracting Result successes)\n *\n * ```ts import.meta.vitest\n * import { Record, Result } from \"effect\"\n *\n * Record.getSuccesses({\n *     a: Result.succeed(1),\n *     b: Result.fail(\"err\"),\n *     c: Result.succeed(2)\n * }) // => { a: 1, c: 2 }\n * ```\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const getSuccesses = self => {\n  const out = empty();\n  for (const key of keys(self)) {\n    const value = self[key];\n    if (R.isSuccess(value)) {\n      InternalRecord.assignProperty(out, key, value.success);\n    }\n  }\n  return out;\n};\n/**\n * Applies a function to each record entry and partitions the returned `Result`\n * values into two records.\n *\n * **Details**\n *\n * Failure values are collected in the left record, and success values are\n * collected in the right record, preserving the original keys.\n *\n * **Example** (Partitioning with Result)\n *\n * ```ts import.meta.vitest\n * import { Record, Result } from \"effect\"\n *\n * const x = { a: 1, b: 2, c: 3 }\n * const f = (n: number) => (n % 2 === 0 ? Result.succeed(n) : Result.fail(n))\n * Record.partition(x, f) // => [{ a: 1, c: 3 }, { b: 2 }]\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const partition = /*#__PURE__*/dual(2, (self, f) => {\n  const left = empty();\n  const right = empty();\n  for (const key of keys(self)) {\n    const e = f(self[key], key);\n    if (R.isFailure(e)) {\n      InternalRecord.assignProperty(left, key, e.failure);\n    } else {\n      InternalRecord.assignProperty(right, key, e.success);\n    }\n  }\n  return [left, right];\n});\n/**\n * Partitions a record of `Result` values into two separate records,\n * one with the `Err` values and one with the `Ok` values.\n *\n * **Example** (Separating Result values)\n *\n * ```ts import.meta.vitest\n * import { Record, Result } from \"effect\"\n *\n * Record.separate({ a: Result.fail(\"e\"), b: Result.succeed(1) }) // => [{ a: \"e\" }, { b: 1 }]\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const separate = /*#__PURE__*/partition(identity);\n/**\n * Retrieves the keys of a given record as an array.\n *\n * **Example** (Getting record keys)\n *\n * ```ts import.meta.vitest\n * import { Record } from \"effect\"\n *\n * Record.keys({ a: 1, b: 2, c: 3 }) // => [\"a\", \"b\", \"c\"]\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const keys = self => Object.keys(self);\n/**\n * Retrieves the values of a given record as an array.\n *\n * **Example** (Getting record values)\n *\n * ```ts import.meta.vitest\n * import { Record } from \"effect\"\n *\n * Record.values({ a: 1, b: 2, c: 3 }) // => [1, 2, 3]\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const values = self => collect(self, (_, a) => a);\n/**\n * Adds a new key-value pair or update an existing key's value in a record.\n *\n * **Example** (Setting a record value)\n *\n * ```ts import.meta.vitest\n * import { Record } from \"effect\"\n *\n * Record.set(\"a\", 5)({ a: 1, b: 2 }) // => { a: 5, b: 2 }\n * Record.set(\"c\", 5)({ a: 1, b: 2 }) // => { a: 1, b: 2, c: 5 }\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const set = /*#__PURE__*/dual(3, (self, key, value) => {\n  return {\n    ...self,\n    [key]: value\n  };\n});\n/**\n * Mutates a record by assigning a value to a property.\n *\n * **When to use**\n *\n * Use when incrementally constructing a new record and copying it for every\n * property would be unnecessary.\n *\n * **Gotchas**\n *\n * This function mutates `self`. When `key` is `\"__proto__\"`, it creates an\n * own data property instead of changing the object's prototype.\n *\n * **Example** (Assigning an external key safely)\n *\n * ```ts import.meta.vitest\n * import { Record } from \"effect\"\n *\n * const key: string = \"__proto__\" // Assume this comes from external input\n * const value = { polluted: true }\n *\n * const unsafe: Record<string, unknown> = {}\n * unsafe[key] = value\n * Object.getPrototypeOf(unsafe) === value // => true\n *\n * const safe: Record<string, unknown> = {}\n * Record.assignProperty(safe, key, value)\n * Object.getPrototypeOf(safe) === Object.prototype // => true\n * safe[key] === value // => true\n * ```\n *\n * @see {@link set} for an immutable update\n * @category mutations\n * @since 4.0.0\n */\nexport const assignProperty = InternalRecord.assignProperty;\n/**\n * Checks whether all the keys and values in one record are also found in another record.\n * Uses the provided equivalence function to compare values.\n *\n * **Example** (Checking subrecords with a custom equivalence)\n *\n * ```ts import.meta.vitest\n * import { Equivalence, Record } from \"effect\"\n *\n * const isSubrecord = Record.isSubrecordBy(\n *   Equivalence.make<string>((self, that) => self.toLowerCase() === that.toLowerCase())\n * )\n *\n * const required: Record.ReadonlyRecord<string, string> = { role: \"Admin\" }\n * const available: Record.ReadonlyRecord<string, string> = {\n *   role: \"admin\",\n *   status: \"active\"\n * }\n *\n * isSubrecord(required, available) // => true\n * isSubrecord({ role: \"Admin\", status: \"inactive\" }, available) // => false\n * isSubrecord(required, { role: \"editor\", status: \"active\" }) // => false\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const isSubrecordBy = equivalence => dual(2, (self, that) => {\n  for (const key of keys(self)) {\n    if (!has(that, key) || !equivalence(self[key], that[key])) {\n      return false;\n    }\n  }\n  return true;\n});\n/**\n * Checks whether the first record is a subrecord of the second record.\n *\n * **Details**\n *\n * Returns `true` when every key and value in `self` is also present in `that`.\n * Values are compared with Effect equality via `Equal.asEquivalence()`.\n *\n * **Example** (Checking subrecords)\n *\n * ```ts import.meta.vitest\n * import { Record } from \"effect\"\n *\n * Record.isSubrecord({ a: 1 } as Record<string, number>, { a: 1, b: 2 }) // => true\n * Record.isSubrecord({ a: 1, b: 2 }, { a: 1 } as Record<string, number>) // => false\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const isSubrecord = /*#__PURE__*/isSubrecordBy(/*#__PURE__*/Equal.asEquivalence());\n/**\n * Reduces a record to a single value by combining its entries with a specified function.\n *\n * **Example** (Reducing record values)\n *\n * ```ts import.meta.vitest\n * import { Record } from \"effect\"\n *\n * Record.reduce({ a: 1, b: 2, c: 3 }, 0, (acc, value) => acc + value) // => 6\n * ```\n *\n * @category folding\n * @since 2.0.0\n */\nexport const reduce = /*#__PURE__*/dual(3, (self, zero, f) => {\n  let out = zero;\n  for (const key of keys(self)) {\n    out = f(out, self[key], key);\n  }\n  return out;\n});\n/**\n * Checks whether all entries in a record meet a specific condition.\n *\n * **Example** (Checking every record value)\n *\n * ```ts import.meta.vitest\n * import { Record } from \"effect\"\n *\n * Record.every({ a: 1, b: 2 }, (n) => n > 0) // => true\n * Record.every({ a: 1, b: -1 }, (n) => n > 0) // => false\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const every = /*#__PURE__*/dual(2, (self, refinement) => {\n  for (const key of keys(self)) {\n    if (!refinement(self[key], key)) {\n      return false;\n    }\n  }\n  return true;\n});\n/**\n * Checks whether any entry in a record meets a specific condition.\n *\n * **Example** (Checking for any matching value)\n *\n * ```ts import.meta.vitest\n * import { Record } from \"effect\"\n *\n * Record.some({ a: 1, b: 2 }, (n) => n > 1) // => true\n * Record.some({ a: 1, b: 2 }, (n) => n > 2) // => false\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const some = /*#__PURE__*/dual(2, (self, predicate) => {\n  for (const key of keys(self)) {\n    if (predicate(self[key], key)) {\n      return true;\n    }\n  }\n  return false;\n});\n/**\n * Merges two records, preserving entries that exist in either of the records.\n * For keys that exist in both records, the provided combine function is used to merge the values.\n *\n * **Example** (Merging records with union)\n *\n * ```ts import.meta.vitest\n * import { Record } from \"effect\"\n *\n * Record.union({ a: 1, b: 2 }, { b: 3, c: 4 }, (a, b) => a + b) // => { a: 1, b: 5, c: 4 }\n * ```\n *\n * @category combining\n * @since 2.0.0\n */\nexport const union = /*#__PURE__*/dual(3, (self, that, combine) => {\n  if (isEmptyRecord(self)) {\n    return {\n      ...that\n    };\n  }\n  if (isEmptyRecord(that)) {\n    return {\n      ...self\n    };\n  }\n  const out = empty();\n  for (const key of keys(self)) {\n    if (has(that, key)) {\n      InternalRecord.assignProperty(out, key, combine(self[key], that[key]));\n    } else {\n      InternalRecord.assignProperty(out, key, self[key]);\n    }\n  }\n  for (const key of keys(that)) {\n    if (!has(out, key)) {\n      InternalRecord.assignProperty(out, key, that[key]);\n    }\n  }\n  return out;\n});\n/**\n * Merges two records, retaining only the entries that exist in both records.\n * For intersecting keys, the provided combine function is used to merge the values.\n *\n * **Example** (Merging intersecting keys)\n *\n * ```ts import.meta.vitest\n * import { Record } from \"effect\"\n *\n * Record.intersection({ a: 1, b: 2 }, { b: 3, c: 4 }, (a, b) => a + b) // => { b: 5 }\n * ```\n *\n * @category combining\n * @since 2.0.0\n */\nexport const intersection = /*#__PURE__*/dual(3, (self, that, combine) => {\n  const out = empty();\n  if (isEmptyRecord(self) || isEmptyRecord(that)) {\n    return out;\n  }\n  for (const key of keys(self)) {\n    if (has(that, key)) {\n      InternalRecord.assignProperty(out, key, combine(self[key], that[key]));\n    }\n  }\n  return out;\n});\n/**\n * Merges two records, preserving only the entries that are unique to each record.\n * Keys that exist in both records are excluded from the result.\n *\n * **Example** (Keeping keys unique to each record)\n *\n * ```ts import.meta.vitest\n * import { Record } from \"effect\"\n *\n * Record.difference({ a: 1, b: 2 }, { b: 3, c: 4 }) // => { a: 1, c: 4 }\n * ```\n *\n * @category combining\n * @since 2.0.0\n */\nexport const difference = /*#__PURE__*/dual(2, (self, that) => {\n  if (isEmptyRecord(self)) {\n    return {\n      ...that\n    };\n  }\n  if (isEmptyRecord(that)) {\n    return {\n      ...self\n    };\n  }\n  const out = {};\n  for (const key of keys(self)) {\n    if (!has(that, key)) {\n      InternalRecord.assignProperty(out, key, self[key]);\n    }\n  }\n  for (const key of keys(that)) {\n    if (!has(self, key)) {\n      InternalRecord.assignProperty(out, key, that[key]);\n    }\n  }\n  return out;\n});\n/**\n * Create an `Equivalence` for records using the provided `Equivalence` for values.\n * Two records are considered equivalent if they have the same keys and their corresponding values are equivalent.\n *\n * **Example** (Comparing records with a value equivalence)\n *\n * ```ts import.meta.vitest\n * import { Equal, Record } from \"effect\"\n *\n * const recordEquivalence = Record.makeEquivalence(Equal.asEquivalence<number>())\n *\n * recordEquivalence({ a: 1, b: 2 }, { a: 1, b: 2 }) // => true\n * recordEquivalence({ a: 1, b: 2 }, { a: 1, b: 3 }) // => false\n * ```\n *\n * @category instances\n * @since 4.0.0\n */\nexport const makeEquivalence = equivalence => {\n  const is = isSubrecordBy(equivalence);\n  return (self, that) => is(self, that) && is(that, self);\n};\n/**\n * Create a non-empty record from a single element.\n *\n * **Example** (Creating a singleton record)\n *\n * ```ts import.meta.vitest\n * import { Record } from \"effect\"\n *\n * Record.singleton(\"a\", 1) // => { a: 1 }\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const singleton = (key, value) => ({\n  [key]: value\n});\n/**\n * Creates a `Reducer` for combining `Record`s using union, with values for keys that exist in both records combined\n * using the provided `Combiner`.\n *\n * **When to use**\n *\n * Use to build a reusable reducer for accumulating many records into one\n * union-shaped record, preserving keys from every input and combining\n * overlapping values with the supplied combiner.\n *\n * **Details**\n *\n * The returned reducer uses `Record.union` for combine and an empty record as\n * `initialValue`, so the default `combineAll` folds from `{}` and accumulates\n * keys from each input record.\n *\n * @see {@link union} for one-off record merging with the same union semantics\n * @see {@link makeReducerIntersection} for a reducer that keeps only keys present on both sides\n *\n * @category combining\n * @since 4.0.0\n */\nexport function makeReducerUnion(combiner) {\n  return Reducer.make((self, that) => union(self, that, combiner.combine), {});\n}\n/**\n * Creates a `Reducer` whose `combine` operation intersects two records and\n * combines values for keys present in both records.\n *\n * **When to use**\n *\n * Use to build a `Reducer` that combines records by retaining only keys shared\n * by both inputs and combining matching values with a `Combiner`.\n *\n * **Gotchas**\n *\n * The reducer's `initialValue` is an empty record. Because intersection with\n * an empty record is empty, the default `combineAll` folds from `{}` and\n * therefore produces `{}` for ordinary non-empty inputs.\n *\n * @see {@link makeReducerUnion} for a reducer that preserves keys from either input record\n * @see {@link intersection} for applying the shared-key merge to one pair of records\n *\n * @category combining\n * @since 4.0.0\n */\nexport function makeReducerIntersection(combiner) {\n  return Reducer.make((self, that) => intersection(self, that, combiner.combine), {});\n}\n/**\n * Returns the first entry that satisfies the specified\n * predicate, or `None` if no such entry exists.\n *\n * **Example** (Finding the first matching entry)\n *\n * ```ts import.meta.vitest\n * import { Option, Record } from \"effect\"\n *\n * const record = { a: 1, b: 2, c: 3 }\n * Record.findFirst(\n *   record,\n *   (value, key) => value > 1 && key !== \"b\"\n * ) // => Option.some([\"c\", 3])\n * ```\n *\n * @category searching\n * @since 3.14.0\n */\nexport const findFirst = /*#__PURE__*/dual(2, (self, f) => {\n  const k = keys(self);\n  for (let i = 0; i < k.length; i++) {\n    const key = k[i];\n    if (f(self[key], key)) {\n      return Option.some([key, self[key]]);\n    }\n  }\n  return Option.none();\n});\n//# sourceMappingURL=Record.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 * 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","import * as Equal from \"./Equal.js\";\nimport { dual } from \"./Function.js\";\nimport * as Option from \"./Option.js\";\nimport * as Predicate from \"./Predicate.js\";\nimport * as Result from \"./Result.js\";\n// -------------------------------------------------------------------------------------\n// Constructors\n// -------------------------------------------------------------------------------------\n/**\n * Creates a Filter from a function that returns either a `pass` or `fail` value.\n *\n * **Details**\n *\n * This is the primary constructor for creating custom filters. The function\n * should return either `Result.succeed(value)` or `Result.fail(value)`.\n *\n * **Example** (Creating custom filters)\n *\n * ```ts import.meta.vitest\n * import { Filter, Result } from \"effect\"\n *\n * // Create a filter for positive numbers\n * const positiveFilter = Filter.make((n: number) => n > 0 ? Result.succeed(n) : Result.fail(n))\n *\n * // Create a filter that transforms strings to uppercase\n * const uppercaseFilter = Filter.make((s: string) =>\n *   s.length > 0 ? Result.succeed(s.toUpperCase()) : Result.fail(s)\n * )\n * positiveFilter(1) // => Result.succeed(1)\n * uppercaseFilter(\"ok\") // => Result.succeed(\"OK\")\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = f => f;\n/**\n * Creates an effectful Filter from a function that returns an Effect.\n *\n * **Details**\n *\n * This constructor is used when the filtering operation needs to perform\n * effectful computations, such as async operations, error handling, or accessing\n * services from the environment.\n *\n * **Example** (Creating effectful filters)\n *\n * ```ts import.meta.vitest\n * import { Effect, Filter, Result } from \"effect\"\n *\n * // Create an effectful filter that validates async\n * const asyncValidate = Filter.makeEffect((id: string) =>\n *   Effect.gen(function*() {\n *     const isValid = yield* Effect.succeed(id.length > 0)\n *     return isValid ? Result.succeed(id) : Result.fail(id)\n *   })\n * )\n *\n * await Effect.runPromise(asyncValidate(\"id\")) // => Result.succeed(\"id\")\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeEffect = f => f;\n/**\n * Transforms the failure value produced by a `Filter`, leaving successful\n * results unchanged.\n *\n * @category mapping\n * @since 4.0.0\n */\nexport const mapFail = /*#__PURE__*/dual(2, (self, f) => input => Result.mapError(self(input), f));\nconst try_ = f => input => {\n  try {\n    return Result.succeed(f(input));\n  } catch {\n    return Result.fail(input);\n  }\n};\nexport {\n/**\n * Creates a Filter that tries to apply a function and returns `fail` on\n * error.\n *\n * @category constructors\n * @since 4.0.0\n */\ntry_ as try };\n/**\n * Creates a Filter from a predicate or refinement function.\n *\n * **Details**\n *\n * This is a convenient way to create filters from boolean-returning functions.\n * When the predicate returns true, the input value is passed through unchanged.\n * When it returns false, the `fail` type is returned.\n *\n * **Example** (Creating filters from predicates)\n *\n * ```ts import.meta.vitest\n * import { Filter, Result } from \"effect\"\n *\n * // Create filter from predicate\n * const positiveNumbers = Filter.fromPredicate((n: number) => n > 0)\n * const nonEmptyStrings = Filter.fromPredicate((s: string) => s.length > 0)\n *\n * // Type refinement\n * const isString = Filter.fromPredicate((x: unknown): x is string =>\n *   typeof x === \"string\"\n * )\n * positiveNumbers(1) // => Result.succeed(1)\n * nonEmptyStrings(\"\") // => Result.fail(\"\")\n * isString(\"ok\") // => Result.succeed(\"ok\")\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromPredicate = predicate => input => predicate(input) ? Result.succeed(input) : Result.fail(input);\n/**\n * Creates a `Filter` from a function that returns an `Option`; `Some(value)`\n * passes with `value`, and `None` fails with the original input.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromPredicateOption = predicate => input => {\n  const o = predicate(input);\n  return o._tag === \"None\" ? Result.fail(input) : Result.succeed(o.value);\n};\n/**\n * Converts a Filter into a predicate function.\n *\n * **When to use**\n *\n * Use to reuse a `Filter` with APIs that accept only boolean predicates when\n * the pass and fail payloads are not needed.\n *\n * @see {@link toOption} for keeping passed values and discarding failure values\n * @see {@link toResult} for preserving both pass and failure values\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toPredicate = self => input => !Result.isFailure(self(input));\n/**\n * A predefined filter that only passes through string values.\n *\n * **Example** (Filtering strings)\n *\n * ```ts import.meta.vitest\n * import { Filter, Result } from \"effect\"\n *\n * Filter.string(\"hello\") // => Result.succeed(\"hello\")\n * Filter.string(42) // => Result.fail(42)\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const string = /*#__PURE__*/fromPredicate(Predicate.isString);\n/**\n * Creates a `Filter` that passes only values strictly equal to the specified\n * value using JavaScript `===` comparison.\n *\n * **When to use**\n *\n * Use when you need a `Filter` that accepts only the exact primitive value or\n * object reference using JavaScript strict equality in a `Filter` / `Result`\n * pipeline.\n *\n * **Gotchas**\n *\n * `NaN` never passes, even when the expected value is `NaN`, and objects pass\n * only when they are the same reference.\n *\n * @see {@link equals} for structural equality when distinct values with equal\n * contents should pass\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const equalsStrict = value => u => u === value ? Result.succeed(value) : Result.fail(u);\n/**\n * Creates a `Filter` that passes inputs whose `has(key)` method returns\n * `true` for the specified key.\n *\n * **When to use**\n *\n * Use to keep inputs that expose a `has` method, such as `Set` or `Map`, when\n * they contain a required key.\n *\n * @see {@link fromPredicate} for custom predicate filters or inputs without a\n * `has` method\n * @see {@link Predicate.hasProperty} for guarding property presence instead of\n * calling an input's `has` method\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const has = key => input => input.has(key) ? Result.succeed(input) : Result.fail(input);\n/**\n * Creates a filter that only passes instances of the given constructor.\n *\n * **When to use**\n *\n * Use to narrow unknown input to values created by a specific JavaScript\n * constructor while keeping the result in the `Filter` / `Result` pipeline.\n *\n * **Details**\n *\n * The filter succeeds when the input satisfies `instanceof constructor`.\n * Otherwise it fails with the original input.\n *\n * **Gotchas**\n *\n * This uses JavaScript `instanceof` semantics, including prototype-chain and\n * realm behavior.\n *\n * @see {@link fromPredicate} for custom predicate-based narrowing\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const instanceOf = constructor => u => u instanceof constructor ? Result.succeed(u) : Result.fail(u);\n/**\n * A predefined filter that only passes through number values.\n *\n * **Example** (Filtering numbers)\n *\n * ```ts import.meta.vitest\n * import { Filter, Result } from \"effect\"\n *\n * Filter.number(42) // => Result.succeed(42)\n * Filter.number(\"42\") // => Result.fail(\"42\")\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const number = /*#__PURE__*/fromPredicate(Predicate.isNumber);\n/**\n * A predefined filter that only passes through boolean values.\n *\n * **When to use**\n *\n * Use when accepting an unknown input only if it is already a boolean and you\n * want a `Filter` result rather than a plain predicate result.\n *\n * **Details**\n *\n * Implemented with `fromPredicate(Predicate.isBoolean)`, so `true` and `false`\n * succeed and non-booleans fail with the original input.\n *\n * @see {@link Predicate.isBoolean} for the underlying guard\n * @see {@link fromPredicate} for custom predicate-based filters\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const boolean = /*#__PURE__*/fromPredicate(Predicate.isBoolean);\n/**\n * A predefined filter that only passes through `bigint` primitive values.\n *\n * **When to use**\n *\n * Use to keep primitive big integer values from unknown input while staying in\n * the composable `Filter` / `Result` pipeline.\n *\n * **Details**\n *\n * Implemented with `fromPredicate(Predicate.isBigInt)`, so values where\n * `typeof input === \"bigint\"` succeed and all other inputs fail with the\n * original input.\n *\n * **Gotchas**\n *\n * This filter does not coerce numbers or strings; `1n` passes while `1` fails.\n *\n * @see {@link number} for JavaScript `number` values\n * @see {@link Predicate.isBigInt} for the underlying guard\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const bigint = /*#__PURE__*/fromPredicate(Predicate.isBigInt);\n/**\n * A predefined filter that only passes through Symbol values.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const symbol = /*#__PURE__*/fromPredicate(Predicate.isSymbol);\n/**\n * A predefined filter that only passes through Date objects.\n *\n * **When to use**\n *\n * Use when you need to narrow unknown input to JavaScript `Date` instances with\n * a reusable `Filter`.\n *\n * **Details**\n *\n * Implemented with `fromPredicate(Predicate.isDate)`, so passing values return\n * `Result.succeed(input)` and failing values return `Result.fail(input)`.\n *\n * **Gotchas**\n *\n * The check uses `instanceof Date`, so invalid `Date` objects still pass; the\n * filter does not validate the timestamp.\n *\n * @see {@link Predicate.isDate} for the underlying guard\n * @see {@link instanceOf} for constructor-based filtering\n * @see {@link fromPredicate} for custom date checks\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const date = /*#__PURE__*/fromPredicate(Predicate.isDate);\n/**\n * Creates a filter that checks if an input is tagged with a specific tag.\n *\n * **When to use**\n *\n * Use to keep only the matching member of a `_tag`-discriminated union while\n * staying in a composable `Filter` / `Result` pipeline.\n *\n * **Details**\n *\n * The filter succeeds when `Predicate.isTagged(input, tag)` returns `true`.\n * Otherwise it fails with the original input.\n *\n * **Gotchas**\n *\n * This only checks `_tag`; it does not validate the rest of the variant fields.\n *\n * @see {@link Predicate.isTagged} for the underlying boolean guard when a\n * `Filter` result is not needed\n * @see {@link reason} for extracting a nested reason variant from tagged errors\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const tagged = function () {\n  return arguments.length === 0 ? taggedImpl : taggedImpl(arguments[0]);\n};\nconst taggedImpl = tag => input => Predicate.isTagged(input, tag) ? Result.succeed(input) : Result.fail(input);\n/**\n * Creates a filter that extracts a reason from a tagged error.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const reason = function () {\n  return arguments.length === 0 ? reasonImpl : reasonImpl(arguments[0], arguments[1]);\n};\nconst reasonImpl = (tag, reasonTag) => input => {\n  if (Predicate.isTagged(input, tag) && Predicate.hasProperty(input, \"reason\") && Predicate.isTagged(input.reason, reasonTag)) {\n    return Result.succeed(input.reason);\n  }\n  return Result.fail(input);\n};\n/**\n * Creates a filter that only passes values equal to the specified value using structural equality.\n *\n * **When to use**\n *\n * Use to accept inputs that are structurally equal to a known expected value\n * while staying in a composable `Filter` / `Result` pipeline.\n *\n * **Details**\n *\n * Delegates to `Equal.equals`. On success it returns `Result.succeed(value)`;\n * on failure it returns `Result.fail(input)`.\n *\n * @see {@link equalsStrict} for JavaScript `===` matching instead of structural\n * equality\n * @see {@link Equal.equals} for the underlying structural equality semantics\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const equals = value => u => Equal.equals(u, value) ? Result.succeed(value) : Result.fail(u);\n/**\n * Combines two filters with logical OR semantics.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const or = /*#__PURE__*/dual(2, (self, that) => input => {\n  const selfResult = self(input);\n  return Result.isSuccess(selfResult) ? selfResult : that(input);\n});\n/**\n * Combines two filters and applies a function to their results.\n *\n * **When to use**\n *\n * Use to combine two filters with a custom function to merge their outputs.\n *\n * **Details**\n *\n * Both filters must succeed (not return `fail`) for the combination to succeed.\n * If both filters pass, their outputs are combined using the provided function.\n *\n * @see {@link zip} for combining two filters into a tuple\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const zipWith = /*#__PURE__*/dual(3, (left, right, f) => input => {\n  const leftResult = left(input);\n  if (Result.isFailure(leftResult)) return leftResult;\n  const rightResult = right(input);\n  if (Result.isFailure(rightResult)) return rightResult;\n  return Result.succeed(f(leftResult.success, rightResult.success));\n});\n/**\n * Combines two filters into a tuple of their results.\n *\n * **Details**\n *\n * Both filters must succeed for the combination to succeed. If both pass, their\n * outputs are combined into a tuple.\n *\n * **Example** (Zipping filters)\n *\n * ```ts import.meta.vitest\n * import { Filter, Result } from \"effect\"\n *\n * const positiveNumbers = Filter.fromPredicate((n: number) => n > 0)\n * const evenNumbers = Filter.fromPredicate((n: number) => n % 2 === 0)\n *\n * const positiveAndEven = Filter.zip(positiveNumbers, evenNumbers)\n * positiveAndEven(2) // => Result.succeed([2, 2])\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const zip = /*#__PURE__*/dual(2, (left, right) => zipWith(left, right, (leftResult, rightResult) => [leftResult, rightResult]));\n/**\n * Combines two filters but only returns the result of the left filter.\n *\n * **Example** (Keeping the left filter result)\n *\n * ```ts import.meta.vitest\n * import { Filter, Result } from \"effect\"\n *\n * const positiveNumbers = Filter.fromPredicate((n: number) => n > 0)\n * const evenNumbers = Filter.fromPredicate((n: number) => n % 2 === 0)\n *\n * const positiveEven = Filter.andLeft(positiveNumbers, evenNumbers)\n * positiveEven(2) // => Result.succeed(2)\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const andLeft = /*#__PURE__*/dual(2, (left, right) => zipWith(left, right, leftResult => leftResult));\n/**\n * Combines two filters but only returns the result of the right filter.\n *\n * **Example** (Keeping the right filter result)\n *\n * ```ts import.meta.vitest\n * import { Filter, Result } from \"effect\"\n *\n * const positiveNumbers = Filter.fromPredicate((n: number) => n > 0)\n * const doubleNumbers = Filter.make((n: number) =>\n *   n > 0 ? Result.succeed(n * 2) : Result.fail(n)\n * )\n *\n * const positiveDoubled = Filter.andRight(positiveNumbers, doubleNumbers)\n * positiveDoubled(2) // => Result.succeed(4)\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const andRight = /*#__PURE__*/dual(2, (left, right) => zipWith(left, right, (_, rightResult) => rightResult));\n/**\n * Composes two filters sequentially, feeding the output of the first into the second.\n *\n * **Example** (Composing filters)\n *\n * ```ts import.meta.vitest\n * import { Filter, Result } from \"effect\"\n *\n * const stringFilter = Filter.string\n * const nonEmptyUpper = Filter.make((s: string) =>\n *   s.length > 0 ? Result.succeed(s.toUpperCase()) : Result.fail(s)\n * )\n *\n * const stringToUpper = Filter.compose(stringFilter, nonEmptyUpper)\n * stringToUpper(\"hello\") // => Result.succeed(\"HELLO\")\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const compose = /*#__PURE__*/dual(2, (left, right) => input => {\n  const leftOut = left(input);\n  if (Result.isFailure(leftOut)) return leftOut;\n  return right(leftOut.success);\n});\n/**\n * Composes two filters sequentially, passing the successful output of the first\n * filter to the second.\n *\n * **Details**\n *\n * If either filter fails, the returned filter fails with the original input\n * instead of the intermediate failure value.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const composePassthrough = /*#__PURE__*/dual(2, (left, right) => input => {\n  const leftOut = left(input);\n  if (Result.isFailure(leftOut)) return Result.fail(input);\n  const rightOut = right(leftOut.success);\n  if (Result.isFailure(rightOut)) return Result.fail(input);\n  return rightOut;\n});\n/**\n * Converts a `Filter` into a function that returns `Some` for passed values\n * and `None` for filtered-out values.\n *\n * **When to use**\n *\n * Use when adapting a `Filter` to `Option`-based code where passed values\n * become `Some` and filtered-out inputs become `None`.\n *\n * @see {@link toResult} for keeping the filter failure value\n * @see {@link toPredicate} for plain boolean pass/fail checks\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toOption = self => input => {\n  const result = self(input);\n  return Result.isFailure(result) ? Option.none() : Option.some(result.success);\n};\n/**\n * Converts a `Filter` into a function that returns the underlying\n * `Result.Result` for each input.\n *\n * **When to use**\n *\n * Use to adapt a `Filter` to APIs that expect a plain function returning\n * `Result`, while preserving both the pass value and the failure value.\n *\n * @see {@link toOption} for keeping only passed values\n * @see {@link toPredicate} for plain boolean pass/fail checks\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toResult = self => input => {\n  const result = self(input);\n  return Result.isFailure(result) ? Result.fail(result.failure) : Result.succeed(result.success);\n};\n//# sourceMappingURL=Filter.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 * 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 { 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","/**\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","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","/**\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 { IllegalArgumentError } from \"../Cause.js\";\nimport * as Clock from \"../Clock.js\";\nimport * as Duration from \"../Duration.js\";\nimport * as Equal from \"../Equal.js\";\nimport * as Equ from \"../Equivalence.js\";\nimport { dual } from \"../Function.js\";\nimport * as Hash from \"../Hash.js\";\nimport * as Inspectable from \"../Inspectable.js\";\nimport * as Option from \"../Option.js\";\nimport * as order from \"../Order.js\";\nimport { pipeArguments } from \"../Pipeable.js\";\nimport * as Predicate from \"../Predicate.js\";\nimport * as effect from \"./effect.js\";\n/** @internal */\nexport const TypeId = \"~effect/DateTime\";\n/** @internal */\nexport const TimeZoneTypeId = \"~effect/DateTime/TimeZone\";\nconst Proto = {\n  [TypeId]: TypeId,\n  pipe() {\n    return pipeArguments(this, arguments);\n  },\n  [Inspectable.NodeInspectSymbol]() {\n    return this.toString();\n  },\n  toJSON() {\n    return toDateUtc(this).toJSON();\n  }\n};\nconst ProtoUtc = {\n  ...Proto,\n  _tag: \"Utc\",\n  [Hash.symbol]() {\n    return Hash.number(this.epochMilliseconds);\n  },\n  [Equal.symbol](that) {\n    return isDateTime(that) && that._tag === \"Utc\" && this.epochMilliseconds === that.epochMilliseconds;\n  },\n  toString() {\n    return `DateTime.Utc(${toDateUtc(this).toJSON()})`;\n  }\n};\nconst ProtoZoned = {\n  ...Proto,\n  _tag: \"Zoned\",\n  [Hash.symbol]() {\n    return Hash.combine(Hash.number(this.epochMilliseconds))(Hash.hash(this.zone));\n  },\n  [Equal.symbol](that) {\n    return isDateTime(that) && that._tag === \"Zoned\" && this.epochMilliseconds === that.epochMilliseconds && Equal.equals(this.zone, that.zone);\n  },\n  toString() {\n    return `DateTime.Zoned(${formatIsoZoned(this)})`;\n  }\n};\nconst ProtoTimeZone = {\n  [TimeZoneTypeId]: TimeZoneTypeId,\n  [Inspectable.NodeInspectSymbol]() {\n    return this.toString();\n  }\n};\nconst ProtoTimeZoneNamed = {\n  ...ProtoTimeZone,\n  _tag: \"Named\",\n  [Hash.symbol]() {\n    return Hash.string(`Named:${this.id}`);\n  },\n  [Equal.symbol](that) {\n    return isTimeZone(that) && that._tag === \"Named\" && this.id === that.id;\n  },\n  toString() {\n    return `TimeZone.Named(${this.id})`;\n  },\n  toJSON() {\n    return {\n      _id: \"TimeZone\",\n      _tag: \"Named\",\n      id: this.id\n    };\n  }\n};\nconst ProtoTimeZoneOffset = {\n  ...ProtoTimeZone,\n  _tag: \"Offset\",\n  [Hash.symbol]() {\n    return Hash.string(`Offset:${this.offset}`);\n  },\n  [Equal.symbol](that) {\n    return isTimeZone(that) && that._tag === \"Offset\" && this.offset === that.offset;\n  },\n  toString() {\n    return `TimeZone.Offset(${offsetToString(this.offset)})`;\n  },\n  toJSON() {\n    return {\n      _id: \"TimeZone\",\n      _tag: \"Offset\",\n      offset: this.offset\n    };\n  }\n};\n/** @internal */\nexport const makeZonedProto = (epochMillis, zone, partsUtc) => {\n  const self = Object.create(ProtoZoned);\n  self.epochMilliseconds = epochMillis;\n  self.zone = zone;\n  Object.defineProperty(self, \"partsUtc\", {\n    value: partsUtc,\n    enumerable: false,\n    writable: true\n  });\n  Object.defineProperty(self, \"adjustedEpochMillis\", {\n    value: undefined,\n    enumerable: false,\n    writable: true\n  });\n  Object.defineProperty(self, \"partsAdjusted\", {\n    value: undefined,\n    enumerable: false,\n    writable: true\n  });\n  return self;\n};\n// =============================================================================\n// guards\n// =============================================================================\n/** @internal */\nexport const isDateTime = u => Predicate.hasProperty(u, TypeId);\nconst isDateTimeArgs = args => isDateTime(args[0]);\n/** @internal */\nexport const isTimeZone = u => Predicate.hasProperty(u, TimeZoneTypeId);\n/** @internal */\nexport const isTimeZoneOffset = u => isTimeZone(u) && u._tag === \"Offset\";\n/** @internal */\nexport const isTimeZoneNamed = u => isTimeZone(u) && u._tag === \"Named\";\n/** @internal */\nexport const isUtc = self => self._tag === \"Utc\";\n/** @internal */\nexport const isZoned = self => self._tag === \"Zoned\";\n// =============================================================================\n// instances\n// =============================================================================\n/** @internal */\nexport const Equivalence = /*#__PURE__*/Equ.make((a, b) => a.epochMilliseconds === b.epochMilliseconds);\n/** @internal */\nexport const Order = /*#__PURE__*/order.make((self, that) => self.epochMilliseconds < that.epochMilliseconds ? -1 : self.epochMilliseconds > that.epochMilliseconds ? 1 : 0);\n/** @internal */\nexport const clamp = /*#__PURE__*/order.clamp(Order);\n// =============================================================================\n// constructors\n// =============================================================================\nconst makeUtc = epochMillis => {\n  const self = Object.create(ProtoUtc);\n  self.epochMilliseconds = epochMillis;\n  Object.defineProperty(self, \"partsUtc\", {\n    value: undefined,\n    enumerable: false,\n    writable: true\n  });\n  return self;\n};\n/** @internal */\nexport const fromDateUnsafe = date => {\n  const epochMillis = date.getTime();\n  if (Number.isNaN(epochMillis)) {\n    throw new IllegalArgumentError(\"Invalid date\");\n  }\n  return makeUtc(epochMillis);\n};\n/** @internal */\nexport const makeUnsafe = input => {\n  if (isDateTime(input)) {\n    return input;\n  } else if (input instanceof Date) {\n    return fromDateUnsafe(input);\n  } else if (typeof input === \"object\") {\n    if (\"epochMilliseconds\" in input) {\n      return fromDateUnsafe(new Date(input.epochMilliseconds));\n    }\n    const date = new Date(0);\n    setPartsDate(date, input);\n    return fromDateUnsafe(date);\n  } else if (typeof input === \"string\" && !hasZone(input)) {\n    return fromDateUnsafe(new Date(input + \"Z\"));\n  }\n  return fromDateUnsafe(new Date(input));\n};\n/**\n * Detects whether a date string already contains timezone info.\n * Without a zone, `new Date(\"2024-01-01T12:00:00\")` is parsed as local time,\n * so `makeUnsafe` appends \"Z\" to force UTC interpretation.\n * This check prevents appending \"Z\" to strings that already have a zone\n * (e.g. \"2024-01-01T12:00:00Z\", \"...+05:30\", \"...GMT\"), which would produce invalid dates.\n */\nconst hasZone = input => /Z|GMT|[+-]\\d{2}$|[+-]\\d{2}:?\\d{2}$|\\]$/.test(input);\nconst minEpochMillis = -8640000000000000 + 12 * 60 * 60 * 1000;\nconst maxEpochMillis = 8640000000000000 - 14 * 60 * 60 * 1000;\n/** @internal */\nexport const makeZonedUnsafe = (input, options) => {\n  let timeZoneOption = options?.timeZone;\n  if (timeZoneOption === undefined && isDateTime(input) && isZoned(input)) {\n    return input;\n  }\n  const self = makeUnsafe(input);\n  if (self.epochMilliseconds < minEpochMillis || self.epochMilliseconds > maxEpochMillis) {\n    throw new RangeError(`Epoch millis out of range: ${self.epochMilliseconds}`);\n  }\n  if (timeZoneOption === undefined && typeof input === \"object\" && \"timeZoneId\" in input) {\n    timeZoneOption = input.timeZoneId;\n  }\n  let zone;\n  if (timeZoneOption === undefined) {\n    const offset = new Date(self.epochMilliseconds).getTimezoneOffset() * -60 * 1000;\n    zone = zoneMakeOffset(offset);\n  } else if (isTimeZone(timeZoneOption)) {\n    zone = timeZoneOption;\n  } else if (typeof timeZoneOption === \"number\") {\n    zone = zoneMakeOffset(timeZoneOption);\n  } else {\n    const parsedZone = zoneFromString(timeZoneOption);\n    if (Option.isNone(parsedZone)) {\n      throw new IllegalArgumentError(`Invalid time zone: ${timeZoneOption}`);\n    }\n    zone = parsedZone.value;\n  }\n  if (options?.adjustForTimeZone !== true) {\n    return makeZonedProto(self.epochMilliseconds, zone, self.partsUtc);\n  }\n  return makeZonedFromAdjusted(self.epochMilliseconds, zone, options?.disambiguation ?? \"compatible\");\n};\n/** @internal */\nexport const makeZoned = /*#__PURE__*/Option.liftThrowable(makeZonedUnsafe);\n/** @internal */\nexport const make = /*#__PURE__*/Option.liftThrowable(makeUnsafe);\nconst zonedStringRegExp = /^(.{17,35})\\[(.+)\\]$/;\n/** @internal */\nexport const makeZonedFromString = input => {\n  const match = zonedStringRegExp.exec(input);\n  if (match === null) {\n    const offset = parseOffset(input);\n    return offset !== null ? makeZoned(input, {\n      timeZone: offset\n    }) : Option.none();\n  }\n  const [, isoString, timeZone] = match;\n  return makeZoned(isoString, {\n    timeZone\n  });\n};\n/** @internal */\nexport const now = /*#__PURE__*/effect.map(Clock.currentTimeMillis, makeUtc);\n/** @internal */\nexport const nowAsDate = /*#__PURE__*/effect.map(Clock.currentTimeMillis, millis => new Date(millis));\n/** @internal */\nexport const nowUnsafe = () => makeUtc(Date.now());\n// =============================================================================\n// time zones\n// =============================================================================\n/** @internal */\nexport const toUtc = self => makeUtc(self.epochMilliseconds);\n/** @internal */\nexport const setZone = /*#__PURE__*/dual(isDateTimeArgs, (self, zone, options) => options?.adjustForTimeZone === true ? makeZonedFromAdjusted(self.epochMilliseconds, zone, options?.disambiguation ?? \"compatible\") : makeZonedProto(self.epochMilliseconds, zone, self.partsUtc));\n/** @internal */\nexport const setZoneOffset = /*#__PURE__*/dual(isDateTimeArgs, (self, offset, options) => setZone(self, zoneMakeOffset(offset), options));\nconst validZoneCache = /*#__PURE__*/new Map();\nconst formatOptions = {\n  day: \"numeric\",\n  month: \"numeric\",\n  year: \"numeric\",\n  hour: \"numeric\",\n  minute: \"numeric\",\n  second: \"numeric\",\n  timeZoneName: \"longOffset\",\n  fractionalSecondDigits: 3,\n  hourCycle: \"h23\"\n};\nconst zoneMakeIntl = format => {\n  const zoneId = format.resolvedOptions().timeZone;\n  if (validZoneCache.has(zoneId)) {\n    return validZoneCache.get(zoneId);\n  }\n  const zone = Object.create(ProtoTimeZoneNamed);\n  zone.id = zoneId;\n  zone.format = format;\n  validZoneCache.set(zoneId, zone);\n  return zone;\n};\n/** @internal */\nexport const zoneMakeNamedUnsafe = zoneId => {\n  if (validZoneCache.has(zoneId)) {\n    return validZoneCache.get(zoneId);\n  }\n  try {\n    return zoneMakeIntl(new Intl.DateTimeFormat(\"en-US\", {\n      ...formatOptions,\n      timeZone: zoneId\n    }));\n  } catch {\n    throw new IllegalArgumentError(`Invalid time zone: ${zoneId}`);\n  }\n};\n/** @internal */\nexport const zoneMakeOffset = offset => {\n  const zone = Object.create(ProtoTimeZoneOffset);\n  zone.offset = offset;\n  return zone;\n};\n/** @internal */\nexport const zoneMakeNamed = /*#__PURE__*/Option.liftThrowable(zoneMakeNamedUnsafe);\n/** @internal */\nexport const zoneMakeNamedEffect = zoneId => effect.try({\n  try: () => zoneMakeNamedUnsafe(zoneId),\n  catch: e => e\n});\n/** @internal */\nexport const zoneMakeLocal = () => zoneMakeIntl(new Intl.DateTimeFormat(\"en-US\", formatOptions));\nconst offsetZoneRegExp = /^(?:GMT|[+-])/;\n/** @internal */\nexport const zoneFromString = zone => {\n  if (offsetZoneRegExp.test(zone)) {\n    const offset = parseOffset(zone);\n    return offset === null ? Option.none() : Option.some(zoneMakeOffset(offset));\n  }\n  return zoneMakeNamed(zone);\n};\n/** @internal */\nexport const zoneToString = self => {\n  if (self._tag === \"Offset\") {\n    return offsetToString(self.offset);\n  }\n  return self.id;\n};\n/** @internal */\nexport const setZoneNamed = /*#__PURE__*/dual(isDateTimeArgs, (self, zoneId, options) => Option.map(zoneMakeNamed(zoneId), zone => setZone(self, zone, options)));\n/** @internal */\nexport const setZoneNamedUnsafe = /*#__PURE__*/dual(isDateTimeArgs, (self, zoneId, options) => setZone(self, zoneMakeNamedUnsafe(zoneId), options));\n// =============================================================================\n// comparisons\n// =============================================================================\n/** @internal */\nexport const distance = /*#__PURE__*/dual(2, (self, other) => Duration.millis(toEpochMillis(other) - toEpochMillis(self)));\n/** @internal */\nexport const min = /*#__PURE__*/order.min(Order);\n/** @internal */\nexport const max = /*#__PURE__*/order.max(Order);\n/** @internal */\nexport const isGreaterThan = /*#__PURE__*/order.isGreaterThan(Order);\n/** @internal */\nexport const isGreaterThanOrEqualTo = /*#__PURE__*/order.isGreaterThanOrEqualTo(Order);\n/** @internal */\nexport const isLessThan = /*#__PURE__*/order.isLessThan(Order);\n/** @internal */\nexport const isLessThanOrEqualTo = /*#__PURE__*/order.isLessThanOrEqualTo(Order);\n/** @internal */\nexport const between = /*#__PURE__*/order.isBetween(Order);\n/** @internal */\nexport const isFuture = self => effect.map(now, isLessThan(self));\n/** @internal */\nexport const isFutureUnsafe = self => isLessThan(nowUnsafe(), self);\n/** @internal */\nexport const isPast = self => effect.map(now, isGreaterThan(self));\n/** @internal */\nexport const isPastUnsafe = self => isGreaterThan(nowUnsafe(), self);\n// =============================================================================\n// conversions\n// =============================================================================\n/** @internal */\nexport const toDateUtc = self => new Date(self.epochMilliseconds);\n/** @internal */\nexport const toDate = self => {\n  if (self._tag === \"Utc\") {\n    return new Date(self.epochMilliseconds);\n  } else if (self.zone._tag === \"Offset\") {\n    return new Date(self.epochMilliseconds + self.zone.offset);\n  } else if (self.adjustedEpochMilliseconds !== undefined) {\n    return new Date(self.adjustedEpochMilliseconds);\n  }\n  const parts = self.zone.format.formatToParts(self.epochMilliseconds).filter(_ => _.type !== \"literal\");\n  const date = new Date(0);\n  date.setUTCFullYear(Number(parts[2].value), Number(parts[0].value) - 1, Number(parts[1].value));\n  date.setUTCHours(Number(parts[3].value), Number(parts[4].value), Number(parts[5].value), Number(parts[6].value));\n  self.adjustedEpochMilliseconds = date.getTime();\n  return date;\n};\n/** @internal */\nexport const zonedOffset = self => {\n  const date = toDate(self);\n  return date.getTime() - toEpochMillis(self);\n};\nconst offsetToString = offset => {\n  const abs = Math.abs(offset);\n  let hours = Math.floor(abs / (60 * 60 * 1000));\n  let minutes = Math.round(abs % (60 * 60 * 1000) / (60 * 1000));\n  if (minutes === 60) {\n    hours += 1;\n    minutes = 0;\n  }\n  return `${offset < 0 ? \"-\" : \"+\"}${String(hours).padStart(2, \"0\")}:${String(minutes).padStart(2, \"0\")}`;\n};\n/** @internal */\nexport const zonedOffsetIso = self => offsetToString(zonedOffset(self));\n/** @internal */\nexport const toEpochMillis = self => self.epochMilliseconds;\n/** @internal */\nexport const toEpochSeconds = self => Math.floor(self.epochMilliseconds / 1000);\n/** @internal */\nexport const fromEpochSeconds = seconds => makeUtc(seconds * 1000);\n/** @internal */\nexport const removeTime = self => withDate(self, date => {\n  date.setUTCHours(0, 0, 0, 0);\n  return makeUtc(date.getTime());\n});\n// =============================================================================\n// parts\n// =============================================================================\nconst dateToParts = date => ({\n  millisecond: date.getUTCMilliseconds(),\n  second: date.getUTCSeconds(),\n  minute: date.getUTCMinutes(),\n  hour: date.getUTCHours(),\n  day: date.getUTCDate(),\n  weekDay: date.getUTCDay(),\n  month: date.getUTCMonth() + 1,\n  year: date.getUTCFullYear()\n});\n/** @internal */\nexport const toParts = self => {\n  if (self._tag === \"Utc\") {\n    return toPartsUtc(self);\n  } else if (self.partsAdjusted !== undefined) {\n    return self.partsAdjusted;\n  }\n  self.partsAdjusted = withDate(self, dateToParts);\n  return self.partsAdjusted;\n};\n/** @internal */\nexport const toPartsUtc = self => {\n  if (self.partsUtc !== undefined) {\n    return self.partsUtc;\n  }\n  self.partsUtc = withDateUtc(self, dateToParts);\n  return self.partsUtc;\n};\n/** @internal */\nexport const getPartUtc = /*#__PURE__*/dual(2, (self, part) => toPartsUtc(self)[part]);\n/** @internal */\nexport const getPart = /*#__PURE__*/dual(2, (self, part) => toParts(self)[part]);\nconst setPartsDate = (date, parts) => {\n  if (parts.year !== undefined || parts.month !== undefined || parts.day !== undefined) {\n    date.setUTCFullYear(parts.year ?? date.getUTCFullYear(), parts.month !== undefined ? parts.month - 1 : date.getUTCMonth(), parts.day ?? date.getUTCDate());\n  }\n  if (parts.weekDay !== undefined) {\n    const diff = parts.weekDay - date.getUTCDay();\n    date.setUTCDate(date.getUTCDate() + diff);\n  }\n  if (parts.hour !== undefined) {\n    date.setUTCHours(parts.hour);\n  }\n  if (parts.minute !== undefined) {\n    date.setUTCMinutes(parts.minute);\n  }\n  if (parts.second !== undefined) {\n    date.setUTCSeconds(parts.second);\n  }\n  if (parts.millisecond !== undefined) {\n    date.setUTCMilliseconds(parts.millisecond);\n  }\n};\n/** @internal */\nexport const setParts = /*#__PURE__*/dual(2, (self, parts) => mutate(self, date => setPartsDate(date, parts)));\n/** @internal */\nexport const setPartsUtc = /*#__PURE__*/dual(2, (self, parts) => mutateUtc(self, date => setPartsDate(date, parts)));\n// =============================================================================\n// mapping\n// =============================================================================\nconst constDayMillis = 24 * 60 * 60 * 1000;\nconst makeZonedFromAdjusted = (adjustedMillis, zone, disambiguation) => {\n  if (zone._tag === \"Offset\") {\n    return makeZonedProto(adjustedMillis - zone.offset, zone);\n  }\n  const beforeOffset = calculateNamedOffset(adjustedMillis - constDayMillis, adjustedMillis, zone);\n  const afterOffset = calculateNamedOffset(adjustedMillis + constDayMillis, adjustedMillis, zone);\n  // If there is no transition, we can return early\n  if (beforeOffset === afterOffset) {\n    return makeZonedProto(adjustedMillis - beforeOffset, zone);\n  }\n  const isForwards = beforeOffset < afterOffset;\n  const transitionMillis = beforeOffset - afterOffset;\n  // If the transition is forwards, we only need to check if we should move the\n  // local wall clock time forward if it is inside the gap\n  if (isForwards) {\n    const currentAfterOffset = calculateNamedOffset(adjustedMillis - afterOffset, adjustedMillis, zone);\n    if (currentAfterOffset === afterOffset) {\n      return makeZonedProto(adjustedMillis - afterOffset, zone);\n    }\n    const before = makeZonedProto(adjustedMillis - beforeOffset, zone);\n    const beforeAdjustedMillis = toDate(before).getTime();\n    // If the wall clock time has changed, we are inside the gap\n    if (adjustedMillis !== beforeAdjustedMillis) {\n      switch (disambiguation) {\n        case \"reject\":\n          {\n            const formatted = new Date(adjustedMillis).toISOString();\n            throw new RangeError(`Gap time: ${formatted} does not exist in time zone ${zone.id}`);\n          }\n        case \"earlier\":\n          return makeZonedProto(adjustedMillis - afterOffset, zone);\n        case \"compatible\":\n        case \"later\":\n          return before;\n      }\n    }\n    // The wall clock time is in the earlier offset, so we use that\n    return before;\n  }\n  const currentBeforeOffset = calculateNamedOffset(adjustedMillis - beforeOffset, adjustedMillis, zone);\n  // The wall clock time is in the earlier offset, so we use that\n  if (currentBeforeOffset === beforeOffset) {\n    if (disambiguation === \"earlier\" || disambiguation === \"compatible\") {\n      return makeZonedProto(adjustedMillis - beforeOffset, zone);\n    }\n    const laterOffset = calculateNamedOffset(adjustedMillis - beforeOffset + transitionMillis, adjustedMillis + transitionMillis, zone);\n    if (laterOffset === beforeOffset) {\n      return makeZonedProto(adjustedMillis - beforeOffset, zone);\n    }\n    // If the offset changed in this period, then we are inside the period where\n    // the wall clock time occurs twice, once in the earlier offset and once in\n    // the later offset.\n    if (disambiguation === \"reject\") {\n      const formatted = new Date(adjustedMillis).toISOString();\n      throw new RangeError(`Ambiguous time: ${formatted} occurs twice in time zone ${zone.id}`);\n    }\n    // If the disambiguation is \"later\", we return the later offset below\n  }\n  return makeZonedProto(adjustedMillis - afterOffset, zone);\n};\nconst offsetRegExp = /([+-])(\\d{2}):(\\d{2})$/;\nconst parseOffset = offset => {\n  const match = offsetRegExp.exec(offset);\n  if (match === null) {\n    return null;\n  }\n  const [, sign, hours, minutes] = match;\n  return (sign === \"+\" ? 1 : -1) * (Number(hours) * 60 + Number(minutes)) * 60 * 1000;\n};\nconst calculateNamedOffset = (utcMillis, adjustedMillis, zone) => {\n  const offset = zone.format.formatToParts(utcMillis).find(_ => _.type === \"timeZoneName\")?.value ?? \"\";\n  if (offset === \"GMT\") {\n    return 0;\n  }\n  const result = parseOffset(offset);\n  if (result === null) {\n    // fallback to using the adjusted date\n    return zonedOffset(makeZonedProto(adjustedMillis, zone));\n  }\n  return result;\n};\n/** @internal */\nexport const mutate = /*#__PURE__*/dual(isDateTimeArgs, (self, f, options) => {\n  if (self._tag === \"Utc\") {\n    const date = toDateUtc(self);\n    f(date);\n    return makeUtc(date.getTime());\n  }\n  const adjustedDate = toDate(self);\n  const newAdjustedDate = new Date(adjustedDate.getTime());\n  f(newAdjustedDate);\n  return makeZonedFromAdjusted(newAdjustedDate.getTime(), self.zone, options?.disambiguation ?? \"compatible\");\n});\n/** @internal */\nexport const mutateUtc = /*#__PURE__*/dual(2, (self, f) => mapEpochMillis(self, millis => {\n  const date = new Date(millis);\n  f(date);\n  return date.getTime();\n}));\n/** @internal */\nexport const mapEpochMillis = /*#__PURE__*/dual(2, (self, f) => {\n  const millis = f(toEpochMillis(self));\n  return self._tag === \"Utc\" ? makeUtc(millis) : makeZonedProto(millis, self.zone);\n});\n/** @internal */\nexport const withDate = /*#__PURE__*/dual(2, (self, f) => f(toDate(self)));\n/** @internal */\nexport const withDateUtc = /*#__PURE__*/dual(2, (self, f) => f(toDateUtc(self)));\n/** @internal */\nexport const match = /*#__PURE__*/dual(2, (self, options) => self._tag === \"Utc\" ? options.onUtc(self) : options.onZoned(self));\n// =============================================================================\n// math\n// =============================================================================\n/** @internal */\nexport const addDuration = /*#__PURE__*/dual(2, (self, duration) => mapEpochMillis(self, millis => millis + Duration.toMillis(Duration.fromInputUnsafe(duration))));\n/** @internal */\nexport const subtractDuration = /*#__PURE__*/dual(2, (self, duration) => mapEpochMillis(self, millis => millis - Duration.toMillis(Duration.fromInputUnsafe(duration))));\nconst addMillis = (date, amount) => {\n  date.setTime(date.getTime() + amount);\n};\n/** @internal */\nexport const add = /*#__PURE__*/dual(2, (self, parts) => mutate(self, date => {\n  if (parts.milliseconds) {\n    addMillis(date, parts.milliseconds);\n  }\n  if (parts.seconds) {\n    addMillis(date, parts.seconds * 1000);\n  }\n  if (parts.minutes) {\n    addMillis(date, parts.minutes * 60 * 1000);\n  }\n  if (parts.hours) {\n    addMillis(date, parts.hours * 60 * 60 * 1000);\n  }\n  if (parts.days) {\n    date.setUTCDate(date.getUTCDate() + parts.days);\n  }\n  if (parts.weeks) {\n    date.setUTCDate(date.getUTCDate() + parts.weeks * 7);\n  }\n  if (parts.months) {\n    const day = date.getUTCDate();\n    date.setUTCMonth(date.getUTCMonth() + parts.months + 1, 0);\n    if (day < date.getUTCDate()) {\n      date.setUTCDate(day);\n    }\n  }\n  if (parts.years) {\n    const day = date.getUTCDate();\n    const month = date.getUTCMonth();\n    date.setUTCFullYear(date.getUTCFullYear() + parts.years, month + 1, 0);\n    if (day < date.getUTCDate()) {\n      date.setUTCDate(day);\n    }\n  }\n}));\n/** @internal */\nexport const subtract = /*#__PURE__*/dual(2, (self, parts) => {\n  const newParts = {};\n  for (const key in parts) {\n    newParts[key] = -1 * parts[key];\n  }\n  return add(self, newParts);\n});\nconst startOfDate = (date, part, options) => {\n  switch (part) {\n    case \"second\":\n      {\n        date.setUTCMilliseconds(0);\n        break;\n      }\n    case \"minute\":\n      {\n        date.setUTCSeconds(0, 0);\n        break;\n      }\n    case \"hour\":\n      {\n        date.setUTCMinutes(0, 0, 0);\n        break;\n      }\n    case \"day\":\n      {\n        date.setUTCHours(0, 0, 0, 0);\n        break;\n      }\n    case \"week\":\n      {\n        const weekStartsOn = options?.weekStartsOn ?? 0;\n        const day = date.getUTCDay();\n        const diff = (day - weekStartsOn + 7) % 7;\n        date.setUTCDate(date.getUTCDate() - diff);\n        date.setUTCHours(0, 0, 0, 0);\n        break;\n      }\n    case \"month\":\n      {\n        date.setUTCDate(1);\n        date.setUTCHours(0, 0, 0, 0);\n        break;\n      }\n    case \"year\":\n      {\n        date.setUTCMonth(0, 1);\n        date.setUTCHours(0, 0, 0, 0);\n        break;\n      }\n  }\n};\n/** @internal */\nexport const startOf = /*#__PURE__*/dual(isDateTimeArgs, (self, part, options) => mutate(self, date => startOfDate(date, part, options)));\nconst endOfDate = (date, part, options) => {\n  switch (part) {\n    case \"second\":\n      {\n        date.setUTCMilliseconds(999);\n        break;\n      }\n    case \"minute\":\n      {\n        date.setUTCSeconds(59, 999);\n        break;\n      }\n    case \"hour\":\n      {\n        date.setUTCMinutes(59, 59, 999);\n        break;\n      }\n    case \"day\":\n      {\n        date.setUTCHours(23, 59, 59, 999);\n        break;\n      }\n    case \"week\":\n      {\n        const weekStartsOn = options?.weekStartsOn ?? 0;\n        const day = date.getUTCDay();\n        const diff = (day - weekStartsOn + 7) % 7;\n        date.setUTCDate(date.getUTCDate() - diff + 6);\n        date.setUTCHours(23, 59, 59, 999);\n        break;\n      }\n    case \"month\":\n      {\n        date.setUTCMonth(date.getUTCMonth() + 1, 0);\n        date.setUTCHours(23, 59, 59, 999);\n        break;\n      }\n    case \"year\":\n      {\n        date.setUTCMonth(11, 31);\n        date.setUTCHours(23, 59, 59, 999);\n        break;\n      }\n  }\n};\n/** @internal */\nexport const endOf = /*#__PURE__*/dual(isDateTimeArgs, (self, part, options) => mutate(self, date => endOfDate(date, part, options)));\n/** @internal */\nexport const nearest = /*#__PURE__*/dual(isDateTimeArgs, (self, part, options) => mutate(self, date => {\n  if (part === \"millisecond\") return;\n  const millis = date.getTime();\n  const start = new Date(millis);\n  startOfDate(start, part, options);\n  const startMillis = start.getTime();\n  const end = new Date(millis);\n  endOfDate(end, part, options);\n  const endMillis = end.getTime() + 1;\n  const diffStart = millis - startMillis;\n  const diffEnd = endMillis - millis;\n  if (diffStart < diffEnd) {\n    date.setTime(startMillis);\n  } else {\n    date.setTime(endMillis);\n  }\n}));\n// =============================================================================\n// formatting\n// =============================================================================\nconst intlTimeZone = self => {\n  if (self._tag === \"Named\") {\n    return self.id;\n  }\n  return offsetToString(self.offset);\n};\n/** @internal */\nexport const format = /*#__PURE__*/dual(isDateTimeArgs, (self, options) => {\n  try {\n    return new Intl.DateTimeFormat(options?.locale, {\n      timeZone: self._tag === \"Utc\" ? \"UTC\" : intlTimeZone(self.zone),\n      ...options\n    }).format(self.epochMilliseconds);\n  } catch {\n    return new Intl.DateTimeFormat(options?.locale, {\n      timeZone: \"UTC\",\n      ...options\n    }).format(toDate(self));\n  }\n});\n/** @internal */\nexport const formatLocal = /*#__PURE__*/dual(isDateTimeArgs, (self, options) => new Intl.DateTimeFormat(options?.locale, options).format(self.epochMilliseconds));\n/** @internal */\nexport const formatUtc = /*#__PURE__*/dual(isDateTimeArgs, (self, options) => new Intl.DateTimeFormat(options?.locale, {\n  ...options,\n  timeZone: \"UTC\"\n}).format(self.epochMilliseconds));\n/** @internal */\nexport const formatIntl = /*#__PURE__*/dual(2, (self, format) => format.format(self.epochMilliseconds));\n/** @internal */\nexport const formatIso = self => toDateUtc(self).toISOString();\n/** @internal */\nexport const formatIsoDate = self => toDate(self).toISOString().slice(0, 10);\n/** @internal */\nexport const formatIsoDateUtc = self => toDateUtc(self).toISOString().slice(0, 10);\n/** @internal */\nexport const formatIsoOffset = self => {\n  const date = toDate(self);\n  return self._tag === \"Utc\" ? date.toISOString() : `${date.toISOString().slice(0, -1)}${zonedOffsetIso(self)}`;\n};\n/** @internal */\nexport const formatIsoZoned = self => self.zone._tag === \"Offset\" ? formatIsoOffset(self) : `${formatIsoOffset(self)}[${self.zone.id}]`;\n//# sourceMappingURL=dateTime.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 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 * 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","/**\n * Works with JavaScript `bigint` values.\n *\n * This module exposes the native `BigInt` constructor together with helpers for\n * checking, arithmetic, comparison, range checks, safe parsing and conversions\n * that return `Option`, integer square roots, aggregation, ordering,\n * equivalence, reducers, and combiners.\n *\n * @since 2.0.0\n */\nimport * as Combiner from \"./Combiner.js\";\nimport * as Equ from \"./Equivalence.js\";\nimport { dual } from \"./Function.js\";\nimport * as Option from \"./Option.js\";\nimport * as order from \"./Order.js\";\nimport * as predicate from \"./Predicate.js\";\nimport * as Reducer from \"./Reducer.js\";\n/**\n * Exposes the global bigint constructor for JavaScript bigint coercion.\n *\n * **When to use**\n *\n * Use to access native JavaScript bigint constructor coercion from the Effect\n * module namespace.\n *\n * **Gotchas**\n *\n * This follows native `BigInt` coercion rules. It throws for invalid strings or\n * non-integral numbers, and whitespace-only strings coerce to `0n`.\n *\n * @see {@link fromString} for parsing strings into an `Option`\n * @see {@link fromNumber} for converting safe integers into an `Option`\n *\n * **Example** (Constructing bigints)\n *\n * ```ts import.meta.vitest\n * import { BigInt } from \"effect\"\n *\n * BigInt.BigInt(123) // => 123n\n * BigInt.BigInt(\"456\") // => 456n\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const BigInt = globalThis.BigInt;\nconst bigint0 = /*#__PURE__*/BigInt(0);\nconst bigint1 = /*#__PURE__*/BigInt(1);\nconst bigint2 = /*#__PURE__*/BigInt(2);\n/**\n * Checks whether a value is a `bigint`.\n *\n * **When to use**\n *\n * Use to validate unknown input and narrow it to `bigint`.\n *\n * **Example** (Checking for bigints)\n *\n * ```ts import.meta.vitest\n * import { BigInt } from \"effect\"\n *\n * BigInt.isBigInt(1n) // => true\n * BigInt.isBigInt(1) // => false\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isBigInt = predicate.isBigInt;\n/**\n * Provides an addition operation on `bigint`s.\n *\n * **When to use**\n *\n * Use when you need a binary addition function for piping or higher-order APIs\n * instead of the infix addition operator.\n *\n * **Example** (Adding bigints)\n *\n * ```ts import.meta.vitest\n * import { BigInt } from \"effect\"\n *\n * BigInt.sum(2n, 3n) // => 5n\n * ```\n *\n * @see {@link sumAll} for summing an iterable of `bigint` values\n *\n * @category math\n * @since 2.0.0\n */\nexport const sum = /*#__PURE__*/dual(2, (self, that) => self + that);\n/**\n * Provides a multiplication operation on `bigint`s.\n *\n * **When to use**\n *\n * Use to multiply two `bigint` values.\n *\n * **Example** (Multiplying bigints)\n *\n * ```ts import.meta.vitest\n * import { BigInt } from \"effect\"\n *\n * BigInt.multiply(2n, 3n) // => 6n\n * ```\n *\n * @see {@link multiplyAll} for multiplying an iterable of `bigint` values\n *\n * @category math\n * @since 2.0.0\n */\nexport const multiply = /*#__PURE__*/dual(2, (self, that) => self * that);\n/**\n * Provides a subtraction operation on `bigint`s.\n *\n * **When to use**\n *\n * Use to subtract one `bigint` value from another.\n *\n * **Example** (Subtracting bigints)\n *\n * ```ts import.meta.vitest\n * import { BigInt } from \"effect\"\n *\n * BigInt.subtract(2n, 3n) // => -1n\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const subtract = /*#__PURE__*/dual(2, (self, that) => self - that);\n/**\n * Divides one `bigint` by another safely.\n *\n * **When to use**\n *\n * Use to divide `bigint` values while representing division by zero as\n * `Option.none`.\n *\n * **Details**\n *\n * Uses JavaScript `bigint` division, so non-exact quotients are truncated\n * toward zero. Returns `Option.none()` when the divisor is `0n`.\n *\n * **Example** (Dividing bigints safely)\n *\n * ```ts import.meta.vitest\n * import { BigInt, Option } from \"effect\"\n *\n * BigInt.divide(6n, 3n) // => Option.some(2n)\n * BigInt.divide(6n, 0n) // => Option.none()\n * ```\n *\n * @see {@link divideUnsafe} for division that throws when the divisor is `0n`\n * @see {@link remainder} for the JavaScript remainder operation\n *\n * @category math\n * @since 2.0.0\n */\nexport const divide = /*#__PURE__*/dual(2, (self, that) => that === bigint0 ? Option.none() : Option.some(self / that));\n/**\n * Divides one `bigint` by another, throwing if the divisor is zero.\n *\n * **When to use**\n *\n * Use to divide `bigint` values where the divisor is known to be non-zero and\n * division by zero should be a thrown exception.\n *\n * **Details**\n *\n * Uses JavaScript `bigint` division, so non-exact quotients are truncated\n * toward zero.\n *\n * **Gotchas**\n *\n * Throws a `RangeError` when the divisor is `0n`.\n *\n * **Example** (Dividing bigints unsafely)\n *\n * ```ts import.meta.vitest\n * import { BigInt } from \"effect\"\n *\n * BigInt.divideUnsafe(6n, 3n) // => 2n\n * BigInt.divideUnsafe(6n, 4n) // => 1n\n * ```\n *\n * @see {@link divide} for division that returns `Option.none` when the divisor is `0n`\n *\n * @category math\n * @since 4.0.0\n */\nexport const divideUnsafe = /*#__PURE__*/dual(2, (self, that) => self / that);\n/**\n * Returns the result of adding `1n` to a `bigint`.\n *\n * **When to use**\n *\n * Use to increment a `bigint` counter by one.\n *\n * **Example** (Incrementing a bigint)\n *\n * ```ts import.meta.vitest\n * import { BigInt } from \"effect\"\n *\n * BigInt.increment(2n) // => 3n\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const increment = n => n + bigint1;\n/**\n * Returns the result of subtracting `1n` from a `bigint`.\n *\n * **When to use**\n *\n * Use to decrement a `bigint` counter by one.\n *\n * **Example** (Decrementing a bigint)\n *\n * ```ts import.meta.vitest\n * import { BigInt } from \"effect\"\n *\n * BigInt.decrement(3n) // => 2n\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const decrement = n => n - bigint1;\n/**\n * Provides an `Order` instance for `bigint` that allows comparing and sorting BigInt values.\n *\n * **When to use**\n *\n * Use when you need to sort or compare bigint values through APIs that accept\n * an ordering instance.\n *\n * **Example** (Comparing bigints with Order)\n *\n * ```ts import.meta.vitest\n * import { BigInt } from \"effect\"\n *\n * const a = 123n\n * const b = 456n\n * const c = 123n\n *\n * BigInt.Order(a, b) // => -1\n * BigInt.Order(b, a) // => 1\n * BigInt.Order(a, c) // => 0\n * ```\n *\n * @category instances\n * @since 2.0.0\n */\nexport const Order = order.BigInt;\n/**\n * Equivalence instance for bigints using strict equality (`===`).\n *\n * **When to use**\n *\n * Use when checking bigint equality through APIs that accept an equivalence\n * relation.\n *\n * **Example** (Comparing bigints for equivalence)\n *\n * ```ts import.meta.vitest\n * import { BigInt } from \"effect\"\n *\n * BigInt.Equivalence(1n, 1n) // => true\n * BigInt.Equivalence(1n, 2n) // => false\n * ```\n *\n * @category instances\n * @since 2.0.0\n */\nexport const Equivalence = Equ.BigInt;\n/**\n * Returns `true` if the first argument is less than the second, otherwise `false`.\n *\n * **When to use**\n *\n * Use to test whether one `bigint` is strictly less than another.\n *\n * **Example** (Checking less-than comparisons)\n *\n * ```ts import.meta.vitest\n * import { BigInt } from \"effect\"\n *\n * BigInt.isLessThan(2n, 3n) // => true\n * BigInt.isLessThan(3n, 3n) // => false\n * BigInt.isLessThan(4n, 3n) // => false\n * ```\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isLessThan = /*#__PURE__*/order.isLessThan(Order);\n/**\n * Returns a function that checks if a given `bigint` is less than or equal to the provided one.\n *\n * **When to use**\n *\n * Use to test whether one `bigint` is less than or equal to another.\n *\n * **Example** (Checking less-than-or-equal comparisons)\n *\n * ```ts import.meta.vitest\n * import { BigInt } from \"effect\"\n *\n * BigInt.isLessThanOrEqualTo(2n, 3n) // => true\n * BigInt.isLessThanOrEqualTo(3n, 3n) // => true\n * BigInt.isLessThanOrEqualTo(4n, 3n) // => false\n * ```\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isLessThanOrEqualTo = /*#__PURE__*/order.isLessThanOrEqualTo(Order);\n/**\n * Returns `true` if the first argument is greater than the second, otherwise `false`.\n *\n * **When to use**\n *\n * Use to test whether one `bigint` is strictly greater than another.\n *\n * **Example** (Checking greater-than comparisons)\n *\n * ```ts import.meta.vitest\n * import { BigInt } from \"effect\"\n *\n * BigInt.isGreaterThan(2n, 3n) // => false\n * BigInt.isGreaterThan(3n, 3n) // => false\n * BigInt.isGreaterThan(4n, 3n) // => true\n * ```\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isGreaterThan = /*#__PURE__*/order.isGreaterThan(Order);\n/**\n * Returns a function that checks if a given `bigint` is greater than or equal to the provided one.\n *\n * **When to use**\n *\n * Use to test whether one `bigint` is greater than or equal to another.\n *\n * **Example** (Checking greater-than-or-equal comparisons)\n *\n * ```ts import.meta.vitest\n * import { BigInt } from \"effect\"\n *\n * BigInt.isGreaterThanOrEqualTo(2n, 3n) // => false\n * BigInt.isGreaterThanOrEqualTo(3n, 3n) // => true\n * BigInt.isGreaterThanOrEqualTo(4n, 3n) // => true\n * ```\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isGreaterThanOrEqualTo = /*#__PURE__*/order.isGreaterThanOrEqualTo(Order);\n/**\n * Checks whether a `bigint` is between a `minimum` and `maximum` value (inclusive).\n *\n * **When to use**\n *\n * Use to test whether a `bigint` falls inside an inclusive range.\n *\n * **Example** (Checking whether a bigint is within bounds)\n *\n * ```ts import.meta.vitest\n * import { BigInt } from \"effect\"\n *\n * const between = BigInt.between({ minimum: 0n, maximum: 5n })\n *\n * between(3n) // => true\n * between(-1n) // => false\n * between(6n) // => false\n * ```\n *\n * @see {@link clamp} for forcing a `bigint` into an inclusive range\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const between = /*#__PURE__*/order.isBetween(Order);\n/**\n * Restricts the given `bigint` to be within the range specified by the `minimum` and `maximum` values.\n *\n * **When to use**\n *\n * Use to force a `bigint` into an inclusive range.\n *\n * **Details**\n *\n * If the `bigint` is less than the minimum, the function returns the minimum.\n * If the `bigint` is greater than the maximum, the function returns the\n * maximum. Otherwise, it returns the original `bigint`.\n *\n * **Example** (Clamping a bigint to bounds)\n *\n * ```ts import.meta.vitest\n * import { BigInt } from \"effect\"\n *\n * const clamp = BigInt.clamp({ minimum: 1n, maximum: 5n })\n *\n * clamp(3n) // => 3n\n * clamp(0n) // => 1n\n * clamp(6n) // => 5n\n * ```\n *\n * @see {@link between} for checking whether a `bigint` is already inside a range\n *\n * @category math\n * @since 2.0.0\n */\nexport const clamp = /*#__PURE__*/order.clamp(Order);\n/**\n * Returns the minimum between two `bigint`s.\n *\n * **When to use**\n *\n * Use to select the smaller of two `bigint` values.\n *\n * **Example** (Finding the minimum bigint)\n *\n * ```ts import.meta.vitest\n * import { BigInt } from \"effect\"\n *\n * BigInt.min(2n, 3n) // => 2n\n * ```\n *\n * @see {@link max} for selecting the larger value\n *\n * @category math\n * @since 2.0.0\n */\nexport const min = /*#__PURE__*/order.min(Order);\n/**\n * Returns the maximum between two `bigint`s.\n *\n * **When to use**\n *\n * Use to select the larger of two `bigint` values.\n *\n * **Example** (Finding the maximum bigint)\n *\n * ```ts import.meta.vitest\n * import { BigInt } from \"effect\"\n *\n * BigInt.max(2n, 3n) // => 3n\n * ```\n *\n * @see {@link min} for selecting the smaller value\n *\n * @category math\n * @since 2.0.0\n */\nexport const max = /*#__PURE__*/order.max(Order);\n/**\n * Determines the sign of a given `bigint`.\n *\n * **When to use**\n *\n * Use to classify a `bigint` as negative, zero, or positive.\n *\n * **Example** (Determining bigint signs)\n *\n * ```ts import.meta.vitest\n * import { BigInt } from \"effect\"\n *\n * BigInt.sign(-5n) // => -1\n * BigInt.sign(0n) // => 0\n * BigInt.sign(5n) // => 1\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const sign = n => order.BigInt(n, bigint0);\n/**\n * Determines the absolute value of a given `bigint`.\n *\n * **When to use**\n *\n * Use to remove the sign from a `bigint` while preserving its magnitude.\n *\n * **Example** (Calculating absolute values)\n *\n * ```ts import.meta.vitest\n * import { BigInt } from \"effect\"\n *\n * BigInt.abs(-5n) // => 5n\n * BigInt.abs(0n) // => 0n\n * BigInt.abs(5n) // => 5n\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const abs = n => n < bigint0 ? -n : n;\n/**\n * Determines the greatest common divisor of two `bigint`s.\n *\n * **When to use**\n *\n * Use to compute the greatest common divisor of two integer values.\n *\n * **Example** (Calculating greatest common divisors)\n *\n * ```ts import.meta.vitest\n * import { BigInt } from \"effect\"\n *\n * BigInt.gcd(2n, 3n) // => 1n\n * BigInt.gcd(2n, 4n) // => 2n\n * BigInt.gcd(16n, 24n) // => 8n\n * ```\n *\n * @see {@link lcm} for computing the least common multiple\n *\n * @category math\n * @since 2.0.0\n */\nexport const gcd = /*#__PURE__*/dual(2, (self, that) => {\n  while (that !== bigint0) {\n    const t = that;\n    that = self % that;\n    self = t;\n  }\n  return abs(self);\n});\n/**\n * Determines the least common multiple of two `bigint`s.\n *\n * **When to use**\n *\n * Use to compute the least common multiple of two integer values.\n *\n * **Example** (Calculating least common multiples)\n *\n * ```ts import.meta.vitest\n * import { BigInt } from \"effect\"\n *\n * BigInt.lcm(2n, 3n) // => 6n\n * BigInt.lcm(2n, 4n) // => 4n\n * BigInt.lcm(16n, 24n) // => 48n\n * ```\n *\n * @see {@link gcd} for computing the greatest common divisor\n *\n * @category math\n * @since 2.0.0\n */\nexport const lcm = /*#__PURE__*/dual(2, (self, that) => self === bigint0 || that === bigint0 ? bigint0 : abs(self * that / gcd(self, that)));\n/**\n * Returns the integer square root of a non-negative `bigint`.\n *\n * **When to use**\n *\n * Use when you need to compute an integer square root for a `bigint` that has\n * already been validated as non-negative, and you want negative input to throw\n * instead of returning `Option.none`.\n *\n * **Details**\n *\n * For non-perfect squares, returns the largest `bigint` whose square is less\n * than or equal to the input.\n *\n * **Gotchas**\n *\n * Throws a `RangeError` if the input is negative.\n *\n * **Example** (Calculating square roots unsafely)\n *\n * ```ts import.meta.vitest\n * import { BigInt } from \"effect\"\n *\n * BigInt.sqrtUnsafe(4n) // => 2n\n * BigInt.sqrtUnsafe(9n) // => 3n\n * BigInt.sqrtUnsafe(16n) // => 4n\n * ```\n *\n * @see {@link sqrt} for returning `Option.none` when the input is negative\n *\n * @category math\n * @since 4.0.0\n */\nexport const sqrtUnsafe = n => {\n  if (n < bigint0) {\n    throw new RangeError(\"Cannot take the square root of a negative number\");\n  }\n  if (n < bigint2) {\n    return n;\n  }\n  let x = n / bigint2;\n  while (x * x > n) {\n    x = (n / x + x) / bigint2;\n  }\n  return x;\n};\n/**\n * Computes the integer square root of a `bigint` safely.\n *\n * **When to use**\n *\n * Use to compute an integer square root while representing negative input as\n * `Option.none`.\n *\n * **Details**\n *\n * For non-perfect squares, returns the largest `bigint` whose square is less\n * than or equal to the input. Returns `Option.none()` when the input is\n * negative.\n *\n * **Example** (Calculating square roots safely)\n *\n * ```ts import.meta.vitest\n * import { BigInt, Option } from \"effect\"\n *\n * BigInt.sqrt(4n) // => Option.some(2n)\n * BigInt.sqrt(9n) // => Option.some(3n)\n * BigInt.sqrt(16n) // => Option.some(4n)\n * BigInt.sqrt(-1n) // => Option.none()\n * ```\n *\n * @see {@link sqrtUnsafe} for square root computation that throws on negative input\n *\n * @category math\n * @since 2.0.0\n */\nexport const sqrt = n => isGreaterThanOrEqualTo(n, bigint0) ? Option.some(sqrtUnsafe(n)) : Option.none();\n/**\n * Takes an `Iterable` of `bigint`s and returns their sum as a single `bigint`. Returns `0n` for an empty iterable.\n *\n * **When to use**\n *\n * Use when you want an immediate aggregate from an iterable instead of a\n * folding reducer owned by another API.\n *\n * **Example** (Summing iterable bigints)\n *\n * ```ts import.meta.vitest\n * import { BigInt } from \"effect\"\n *\n * BigInt.sumAll([2n, 3n, 4n]) // => 9n\n * ```\n *\n * @see {@link sum} for adding two `bigint` values\n * @see {@link ReducerSum} for summing through APIs that consume a `Reducer`\n *\n * @category math\n * @since 2.0.0\n */\nexport const sumAll = collection => {\n  let out = bigint0;\n  for (const n of collection) {\n    out += n;\n  }\n  return out;\n};\n/**\n * Takes an `Iterable` of `bigint`s and returns their product as a single `bigint`. Returns `1n` for an empty iterable.\n *\n * **When to use**\n *\n * Use to multiply all `bigint` values in an iterable.\n *\n * **Example** (Multiplying iterable bigints)\n *\n * ```ts import.meta.vitest\n * import { BigInt } from \"effect\"\n *\n * BigInt.multiplyAll([2n, 3n, 4n]) // => 24n\n * ```\n *\n * @see {@link multiply} for multiplying two `bigint` values\n * @see {@link ReducerMultiply} for multiplying through APIs that consume a `Reducer`\n *\n * @category math\n * @since 2.0.0\n */\nexport const multiplyAll = collection => {\n  let out = bigint1;\n  for (const n of collection) {\n    if (n === bigint0) {\n      return bigint0;\n    }\n    out *= n;\n  }\n  return out;\n};\n/**\n * Converts a `bigint` to a `number` safely.\n *\n * **When to use**\n *\n * Use to convert a `bigint` to a JavaScript number only when it is a safe\n * integer.\n *\n * **Details**\n *\n * If the `bigint` is outside the safe integer range for JavaScript (`Number.MAX_SAFE_INTEGER`\n * and `Number.MIN_SAFE_INTEGER`), it returns `Option.none()`.\n *\n * **Example** (Converting bigints to numbers)\n *\n * ```ts import.meta.vitest\n * import { BigInt as BI, Option } from \"effect\"\n *\n * BI.toNumber(42n) // => Option.some(42)\n * BI.toNumber(9007199254740992n) // => Option.none()\n * BI.toNumber(-9007199254740992n) // => Option.none()\n * ```\n *\n * @see {@link fromNumber} for converting a safe integer number to `bigint`\n *\n * @category converting\n * @since 2.0.0\n */\nexport const toNumber = b => {\n  if (b > BigInt(Number.MAX_SAFE_INTEGER) || b < BigInt(Number.MIN_SAFE_INTEGER)) {\n    return Option.none();\n  }\n  return Option.some(Number(b));\n};\n/**\n * Parses a string into a `bigint` safely.\n *\n * **When to use**\n *\n * Use to parse a string as a `bigint` without throwing on invalid input.\n *\n * **Details**\n *\n * If the string is empty or contains characters that cannot be converted into a\n * `bigint`, it returns `Option.none()`.\n *\n * **Example** (Parsing strings as bigints)\n *\n * ```ts import.meta.vitest\n * import { BigInt, Option } from \"effect\"\n *\n * BigInt.fromString(\"42\") // => Option.some(42n)\n * BigInt.fromString(\" \") // => Option.none()\n * BigInt.fromString(\"a\") // => Option.none()\n * ```\n *\n * @see {@link BigInt} for native constructor coercion that throws on invalid input\n *\n * @category converting\n * @since 2.4.12\n */\nexport const fromString = s => {\n  try {\n    return s.trim() === \"\" ? Option.none() : Option.some(BigInt(s));\n  } catch {\n    return Option.none();\n  }\n};\n/**\n * Converts a number to a `bigint`.\n *\n * **When to use**\n *\n * Use to convert a JavaScript number to `bigint` only when it is a safe integer.\n *\n * **Details**\n *\n * If the number is outside the safe integer range for JavaScript\n * (`Number.MAX_SAFE_INTEGER` and `Number.MIN_SAFE_INTEGER`) or if the number is\n * not a valid `bigint`, it returns `Option.none()`.\n *\n * **Example** (Converting numbers to bigints)\n *\n * ```ts import.meta.vitest\n * import { BigInt, Option } from \"effect\"\n *\n * BigInt.fromNumber(42) // => Option.some(42n)\n * BigInt.fromNumber(Number.MAX_SAFE_INTEGER + 1) // => Option.none()\n * BigInt.fromNumber(Number.MIN_SAFE_INTEGER - 1) // => Option.none()\n * ```\n *\n * @see {@link toNumber} for converting `bigint` values back to safe integer numbers\n * @see {@link BigInt} for native constructor coercion\n *\n * @category converting\n * @since 2.4.12\n */\nexport function fromNumber(n) {\n  if (n > Number.MAX_SAFE_INTEGER || n < Number.MIN_SAFE_INTEGER) {\n    return Option.none();\n  }\n  try {\n    return Option.some(BigInt(n));\n  } catch {\n    return Option.none();\n  }\n}\n/**\n * Returns the JavaScript remainder of dividing one `bigint` by another.\n *\n * **When to use**\n *\n * Use when you want native remainder semantics, including signed remainders and\n * a thrown division-by-zero error.\n *\n * **Gotchas**\n *\n * Throws a `RangeError` when the divisor is `0n`.\n *\n * **Example** (Calculating remainders)\n *\n * ```ts import.meta.vitest\n * import { BigInt } from \"effect\"\n *\n * BigInt.remainder(10n, 3n) // => 1n\n * BigInt.remainder(15n, 4n) // => 3n\n * ```\n *\n * @see {@link divide} for quotient calculation with division-by-zero represented as `Option.none`\n *\n * @category math\n * @since 4.0.0\n */\nexport const remainder = /*#__PURE__*/dual(2, (self, divisor) => self % divisor);\n/**\n * Reducer for combining `bigint`s using addition.\n *\n * **When to use**\n *\n * Use to sum many `bigint` values through APIs that consume a `Reducer`.\n *\n * **Details**\n *\n * The initial value is `0n`, so `combineAll([])` returns `0n`.\n *\n * @see {@link sumAll} for summing an iterable directly\n * @see {@link ReducerMultiply} for multiplying `bigint` values\n *\n * @category math\n * @since 4.0.0\n */\nexport const ReducerSum = /*#__PURE__*/Reducer.make((a, b) => a + b, bigint0);\n/**\n * Reducer for combining `bigint`s using multiplication.\n *\n * **When to use**\n *\n * Use to multiply many `bigint` values through APIs that consume a `Reducer`.\n *\n * **Details**\n *\n * The initial value is `1n`, so `combineAll([])` returns `1n`.\n *\n * @see {@link multiplyAll} for multiplying an iterable directly\n * @see {@link ReducerSum} for summing `bigint` values\n *\n * @category math\n * @since 4.0.0\n */\nexport const ReducerMultiply = /*#__PURE__*/Reducer.make((a, b) => a * b, bigint1, collection => {\n  let acc = bigint1;\n  for (const n of collection) {\n    if (n === bigint0) return bigint0;\n    acc *= n;\n  }\n  return acc;\n});\n/**\n * Combiner that returns the maximum `bigint`.\n *\n * **When to use**\n *\n * Use to keep the largest `bigint` when an API consumes a `Combiner`.\n *\n * @see {@link CombinerMin} for keeping the smallest `bigint`\n * @see {@link max} for comparing two `bigint` 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 `bigint`.\n *\n * **When to use**\n *\n * Use to keep the smallest `bigint` through APIs that consume a `Combiner`.\n *\n * @see {@link CombinerMax} for keeping the largest `bigint`\n * @see {@link min} for comparing two `bigint` values directly\n *\n * @category math\n * @since 4.0.0\n */\nexport const CombinerMin = /*#__PURE__*/Combiner.min(Order);\n//# sourceMappingURL=BigInt.js.map","/**\n * Represents exact, non-negative, integral byte counts.\n *\n * Decimal units use powers of 1,000 and binary units use powers of 1,024.\n *\n * @since 4.0.0\n */\nimport * as BI from \"./BigInt.js\";\nimport { dual } from \"./Function.js\";\nimport * as Option from \"./Option.js\";\nconst TypeId = \"~effect/ByteSize\";\nconst bigint0 = /*#__PURE__*/BigInt(0);\nconst bigint1 = /*#__PURE__*/BigInt(1);\nconst decimalBase = /*#__PURE__*/BigInt(1000);\nconst binaryBase = /*#__PURE__*/BigInt(1024);\nconst decimalUnits = [{\n  symbol: \"B\",\n  factor: bigint1,\n  names: [\"B\", \"byte\", \"bytes\"]\n}, {\n  symbol: \"kB\",\n  factor: decimalBase,\n  names: [\"kB\", \"kilobyte\", \"kilobytes\"]\n}, {\n  symbol: \"MB\",\n  factor: decimalBase ** /*#__PURE__*/BigInt(2),\n  names: [\"MB\", \"megabyte\", \"megabytes\"]\n}, {\n  symbol: \"GB\",\n  factor: decimalBase ** /*#__PURE__*/BigInt(3),\n  names: [\"GB\", \"gigabyte\", \"gigabytes\"]\n}, {\n  symbol: \"TB\",\n  factor: decimalBase ** /*#__PURE__*/BigInt(4),\n  names: [\"TB\", \"terabyte\", \"terabytes\"]\n}, {\n  symbol: \"PB\",\n  factor: decimalBase ** /*#__PURE__*/BigInt(5),\n  names: [\"PB\", \"petabyte\", \"petabytes\"]\n}, {\n  symbol: \"EB\",\n  factor: decimalBase ** /*#__PURE__*/BigInt(6),\n  names: [\"EB\", \"exabyte\", \"exabytes\"]\n}, {\n  symbol: \"ZB\",\n  factor: decimalBase ** /*#__PURE__*/BigInt(7),\n  names: [\"ZB\", \"zettabyte\", \"zettabytes\"]\n}, {\n  symbol: \"YB\",\n  factor: decimalBase ** /*#__PURE__*/BigInt(8),\n  names: [\"YB\", \"yottabyte\", \"yottabytes\"]\n}, {\n  symbol: \"RB\",\n  factor: decimalBase ** /*#__PURE__*/BigInt(9),\n  names: [\"RB\", \"ronnabyte\", \"ronnabytes\"]\n}, {\n  symbol: \"QB\",\n  factor: decimalBase ** /*#__PURE__*/BigInt(10),\n  names: [\"QB\", \"quettabyte\", \"quettabytes\"]\n}];\nconst binaryUnits = [decimalUnits[0], {\n  symbol: \"KiB\",\n  factor: binaryBase,\n  names: [\"KiB\", \"kibibyte\", \"kibibytes\"]\n}, {\n  symbol: \"MiB\",\n  factor: binaryBase ** /*#__PURE__*/BigInt(2),\n  names: [\"MiB\", \"mebibyte\", \"mebibytes\"]\n}, {\n  symbol: \"GiB\",\n  factor: binaryBase ** /*#__PURE__*/BigInt(3),\n  names: [\"GiB\", \"gibibyte\", \"gibibytes\"]\n}, {\n  symbol: \"TiB\",\n  factor: binaryBase ** /*#__PURE__*/BigInt(4),\n  names: [\"TiB\", \"tebibyte\", \"tebibytes\"]\n}, {\n  symbol: \"PiB\",\n  factor: binaryBase ** /*#__PURE__*/BigInt(5),\n  names: [\"PiB\", \"pebibyte\", \"pebibytes\"]\n}, {\n  symbol: \"EiB\",\n  factor: binaryBase ** /*#__PURE__*/BigInt(6),\n  names: [\"EiB\", \"exbibyte\", \"exbibytes\"]\n}, {\n  symbol: \"ZiB\",\n  factor: binaryBase ** /*#__PURE__*/BigInt(7),\n  names: [\"ZiB\", \"zebibyte\", \"zebibytes\"]\n}, {\n  symbol: \"YiB\",\n  factor: binaryBase ** /*#__PURE__*/BigInt(8),\n  names: [\"YiB\", \"yobibyte\", \"yobibytes\"]\n}];\nconst allUnits = [...decimalUnits, ... /*#__PURE__*/binaryUnits.slice(1)];\nconst unitsByName = /*#__PURE__*/new Map(/*#__PURE__*/allUnits.flatMap(unit => unit.names.map(name => [name, unit])));\nconst unitsBySymbol = /*#__PURE__*/new Map(/*#__PURE__*/allUnits.map(unit => [unit.symbol, unit]));\nconst make = value => value;\n/**\n * The byte size containing zero bytes.\n *\n * @category constants\n * @since 4.0.0\n */\nexport const zero = /*#__PURE__*/make(bigint0);\nconst invalid = message => {\n  throw new Error(`Invalid ByteSize: ${message}`);\n};\nconst fromNumber = input => {\n  if (!Number.isSafeInteger(input) || input < 0) {\n    return invalid(`expected a non-negative safe integer, received ${input}`);\n  }\n  return make(BigInt(input));\n};\nconst fromQuantity = (quantity, unit) => {\n  if (typeof quantity === \"bigint\") {\n    if (quantity < bigint0) return invalid(`expected a non-negative quantity, received ${quantity}`);\n    return make(quantity * unit.factor);\n  }\n  const value = quantity * Number(unit.factor);\n  if (!Number.isSafeInteger(value) || value < 0) {\n    return invalid(`expected an exact non-negative safe-integer byte result, received ${quantity} ${unit.symbol}`);\n  }\n  return make(BigInt(value));\n};\nconst parse = input => {\n  const match = /^\\s*(\\d+)(?:\\.(\\d+))?\\s*([A-Za-z]+)\\s*$/.exec(input);\n  if (match === null) return invalid(`unsupported syntax ${JSON.stringify(input)}`);\n  const unit = unitsByName.get(match[3]);\n  if (unit === undefined) return invalid(`unsupported unit ${JSON.stringify(match[3])}`);\n  const fraction = match[2] ?? \"\";\n  const scale = BigInt(10) ** BigInt(fraction.length);\n  const numerator = BigInt(match[1] + fraction) * unit.factor;\n  if (numerator % scale !== bigint0) {\n    return invalid(`${JSON.stringify(input)} does not represent an integral number of bytes`);\n  }\n  return make(numerator / scale);\n};\n/**\n * Decodes a trusted input into a byte size and throws for invalid input.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromInputUnsafe = input => {\n  switch (typeof input) {\n    case \"bigint\":\n      if (input < bigint0) return invalid(`expected a non-negative bigint, received ${input}`);\n      return make(input);\n    case \"number\":\n      return fromNumber(input);\n    case \"string\":\n      return parse(input);\n  }\n  return invalid(`unsupported input ${input}`);\n};\n/**\n * Decodes an input into a byte size, returning `None` for invalid input.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromInput = /*#__PURE__*/Option.liftThrowable(fromInputUnsafe);\n/**\n * Creates a byte size from a non-negative byte count.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const bytes = value => typeof value === \"bigint\" ? fromInputUnsafe(value) : fromNumber(value);\nconst unitConstructor = symbol => value => fromQuantity(value, unitsBySymbol.get(symbol));\n/**\n * Creates a decimal kilobyte value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const kilobytes = /*#__PURE__*/unitConstructor(\"kB\");\n/**\n * Creates a decimal megabyte value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const megabytes = /*#__PURE__*/unitConstructor(\"MB\");\n/**\n * Creates a decimal gigabyte value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const gigabytes = /*#__PURE__*/unitConstructor(\"GB\");\n/**\n * Creates a decimal terabyte value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const terabytes = /*#__PURE__*/unitConstructor(\"TB\");\n/**\n * Creates a decimal petabyte value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const petabytes = /*#__PURE__*/unitConstructor(\"PB\");\n/**\n * Creates a decimal exabyte value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const exabytes = /*#__PURE__*/unitConstructor(\"EB\");\n/**\n * Creates a decimal zettabyte value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const zettabytes = /*#__PURE__*/unitConstructor(\"ZB\");\n/**\n * Creates a decimal yottabyte value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const yottabytes = /*#__PURE__*/unitConstructor(\"YB\");\n/**\n * Creates a decimal ronnabyte value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const ronnabytes = /*#__PURE__*/unitConstructor(\"RB\");\n/**\n * Creates a decimal quettabyte value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const quettabytes = /*#__PURE__*/unitConstructor(\"QB\");\n/**\n * Creates a binary kibibyte value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const kibibytes = /*#__PURE__*/unitConstructor(\"KiB\");\n/**\n * Creates a binary mebibyte value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const mebibytes = /*#__PURE__*/unitConstructor(\"MiB\");\n/**\n * Creates a binary gibibyte value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const gibibytes = /*#__PURE__*/unitConstructor(\"GiB\");\n/**\n * Creates a binary tebibyte value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const tebibytes = /*#__PURE__*/unitConstructor(\"TiB\");\n/**\n * Creates a binary pebibyte value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const pebibytes = /*#__PURE__*/unitConstructor(\"PiB\");\n/**\n * Creates a binary exbibyte value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const exbibytes = /*#__PURE__*/unitConstructor(\"EiB\");\n/**\n * Creates a binary zebibyte value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const zebibytes = /*#__PURE__*/unitConstructor(\"ZiB\");\n/**\n * Creates a binary yobibyte value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const yobibytes = /*#__PURE__*/unitConstructor(\"YiB\");\n/**\n * Checks whether a value is a byte size.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isByteSize = input => typeof input === \"bigint\" && input >= bigint0;\n/**\n * Checks whether a byte size is zero.\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isZero = self => self === bigint0;\n/**\n * Returns the exact byte count as a bigint.\n *\n * @category getters\n * @since 4.0.0\n */\nexport const toBigInt = self => self;\n/**\n * Converts a byte size to a safe integer, returning `None` when it is too large.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toNumber = BI.toNumber;\n/**\n * Converts a byte size to a safe integer and throws when it is too large.\n *\n * @category unsafe\n * @since 4.0.0\n */\nexport const toNumberUnsafe = self => Option.getOrThrowWith(toNumber(self), () => new Error(`ByteSize exceeds Number.MAX_SAFE_INTEGER: ${self}`));\n/**\n * Converts a byte size to an approximate number of the specified unit.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toUnit = /*#__PURE__*/dual(2, (self, unit) => Number(self) / Number(unitsBySymbol.get(unit).factor));\n/**\n * Provides an order for byte sizes.\n *\n * @category instances\n * @since 4.0.0\n */\nexport const Order = BI.Order;\n/**\n * Provides an equivalence for byte sizes.\n *\n * @category instances\n * @since 4.0.0\n */\nexport const Equivalence = BI.Equivalence;\n/**\n * Returns whether a byte size is in an inclusive range.\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const between = BI.between;\n/**\n * Returns the smaller byte size.\n *\n * @category ordering\n * @since 4.0.0\n */\nexport const min = BI.min;\n/**\n * Returns the larger byte size.\n *\n * @category ordering\n * @since 4.0.0\n */\nexport const max = BI.max;\n/**\n * Constrains a byte size to an inclusive range.\n *\n * @category ordering\n * @since 4.0.0\n */\nexport const clamp = BI.clamp;\n/**\n * Checks whether the first byte size is less than the second.\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isLessThan = BI.isLessThan;\n/**\n * Checks whether the first byte size is at most the second.\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isLessThanOrEqualTo = BI.isLessThanOrEqualTo;\n/**\n * Checks whether the first byte size is greater than the second.\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isGreaterThan = BI.isGreaterThan;\n/**\n * Checks whether the first byte size is at least the second.\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isGreaterThanOrEqualTo = BI.isGreaterThanOrEqualTo;\n/**\n * Checks whether two byte sizes contain the same count.\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const equals = /*#__PURE__*/dual(2, Equivalence);\n/**\n * Adds two byte sizes exactly.\n *\n * @category math\n * @since 4.0.0\n */\nexport const sum = BI.sum;\n/**\n * Subtracts byte sizes, returning `None` on underflow.\n *\n * @category math\n * @since 4.0.0\n */\nexport const subtract = /*#__PURE__*/dual(2, (self, that) => self < that ? Option.none() : Option.some(make(self - that)));\n/**\n * Subtracts byte sizes and throws on underflow.\n *\n * @category unsafe\n * @since 4.0.0\n */\nexport const subtractUnsafe = /*#__PURE__*/dual(2, (self, that) => {\n  if (self < that) throw new Error(`ByteSize subtraction underflow: ${self} - ${that}`);\n  return make(self - that);\n});\nconst scalar = (input, positive) => {\n  if (typeof input === \"bigint\") return input >= (positive ? bigint1 : bigint0) ? input : undefined;\n  return Number.isSafeInteger(input) && input >= (positive ? 1 : 0) ? BigInt(input) : undefined;\n};\n/**\n * Multiplies a byte size by a non-negative integer scalar.\n *\n * @category math\n * @since 4.0.0\n */\nexport const times = /*#__PURE__*/dual(2, (self, multiplier) => {\n  const value = scalar(multiplier, false);\n  return value === undefined ? Option.none() : Option.some(make(self * value));\n});\n/**\n * Divides a byte size by a positive integer, discarding any remainder.\n *\n * @category math\n * @since 4.0.0\n */\nexport const divide = /*#__PURE__*/dual(2, (self, divisor) => {\n  const value = scalar(divisor, true);\n  return value === undefined ? Option.none() : Option.some(make(self / value));\n});\nconst validatePrecision = precision => {\n  if (!Number.isSafeInteger(precision) || precision < 0 || precision > 20) {\n    throw new Error(`ByteSize format precision must be an integer from 0 to 20, received ${precision}`);\n  }\n  return precision;\n};\nconst formatWithUnit = (value, unit, precision, trailingZeros) => {\n  const scale = BigInt(10) ** BigInt(precision);\n  const rounded = (value * scale * BigInt(2) + unit.factor) / (unit.factor * BigInt(2));\n  const whole = rounded / scale;\n  if (precision === 0) return `${whole} ${unit.symbol}`;\n  let fraction = `${rounded % scale}`.padStart(precision, \"0\");\n  if (!trailingZeros) fraction = fraction.replace(/0+$/, \"\");\n  return `${whole}${fraction.length === 0 ? \"\" : `.${fraction}`} ${unit.symbol}`;\n};\n/**\n * Formats a byte size with canonical decimal or binary unit symbols.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const format = (self, options = {}) => {\n  const precision = validatePrecision(options.precision ?? 2);\n  const trailingZeros = options.trailingZeros ?? false;\n  if (options.unit !== undefined) {\n    return formatWithUnit(self, unitsBySymbol.get(options.unit), precision, trailingZeros);\n  }\n  const units = options.system === \"decimal\" ? decimalUnits : binaryUnits;\n  if (self === bigint0) return \"0 B\";\n  let index = units.length - 1;\n  while (index > 0 && self < units[index].factor) index--;\n  if (index < units.length - 1) {\n    const scale = BigInt(10) ** BigInt(precision);\n    const rounded = (self * scale * BigInt(2) + units[index].factor) / (units[index].factor * BigInt(2));\n    const base = options.system === \"decimal\" ? decimalBase : binaryBase;\n    if (rounded >= base * scale) index++;\n  }\n  return formatWithUnit(self, units[index], precision, trailingZeros);\n};\n/**\n * Reducer that sums byte sizes from zero.\n *\n * @category math\n * @since 4.0.0\n */\nexport const ReducerSum = BI.ReducerSum;\n/**\n * Combiner that keeps the largest byte size.\n *\n * @category math\n * @since 4.0.0\n */\nexport const CombinerMax = BI.CombinerMax;\n/**\n * Combiner that keeps the smallest byte size.\n *\n * @category math\n * @since 4.0.0\n */\nexport const CombinerMin = BI.CombinerMin;\n//# sourceMappingURL=ByteSize.js.map","/**\n * Normalized errors for platform APIs.\n *\n * Platform services such as file systems, terminals, and sockets use\n * `PlatformError` to report host-level failures in a consistent shape. The\n * wrapper records whether the problem came from an invalid argument or from the\n * operating system, while preserving useful details such as the module, method,\n * path, descriptor, description, and original cause when available.\n *\n * @since 4.0.0\n */\nimport * as Data from \"./Data.js\";\nconst TypeId = \"~effect/PlatformError\";\n/**\n * Error data for an invalid argument passed to a platform API.\n *\n * **When to use**\n *\n * Use when you need to model caller input rejected before a platform operation\n * runs, including invalid-argument reason data.\n *\n * **Details**\n *\n * The error records the module and method that rejected the argument, with an\n * optional description and cause. It is usually wrapped in `PlatformError`.\n *\n * @see {@link badArgument} for creating a wrapped `PlatformError` whose reason is `BadArgument`\n * @see {@link SystemError} for failures reported by the host platform or operating system\n * @see {@link PlatformError} for the wrapper used by most platform APIs\n *\n * @category errors\n * @since 4.0.0\n */\nexport class BadArgument extends /*#__PURE__*/Data.TaggedError(\"BadArgument\") {\n  /**\n   * Formats the module, method, and optional description that rejected the argument.\n   *\n   * **When to use**\n   *\n   * Use to read the formatted error message for a rejected platform argument.\n   *\n   * @since 4.0.0\n   */\n  get message() {\n    return `${this.module}.${this.method}${this.description ? `: ${this.description}` : \"\"}`;\n  }\n}\n/**\n * Error data for a platform or system operation failure.\n *\n * **When to use**\n *\n * Use when you need normalized reason data for a platform or system operation\n * failure, including the operation details.\n *\n * **Details**\n *\n * The error records a normalized `_tag`, the module and method that failed,\n * and optional details such as the syscall, path or descriptor, description,\n * and original cause. It is usually wrapped in `PlatformError`.\n *\n * @see {@link systemError} for creating the usual `PlatformError` wrapper from this reason data\n * @see {@link BadArgument} for platform API failures caused by rejected caller input before an operation runs\n * @see {@link SystemErrorTag} for the normalized tag values stored in `_tag`\n *\n * @category errors\n * @since 4.0.0\n */\nexport class SystemError extends Data.Error {\n  /**\n   * Formats the normalized system error tag with operation and path details.\n   *\n   * **When to use**\n   *\n   * Use to read the formatted error message for a normalized system failure.\n   *\n   * @since 4.0.0\n   */\n  get message() {\n    return `${this._tag}: ${this.module}.${this.method}${this.pathOrDescriptor !== undefined ? ` (${this.pathOrDescriptor})` : \"\"}${this.description ? `: ${this.description}` : \"\"}`;\n  }\n}\n/**\n * Tagged error used by platform APIs to report either invalid arguments or\n * system-level failures.\n *\n * **When to use**\n *\n * Use as the shared error type for platform APIs that expose invalid arguments\n * and host or operating-system failures through a single `Effect` error\n * channel.\n *\n * **Details**\n *\n * The `reason` field contains the underlying `BadArgument` or `SystemError`.\n * When that reason has a cause, the cause is preserved on the wrapper.\n *\n * @see {@link BadArgument} for invalid inputs rejected before an operation runs\n * @see {@link SystemError} for failures reported by the host platform or operating system\n * @see {@link badArgument} for creating this wrapper from rejected caller input\n * @see {@link systemError} for creating this wrapper from a host or operating-system failure\n *\n * @category errors\n * @since 4.0.0\n */\nexport class PlatformError extends /*#__PURE__*/Data.TaggedError(\"PlatformError\") {\n  constructor(reason) {\n    if (\"cause\" in reason) {\n      super({\n        reason,\n        cause: reason.cause\n      });\n    } else {\n      super({\n        reason\n      });\n    }\n  }\n  /**\n   * Marks this value as a platform error wrapper for runtime guards.\n   *\n   * **When to use**\n   *\n   * Use to identify `PlatformError` values through their runtime type marker.\n   *\n   * @since 4.0.0\n   */\n  [TypeId] = TypeId;\n  get message() {\n    return this.reason.message;\n  }\n}\n/**\n * Creates a `PlatformError` whose reason is a `SystemError`.\n *\n * **When to use**\n *\n * Use to adapt an operating-system or platform failure into the normalized\n * platform error model.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const systemError = options => new PlatformError(new SystemError(options));\n/**\n * Creates a `PlatformError` whose reason is a `BadArgument`.\n *\n * **When to use**\n *\n * Use to report a platform API rejecting caller input before performing the\n * underlying operation.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const badArgument = options => new PlatformError(new BadArgument(options));\n//# sourceMappingURL=PlatformError.js.map","import * as effect from \"./internal/effect.js\";\nimport { hasProperty } from \"./Predicate.js\";\nconst TypeId = \"~effect/Fiber\";\nconst await_ = effect.fiberAwait;\nexport {\n/**\n * Waits for a fiber to complete and returns its exit value.\n *\n * **When to use**\n *\n * Use when you need to inspect whether the fiber succeeded,\n * failed, died, or was interrupted without propagating the failure.\n *\n * **Details**\n *\n * The returned Effect always succeeds with an `Exit` describing the fiber's\n * outcome.\n *\n * **Gotchas**\n *\n * This does not flatten the fiber result into the current Effect. Use\n * {@link join} when you want fiber failures to fail the current Effect.\n *\n * **Example** (Awaiting a fiber exit)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Fiber } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const fiber = yield* Effect.forkChild(Effect.succeed(42))\n *   return yield* Fiber.await(fiber)\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => Exit.succeed(42)\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nawait_ as await };\n/**\n * Waits for all fibers in the provided iterable to complete and returns\n * an array of their exit values.\n *\n * **When to use**\n *\n * Use when you need every fiber outcome as data, including failures and\n * interruptions.\n *\n * **Details**\n *\n * The returned array is ordered like the input iterable.\n *\n * **Gotchas**\n *\n * Failures are captured as `Exit.Failure` values. Use {@link joinAll} when you\n * want the first failed fiber to fail the returned Effect.\n *\n * **Example** (Awaiting multiple fiber exits)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Fiber } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const fiber1 = yield* Effect.forkChild(Effect.succeed(1))\n *   const fiber2 = yield* Effect.forkChild(Effect.succeed(2))\n *   return yield* Fiber.awaitAll([fiber1, fiber2])\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [Exit.succeed(1), Exit.succeed(2)]\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const awaitAll = effect.fiberAwaitAll;\n/**\n * Joins a fiber, blocking until it completes. If the fiber succeeds,\n * returns its value. If it fails, the error is propagated.\n *\n * **When to use**\n *\n * Use when you need a forked fiber's failure to fail the current Effect because\n * that fiber is part of the current workflow.\n *\n * **Gotchas**\n *\n * Joining a failed fiber propagates the fiber's Cause. Use {@link await_ await} when\n * you need to inspect the `Exit` instead of failing.\n *\n * **Example** (Joining a fiber)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const fiber = yield* Effect.forkChild(Effect.succeed(42))\n *   return yield* Fiber.join(fiber)\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => 42\n * ```\n *\n * @see {@link await_ await} for inspecting the fiber outcome as an Exit\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const join = effect.fiberJoin;\n/**\n * Waits for all fibers to succeed and returns their values in input order.\n *\n * **When to use**\n *\n * Use when you need every fiber to succeed and want the successful values\n * rather than the `Exit` values.\n *\n * **Details**\n *\n * If any fiber fails, the returned `Effect` fails with that fiber's cause and\n * stops waiting for additional results. This does not interrupt the remaining\n * fibers.\n *\n * **Gotchas**\n *\n * A failure stops waiting, but it does not interrupt any other fibers. Use\n * {@link interruptAll} separately when remaining fibers should be stopped.\n *\n * @see {@link awaitAll} for collecting every fiber outcome as an Exit\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const joinAll = effect.fiberJoinAll;\n/**\n * Interrupts a fiber, causing it to stop executing and clean up any\n * acquired resources.\n *\n * **When to use**\n *\n * Use when you need to cancel a forked fiber and wait for its cleanup to\n * complete.\n *\n * **Details**\n *\n * The returned Effect completes only after the interrupted fiber has completed.\n *\n * **Gotchas**\n *\n * Interruption is cooperative. A fiber can continue running while it is inside\n * uninterruptible work or finalizers.\n *\n * **Example** (Interrupting a fiber)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const fiber = yield* Effect.forkChild(\n *     Effect.delay(\"1 second\")(Effect.succeed(42))\n *   )\n *   yield* Fiber.interrupt(fiber)\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @see {@link interruptAs} for specifying the interrupting fiber ID\n * @see {@link await_ await} for observing the interrupted fiber's Exit\n *\n * @category interruption\n * @since 2.0.0\n */\nexport const interrupt = effect.fiberInterrupt;\n/**\n * Interrupts a fiber with a specific fiber ID as the interruptor. This allows\n * tracking which fiber initiated the interruption.\n *\n * **When to use**\n *\n * Use when runtime diagnostics or tracing should attribute the interruption to\n * a specific fiber ID.\n *\n * **Details**\n *\n * The returned Effect completes only after the interrupted fiber has completed.\n *\n * **Gotchas**\n *\n * The supplied ID affects the recorded interruptor. It does not make\n * interruption synchronous or force uninterruptible regions to stop early.\n *\n * **Example** (Interrupting a fiber as another fiber)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const targetFiber = yield* Effect.forkChild(\n *     Effect.delay(\"5 seconds\")(Effect.succeed(\"task completed\"))\n *   )\n *\n *   // Interrupt the fiber, specifying fiber ID 123 as the interruptor\n *   yield* Fiber.interruptAs(targetFiber, 123)\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @see {@link interrupt} for using the current fiber as the interruptor\n *\n * @category interruption\n * @since 2.0.0\n */\nexport const interruptAs = effect.fiberInterruptAs;\n/**\n * Interrupts all fibers in the provided iterable, causing them to stop executing\n * and clean up any acquired resources.\n *\n * **When to use**\n *\n * Use when you need to cancel several forked fibers and wait for their cleanup\n * to complete.\n *\n * **Details**\n *\n * The current fiber is recorded as the interruptor. The returned Effect\n * completes only after all interrupted fibers have completed.\n *\n * **Gotchas**\n *\n * Interruption is cooperative for each fiber. The returned Effect can wait for\n * uninterruptible work and finalizers in any interrupted fiber.\n *\n * **Example** (Interrupting multiple fibers)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const fiber1 = yield* Effect.forkChild(Effect.never)\n *   const fiber2 = yield* Effect.forkChild(Effect.never)\n *   const fiber3 = yield* Effect.forkChild(Effect.never)\n *   yield* Fiber.interruptAll([fiber1, fiber2, fiber3])\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @see {@link interruptAllAs} for specifying the interrupting fiber ID\n *\n * @category interruption\n * @since 2.0.0\n */\nexport const interruptAll = effect.fiberInterruptAll;\n/**\n * Interrupts all fibers in the provided iterable using the specified fiber ID as the\n * interrupting fiber. This allows you to control which fiber is considered the source\n * of the interruption, which can be useful for debugging and tracing.\n *\n * **When to use**\n *\n * Use to interrupt several fibers while recording a specific fiber ID as the\n * interruptor.\n *\n * **Details**\n *\n * The returned Effect completes only after all interrupted fibers have\n * completed.\n *\n * **Gotchas**\n *\n * The supplied ID affects the recorded interruptor. It does not make\n * interruption synchronous or force uninterruptible regions to stop early.\n *\n * **Example** (Interrupting multiple fibers as another fiber)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   // Create a controlling fiber\n *   const controllerFiber = yield* Effect.forkChild(Effect.succeed(\"controller\"))\n *\n *   const worker1 = yield* Effect.forkChild(Effect.never)\n *   const worker2 = yield* Effect.forkChild(Effect.never)\n *\n *   yield* Fiber.interruptAllAs([worker1, worker2], controllerFiber.id)\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @see {@link interruptAll} for using the current fiber as the interruptor\n *\n * @category interruption\n * @since 2.0.0\n */\nexport const interruptAllAs = effect.fiberInterruptAllAs;\n/**\n * Checks whether a value is a Fiber. This is a type guard that can be used to\n * determine if an unknown value is a Fiber instance.\n *\n * **When to use**\n *\n * Use when checking values at boundaries where an unknown value may be a\n * runtime fiber.\n *\n * **Details**\n *\n * The check looks for the internal Fiber type ID marker and does not inspect\n * the fiber's current state.\n *\n * **Example** (Checking for fibers)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   // Create a fiber\n *   const fiber = yield* Effect.forkChild(Effect.succeed(42))\n *\n *   // Test if values are fibers\n *   return [Fiber.isFiber(fiber), Fiber.isFiber(\"hello\"), Fiber.isFiber(42), Fiber.isFiber(null)]\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [true, false, false, false]\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isFiber = u => hasProperty(u, effect.FiberTypeId);\n/**\n * Returns the current fiber if called from within a fiber context,\n * otherwise returns `undefined`.\n *\n * **When to use**\n *\n * Use when you need low-level runtime integrations that need access to the currently\n * executing fiber.\n *\n * **Gotchas**\n *\n * This is a synchronous accessor, not an Effect. It returns `undefined` outside\n * an active fiber runtime context.\n *\n * **Example** (Getting the current fiber)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const current = Fiber.getCurrent()\n *   return current !== undefined\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => true\n * ```\n *\n * @category getters\n * @since 4.0.0\n */\nexport const getCurrent = effect.getCurrentFiber;\n/**\n * Adds a fiber to a `Scope` and returns the same fiber.\n *\n * **When to use**\n *\n * Use when a manually managed fiber should be interrupted when a Scope closes.\n *\n * **Details**\n *\n * When the scope is closed, the fiber is interrupted. If the scope is already\n * closed, the fiber is interrupted immediately.\n *\n * **Gotchas**\n *\n * This does not wait for the fiber to complete. It only registers the\n * interruption finalizer and returns the same fiber.\n *\n * @see {@link interrupt} for interrupting and waiting for completion\n *\n * @category resource management\n * @since 4.0.0\n */\nexport const runIn = effect.fiberRunIn;\n//# sourceMappingURL=Fiber.js.map","import * as internal from \"./internal/effect.js\";\n/**\n * Creates a `Latch` synchronously, outside of `Effect`.\n *\n * **When to use**\n *\n * Use when you need to allocate a `Latch` synchronously outside an Effect\n * workflow.\n *\n * **Details**\n *\n * The latch starts closed by default; pass `true` to create it open.\n *\n * **Example** (Creating a latch unsafely)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber, Latch } from \"effect\"\n *\n * const latch = Latch.makeUnsafe(false)\n * const waiter = latch.await.pipe(Effect.as(\"opened\"))\n *\n * const program = Effect.gen(function*() {\n *   const fiber = yield* Effect.forkChild(waiter)\n *   yield* latch.open\n *   return yield* Fiber.join(fiber)\n * })\n *\n * await Effect.runPromise(program) // => \"opened\"\n * ```\n *\n * @see {@link make} for creating a latch inside Effect code\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeUnsafe = internal.makeLatchUnsafe;\n/**\n * Creates a `Latch` inside `Effect`.\n *\n * **When to use**\n *\n * Use to create a latch for coordinating fibers inside Effect code.\n *\n * **Details**\n *\n * The latch starts closed by default; pass `true` to create it open.\n *\n * **Example** (Creating a latch)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber, Latch } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const latch = yield* Latch.make(false)\n *   const waiter = latch.await.pipe(Effect.as(\"opened\"))\n *\n *   const fiber = yield* Effect.forkChild(waiter)\n *   yield* latch.open\n *   return yield* Fiber.join(fiber)\n * })\n *\n * await Effect.runPromise(program) // => \"opened\"\n * ```\n *\n * @see {@link makeUnsafe} for synchronous allocation outside Effect code\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = internal.makeLatch;\n/**\n * Opens the latch and releases fibers waiting on it.\n *\n * **When to use**\n *\n * Use to open a latch and release all fibers that are waiting on it.\n *\n * **Details**\n *\n * The returned effect succeeds with `true` when this call changed the latch\n * from closed to open, or `false` if it was already open.\n *\n * @see {@link openUnsafe} for a synchronous variant\n * @see {@link release} to release waiting fibers without opening the latch\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const open = self => self.open;\n/**\n * Opens the latch synchronously and releases fibers waiting on it.\n *\n * **When to use**\n *\n * Use when you need synchronous code to open a latch immediately and release\n * the fibers waiting on it.\n *\n * **Details**\n *\n * Returns `true` when this call changed the latch from closed to open, or\n * `false` if it was already open. This unsafe variant performs the state\n * change immediately instead of returning an `Effect`.\n *\n * @see {@link open} for the effectful variant\n * @see {@link release} to release waiting fibers without opening the latch\n * @see {@link closeUnsafe} for the synchronous inverse operation\n *\n * @category unsafe\n * @since 4.0.0\n */\nexport const openUnsafe = self => self.openUnsafe();\n/**\n * Releases the fibers currently waiting on a closed latch without opening it.\n *\n * **When to use**\n *\n * Use to let the fibers currently waiting on a latch proceed while keeping the\n * latch closed for future waiters.\n *\n * **Details**\n *\n * The returned effect succeeds with `true` when release was requested while\n * the latch was closed, or `false` if the latch was already open. Future\n * waiters still suspend until the latch is opened or released again.\n *\n * @see {@link open} for opening the latch for current and future waiters\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const release = self => self.release;\nconst _await = self => self.await;\nexport {\n/**\n * Waits for the latch to be opened.\n *\n * **When to use**\n *\n * Use to suspend the current fiber until the latch is opened or the current\n * set of waiters is released.\n *\n * **Details**\n *\n * Awaiting an already open latch completes immediately. Awaiting a closed\n * latch suspends until `open` or `release` resumes the waiters.\n *\n * **Gotchas**\n *\n * `release` can resume current waiters without opening the latch, so later\n * waiters may still suspend.\n *\n * @see {@link open} for opening the latch for current and future waiters\n * @see {@link release} for resuming current waiters without opening the latch\n * @see {@link whenOpen} for waiting before running another effect\n *\n * @category getters\n * @since 4.0.0\n */\n_await as await };\n/**\n * Closes the latch so future `await` and `whenOpen` calls suspend.\n *\n * **When to use**\n *\n * Use to re-enable waiting on a latch after it was opened, so later `await`\n * and `whenOpen` calls suspend again.\n *\n * **Details**\n *\n * The returned effect succeeds with `true` when this call changed the latch\n * from open to closed, or `false` if it was already closed.\n *\n * @see {@link closeUnsafe} for a synchronous variant\n * @see {@link open} for opening the latch for current and future waiters\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const close = self => self.close;\n/**\n * Closes the latch synchronously so future `await` and `whenOpen` calls\n * suspend.\n *\n * **When to use**\n *\n * Use to close a latch synchronously when the state change must happen outside\n * an `Effect`.\n *\n * **Details**\n *\n * Returns `true` when this call changed the latch from open to closed, or\n * `false` if it was already closed. This unsafe variant performs the state\n * change immediately instead of returning an `Effect`.\n *\n * @see {@link close} for the effectful variant\n * @see {@link openUnsafe} to synchronously open the latch and release waiting\n * fibers\n *\n * @category unsafe\n * @since 4.0.0\n */\nexport const closeUnsafe = self => self.closeUnsafe();\n/**\n * Waits on the latch, then runs the provided effect.\n *\n * **When to use**\n *\n * Use to gate another effect so it starts only after the latch is opened or\n * the current waiters are released.\n *\n * **Details**\n *\n * If the latch is open, the effect runs immediately. If it is closed, the\n * returned effect suspends until the latch is opened or the current waiters are\n * released. The provided effect's success, failure, and requirements are\n * preserved.\n *\n * @see `await` for waiting without running another effect\n * @see {@link open} for opening the latch for current and future waiters\n * @see {@link release} for resuming current waiters without opening the latch\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const whenOpen = (...args) => {\n  if (args.length === 1) {\n    const [self] = args;\n    return effect => self.whenOpen(effect);\n  }\n  const [self, effect] = args;\n  return self.whenOpen(effect);\n};\n/**\n * Checks whether the latch is currently open or closed.\n *\n * **When to use**\n *\n * Use to check the state of the latch without suspending or changing its state.\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isOpen = self => self.isOpen();\n//# sourceMappingURL=Latch.js.map","/**\n * Stores synchronous mutable state in a small reference object.\n *\n * A `MutableRef<A>` stores one current value and exposes it through `.current`.\n * Unlike `Ref`, its operations are synchronous and update the same object in\n * place. This module includes pipeable helpers for reading, setting, comparing,\n * and updating the value, plus numeric increment/decrement helpers and a\n * boolean toggle helper.\n *\n * @since 2.0.0\n */\nimport * as Equal from \"./Equal.js\";\nimport * as Dual from \"./Function.js\";\nimport { toJson } from \"./Inspectable.js\";\nimport { PipeInspectableProto } from \"./internal/core.js\";\nconst TypeId = \"~effect/MutableRef\";\nconst MutableRefProto = {\n  [TypeId]: TypeId,\n  ...PipeInspectableProto,\n  toJSON() {\n    return {\n      _id: \"MutableRef\",\n      current: toJson(this.current)\n    };\n  }\n};\n/**\n * Creates a new MutableRef with the specified initial value.\n *\n * **When to use**\n *\n * Use to create a synchronous `MutableRef` initialized with a value.\n *\n * **Example** (Creating mutable refs)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * // Create a counter reference\n * const counter = MutableRef.make(0)\n *\n * MutableRef.get(counter) // => 0\n *\n * // Create a configuration reference\n * const config = MutableRef.make({ debug: false, timeout: 5000 })\n *\n * MutableRef.get(config) // => { debug: false, timeout: 5000 }\n *\n * // Create a string reference\n * const status = MutableRef.make(\"idle\")\n * MutableRef.set(status, \"running\")\n *\n * MutableRef.get(status) // => \"running\"\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const make = value => {\n  const ref = Object.create(MutableRefProto);\n  ref.current = value;\n  return ref;\n};\n/**\n * Sets the value to newValue atomically if the current value equals oldValue.\n * Returns true if the value was updated, false otherwise.\n * Uses Effect's Equal interface for value comparison.\n *\n * **When to use**\n *\n * Use to replace a `MutableRef` value only when the current value still matches\n * an expected value.\n *\n * **Example** (Comparing and setting values)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const ref = MutableRef.make(\"initial\")\n *\n * // Successful compare and set\n * const updated = MutableRef.compareAndSet(ref, \"initial\", \"updated\")\n *\n * updated // => true\n * MutableRef.get(ref) // => \"updated\"\n *\n * // Failed compare and set (value doesn't match)\n * const failed = MutableRef.compareAndSet(ref, \"initial\", \"failed\")\n *\n * failed // => false\n * MutableRef.get(ref) // => \"updated\"\n *\n * // Thread-safe counter increment\n * const counter = MutableRef.make(5)\n * let current: number\n * do {\n *   current = MutableRef.get(counter)\n * } while (!MutableRef.compareAndSet(counter, current, current + 1))\n *\n * MutableRef.get(counter) // => 6\n *\n * // Pipe-able version\n * const casUpdate = MutableRef.compareAndSet(\"updated\", \"final\")\n *\n * casUpdate(ref) // => true\n * MutableRef.get(ref) // => \"final\"\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const compareAndSet = /*#__PURE__*/Dual.dual(3, (self, oldValue, newValue) => {\n  if (Equal.equals(oldValue, self.current)) {\n    self.current = newValue;\n    return true;\n  }\n  return false;\n});\n/**\n * Decrements a numeric MutableRef by 1 and returns the reference.\n *\n * **When to use**\n *\n * Use when you need an in-place `MutableRef` decrement that returns the same\n * `MutableRef`.\n *\n * **Example** (Decrementing numeric refs)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const counter = MutableRef.make(5)\n *\n * // Decrement the counter\n * MutableRef.decrement(counter)\n *\n * MutableRef.get(counter) // => 4\n *\n * // Chain operations\n * MutableRef.decrement(counter)\n * MutableRef.decrement(counter)\n *\n * MutableRef.get(counter) // => 2\n *\n * // Useful for countdown scenarios\n * const countdown = MutableRef.make(10)\n * while (MutableRef.get(countdown) > 0) {\n *   MutableRef.decrement(countdown)\n * }\n *\n * MutableRef.get(countdown) // => 0\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const decrement = self => update(self, n => n - 1);\n/**\n * Decrements a numeric MutableRef by 1 and returns the new value.\n *\n * **When to use**\n *\n * Use to decrement a numeric `MutableRef` and immediately read the updated\n * value.\n *\n * **Example** (Decrementing and reading refs)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const counter = MutableRef.make(5)\n *\n * // Decrement and get the new value\n * const newValue = MutableRef.decrementAndGet(counter)\n *\n * newValue // => 4\n * MutableRef.get(counter) // => 4\n *\n * // Use in expressions\n * const lives = MutableRef.make(3)\n * const message = `Lives remaining: ${MutableRef.decrementAndGet(lives)}`\n *\n * message // => \"Lives remaining: 2\"\n *\n * // Conditional logic based on decremented value\n * const attempts = MutableRef.make(3)\n * let retries = 0\n * while (MutableRef.decrementAndGet(attempts) >= 0) {\n *   retries += 1\n * }\n *\n * retries // => 3\n * MutableRef.get(attempts) // => -1\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const decrementAndGet = self => updateAndGet(self, n => n - 1);\n/**\n * Gets the current value of the MutableRef.\n *\n * **When to use**\n *\n * Use to read the current `MutableRef` value without mutating it.\n *\n * **Example** (Reading current values)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const ref = MutableRef.make(\"hello\")\n *\n * MutableRef.get(ref) // => \"hello\"\n *\n * MutableRef.set(ref, \"world\")\n *\n * MutableRef.get(ref) // => \"world\"\n *\n * // Reading complex objects\n * const config = MutableRef.make({ port: 3000, host: \"localhost\" })\n * const currentConfig = MutableRef.get(config)\n *\n * currentConfig // => { port: 3000, host: \"localhost\" }\n *\n * // Multiple reads return the same value\n * const value1 = MutableRef.get(ref)\n * const value2 = MutableRef.get(ref)\n *\n * value1 === value2 // => true\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const get = self => self.current;\n/**\n * Decrements a numeric MutableRef by 1 and returns the previous value.\n *\n * **When to use**\n *\n * Use to read the current numeric `MutableRef` value before decrementing it.\n *\n * **Example** (Reading before decrementing)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const counter = MutableRef.make(5)\n *\n * // Get current value and then decrement\n * const previousValue = MutableRef.getAndDecrement(counter)\n *\n * previousValue // => 5\n * MutableRef.get(counter) // => 4\n *\n * // Useful for processing where you need the original value\n * const itemsLeft = MutableRef.make(10)\n * const processedItems: Array<number> = []\n * while (MutableRef.get(itemsLeft) > 0) {\n *   const currentItem = MutableRef.getAndDecrement(itemsLeft)\n *   processedItems.push(currentItem)\n * }\n *\n * processedItems // => [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]\n * MutableRef.get(itemsLeft) // => 0\n *\n * // Post-decrement semantics (like i-- in other languages)\n * const index = MutableRef.make(3)\n * const currentIndex = MutableRef.getAndDecrement(index)\n * const nextIndex = MutableRef.get(index)\n *\n * currentIndex // => 3\n * nextIndex // => 2\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const getAndDecrement = self => getAndUpdate(self, n => n - 1);\n/**\n * Increments a numeric MutableRef by 1 and returns the previous value.\n *\n * **When to use**\n *\n * Use to read the current numeric `MutableRef` value before incrementing it.\n *\n * **Example** (Reading before incrementing)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const counter = MutableRef.make(5)\n *\n * // Get current value and then increment\n * const previousValue = MutableRef.getAndIncrement(counter)\n *\n * previousValue // => 5\n * MutableRef.get(counter) // => 6\n *\n * // Useful for ID generation\n * const idGenerator = MutableRef.make(0)\n * const getId = () => MutableRef.getAndIncrement(idGenerator)\n * const ids = [getId(), getId(), getId()]\n *\n * ids // => [0, 1, 2]\n *\n * // Post-increment semantics (like i++ in other languages)\n * const position = MutableRef.make(0)\n * const currentPos = MutableRef.getAndIncrement(position)\n * const nextPos = MutableRef.get(position)\n *\n * currentPos // => 0\n * nextPos // => 1\n *\n * // Useful for iteration counters\n * const iterations = MutableRef.make(0)\n * const visited: Array<number> = []\n * while (MutableRef.get(iterations) < 5) {\n *   const iteration = MutableRef.getAndIncrement(iterations)\n *   visited.push(iteration)\n * }\n *\n * visited // => [0, 1, 2, 3, 4]\n * MutableRef.get(iterations) // => 5\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const getAndIncrement = self => getAndUpdate(self, n => n + 1);\n/**\n * Sets the MutableRef to a new value and returns the previous value.\n *\n * **When to use**\n *\n * Use to replace the current `MutableRef` value while keeping the previous\n * value.\n *\n * **Example** (Reading before setting)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const ref = MutableRef.make(\"old\")\n *\n * // Set new value and get the previous one\n * const previous = MutableRef.getAndSet(ref, \"new\")\n *\n * previous // => \"old\"\n * MutableRef.get(ref) // => \"new\"\n *\n * // Swapping values\n * const counter = MutableRef.make(5)\n * const oldValue = MutableRef.getAndSet(counter, 10)\n * const newValue = MutableRef.get(counter)\n *\n * oldValue // => 5\n * newValue // => 10\n *\n * // Pipe-able version\n * const setValue = MutableRef.getAndSet(\"final\")\n * const previousValue = setValue(ref)\n *\n * previousValue // => \"new\"\n * MutableRef.get(ref) // => \"final\"\n *\n * // Useful for atomic swaps in algorithms\n * const buffer = MutableRef.make<Array<string>>([\"a\", \"b\", \"c\"])\n * const oldBuffer = MutableRef.getAndSet(buffer, [])\n *\n * oldBuffer // => [\"a\", \"b\", \"c\"]\n * MutableRef.get(buffer) // => []\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const getAndSet = /*#__PURE__*/Dual.dual(2, (self, value) => {\n  const ret = self.current;\n  self.current = value;\n  return ret;\n});\n/**\n * Updates the MutableRef with the result of applying a function to its current value,\n * and returns the previous value.\n *\n * **When to use**\n *\n * Use to transform the current `MutableRef` value while keeping the previous\n * value.\n *\n * **Example** (Reading before updating)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const counter = MutableRef.make(5)\n *\n * // Increment and get the old value\n * const oldValue = MutableRef.getAndUpdate(counter, (n) => n + 1)\n *\n * oldValue // => 5\n * MutableRef.get(counter) // => 6\n *\n * // Double the value and get the previous one\n * const previous = MutableRef.getAndUpdate(counter, (n) => n * 2)\n *\n * previous // => 6\n * MutableRef.get(counter) // => 12\n *\n * // Transform string and get old value\n * const message = MutableRef.make(\"hello\")\n * const oldMessage = MutableRef.getAndUpdate(message, (s) => s.toUpperCase())\n *\n * oldMessage // => \"hello\"\n * MutableRef.get(message) // => \"HELLO\"\n *\n * // Pipe-able version\n * const addOne = MutableRef.getAndUpdate((n: number) => n + 1)\n * const result = addOne(counter)\n *\n * result // => 12\n * MutableRef.get(counter) // => 13\n *\n * // Useful for implementing atomic operations\n * const list = MutableRef.make<Array<number>>([1, 2, 3])\n * const oldList = MutableRef.getAndUpdate(list, (arr) => [...arr, 4])\n *\n * oldList // => [1, 2, 3]\n * MutableRef.get(list) // => [1, 2, 3, 4]\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const getAndUpdate = /*#__PURE__*/Dual.dual(2, (self, f) => getAndSet(self, f(get(self))));\n/**\n * Increments a numeric MutableRef by 1 and returns the reference.\n *\n * **When to use**\n *\n * Use when you need an in-place `MutableRef` increment that returns the same\n * `MutableRef`.\n *\n * **Example** (Incrementing numeric refs)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const counter = MutableRef.make(5)\n *\n * // Increment the counter\n * MutableRef.increment(counter)\n *\n * MutableRef.get(counter) // => 6\n *\n * // Chain operations\n * MutableRef.increment(counter)\n * MutableRef.increment(counter)\n *\n * MutableRef.get(counter) // => 8\n *\n * // Useful for simple counting\n * const visits = MutableRef.make(0)\n * MutableRef.increment(visits) // User visited\n * MutableRef.increment(visits) // Another visit\n *\n * MutableRef.get(visits) // => 2\n *\n * // Returns the reference for chaining\n * const result = MutableRef.increment(counter)\n *\n * result === counter // => true\n * MutableRef.get(counter) // => 9\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const increment = self => update(self, n => n + 1);\n/**\n * Increments a numeric MutableRef by 1 and returns the new value.\n *\n * **When to use**\n *\n * Use to increment a numeric `MutableRef` and immediately read the updated\n * value.\n *\n * **Example** (Incrementing and reading refs)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const counter = MutableRef.make(5)\n *\n * // Increment and get the new value\n * const newValue = MutableRef.incrementAndGet(counter)\n *\n * newValue // => 6\n * MutableRef.get(counter) // => 6\n *\n * // Use in expressions\n * const score = MutableRef.make(100)\n * const message = `New score: ${MutableRef.incrementAndGet(score)}`\n *\n * message // => \"New score: 101\"\n *\n * // Pre-increment semantics (like ++i in other languages)\n * const level = MutableRef.make(0)\n * const nextLevel = MutableRef.incrementAndGet(level)\n *\n * nextLevel // => 1\n *\n * // Conditional logic based on incremented value\n * const attempts = MutableRef.make(0)\n * const tooManyAttempts = MutableRef.incrementAndGet(attempts) > 3\n *\n * tooManyAttempts // => false\n * MutableRef.get(attempts) // => 1\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const incrementAndGet = self => updateAndGet(self, n => n + 1);\n/**\n * Sets the MutableRef to a new value and returns the reference.\n *\n * **When to use**\n *\n * Use when you need an in-place `MutableRef` replacement that returns the same\n * `MutableRef`.\n *\n * **Example** (Setting values)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const ref = MutableRef.make(\"initial\")\n *\n * // Set a new value\n * MutableRef.set(ref, \"updated\")\n *\n * MutableRef.get(ref) // => \"updated\"\n *\n * // Chain set operations (since it returns the ref)\n * const result = MutableRef.set(ref, \"final\")\n *\n * result === ref // => true\n * MutableRef.get(ref) // => \"final\"\n *\n * // Set complex objects\n * const config = MutableRef.make({ debug: false, verbose: false })\n * MutableRef.set(config, { debug: true, verbose: true })\n *\n * MutableRef.get(config) // => { debug: true, verbose: true }\n *\n * // Pipe-able version\n * const setValue = MutableRef.set(\"new value\")\n * setValue(ref)\n *\n * MutableRef.get(ref) // => \"new value\"\n *\n * // Useful for state management\n * const state = MutableRef.make<\"idle\" | \"loading\" | \"success\" | \"error\">(\"idle\")\n * MutableRef.set(state, \"loading\")\n * // ... perform async operation\n * MutableRef.set(state, \"success\")\n *\n * MutableRef.get(state) // => \"success\"\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const set = /*#__PURE__*/Dual.dual(2, (self, value) => {\n  self.current = value;\n  return self;\n});\n/**\n * Sets the MutableRef to a new value and returns the new value.\n *\n * **When to use**\n *\n * Use to replace the current `MutableRef` value and immediately read the\n * replacement.\n *\n * **Example** (Setting and reading values)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const ref = MutableRef.make(\"old\")\n *\n * // Set and get the new value\n * const newValue = MutableRef.setAndGet(ref, \"new\")\n *\n * newValue // => \"new\"\n * MutableRef.get(ref) // => \"new\"\n *\n * // Useful for assignments that need the value\n * const counter = MutableRef.make(0)\n * const currentValue = MutableRef.setAndGet(counter, 42)\n *\n * currentValue // => 42\n *\n * // Pipe-able version\n * const setValue = MutableRef.setAndGet(\"final\")\n * const result = setValue(ref)\n *\n * result // => \"final\"\n *\n * // Difference from set: returns value instead of reference\n * const ref1 = MutableRef.make(1)\n * const returnedRef = MutableRef.set(ref1, 2) // Returns MutableRef\n * const returnedValue = MutableRef.setAndGet(ref1, 3) // Returns value\n *\n * returnedRef === ref1 // => true\n * returnedValue // => 3\n * MutableRef.get(ref1) // => 3\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const setAndGet = /*#__PURE__*/Dual.dual(2, (self, value) => {\n  self.current = value;\n  return self.current;\n});\n/**\n * Updates the MutableRef with the result of applying a function to its current value,\n * and returns the reference.\n *\n * **When to use**\n *\n * Use when you need an in-place `MutableRef` value transformation that returns\n * the same `MutableRef`.\n *\n * **Example** (Updating values)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const counter = MutableRef.make(5)\n *\n * // Increment the counter\n * MutableRef.update(counter, (n) => n + 1)\n *\n * MutableRef.get(counter) // => 6\n *\n * // Chain updates (since it returns the ref)\n * const result = MutableRef.update(counter, (n) => n * 2)\n *\n * result === counter // => true\n * MutableRef.get(counter) // => 12\n *\n * // Transform string\n * const message = MutableRef.make(\"hello\")\n * MutableRef.update(message, (s) => s.toUpperCase())\n *\n * MutableRef.get(message) // => \"HELLO\"\n *\n * // Update complex objects\n * const user = MutableRef.make({ name: \"Alice\", age: 30 })\n * MutableRef.update(user, (u) => ({ ...u, age: u.age + 1 }))\n *\n * MutableRef.get(user) // => { name: \"Alice\", age: 31 }\n *\n * // Pipe-able version\n * const double = MutableRef.update((n: number) => n * 2)\n * double(counter)\n *\n * MutableRef.get(counter) // => 24\n *\n * // Array operations\n * const list = MutableRef.make<Array<number>>([1, 2, 3])\n * MutableRef.update(list, (arr) => [...arr, 4])\n *\n * MutableRef.get(list) // => [1, 2, 3, 4]\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const update = /*#__PURE__*/Dual.dual(2, (self, f) => set(self, f(get(self))));\n/**\n * Updates the MutableRef with the result of applying a function to its current value,\n * and returns the new value.\n *\n * **When to use**\n *\n * Use to transform the current `MutableRef` value and immediately read the\n * updated value.\n *\n * **Example** (Updating and reading values)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const counter = MutableRef.make(5)\n *\n * // Increment and get the new value\n * const newValue = MutableRef.updateAndGet(counter, (n) => n + 1)\n *\n * newValue // => 6\n * MutableRef.get(counter) // => 6\n *\n * // Double the value and get the result\n * const doubled = MutableRef.updateAndGet(counter, (n) => n * 2)\n *\n * doubled // => 12\n *\n * // Transform string and get result\n * const message = MutableRef.make(\"hello\")\n * const upperCase = MutableRef.updateAndGet(message, (s) => s.toUpperCase())\n *\n * upperCase // => \"HELLO\"\n *\n * // Pipe-able version\n * const increment = MutableRef.updateAndGet((n: number) => n + 1)\n * const result = increment(counter)\n *\n * result // => 13\n *\n * // Useful for calculations that need the result\n * const score = MutableRef.make(100)\n * const bonus = 50\n * const newScore = MutableRef.updateAndGet(score, (s) => s + bonus)\n *\n * newScore // => 150\n *\n * // Array transformations\n * const list = MutableRef.make<Array<number>>([1, 2, 3])\n * const newList = MutableRef.updateAndGet(list, (arr) => arr.map((x) => x * 2))\n *\n * newList // => [2, 4, 6]\n * MutableRef.get(list) // => [2, 4, 6]\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const updateAndGet = /*#__PURE__*/Dual.dual(2, (self, f) => setAndGet(self, f(get(self))));\n/**\n * Switches a boolean `MutableRef` between `true` and `false`, then returns the\n * reference.\n *\n * **When to use**\n *\n * Use when you need an in-place boolean `MutableRef` toggle that returns the\n * same `MutableRef`.\n *\n * **Example** (Toggling boolean refs)\n *\n * ```ts import.meta.vitest\n * import { MutableRef } from \"effect\"\n *\n * const flag = MutableRef.make(false)\n *\n * // Toggle the flag\n * MutableRef.toggle(flag)\n *\n * MutableRef.get(flag) // => true\n *\n * // Toggle again\n * MutableRef.toggle(flag)\n *\n * MutableRef.get(flag) // => false\n *\n * // Useful for state switches\n * const isVisible = MutableRef.make(true)\n * MutableRef.toggle(isVisible) // Hide\n *\n * MutableRef.get(isVisible) // => false\n *\n * // Toggle button implementation\n * const darkMode = MutableRef.make(false)\n * const toggleDarkMode = () => {\n *   MutableRef.toggle(darkMode)\n *   return MutableRef.get(darkMode) ? \"ON\" : \"OFF\"\n * }\n *\n * toggleDarkMode() // => \"ON\"\n * toggleDarkMode() // => \"OFF\"\n *\n * // Returns the reference for chaining\n * const result = MutableRef.toggle(flag)\n *\n * result === flag // => true\n * MutableRef.get(flag) // => true\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const toggle = self => update(self, _ => !_);\n//# sourceMappingURL=MutableRef.js.map","/**\n * Mutable lists for collecting ordered values and draining them from the front.\n * A `MutableList<A>` can append values to the end, prepend values to the\n * beginning, take one or more values from the front, inspect its contents as an\n * array, filter values, remove values, and clear itself. All operations update\n * the same list object in place and keep its `length` field current. Taking\n * from an empty list returns the `Empty` symbol.\n *\n * @since 4.0.0\n */\nimport * as Arr from \"./Array.js\";\nimport * as Count from \"./internal/count.js\";\n/**\n * Defines the unique symbol used to represent an empty result when taking elements from a MutableList.\n * This symbol is returned by `take` when the list is empty, allowing for safe type checking.\n *\n * **When to use**\n *\n * Use to detect that `take` returned no element before handling the result as a\n * list item.\n *\n * **Example** (Checking for empty results)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<string>()\n *\n * MutableList.take(list) === MutableList.Empty // => true\n * ```\n *\n * @category symbols\n * @since 4.0.0\n */\nexport const Empty = /*#__PURE__*/Symbol.for(\"effect/MutableList/Empty\");\n/**\n * Creates an empty MutableList.\n *\n * **Example** (Creating an empty mutable list)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<string>()\n *\n * list.length // => 0\n * MutableList.append(list, \"first\")\n * MutableList.take(list) // => \"first\"\n * list.length // => 0\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const make = () => ({\n  head: undefined,\n  tail: undefined,\n  length: 0\n});\nconst emptyBucket = () => ({\n  array: [],\n  mutable: true,\n  offset: 0,\n  next: undefined\n});\n/**\n * Appends an element to the end of the MutableList.\n * This operation is optimized for high-frequency usage.\n *\n * **Example** (Appending elements)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<number>()\n * MutableList.append(list, 1)\n * MutableList.append(list, 2)\n * MutableList.append(list, 3)\n *\n * MutableList.toArray(list) // => [1, 2, 3]\n * list.length // => 3\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const append = (self, message) => {\n  if (!self.tail) {\n    self.head = self.tail = emptyBucket();\n  } else if (!self.tail.mutable) {\n    self.tail.next = emptyBucket();\n    self.tail = self.tail.next;\n  }\n  self.tail.array.push(message);\n  self.length++;\n};\n/**\n * Prepends an element to the beginning of the MutableList.\n * This operation is optimized for high-frequency usage.\n *\n * **Example** (Prepending elements)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<string>()\n * MutableList.append(list, \"last\")\n * MutableList.prepend(list, \"third\")\n * MutableList.prepend(list, \"second\")\n * MutableList.prepend(list, \"first\")\n *\n * MutableList.toArray(list) // => [\"first\", \"second\", \"third\", \"last\"]\n * ```\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const prepend = (self, message) => {\n  self.head = {\n    array: [message],\n    mutable: true,\n    offset: 0,\n    next: self.head\n  };\n  if (!self.tail) self.tail = self.head;\n  self.length++;\n};\n/**\n * Prepends all elements from an iterable to the beginning of the MutableList.\n * The elements are added in order, so the first element in the iterable becomes\n * the new head of the list.\n *\n * **Example** (Prepending multiple elements)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<number>()\n * MutableList.append(list, 4)\n * MutableList.append(list, 5)\n * MutableList.prependAll(list, [1, 2, 3])\n *\n * MutableList.toArray(list) // => [1, 2, 3, 4, 5]\n * ```\n *\n * @category mutations\n * @since 4.0.0\n */\nexport const prependAll = (self, messages) => prependAllUnsafe(self, Arr.fromIterable(messages), !Array.isArray(messages));\n/**\n * Prepends all elements from a ReadonlyArray to the beginning of the MutableList.\n * This is an optimized version that can reuse the array when mutable=true.\n *\n * **When to use**\n *\n * Use when prepending a trusted array directly is worth the optimized path and\n * you can transfer ownership of the input when enabling mutation.\n *\n * **Gotchas**\n *\n * When mutable=true, ownership of the input array transfers to the list. Do not\n * read or modify the array afterward.\n *\n * **Example** (Transferring an array when prepending)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<number>()\n * MutableList.append(list, 4)\n * const items = [1, 2, 3]\n * MutableList.prependAllUnsafe(list, items, true)\n *\n * MutableList.toArray(list) // => [1, 2, 3, 4]\n * ```\n *\n * @category mutations\n * @since 4.0.0\n */\nexport const prependAllUnsafe = (self, messages, mutable = false) => {\n  self.head = {\n    array: messages,\n    mutable,\n    offset: 0,\n    next: self.head\n  };\n  if (!self.tail && messages.length > 0) self.tail = self.head;\n  self.length += self.head.array.length;\n};\n/**\n * Appends all elements from an iterable to the end of the MutableList.\n * Returns the number of elements added.\n *\n * **Example** (Appending multiple elements)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<number>()\n * MutableList.append(list, 1)\n * MutableList.append(list, 2)\n *\n * MutableList.appendAll(list, [3, 4, 5]) // => 3\n * MutableList.toArray(list) // => [1, 2, 3, 4, 5]\n * list.length // => 5\n * ```\n *\n * @category mutations\n * @since 4.0.0\n */\nexport const appendAll = (self, messages) => appendAllUnsafe(self, Arr.fromIterable(messages), !Array.isArray(messages));\n/**\n * Appends all elements from a ReadonlyArray to the end of the MutableList.\n * This is an optimized version that can reuse the array when mutable=true.\n * Returns the number of elements added.\n *\n * **When to use**\n *\n * Use when appending a trusted array directly is worth the optimized path and\n * you can transfer ownership of the input when enabling mutation.\n *\n * **Gotchas**\n *\n * When mutable=true, ownership of the input array transfers to the list. Do not\n * read or modify the array afterward.\n *\n * **Example** (Transferring an array when appending)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<number>()\n * MutableList.append(list, 1)\n * const items = [2, 3, 4]\n * MutableList.appendAllUnsafe(list, items, true) // => 3\n *\n * MutableList.toArray(list) // => [1, 2, 3, 4]\n * ```\n *\n * @category mutations\n * @since 4.0.0\n */\nexport const appendAllUnsafe = (self, messages, mutable = false) => {\n  if (messages.length === 0) {\n    return 0;\n  }\n  const chunk = {\n    array: messages,\n    mutable,\n    offset: 0,\n    next: undefined\n  };\n  if (self.head) {\n    self.tail = self.tail.next = chunk;\n  } else {\n    self.head = self.tail = chunk;\n  }\n  self.length += messages.length;\n  return messages.length;\n};\n/**\n * Removes all elements from the MutableList, resetting it to an empty state.\n * This operation is highly optimized and releases all internal memory.\n *\n * **Example** (Clearing a mutable list)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<number>()\n * MutableList.appendAll(list, [1, 2, 3, 4, 5])\n *\n * MutableList.clear(list)\n *\n * MutableList.toArray(list) // => []\n * list.length // => 0\n * MutableList.take(list) === MutableList.Empty // => true\n * ```\n *\n * @category mutations\n * @since 4.0.0\n */\nexport const clear = self => {\n  self.head = self.tail = undefined;\n  self.length = 0;\n};\n/**\n * Takes up to N elements from the beginning of the MutableList and returns them as an array.\n * The taken elements are removed from the list. This operation is optimized for performance\n * and includes zero-copy optimizations when possible.\n *\n * **Details**\n *\n * Finite fractional values of `n` are rounded down. `NaN` and non-positive\n * values leave the list unchanged and return an empty array.\n *\n * **Example** (Taking batches)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<number>()\n * MutableList.appendAll(list, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n *\n * MutableList.takeN(list, 3) // => [1, 2, 3]\n * MutableList.toArray(list) // => [4, 5, 6, 7, 8, 9, 10]\n * list.length // => 7\n * ```\n *\n * @category mutations\n * @since 4.0.0\n */\nexport const takeN = (self, n) => {\n  n = Count.normalize(n);\n  if (n <= 0 || !self.head) return [];\n  n = Math.min(n, self.length);\n  if (n === self.length && self.head?.offset === 0 && !self.head.next) {\n    const array = self.head.array;\n    clear(self);\n    return array;\n  }\n  const array = new Array(n);\n  let index = 0;\n  let chunk = self.head;\n  while (chunk) {\n    while (chunk.offset < chunk.array.length) {\n      array[index++] = chunk.array[chunk.offset];\n      if (chunk.mutable) chunk.array[chunk.offset] = undefined;\n      chunk.offset++;\n      if (index === n) {\n        self.head = chunk;\n        self.length -= n;\n        if (self.length === 0) clear(self);\n        return array;\n      }\n    }\n    chunk = chunk.next;\n  }\n  clear(self);\n  return array;\n};\n/**\n * Removes up to `n` elements from the beginning of the `MutableList` without\n * returning them.\n *\n * **When to use**\n *\n * Use to discard a bounded number of values from the head of a `MutableList`\n * when the removed values are not needed.\n *\n * **Details**\n *\n * Finite fractional values of `n` are rounded down. If `n` is `NaN` or\n * non-positive, or the list is empty, the list is left unchanged. If the\n * normalized count is greater than or equal to the current length, the list is\n * cleared.\n *\n * @see {@link takeN} for removing up to `n` values and returning them as an array\n * @see {@link clear} for removing every value from the list\n *\n * @category mutations\n * @since 4.0.0\n */\nexport const takeNVoid = (self, n) => {\n  n = Count.normalize(n);\n  if (n <= 0 || !self.head) return;\n  n = Math.min(n, self.length);\n  if (n === self.length && self.head?.offset === 0 && !self.head.next) {\n    clear(self);\n    return;\n  }\n  let count = 0;\n  let chunk = self.head;\n  while (chunk) {\n    const size = chunk.array.length - chunk.offset;\n    if (count + size > n) {\n      chunk.offset += n - count;\n      self.head = chunk;\n      self.length -= n;\n      return;\n    }\n    count += size;\n    chunk = chunk.next;\n  }\n  clear(self);\n  return;\n};\n/**\n * Takes all elements from the MutableList and returns them as an array.\n * The list becomes empty after this operation. This is equivalent to takeN(list, list.length).\n *\n * **Example** (Draining all elements)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<string>()\n * MutableList.appendAll(list, [\"apple\", \"banana\", \"cherry\"])\n *\n * MutableList.takeAll(list) // => [\"apple\", \"banana\", \"cherry\"]\n * list.length // => 0\n * ```\n *\n * @category mutations\n * @since 4.0.0\n */\nexport const takeAll = self => takeN(self, self.length);\n/**\n * Takes a single element from the beginning of the MutableList.\n * Returns the element if available, or the Empty symbol if the list is empty.\n * The taken element is removed from the list.\n *\n * **Example** (Taking one element)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<string>()\n * MutableList.appendAll(list, [\"first\", \"second\", \"third\"])\n *\n * MutableList.take(list) // => \"first\"\n * MutableList.toArray(list) // => [\"second\", \"third\"]\n * list.length // => 2\n * ```\n *\n * @category mutations\n * @since 4.0.0\n */\nexport const take = self => {\n  if (!self.head) return Empty;\n  const message = self.head.array[self.head.offset];\n  if (self.head.mutable) self.head.array[self.head.offset] = undefined;\n  self.head.offset++;\n  self.length--;\n  if (self.head.offset === self.head.array.length) {\n    if (self.head.next) {\n      self.head = self.head.next;\n    } else {\n      clear(self);\n    }\n  }\n  return message;\n};\n/**\n * Copies up to `n` elements from the beginning of the `MutableList` into a new\n * array without modifying the list.\n *\n * **When to use**\n *\n * Use when you need to inspect or snapshot a bounded prefix of the list without\n * consuming it.\n *\n * **Details**\n *\n * Finite fractional values of `n` are rounded down. `NaN` and non-positive\n * values return an empty array.\n *\n * @see {@link takeN} for removing up to `n` values and returning them as an array\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toArrayN = (self, n) => {\n  n = Count.normalize(n);\n  if (n <= 0) return [];\n  const length = Math.min(n, self.length);\n  const out = new Array(length);\n  let index = 0;\n  let bucket = self.head;\n  while (bucket) {\n    for (let i = bucket.offset; i < bucket.array.length; i++) {\n      out[index++] = bucket.array[i];\n      if (index === length) return out;\n    }\n    bucket = bucket.next;\n  }\n  return out;\n};\n/**\n * Copies all current elements of the `MutableList` into a new array without\n * modifying the list.\n *\n * **When to use**\n *\n * Use when you need a snapshot of all current elements while keeping the list\n * unchanged.\n *\n * @see {@link takeAll} for converting all elements to an array and clearing the list\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toArray = self => toArrayN(self, self.length);\n/**\n * Filters the MutableList in place, keeping only elements that satisfy the predicate.\n * This operation modifies the list and rebuilds its internal structure for efficiency.\n *\n * **Example** (Filtering in place)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<number>()\n * MutableList.appendAll(list, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n *\n * MutableList.filter(list, (n) => n % 2 === 0)\n *\n * MutableList.toArray(list) // => [2, 4, 6, 8, 10]\n * ```\n *\n * @category mutations\n * @since 4.0.0\n */\nexport const filter = (self, f) => {\n  const array = [];\n  let chunk = self.head;\n  while (chunk) {\n    for (let i = chunk.offset; i < chunk.array.length; i++) {\n      if (f(chunk.array[i], i)) {\n        array.push(chunk.array[i]);\n      }\n    }\n    chunk = chunk.next;\n  }\n  if (array.length === 0) {\n    clear(self);\n    return;\n  }\n  self.head = self.tail = {\n    array,\n    mutable: true,\n    offset: 0,\n    next: undefined\n  };\n  self.length = array.length;\n};\n/**\n * Removes all occurrences of a value from the `MutableList` using JavaScript\n * strict equality semantics.\n *\n * **When to use**\n *\n * Use when in-place removal should use JavaScript identity/strict equality\n * rather than Effect structural equality.\n *\n * **Details**\n *\n * The list is modified in place.\n *\n * **Gotchas**\n *\n * Values are compared with `!==`, so this does not use Effect structural\n * equality.\n *\n * **Example** (Removing matching values)\n *\n * ```ts import.meta.vitest\n * import { MutableList } from \"effect\"\n *\n * const list = MutableList.make<string>()\n * MutableList.appendAll(list, [\"apple\", \"banana\", \"apple\", \"cherry\", \"apple\"])\n *\n * MutableList.remove(list, \"apple\")\n *\n * MutableList.toArray(list) // => [\"banana\", \"cherry\"]\n * ```\n *\n * @category mutations\n * @since 4.0.0\n */\nexport const remove = (self, value) => filter(self, v => v !== value);\n//# sourceMappingURL=MutableList.js.map","/**\n * Passes values asynchronously between fibers.\n *\n * A `Queue<A, E>` accepts values, hands each value to one consumer in offer\n * order, and can complete, fail, interrupt, or shut down. Queues can be bounded\n * or unbounded, and bounded queues can suspend, drop, or slide values when\n * producers are faster than consumers.\n *\n * @since 3.8.0\n */\nimport * as Arr from \"./Array.js\";\nimport { constant, constTrue, dual, identity } from \"./Function.js\";\nimport * as core from \"./internal/core.js\";\nimport { PipeInspectableProto } from \"./internal/core.js\";\nimport * as Count from \"./internal/count.js\";\nimport * as internalEffect from \"./internal/effect.js\";\nimport * as MutableList from \"./MutableList.js\";\nimport * as Option from \"./Option.js\";\nimport { hasProperty } from \"./Predicate.js\";\nimport * as Pull from \"./Pull.js\";\nconst TypeId = \"~effect/Queue\";\nconst EnqueueTypeId = \"~effect/Queue/Enqueue\";\nconst DequeueTypeId = \"~effect/Queue/Dequeue\";\n/**\n * Type guard to check if a value is a Queue.\n *\n * **When to use**\n *\n * Use to narrow an unknown value to a full `Queue` before passing it to APIs\n * that need both offering and taking capabilities.\n *\n * @see {@link isEnqueue} for checking values that only need write access\n * @see {@link isDequeue} for checking values that only need read access\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isQueue = u => hasProperty(u, TypeId);\n/**\n * Type guard to check if a value is an Enqueue.\n *\n * **When to use**\n *\n * Use to narrow an unknown value before calling queue operations that require\n * write-side access.\n *\n * **Gotchas**\n *\n * A full `Queue` also satisfies this guard because every queue includes the\n * enqueue side.\n *\n * @see {@link isQueue} for checking for a full read-write queue handle\n * @see {@link isDequeue} for checking for the read side of a queue\n * @see {@link asEnqueue} for narrowing an existing `Queue` to its write-only interface\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isEnqueue = u => hasProperty(u, EnqueueTypeId);\n/**\n * Type guard to check if a value is a Dequeue.\n *\n * **When to use**\n *\n * Use to narrow an unknown value before passing it to read-side queue\n * operations.\n *\n * @see {@link Dequeue} for the read-side queue handle checked by this guard\n * @see {@link isQueue} for checking for a full read-write queue handle\n * @see {@link isEnqueue} for checking for the write side of a queue\n * @see {@link asDequeue} for narrowing an existing `Queue` to its read-only interface\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isDequeue = u => hasProperty(u, DequeueTypeId);\n/**\n * Converts a `Queue` to its write-only `Enqueue` interface.\n *\n * **When to use**\n *\n * Use to expose only the producer side of a `Queue` to code that should offer\n * values or signal queue lifecycle.\n *\n * **Gotchas**\n *\n * This is a type-level capability restriction. It returns the same queue\n * object, so it does not hide read operations at runtime.\n *\n * @see {@link asDequeue} for exposing only the read side of a `Queue`\n * @see {@link Enqueue} for the write-only queue handle returned by this conversion\n *\n * @category converting\n * @since 4.0.0\n */\nexport const asEnqueue = self => self;\n/**\n * Narrows a `Queue` to a `Dequeue`, exposing the consumer side of the queue.\n *\n * **When to use**\n *\n * Use to pass a queue to code that should consume values while keeping\n * producer-side operations out of that code's TypeScript type.\n *\n * **Gotchas**\n *\n * This is a type-level narrowing operation. It returns the same queue object\n * and does not create a runtime wrapper.\n *\n * @see {@link asEnqueue} for narrowing a queue to its producer side\n * @see {@link Dequeue} for the consumer-side queue handle returned by this function\n *\n * @category converting\n * @since 4.0.0\n */\nexport const asDequeue = identity;\nconst variance = {\n  _A: identity,\n  _E: identity\n};\nconst QueueProto = {\n  [TypeId]: variance,\n  [EnqueueTypeId]: variance,\n  [DequeueTypeId]: variance,\n  ...PipeInspectableProto,\n  toJSON() {\n    return {\n      _id: \"effect/Queue\",\n      state: this.state._tag,\n      size: sizeUnsafe(this)\n    };\n  }\n};\n/**\n * Creates a `Queue` with optional capacity and overflow strategy.\n *\n * **Details**\n *\n * By default the queue is unbounded and uses the `\"suspend\"` strategy. Provide\n * `capacity` for a bounded queue and choose `\"suspend\"`, `\"dropping\"`, or\n * `\"sliding\"` to control what happens when the queue is full. The returned\n * queue can be offered to, taken from, failed, ended, interrupted, or shut down.\n *\n * **Example** (Creating queues)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.make<number, string | Cause.Done>()\n *\n *   // add messages to the queue\n *   yield* Queue.offer(queue, 1)\n *   yield* Queue.offer(queue, 2)\n *   yield* Queue.offerAll(queue, [3, 4, 5])\n *\n *   // take messages from the queue\n *   const messages = yield* Queue.takeAll(queue)\n *\n *   // signal that the queue is done\n *   yield* Queue.end(queue)\n *   const done = yield* Effect.flip(Queue.take(queue))\n *\n *   // signal that another queue has failed\n *   const failedQueue = yield* Queue.make<number, string>()\n *   const failed = yield* Queue.fail(failedQueue, \"boom\")\n *   return { messages, done, failed }\n * })\n *\n * await Effect.runPromise(program) // => { messages: [1, 2, 3, 4, 5], done: Cause.Done(), failed: true }\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = options => core.withFiber(fiber => {\n  const self = Object.create(QueueProto);\n  self.dispatcher = fiber.currentDispatcher;\n  self.capacity = options?.capacity ?? Number.POSITIVE_INFINITY;\n  self.strategy = options?.strategy ?? \"suspend\";\n  self.messages = MutableList.make();\n  self.scheduleRunning = false;\n  self.state = {\n    _tag: \"Open\",\n    takers: new Set(),\n    offers: new Set(),\n    awaiters: new Set()\n  };\n  return internalEffect.succeed(self);\n});\n/**\n * Creates a bounded queue with the specified capacity that uses backpressure strategy.\n *\n * **Details**\n *\n * When the queue reaches capacity, producers will be suspended until space becomes available.\n * This ensures all messages are processed but may slow down producers.\n *\n * **Example** (Creating bounded queues)\n *\n * ```ts import.meta.vitest\n * import { Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<string>(5)\n *\n *   // This will succeed as queue has capacity\n *   yield* Queue.offer(queue, \"first\")\n *   yield* Queue.offer(queue, \"second\")\n *\n *   const size = yield* Queue.size(queue)\n *   return size\n * })\n *\n * await Effect.runPromise(program) // => 2\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const bounded = capacity => make({\n  capacity\n});\n/**\n * Creates a bounded queue with sliding strategy. When the queue reaches capacity,\n * new elements are added and the oldest elements are dropped.\n *\n * **When to use**\n *\n * Use when you need producer offers not to block and can accept dropping the\n * oldest messages, such as when maintaining a rolling window of recent values.\n *\n * **Example** (Creating sliding queues)\n *\n * ```ts import.meta.vitest\n * import { Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.sliding<number>(3)\n *\n *   // Fill the queue to capacity\n *   yield* Queue.offer(queue, 1)\n *   yield* Queue.offer(queue, 2)\n *   yield* Queue.offer(queue, 3)\n *\n *   // This will succeed, dropping the oldest element (1)\n *   yield* Queue.offer(queue, 4)\n *\n *   const all = yield* Queue.takeAll(queue)\n *   return all\n * })\n *\n * await Effect.runPromise(program) // => [2, 3, 4]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const sliding = capacity => make({\n  capacity,\n  strategy: \"sliding\"\n});\n/**\n * Creates a bounded queue with dropping strategy. When the queue reaches capacity,\n * new elements are dropped and the offer operation returns false.\n *\n * **When to use**\n *\n * Use when you need producer offers not to block while preserving existing\n * queued messages, even if new messages may be dropped when the queue is full.\n *\n * **Example** (Creating dropping queues)\n *\n * ```ts import.meta.vitest\n * import { Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.dropping<number>(2)\n *\n *   // Fill the queue to capacity\n *   const success1 = yield* Queue.offer(queue, 1)\n *   const success2 = yield* Queue.offer(queue, 2)\n *\n *   // This will be dropped\n *   const success3 = yield* Queue.offer(queue, 3)\n *\n *   const all = yield* Queue.takeAll(queue)\n *   return [success1, success2, success3, all]\n * })\n *\n * await Effect.runPromise(program) // => [true, true, false, [1, 2]]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const dropping = capacity => make({\n  capacity,\n  strategy: \"dropping\"\n});\n/**\n * Creates an unbounded queue that can grow to any size without blocking producers.\n *\n * **When to use**\n *\n * Use when you need producers to add messages without backpressure and accept\n * unbounded memory growth.\n *\n * **Example** (Creating unbounded queues)\n *\n * ```ts import.meta.vitest\n * import { Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.unbounded<string>()\n *\n *   // Producers can always add messages without blocking\n *   yield* Queue.offer(queue, \"message1\")\n *   yield* Queue.offer(queue, \"message2\")\n *   yield* Queue.offerAll(queue, [\"message3\", \"message4\", \"message5\"])\n *\n *   // Check current size\n *   const size = yield* Queue.size(queue)\n *\n *   // Take all messages\n *   const messages = yield* Queue.takeAll(queue)\n *   return { size, messages }\n * })\n *\n * await Effect.runPromise(program) // => { size: 5, messages: [\"message1\", \"message2\", \"message3\", \"message4\", \"message5\"] }\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const unbounded = () => make();\n/**\n * Adds a message to the queue. Returns `false` if the queue is done.\n *\n * **Details**\n *\n * For bounded queues, this operation may suspend if the queue is at capacity,\n * depending on the backpressure strategy. For dropping/sliding queues, it may\n * return false or succeed immediately by dropping/sliding existing messages.\n *\n * **Example** (Offering a value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<number>(3)\n *\n *   // Successfully add messages to queue\n *   const success1 = yield* Queue.offer(queue, 1)\n *   const success2 = yield* Queue.offer(queue, 2)\n *\n *   // Queue state\n *   const size = yield* Queue.size(queue)\n *   return { offered: [success1, success2], size }\n * })\n *\n * await Effect.runPromise(program) // => { offered: [true, true], size: 2 }\n * ```\n *\n * @category offering\n * @since 2.0.0\n */\nexport const offer = (self, message) => internalEffect.suspend(() => {\n  if (self.state._tag !== \"Open\") {\n    return exitFalse;\n  } else if (self.messages.length >= self.capacity) {\n    switch (self.strategy) {\n      case \"dropping\":\n        return exitFalse;\n      case \"suspend\":\n        if (self.capacity <= 0 && self.state.takers.size > 0) {\n          MutableList.append(self.messages, message);\n          releaseTakers(self);\n          return exitTrue;\n        }\n        return offerRemainingSingle(self, message);\n      case \"sliding\":\n        MutableList.take(self.messages);\n        MutableList.append(self.messages, message);\n        return exitTrue;\n    }\n  }\n  MutableList.append(self.messages, message);\n  scheduleReleaseTaker(self);\n  return exitTrue;\n});\n/**\n * Adds a message to the queue synchronously. Returns `false` if the queue is done.\n *\n * **When to use**\n *\n * Use when you are already in synchronous queue internals or a performance\n * boundary where wrapping the mutation in `Effect` is intentionally avoided.\n *\n * **Gotchas**\n *\n * This is an unsafe operation that directly modifies the queue without Effect wrapping.\n * Use this only when you're certain about the synchronous nature of the operation.\n *\n * **Example** (Offering a value synchronously)\n *\n * ```ts import.meta.vitest\n * import { Effect, Queue } from \"effect\"\n *\n * // Create a queue effect and extract the queue for unsafe operations\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<number>(3)\n *\n *   // Add messages synchronously using unsafe API\n *   const success1 = Queue.offerUnsafe(queue, 1)\n *   const success2 = Queue.offerUnsafe(queue, 2)\n *\n *   // Check current size\n *   const size = Queue.sizeUnsafe(queue)\n *   return { offered: [success1, success2], size }\n * })\n *\n * await Effect.runPromise(program) // => { offered: [true, true], size: 2 }\n * ```\n *\n * @category offering\n * @since 4.0.0\n */\nexport const offerUnsafe = (self, message) => {\n  if (self.state._tag !== \"Open\") {\n    return false;\n  } else if (self.messages.length >= self.capacity) {\n    if (self.strategy === \"sliding\") {\n      MutableList.take(self.messages);\n      MutableList.append(self.messages, message);\n      return true;\n    } else if (self.capacity <= 0 && self.state.takers.size > 0) {\n      MutableList.append(self.messages, message);\n      releaseTakers(self);\n      return true;\n    }\n    return false;\n  }\n  MutableList.append(self.messages, message);\n  scheduleReleaseTaker(self);\n  return true;\n};\n/**\n * Adds multiple messages to the queue. Returns the remaining messages that\n * were not added.\n *\n * **When to use**\n *\n * Use when producers can submit a batch at once and need to know which messages\n * did not fit under the queue's capacity strategy.\n *\n * **Details**\n *\n * For bounded queues, this operation may suspend if the queue doesn't have\n * enough capacity. The operation returns an array of messages that couldn't\n * be added (empty array means all messages were successfully added).\n *\n * **Example** (Offering multiple values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.dropping<number>(3)\n *\n *   // Try to add more messages than capacity without suspending\n *   const remaining1 = yield* Queue.offerAll(queue, [1, 2, 3, 4, 5])\n *   return remaining1\n * })\n *\n * await Effect.runPromise(program) // => [4, 5]\n * ```\n *\n * @category offering\n * @since 2.0.0\n */\nexport const offerAll = (self, messages) => internalEffect.suspend(() => {\n  if (self.state._tag !== \"Open\") {\n    return internalEffect.succeed(Arr.fromIterable(messages));\n  }\n  const remaining = offerAllUnsafe(self, messages);\n  if (remaining.length === 0) {\n    return core.exitSucceed([]);\n  } else if (self.strategy === \"dropping\") {\n    return internalEffect.succeed(remaining);\n  }\n  return offerRemainingArray(self, remaining);\n});\n/**\n * Adds multiple messages to the queue synchronously. Returns the remaining messages that\n * were not added.\n *\n * **When to use**\n *\n * Use when queue internals or a performance boundary need a synchronous batch\n * offer and can handle any messages that do not fit.\n *\n * **Gotchas**\n *\n * This is an unsafe operation that directly modifies the queue without Effect wrapping.\n *\n * **Example** (Offering multiple values synchronously)\n *\n * ```ts import.meta.vitest\n * import { Effect, Queue } from \"effect\"\n *\n * // Create a bounded queue and use unsafe API\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<number>(3)\n *\n *   // Try to add 5 messages to capacity-3 queue using unsafe API\n *   const remaining = Queue.offerAllUnsafe(queue, [1, 2, 3, 4, 5])\n *\n *   // Check what's in the queue\n *   const size = Queue.sizeUnsafe(queue)\n *   return { remaining, size }\n * })\n *\n * await Effect.runPromise(program) // => { remaining: [4, 5], size: 3 }\n * ```\n *\n * @category offering\n * @since 4.0.0\n */\nexport const offerAllUnsafe = (self, messages) => {\n  if (self.state._tag !== \"Open\") {\n    return Arr.fromIterable(messages);\n  } else if (self.capacity === Number.POSITIVE_INFINITY || self.strategy === \"sliding\") {\n    MutableList.appendAll(self.messages, messages);\n    if (self.strategy === \"sliding\") {\n      MutableList.takeN(self.messages, self.messages.length - self.capacity);\n    }\n    scheduleReleaseTaker(self);\n    return [];\n  }\n  const free = self.capacity <= 0 ? self.state.takers.size : self.capacity - self.messages.length;\n  if (free === 0) {\n    return Arr.fromIterable(messages);\n  }\n  const remaining = [];\n  let i = 0;\n  for (const message of messages) {\n    if (i < free) {\n      MutableList.append(self.messages, message);\n    } else {\n      remaining.push(message);\n    }\n    i++;\n  }\n  scheduleReleaseTaker(self);\n  return remaining;\n};\n/**\n * Fails the queue with an error. If the queue is already done, `false` is\n * returned.\n *\n * **Example** (Failing queues with an error)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<number, string>(10)\n *\n *   // Fail the queue with an error\n *   const failed = yield* Queue.fail(queue, \"Something went wrong\")\n *\n *   // Taking from the failed queue fails with the error\n *   const exit = yield* Effect.exit(Queue.take(queue))\n *   return [failed, exit]\n * })\n *\n * await Effect.runPromise(program) // => [true, Exit.fail(\"Something went wrong\")]\n * ```\n *\n * @category completion\n * @since 4.0.0\n */\nexport const fail = (self, error) => failCause(self, core.causeFail(error));\n/**\n * Fails the queue with a cause. If the queue is already done, `false` is\n * returned.\n *\n * **Example** (Failing queues with a cause)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Exit, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<number, string>(10)\n *\n *   // Create a cause and fail the queue\n *   const cause = Cause.fail(\"Queue processing failed\")\n *   const failed = yield* Queue.failCause(queue, cause)\n *\n *   // The queue is now done with the specified failure cause\n *   const exit = yield* Effect.exit(Queue.take(queue))\n *   return [failed, exit]\n * })\n *\n * await Effect.runPromise(program) // => [true, Exit.failCause(Cause.fail(\"Queue processing failed\"))]\n * ```\n *\n * @category completion\n * @since 4.0.0\n */\nexport const failCause = /*#__PURE__*/dual(2, (self, cause) => internalEffect.sync(() => failCauseUnsafe(self, cause)));\n/**\n * Fails the queue with a cause synchronously. If the queue is already done, `false` is\n * returned.\n *\n * **When to use**\n *\n * Use when queue completion must be driven from synchronous internals while\n * preserving the full failure `Cause`.\n *\n * **Gotchas**\n *\n * This is an unsafe operation that directly modifies the queue without Effect wrapping.\n *\n * **Example** (Failing queues with a cause synchronously)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Exit, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<number, string>(10)\n *\n *   // Create a cause and fail the queue synchronously\n *   const cause = Cause.fail(\"Processing error\")\n *   const failed = Queue.failCauseUnsafe(queue, cause)\n *\n *   // The queue is now done with the specified failure cause\n *   const exit = Queue.takeUnsafe(queue)\n *   return [failed, exit]\n * })\n *\n * await Effect.runPromise(program) // => [true, Exit.failCause(Cause.fail(\"Processing error\"))]\n * ```\n *\n * @category completion\n * @since 4.0.0\n */\nexport const failCauseUnsafe = (self, cause) => {\n  if (self.state._tag !== \"Open\") {\n    return false;\n  }\n  const exit = core.exitFailCause(cause);\n  const fail = internalEffect.exitZipRight(exit, exitFailDone);\n  if (self.state.offers.size === 0 && self.messages.length === 0) {\n    finalize(self, fail);\n    return true;\n  }\n  self.state = {\n    ...self.state,\n    _tag: \"Closing\",\n    exit: fail\n  };\n  return true;\n};\n/**\n * Signals queue completion.\n *\n * **When to use**\n *\n * Use to stop accepting new offers while allowing already queued messages to be\n * consumed.\n *\n * **Details**\n *\n * Returns `false` if the queue is already done.\n *\n * **Example** (Ending queues)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<number, Cause.Done>(10)\n *\n *   // Add some messages\n *   yield* Queue.offer(queue, 1)\n *   yield* Queue.offer(queue, 2)\n *\n *   // Signal completion - no more messages will be accepted\n *   const ended = yield* Queue.end(queue)\n *\n *   // Trying to offer more messages will return false\n *   const offerResult = yield* Queue.offer(queue, 3)\n *\n *   // But we can still take existing messages\n *   const message = yield* Queue.take(queue)\n *   return [ended, offerResult, message]\n * })\n *\n * await Effect.runPromise(program) // => [true, false, 1]\n * ```\n *\n * @category completion\n * @since 4.0.0\n */\nexport const end = self => failCause(self, core.causeFail(core.Done()));\n/**\n * Signals queue completion synchronously.\n *\n * **When to use**\n *\n * Use when implementing low-level queue integrations that must complete a queue\n * without wrapping the operation in `Effect`.\n *\n * **Details**\n *\n * Returns `false` if the queue is already done.\n *\n * **Gotchas**\n *\n * This is an unsafe operation that directly modifies the queue without Effect wrapping.\n *\n * **Example** (Ending queues synchronously)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue } from \"effect\"\n *\n * // Create a queue and use unsafe operations\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<number, Cause.Done>(10)\n *\n *   // Add some messages\n *   Queue.offerUnsafe(queue, 1)\n *   Queue.offerUnsafe(queue, 2)\n *\n *   // End the queue synchronously\n *   const ended = Queue.endUnsafe(queue)\n *\n *   // Existing messages can still be consumed while the queue is closing\n *   const states = [queue.state._tag]\n *\n *   Queue.takeUnsafe(queue)\n *   Queue.takeUnsafe(queue)\n *\n *   // After buffered messages are consumed, the queue is done\n *   states.push(queue.state._tag)\n *   return { ended, states }\n * })\n *\n * await Effect.runPromise(program) // => { ended: true, states: [\"Closing\", \"Done\"] }\n * ```\n *\n * @category completion\n * @since 4.0.0\n */\nexport const endUnsafe = self => failCauseUnsafe(self, core.causeFail(core.Done()));\n/**\n * Interrupts the queue gracefully, transitioning it to a closing state.\n *\n * **Details**\n *\n * This operation stops accepting new offers but allows existing messages to be consumed.\n * Once all messages are drained, the queue transitions to the Done state with an interrupt cause.\n *\n * **Example** (Interrupting queues gracefully)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<number>(10)\n *\n *   // Add some messages\n *   yield* Queue.offer(queue, 1)\n *   yield* Queue.offer(queue, 2)\n *\n *   // Interrupt gracefully - no more offers accepted, but messages can be consumed\n *   const interrupted = yield* Queue.interrupt(queue)\n *\n *   // Trying to offer more messages will return false\n *   const offerResult = yield* Queue.offer(queue, 3)\n *\n *   // But we can still take existing messages\n *   const message1 = yield* Queue.take(queue)\n *\n *   const message2 = yield* Queue.take(queue)\n *\n *   // After all messages are consumed, queue is done\n *   const isDone = queue.state._tag === \"Done\"\n *   return { interrupted, offerResult, messages: [message1, message2], isDone }\n * })\n *\n * await Effect.runPromise(program) // => { interrupted: true, offerResult: false, messages: [1, 2], isDone: true }\n * ```\n *\n * @category completion\n * @since 4.0.0\n */\nexport const interrupt = self => core.withFiber(fiber => failCause(self, internalEffect.causeInterrupt(fiber.id)));\n/**\n * Shuts down the queue immediately, discarding buffered messages and resuming\n * pending operations.\n *\n * **Details**\n *\n * The operation is idempotent and returns `true`, including when the queue has\n * already been shut down or completed.\n *\n * **Example** (Shutting down queues)\n *\n * ```ts import.meta.vitest\n * import { Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<number>(2)\n *\n *   // Add messages\n *   yield* Queue.offer(queue, 1)\n *   yield* Queue.offer(queue, 2)\n *\n *   // Shutdown clears buffered messages and prevents further offers\n *   const wasShutdown = yield* Queue.shutdown(queue)\n *\n *   // Queue is now done and cleared\n *   const size = yield* Queue.size(queue)\n *   return { wasShutdown, size }\n * })\n *\n * await Effect.runPromise(program) // => { wasShutdown: true, size: 0 }\n * ```\n *\n * @category completion\n * @since 2.0.0\n */\nexport const shutdown = self => internalEffect.sync(() => {\n  if (self.state._tag === \"Done\") {\n    return true;\n  }\n  MutableList.clear(self.messages);\n  const offers = self.state.offers;\n  finalize(self, self.state._tag === \"Open\" ? exitInterrupt : self.state.exit);\n  if (offers.size > 0) {\n    for (const entry of offers) {\n      if (entry._tag === \"Single\") {\n        entry.resume(exitFalse);\n      } else {\n        entry.resume(core.exitSucceed(entry.remaining.slice(entry.offset)));\n      }\n    }\n    offers.clear();\n  }\n  return true;\n});\n/**\n * Takes and returns all currently buffered messages without waiting for more.\n *\n * **Details**\n *\n * Returns an empty array when the queue is empty or has completed normally. If\n * the queue has failed, the effect fails with the queue's error.\n *\n * **Example** (Clearing queued values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<number>(10)\n *\n *   // Add several messages\n *   yield* Queue.offerAll(queue, [1, 2, 3, 4, 5])\n *\n *   // Clear all messages from the queue\n *   const messages = yield* Queue.clear(queue)\n *\n *   // Queue is now empty\n *   const size = yield* Queue.size(queue)\n *\n *   // Clearing empty queue returns empty array\n *   const empty = yield* Queue.clear(queue)\n *   return { messages, size, empty }\n * })\n *\n * await Effect.runPromise(program) // => { messages: [1, 2, 3, 4, 5], size: 0, empty: [] }\n * ```\n *\n * @category taking\n * @since 4.0.0\n */\nexport const clear = self => internalEffect.suspend(() => {\n  if (self.state._tag === \"Done\") {\n    if (Pull.isDoneCause(self.state.exit.cause)) {\n      return internalEffect.succeed([]);\n    }\n    return self.state.exit;\n  }\n  const messages = takeAllUnsafe(self);\n  releaseCapacity(self);\n  return internalEffect.succeed(messages);\n});\n/**\n * Takes all currently available messages, waiting until at least one message\n * is available when the queue is empty.\n *\n * **When to use**\n *\n * Use when consumers should process the next non-empty batch of buffered\n * messages instead of repeatedly taking one message at a time.\n *\n * **Details**\n *\n * Returns a non-empty array. If the queue completes or fails before a message\n * can be taken, the effect fails with the queue's terminal error.\n *\n * **Example** (Taking all available values)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<number, Cause.Done>(5)\n *\n *   // Add several messages\n *   yield* Queue.offerAll(queue, [1, 2, 3, 4, 5])\n *\n *   // Take all available messages\n *   const messages1 = yield* Queue.takeAll(queue)\n *   return messages1\n * })\n *\n * await Effect.runPromise(program) // => [1, 2, 3, 4, 5]\n * ```\n *\n * @category taking\n * @since 2.0.0\n */\nexport const takeAll = self => takeBetween(self, 1, Number.POSITIVE_INFINITY);\n/**\n * Takes all messages from the queue, until the queue has errored or is done.\n *\n * **Example** (Collecting values until completion)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<number, Cause.Done>(5)\n *\n *   // Add several messages\n *   yield* Queue.offerAll(queue, [1, 2, 3, 4, 5])\n *   yield* Queue.end(queue)\n *\n *   // Collect all available messages\n *   return yield* Queue.collect(queue)\n * })\n *\n * await Effect.runPromise(program) // => [1, 2, 3, 4, 5]\n * ```\n *\n * @category taking\n * @since 4.0.0\n */\nexport const collect = self => internalEffect.suspend(() => {\n  const out = Arr.empty();\n  return internalEffect.as(Pull.catchDone(internalEffect.whileLoop({\n    while: constTrue,\n    body: constant(takeAll(self)),\n    step(items) {\n      for (let i = 0; i < items.length; i++) {\n        out.push(items[i]);\n      }\n    }\n  }), () => internalEffect.void), out);\n});\n/**\n * Takes up to `n` messages from the queue.\n *\n * **Details**\n *\n * The operation may wait until enough messages are available to satisfy the\n * queue's batching rules. Finite fractional values of `n` are rounded down.\n * If `n` is `NaN` or non-positive, it succeeds with an empty array. If the\n * queue completes or fails before messages can be taken, the effect fails with\n * the queue's terminal error.\n *\n * **Example** (Taking a fixed number of values)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<number, Cause.Done>(10)\n *\n *   // Add several messages\n *   yield* Queue.offerAll(queue, [1, 2, 3, 4, 5, 6, 7])\n *\n *   // Take exactly 3 messages\n *   const first3 = yield* Queue.takeN(queue, 3)\n *\n *   // Take exactly 2 more messages\n *   const next2 = yield* Queue.takeN(queue, 2)\n *\n *   // Take remaining messages\n *   const remaining = yield* Queue.takeN(queue, 2)\n *   return [first3, next2, remaining]\n * })\n *\n * await Effect.runPromise(program) // => [[1, 2, 3], [4, 5], [6, 7]]\n * ```\n *\n * @category taking\n * @since 2.0.0\n */\nexport const takeN = (self, n) => takeBetween(self, n, n);\n/**\n * Takes between `min` and `max` messages from the queue.\n *\n * **Details**\n *\n * The operation waits when fewer than the required minimum messages are\n * available. It returns at most `max` messages. Finite fractional bounds are\n * rounded down, while `NaN` and non-positive bounds are treated as `0`. If the\n * queue completes or fails before the minimum can be satisfied, the effect\n * fails with the queue's terminal error.\n *\n * **Example** (Taking a bounded batch of values)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<number>(10)\n *\n *   // Add several messages\n *   yield* Queue.offerAll(queue, [1, 2, 3, 4, 5, 6, 7, 8])\n *\n *   // Take between 2 and 5 messages\n *   const batch1 = yield* Queue.takeBetween(queue, 2, 5)\n *\n *   // Take between 1 and 10 messages (but only 3 remain)\n *   const batch2 = yield* Queue.takeBetween(queue, 1, 10)\n *\n *   // No more messages available, will wait or return done\n *   // const batch3 = yield* Queue.takeBetween(queue, 1, 3)\n *   return [batch1, batch2]\n * })\n *\n * await Effect.runPromise(program) // => [[1, 2, 3, 4, 5], [6, 7, 8]]\n * ```\n *\n * @category taking\n * @since 2.0.0\n */\nexport const takeBetween = (self, min, max) => {\n  min = Count.normalize(min);\n  max = Count.normalize(max);\n  return internalEffect.suspend(() => takeBetweenUnsafe(self, min, max) ?? internalEffect.andThen(awaitTake(self), takeBetween(self, 1, max)));\n};\n/**\n * Takes a single message from the queue, or wait for a message to be\n * available.\n *\n * **Details**\n *\n * If the queue is done, it will fail with `Done`. If the\n * queue fails, the Effect will fail with the error.\n *\n * **Example** (Taking one value)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Exit, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<string, Cause.Done>(3)\n *\n *   // Add some messages\n *   yield* Queue.offer(queue, \"first\")\n *   yield* Queue.offer(queue, \"second\")\n *\n *   // Take messages one by one\n *   const msg1 = yield* Queue.take(queue)\n *   const msg2 = yield* Queue.take(queue)\n *\n *   // End the queue\n *   yield* Queue.end(queue)\n *\n *   // Taking from an ended queue fails with Done\n *   const result = yield* Effect.exit(Queue.take(queue))\n *   return [[msg1, msg2], result]\n * })\n *\n * await Effect.runPromise(program) // => [[\"first\", \"second\"], Exit.fail(Cause.Done())]\n * ```\n *\n * @category taking\n * @since 2.0.0\n */\nexport const take = self => internalEffect.suspend(() => takeUnsafe(self) ?? internalEffect.andThen(awaitTake(self), take(self)));\n/**\n * Attempts to take one item from the queue without waiting.\n *\n * **Details**\n *\n * Returns `Option.some` when an item is immediately available. Returns\n * `Option.none` when no item is available, when the queue is done, or when the\n * immediate take observes a queue failure.\n *\n * **Example** (Polling without blocking)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<number>(10)\n *\n *   // Poll returns Option.none if empty\n *   const maybe1 = yield* Queue.poll(queue)\n *\n *   // Add an item\n *   yield* Queue.offer(queue, 42)\n *\n *   // Poll returns Option.some with the item\n *   const maybe2 = yield* Queue.poll(queue)\n *   return [maybe1, maybe2]\n * })\n *\n * await Effect.runPromise(program) // => [Option.none(), Option.some(42)]\n * ```\n *\n * @category taking\n * @since 2.0.0\n */\nexport const poll = self => internalEffect.suspend(() => {\n  const result = takeUnsafe(self);\n  if (result === undefined) {\n    return internalEffect.succeed(Option.none());\n  }\n  if (result._tag === \"Success\") {\n    return internalEffect.succeed(Option.some(result.value));\n  }\n  return internalEffect.succeed(Option.none());\n});\n/**\n * Peeks at the next item without removing it.\n *\n * **Details**\n *\n * Blocks until an item is available. If the queue is done or fails, the error is propagated.\n *\n * **Example** (Peeking at the next value)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<number>(10)\n *   yield* Queue.offer(queue, 42)\n *\n *   // Peek at the next item without removing it\n *   const item = yield* Queue.peek(queue)\n *   return item\n * })\n *\n * await Effect.runPromise(program) // => 42\n * ```\n *\n * @category taking\n * @since 4.0.0\n */\nexport const peek = self => internalEffect.suspend(() => {\n  if (self.state._tag === \"Done\") {\n    return self.state.exit;\n  }\n  if (self.messages.length > 0 && self.messages.head) {\n    return internalEffect.succeed(self.messages.head.array[self.messages.head.offset]);\n  }\n  return internalEffect.andThen(awaitTake(self), peek(self));\n});\n/**\n * Attempts to take one message from the queue synchronously.\n *\n * **When to use**\n *\n * Use when polling queue internals must not suspend or register a waiting taker,\n * and `undefined` is an acceptable result for an empty queue.\n *\n * **Details**\n *\n * Returns an `Exit` for an immediately available message or for the queue's\n * terminal state. Returns `undefined` when no message is immediately available.\n * This operation does not wait or register a taker.\n *\n * **Example** (Taking one value synchronously)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Queue } from \"effect\"\n *\n * // Create a queue and use unsafe operations\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<number>(10)\n *\n *   // Add some messages\n *   Queue.offerUnsafe(queue, 1)\n *   Queue.offerUnsafe(queue, 2)\n *\n *   // Take a message synchronously\n *   const result1 = Queue.takeUnsafe(queue)\n *\n *   const result2 = Queue.takeUnsafe(queue)\n *\n *   // No more messages - returns undefined\n *   const result3 = Queue.takeUnsafe(queue)\n *   return [result1, result2, result3]\n * })\n *\n * await Effect.runPromise(program) // => [Exit.succeed(1), Exit.succeed(2), undefined]\n * ```\n *\n * @category taking\n * @since 4.0.0\n */\nexport const takeUnsafe = self => {\n  if (self.state._tag === \"Done\") {\n    return self.state.exit;\n  }\n  if (self.messages.length > 0) {\n    const message = MutableList.take(self.messages);\n    releaseCapacity(self);\n    return core.exitSucceed(message);\n  } else if (self.capacity <= 0 && self.state.offers.size > 0) {\n    const message = takeOfferUnsafe(self.state.offers);\n    releaseCapacity(self);\n    return core.exitSucceed(message);\n  }\n  return undefined;\n};\n/**\n * Manually releases current queue takers synchronously.\n *\n * **When to use**\n *\n * Use when synchronous offers should release waiting consumers immediately\n * instead of waiting for the scheduled release task.\n *\n * **Details**\n *\n * This immediately runs the queue's taker-release pass instead of waiting for\n * its scheduled task. It does not complete the queue or resume fibers waiting\n * on `Queue.await`.\n *\n * **Example** (Releasing a waiting taker synchronously)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.unbounded<number>()\n *   const taker = yield* Queue.take(queue).pipe(Effect.forkChild)\n *   yield* Effect.yieldNow\n *\n *   Queue.offerUnsafe(queue, 1)\n *   Queue.flushUnsafe(queue)\n *\n *   return yield* Fiber.join(taker)\n * })\n *\n * await Effect.runPromise(program) // => 1\n * ```\n *\n * @category offering\n * @since 4.0.0\n */\nexport const flushUnsafe = self => releaseTakers(self);\n/**\n * Manually releases current queue takers.\n *\n * **When to use**\n *\n * Use when synchronous offers should release waiting consumers through an\n * `Effect` instead of waiting for the scheduled release task.\n *\n * **Details**\n *\n * This immediately runs the queue's taker-release pass instead of waiting for\n * its scheduled task. It does not complete the queue or resume fibers waiting\n * on `Queue.await`.\n *\n * **Example** (Releasing a waiting taker)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.unbounded<number>()\n *   const taker = yield* Queue.take(queue).pipe(Effect.forkChild)\n *   yield* Effect.yieldNow\n *\n *   Queue.offerUnsafe(queue, 1)\n *   yield* Queue.flush(queue)\n *\n *   return yield* Fiber.join(taker)\n * })\n *\n * await Effect.runPromise(program) // => 1\n * ```\n *\n * @category offering\n * @since 4.0.0\n */\nexport const flush = self => internalEffect.sync(() => flushUnsafe(self));\nconst await_ = self => internalEffect.callback(resume => {\n  const awaiter = effect => resume(Pull.catchDone(effect, () => internalEffect.exitVoid));\n  if (self.state._tag === \"Done\") {\n    return awaiter(self.state.exit);\n  }\n  self.state.awaiters.add(awaiter);\n  return internalEffect.sync(() => {\n    if (self.state._tag !== \"Done\") {\n      self.state.awaiters.delete(awaiter);\n    }\n  });\n});\nexport {\n/**\n * Waits until a queue reaches the `Done` state.\n *\n * **When to use**\n *\n * Use to suspend a fiber until no further values can be taken from the queue\n * and its terminal outcome is known.\n *\n * **Details**\n *\n * The effect succeeds with `void` for normal `Done` completion. Other\n * terminal causes are preserved, so failures and interruptions complete this\n * effect with the same terminal outcome.\n *\n * **Gotchas**\n *\n * A queue can be closing before it is done. `await` resumes at `Done`, not at\n * the first completion signal, so buffered messages may need to be drained\n * first.\n *\n * @see {@link end} for signaling normal completion while preserving buffered messages for consumers\n * @see {@link fail} for signaling an error while preserving buffered messages for consumers\n * @see {@link interrupt} for graceful interruption after buffered messages are drained\n * @see {@link shutdown} for immediately discarding buffered messages and resuming pending operations\n *\n * @category completion\n * @since 4.0.0\n */\nawait_ as await };\n/**\n * Returns the current number of buffered messages in the queue.\n *\n * **Details**\n *\n * After `end`, a queue remains `Closing` while buffered messages are drained,\n * and its size continues to include those messages. A `Done` queue reports a\n * size of `0`.\n *\n * **Example** (Checking queue size)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<number, Cause.Done>(10)\n *\n *   // Check size of empty queue\n *   const size1 = yield* Queue.size(queue)\n *\n *   // Add some messages\n *   yield* Queue.offerAll(queue, [1, 2, 3, 4, 5])\n *\n *   // Check size after adding messages\n *   const size2 = yield* Queue.size(queue)\n *\n *   // End the queue\n *   yield* Queue.end(queue)\n *\n *   // Ending retains the buffered size while the queue is Closing\n *   const size3 = yield* Queue.size(queue)\n *   return [size1, size2, size3]\n * })\n *\n * await Effect.runPromise(program) // => [0, 5, 5]\n * ```\n *\n * @category sizes\n * @since 2.0.0\n */\nexport const size = self => internalEffect.sync(() => sizeUnsafe(self));\n/**\n * Checks whether the queue is full.\n *\n * **Example** (Checking if queues are full)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<number, Cause.Done>(3)\n *\n *   const before = yield* Queue.isFull(queue)\n *\n *   // Add some messages\n *   yield* Queue.offerAll(queue, [1, 2, 3])\n *\n *   const after = yield* Queue.isFull(queue)\n *   return [before, after]\n * })\n *\n * await Effect.runPromise(program) // => [false, true]\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const isFull = self => internalEffect.sync(() => isFullUnsafe(self));\n/**\n * Returns the current number of buffered messages in the queue synchronously.\n *\n * **When to use**\n *\n * Use when you need an immediate `Queue` size snapshot for diagnostics or\n * internals and do not need the read wrapped in `Effect`.\n *\n * **Details**\n *\n * After `endUnsafe`, a queue remains `Closing` while buffered messages are\n * drained, and its size continues to include those messages. A `Done` queue\n * reports a size of `0`. This unsafe operation reads the queue state directly\n * without Effect wrapping.\n *\n * **Example** (Checking queue size synchronously)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<number, Cause.Done>(10)\n *\n *   // Check size of empty queue\n *   const size1 = Queue.sizeUnsafe(queue)\n *\n *   // Add some messages\n *   Queue.offerUnsafe(queue, 1)\n *   Queue.offerUnsafe(queue, 2)\n *   Queue.offerUnsafe(queue, 3)\n *\n *   // Check size after adding messages\n *   const size2 = Queue.sizeUnsafe(queue)\n *\n *   // End the queue\n *   Queue.endUnsafe(queue)\n *\n *   // Ending retains the buffered size while the queue is Closing\n *   const size3 = Queue.sizeUnsafe(queue)\n *   return [size1, size2, size3]\n * })\n *\n * await Effect.runPromise(program) // => [0, 3, 3]\n * ```\n *\n * @category sizes\n * @since 4.0.0\n */\nexport const sizeUnsafe = self => self.state._tag === \"Done\" ? 0 : self.messages.length;\n/**\n * Checks whether the queue is full synchronously.\n *\n * **When to use**\n *\n * Use when an immediate `Queue` capacity snapshot is needed outside effectful\n * code and racing queue changes are acceptable.\n *\n * **Example** (Checking fullness synchronously)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<number, Cause.Done>(3)\n *\n *   const before = Queue.isFullUnsafe(queue)\n *\n *   // Add some messages\n *   yield* Queue.offerAll(queue, [1, 2, 3])\n *\n *   const after = Queue.isFullUnsafe(queue)\n *   return [before, after]\n * })\n *\n * await Effect.runPromise(program) // => [false, true]\n * ```\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isFullUnsafe = self => sizeUnsafe(self) === self.capacity;\n/**\n * Runs an `Effect` into a `Queue`, where success ends the queue and failure\n * fails the queue.\n *\n * **Example** (Running effects into queues)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Exit, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<number, Cause.Done>(10)\n *\n *   // Create an effect that succeeds\n *   const dataProcessing = Effect.gen(function*() {\n *     yield* Effect.yieldNow\n *     return \"Processing completed successfully\"\n *   })\n *\n *   // Pipe the effect into the queue\n *   // If dataProcessing succeeds, queue ends successfully\n *   // If dataProcessing fails, queue fails with the error\n *   const effectIntoQueue = Queue.into(queue)(dataProcessing)\n *\n *   const wasCompleted = yield* effectIntoQueue\n *   const exit = yield* Effect.exit(Queue.take(queue))\n *   return [wasCompleted, exit]\n * })\n *\n * await Effect.runPromise(program) // => [true, Exit.fail(Cause.Done())]\n * ```\n *\n * @category completion\n * @since 4.0.0\n */\nexport const into = /*#__PURE__*/dual(2, (effect, self) => internalEffect.uninterruptibleMask(restore => internalEffect.matchCauseEffect(restore(effect), {\n  onFailure: cause => failCause(self, cause),\n  onSuccess: _ => end(self)\n})));\n// -----------------------------------------------------------------------------\n// internals\n// -----------------------------------------------------------------------------\n//\nconst exitFalse = /*#__PURE__*/core.exitSucceed(false);\nconst exitTrue = /*#__PURE__*/core.exitSucceed(true);\nconst exitFailDone = /*#__PURE__*/core.exitFail(/*#__PURE__*/core.Done());\nconst exitInterrupt = /*#__PURE__*/internalEffect.exitInterrupt();\nconst releaseTakers = self => {\n  if (self.state._tag === \"Done\" || self.state.takers.size === 0) {\n    return;\n  }\n  for (const taker of self.state.takers) {\n    self.state.takers.delete(taker);\n    taker(internalEffect.exitVoid);\n    if (self.messages.length === 0) {\n      break;\n    }\n  }\n};\nconst scheduleReleaseTaker = self => {\n  if (self.scheduleRunning || self.state._tag === \"Done\" || self.state.takers.size === 0) {\n    return;\n  }\n  self.scheduleRunning = true;\n  self.dispatcher.scheduleTask(() => {\n    self.scheduleRunning = false;\n    releaseTakers(self);\n  }, 0);\n};\nconst takeBetweenUnsafe = (self, min, max) => {\n  if (self.state._tag === \"Done\") {\n    return self.state.exit;\n  } else if (max <= 0 || min <= 0) {\n    return core.exitSucceed([]);\n  } else if (self.capacity <= 0 && self.messages.length === 0 && self.state.offers.size > 0) {\n    const messages = [takeOfferUnsafe(self.state.offers)];\n    releaseCapacity(self);\n    return core.exitSucceed(messages);\n  }\n  min = Math.min(min, self.capacity || 1);\n  if (min <= self.messages.length) {\n    const messages = MutableList.takeN(self.messages, max);\n    releaseCapacity(self);\n    return core.exitSucceed(messages);\n  }\n};\nconst offerRemainingSingle = (self, message) => {\n  return internalEffect.callback(resume => {\n    if (self.state._tag !== \"Open\") {\n      return resume(exitFalse);\n    }\n    const entry = {\n      _tag: \"Single\",\n      message,\n      resume\n    };\n    self.state.offers.add(entry);\n    return internalEffect.sync(() => {\n      if (self.state._tag === \"Open\") {\n        self.state.offers.delete(entry);\n      }\n    });\n  });\n};\nconst offerRemainingArray = (self, remaining) => {\n  return internalEffect.callback(resume => {\n    if (self.state._tag !== \"Open\") {\n      return resume(core.exitSucceed(remaining));\n    }\n    const entry = {\n      _tag: \"Array\",\n      remaining,\n      offset: 0,\n      resume\n    };\n    self.state.offers.add(entry);\n    return internalEffect.sync(() => {\n      if (self.state._tag === \"Open\") {\n        self.state.offers.delete(entry);\n      }\n    });\n  });\n};\n// Reserve a pending message for the consumer before the producer can reenter.\nconst takeOfferUnsafe = offers => {\n  const entry = offers.values().next().value;\n  if (entry._tag === \"Single\") {\n    offers.delete(entry);\n    entry.resume(exitTrue);\n    return entry.message;\n  }\n  const message = entry.remaining[entry.offset++];\n  if (entry.offset === entry.remaining.length) {\n    offers.delete(entry);\n    entry.resume(core.exitSucceed([]));\n  }\n  return message;\n};\nconst releaseCapacity = self => {\n  if (self.state._tag === \"Done\") {\n    return Pull.isDoneCause(self.state.exit.cause);\n  } else if (self.state.offers.size === 0) {\n    if (self.state._tag === \"Closing\" && self.messages.length === 0) {\n      finalize(self, self.state.exit);\n      return Pull.isDoneCause(self.state.exit.cause);\n    }\n    return false;\n  }\n  // Resuming a producer can synchronously take, offer, or shut down this queue.\n  for (const entry of self.state.offers) {\n    let n = self.capacity - self.messages.length;\n    if (n <= 0) break;else if (entry._tag === \"Single\") {\n      MutableList.append(self.messages, entry.message);\n      self.state.offers.delete(entry);\n      entry.resume(exitTrue);\n    } else {\n      for (; entry.offset < entry.remaining.length; entry.offset++) {\n        if (n === 0) return false;\n        MutableList.append(self.messages, entry.remaining[entry.offset]);\n        n--;\n      }\n      self.state.offers.delete(entry);\n      entry.resume(core.exitSucceed([]));\n    }\n  }\n  return false;\n};\nconst awaitTake = self => internalEffect.callback(resume => {\n  if (self.state._tag === \"Done\") {\n    return resume(self.state.exit);\n  }\n  self.state.takers.add(resume);\n  return internalEffect.sync(() => {\n    if (self.state._tag !== \"Done\") {\n      self.state.takers.delete(resume);\n    }\n  });\n});\nconst takeAllUnsafe = self => {\n  if (self.messages.length > 0) {\n    const messages = MutableList.takeAll(self.messages);\n    releaseCapacity(self);\n    return messages;\n  } else if (self.state._tag !== \"Done\" && self.state.offers.size > 0) {\n    const messages = [takeOfferUnsafe(self.state.offers)];\n    releaseCapacity(self);\n    return messages;\n  }\n  return [];\n};\nconst finalize = (self, exit) => {\n  if (self.state._tag === \"Done\") {\n    return;\n  }\n  const openState = self.state;\n  self.state = {\n    _tag: \"Done\",\n    exit\n  };\n  for (const taker of openState.takers) {\n    taker(exit);\n  }\n  openState.takers.clear();\n  for (const awaiter of openState.awaiters) {\n    awaiter(exit);\n  }\n  openState.awaiters.clear();\n};\n//# sourceMappingURL=Queue.js.map","import { dual } from \"./Function.js\";\nimport * as core from \"./internal/core.js\";\nimport * as internal from \"./internal/effect.js\";\n/**\n * Creates a `Semaphore` synchronously with the specified total\n * number of permits.\n *\n * **When to use**\n *\n * Use to construct a semaphore synchronously when an immediate value is\n * required outside an Effect workflow.\n *\n * **Example** (Creating an unsafe semaphore)\n *\n * ```ts import.meta.vitest\n * import { Effect, Semaphore } from \"effect\"\n *\n * const semaphore = Semaphore.makeUnsafe(3)\n *\n * const task = (id: number) =>\n *   semaphore.withPermits(1)(\n *     Effect.gen(function*() {\n *       yield* Effect.yieldNow\n *       return id\n *     })\n *   )\n *\n * // Only 3 tasks can run concurrently\n * const program = Effect.all([\n *   task(1),\n *   task(2),\n *   task(3),\n *   task(4),\n *   task(5)\n * ], { concurrency: \"unbounded\" })\n *\n * await Effect.runPromise(program) // => [1, 2, 3, 4, 5]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeUnsafe = permits => new SemaphoreImpl(permits);\nconst waitForPermits = (self, n, effect) => internal.callback(resume => {\n  if (self.free >= n) return resume(effect);\n  const observer = () => {\n    if (self.free < n) return;\n    self.waiters.delete(observer);\n    resume(effect);\n  };\n  self.waiters.add(observer);\n  return internal.sync(() => {\n    self.waiters.delete(observer);\n  });\n});\nclass SemaphoreImpl {\n  waiters = /*#__PURE__*/new Set();\n  taken = 0;\n  permits;\n  constructor(permits) {\n    this.permits = permits;\n  }\n  get free() {\n    return this.permits - this.taken;\n  }\n  take(n) {\n    const take = internal.suspend(() => {\n      if (this.free < n) {\n        return waitForPermits(this, n, take);\n      }\n      this.taken += n;\n      return internal.succeed(n);\n    });\n    return take;\n  }\n  takeIfAvailable(n) {\n    return internal.suspend(() => {\n      if (this.free < n) return internal.succeed(false);\n      this.taken += n;\n      return internal.succeed(true);\n    });\n  }\n  releaseUnsafe(fiber, n) {\n    this.taken -= n;\n    if (this.waiters.size > 0) {\n      fiber.currentDispatcher.scheduleTask(() => {\n        for (const observer of this.waiters) {\n          if (this.free <= 0) break;\n          observer();\n        }\n      }, 0);\n    }\n    return this.free;\n  }\n  resize(permits) {\n    return core.withFiber(fiber => {\n      this.permits = permits;\n      if (this.free < 0) return internal.void;\n      this.releaseUnsafe(fiber, 0);\n      return internal.void;\n    });\n  }\n  release(n) {\n    return core.withFiber(fiber => internal.succeed(this.releaseUnsafe(fiber, n)));\n  }\n  get releaseAll() {\n    return core.withFiber(fiber => internal.succeed(this.releaseUnsafe(fiber, this.taken)));\n  }\n  withPermits(n) {\n    return self => internal.uninterruptibleMask(restore => {\n      const acquire = internal.suspend(() => {\n        if (this.free < n) {\n          const wait = waitForPermits(this, n, internal.void);\n          return internal.flatMap(restore(wait), () => acquire);\n        }\n        this.taken += n;\n        return internal.onExitPrimitive(restore(self), () => {\n          this.releaseUnsafe(internal.getCurrentFiber(), n);\n          return undefined;\n        }, true);\n      });\n      return acquire;\n    });\n  }\n  withPermit = /*#__PURE__*/this.withPermits(1);\n  withPermitsIfAvailable(n) {\n    return self => internal.uninterruptibleMask(restore => {\n      if (this.free < n) return internal.succeedNone;\n      this.taken += n;\n      return internal.onExitPrimitive(restore(internal.asSome(self)), () => {\n        this.releaseUnsafe(internal.getCurrentFiber(), n);\n        return undefined;\n      }, true);\n    });\n  }\n}\n/**\n * Creates a `Semaphore` initialized with the specified total number of permits.\n *\n * **When to use**\n *\n * Use to create a semaphore inside Effect code for bounding concurrency with\n * automatic or manual permit management.\n *\n * **Example** (Creating a semaphore)\n *\n * ```ts import.meta.vitest\n * import { Effect, Semaphore } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const semaphore = yield* Semaphore.make(2)\n *\n *   const task = (id: number) =>\n *     semaphore.withPermits(1)(\n *       Effect.gen(function*() {\n *         yield* Effect.yieldNow\n *         return id\n *       })\n *     )\n *\n *   // Run 4 tasks, but only 2 can run concurrently\n *   return yield* Effect.all([task(1), task(2), task(3), task(4)])\n * })\n *\n * await Effect.runPromise(program) // => [1, 2, 3, 4]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = permits => internal.sync(() => new SemaphoreImpl(permits));\n/**\n * Sets the total number of permits managed by the semaphore.\n *\n * **When to use**\n *\n * Use to change the concurrency limit of an existing semaphore while keeping\n * current acquisitions in place.\n *\n * **Details**\n *\n * Existing acquisitions remain taken after resizing. If the new total is less\n * than the currently taken permit count, new acquisitions wait until enough\n * permits are released.\n *\n * @see {@link make} for creating a semaphore with an initial permit count\n * @see {@link release} for returning permits without changing semaphore capacity\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const resize = /*#__PURE__*/dual(2, (self, permits) => self.resize(permits));\n/**\n * Runs an effect with the given number of permits and releases the permits when\n * the effect completes.\n *\n * **When to use**\n *\n * Use to run an effect while holding a specified number of semaphore permits\n * for the duration of that effect.\n *\n * **Details**\n *\n * The effect waits until enough permits are available. Acquired permits are\n * released when the wrapped effect exits.\n *\n * @see {@link withPermit} for acquiring exactly one permit\n * @see {@link withPermitsIfAvailable} for running only when permits are immediately available\n * @see {@link take} for manually acquiring permits\n * @see {@link release} for manually returning permits\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withPermits = (self, permits, effect) => {\n  const withPermits = self.withPermits(permits);\n  return effect ? withPermits(effect) : withPermits;\n};\n/**\n * Runs an effect with a single permit and releases the permit when the effect\n * completes.\n *\n * **When to use**\n *\n * Use to guard an effect with exactly one semaphore permit while automatically\n * releasing that permit when the effect exits.\n *\n * @see {@link withPermits} for acquiring more than one permit\n * @see {@link withPermitsIfAvailable} for running only when permits are immediately available\n * @see {@link take} for manually acquiring permits\n * @see {@link release} for manually returning permits\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withPermit = (self, effect) => {\n  if (!effect) return self.withPermit;\n  return self.withPermit(effect);\n};\n/**\n * Runs an effect only if the specified number of permits are immediately\n * available.\n *\n * **When to use**\n *\n * Use when guarded work should run only if the requested permits are\n * immediately available.\n *\n * **Details**\n *\n * When the permits are unavailable, the effect is not run and the result is\n * `Option.none`. When permits are available, the effect is run, its result is\n * wrapped in `Option.some`, and the acquired permits are released when the\n * effect exits.\n *\n * @see {@link withPermits} for the variant that waits until permits are available\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withPermitsIfAvailable = (self, permits, effect) => {\n  const withPermits = self.withPermitsIfAvailable(permits);\n  return effect ? withPermits(effect) : withPermits;\n};\n/**\n * Acquires the specified number of permits and returns the acquired permit\n * count.\n *\n * **When to use**\n *\n * Use when you need manual permit acquisition for a lower-level protocol with\n * explicit acquisition and release control.\n *\n * **Details**\n *\n * The effect waits until enough permits are available.\n *\n * @see {@link withPermit} for automatically acquiring and releasing one permit around an effect\n * @see {@link withPermits} for automatically acquiring and releasing multiple permits around an effect\n * @see {@link takeIfAvailable} for manually acquiring permits without waiting\n * @see {@link release} for returning manually acquired permits\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const take = /*#__PURE__*/dual(2, (self, permits) => self.take(permits));\n/**\n * Acquires the specified number of permits only if they are immediately\n * available.\n *\n * **When to use**\n *\n * Use when you need fail-fast manual permit acquisition for a lower-level\n * protocol with explicit acquisition and release control.\n *\n * **Details**\n *\n * If enough permits are available, they are acquired and the effect returns\n * `true`. Otherwise, the effect returns `false` immediately without acquiring\n * any permits.\n *\n * @see {@link take} for the variant that waits until permits are available\n * @see {@link release} for returning manually acquired permits\n * @see {@link withPermitsIfAvailable} for automatic acquisition and release around an effect\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const takeIfAvailable = /*#__PURE__*/dual(2, (self, permits) => self.takeIfAvailable(permits));\n/**\n * Releases the specified number of permits and returns the resulting available\n * permits.\n *\n * **When to use**\n *\n * Use when you need to return permits acquired with `take` in a lower-level\n * permit protocol with explicit release control.\n *\n * **Details**\n *\n * Running the effect releases the requested permits, wakes waiting acquirers\n * when permits become available, and returns the current available permit\n * count.\n *\n * **Gotchas**\n *\n * Manual `take` / `release` usage must keep permit counts balanced. Prefer\n * `withPermit` or `withPermits` when the acquisition can be scoped to one\n * effect.\n *\n * @see {@link take} for manually acquiring permits\n * @see {@link releaseAll} for returning every currently taken permit\n * @see {@link withPermits} for automatic acquire and release around an effect\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const release = /*#__PURE__*/dual(2, (self, permits) => self.release(permits));\n/**\n * Releases all permits held by this semaphore and returns the resulting\n * available permits.\n *\n * **When to use**\n *\n * Use to return every currently taken permit to a semaphore at once, typically\n * during cleanup of manual `take` / `release` protocols.\n *\n * @see {@link release} for releasing a known permit count\n * @see {@link withPermits} for automatic acquire and release around an effect\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const releaseAll = self => self.releaseAll;\n//# sourceMappingURL=Semaphore.js.map","/**\n * Provides low-level building blocks for streaming data through Effect.\n *\n * A `Channel` can read input elements, write output elements, fail with a typed\n * error, and finish with a typed result while managing resources safely.\n * Streams and sinks are built on channels, so most application code uses those\n * higher-level modules instead. This module is useful when implementing stream\n * operators or specialized streaming workflows.\n *\n * @since 2.0.0\n */\n// @effect-diagnostics returnEffectInGen:off\nimport * as Arr from \"./Array.js\";\nimport * as Cause from \"./Cause.js\";\nimport * as Chunk from \"./Chunk.js\";\nimport * as Context from \"./Context.js\";\nimport * as Effect from \"./Effect.js\";\nimport * as Exit from \"./Exit.js\";\nimport * as Fiber from \"./Fiber.js\";\nimport { constant, constTrue, constVoid, dual, identity as identity_ } from \"./Function.js\";\nimport * as Count from \"./internal/count.js\";\nimport { ClockRef, endSpan, scopeFinalizerCountUnsafe } from \"./internal/effect.js\";\nimport { addSpanStackTrace } from \"./internal/tracer.js\";\nimport * as Iterable from \"./Iterable.js\";\nimport * as Latch from \"./Latch.js\";\nimport * as Layer from \"./Layer.js\";\nimport * as MutableRef from \"./MutableRef.js\";\nimport * as Option from \"./Option.js\";\nimport { pipeArguments } from \"./Pipeable.js\";\nimport { hasProperty, isTagged } from \"./Predicate.js\";\nimport * as PubSub from \"./PubSub.js\";\nimport * as Pull from \"./Pull.js\";\nimport * as Queue from \"./Queue.js\";\nimport { TracerTimingEnabled } from \"./References.js\";\nimport * as Result from \"./Result.js\";\nimport * as Schedule from \"./Schedule.js\";\nimport * as Scope from \"./Scope.js\";\nimport * as Semaphore from \"./Semaphore.js\";\nimport * as String from \"./String.js\";\nimport * as Take from \"./Take.js\";\nimport { ParentSpan } from \"./Tracer.js\";\n/**\n * Runtime identifier stored on `Channel` values and used by `isChannel` to\n * recognize them.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const TypeId = \"~effect/Channel\";\n/**\n * Checks whether a value is a `Channel`.\n *\n * **Example** (Checking for channels)\n *\n * ```ts import.meta.vitest\n * import { Channel } from \"effect\"\n *\n * const channel = Channel.succeed(42)\n * Channel.isChannel(channel) // => true\n * Channel.isChannel(\"not a channel\") // => false\n * ```\n *\n * @category guards\n * @since 3.5.4\n */\nexport const isChannel = u => hasProperty(u, TypeId);\nconst ChannelProto = {\n  [TypeId]: {\n    _Env: identity_,\n    _InErr: identity_,\n    _InElem: identity_,\n    _OutErr: identity_,\n    _OutElem: identity_\n  },\n  pipe() {\n    return pipeArguments(this, arguments);\n  }\n};\n// -----------------------------------------------------------------------------\n// Constructors\n// -----------------------------------------------------------------------------\n/**\n * Creates a `Channel` from a transformation function that operates on upstream pulls.\n *\n * **Example** (Creating channels from transforms)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const channel = Channel.fromTransform((upstream, scope) =>\n *   Effect.succeed(upstream)\n * )\n * await Effect.runPromise(Channel.runCollect(channel)) // => []\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromTransform = transform => {\n  const self = Object.create(ChannelProto);\n  self.transform = (upstream, scope) => Effect.catchCause(transform(upstream, scope), cause => Effect.succeed(Effect.failCause(cause)));\n  return self;\n};\n/**\n * Transforms a Channel by applying a function to its Pull implementation.\n *\n * **Example** (Transforming pull behavior)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * // Transform a channel by modifying its pull behavior\n * const originalChannel = Channel.fromIterable([1, 2, 3])\n *\n * const transformedChannel = Channel.transformPull(\n *   originalChannel,\n *   (pull, scope) =>\n *     Effect.succeed(\n *       Effect.map(pull, (value) => value * 2)\n *     )\n * )\n * await Effect.runPromise(Channel.runCollect(transformedChannel)) // => [2, 4, 6]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const transformPull = (self, f) => fromTransform((upstream, scope) => Effect.flatMap(toTransform(self)(upstream, scope), pull => f(pull, scope)));\n/**\n * Creates a `Channel` from an `Effect` that produces a `Pull`.\n *\n * **Example** (Creating channels from pulls)\n *\n * ```ts import.meta.vitest\n * import { Cause, Channel, Effect } from \"effect\"\n *\n * const channel = Channel.fromPull(Effect.sync(() => {\n *   let emitted = false\n *   return Effect.suspend(() => {\n *     if (emitted) return Cause.done()\n *     emitted = true\n *     return Effect.succeed(42)\n *   })\n * }))\n * await Effect.runPromise(Channel.runCollect(channel)) // => [42]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromPull = effect => fromTransform((_, __) => effect);\n/**\n * Creates a `Channel` from a transformation function that operates on upstream\n * pulls, but also provides a forked scope that closes when the resulting\n * Channel completes.\n *\n * **When to use**\n *\n * Use when building channels that require scoped resource lifecycle management,\n * providing both the channel scope and a forked scope that automatically closes\n * when the channel completes.\n *\n * @see {@link fromTransform} for a simpler transformation without a forked scope\n * @category constructors\n * @since 4.0.0\n */\nexport const fromTransformBracket = f => fromTransform(Effect.fnUntraced(function* (upstream, scope) {\n  const closableScope = Scope.forkUnsafe(scope);\n  const onCause = cause => Scope.close(closableScope, Pull.doneExitFromCause(cause));\n  const pull = yield* Effect.onError(f(upstream, scope, closableScope), onCause);\n  return Effect.onError(pull, onCause);\n}));\n/**\n * Converts a `Channel` back to its underlying transformation function.\n *\n * **Example** (Extracting channel transforms)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const channel = Channel.succeed(42)\n * const transform = Channel.toTransform(channel)\n * typeof transform // => \"function\"\n * Effect.runSync(Channel.runCollect(channel)) // => [42]\n * ```\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const toTransform = channel => channel.transform;\n/**\n * The default chunk size used by channels for batching operations.\n *\n * **Example** (Reading the default chunk size)\n *\n * ```ts import.meta.vitest\n * import { Channel } from \"effect\"\n *\n * Channel.DefaultChunkSize // => 4096\n * ```\n *\n * @category constants\n * @since 4.0.0\n */\nexport const DefaultChunkSize = 4096;\nconst asyncQueue = (scope, f, options) => Queue.make({\n  capacity: options?.bufferSize,\n  strategy: options?.strategy\n}).pipe(Effect.tap(queue => Scope.addFinalizer(scope, Queue.shutdown(queue))), Effect.tap(queue => Effect.forkIn(Scope.provide(f(queue), scope), scope)));\n/**\n * Creates a `Channel` that interacts with a callback function using a queue.\n *\n * **Example** (Creating channels from callbacks)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect, Queue } from \"effect\"\n *\n * const channel = Channel.callback<number>((queue) =>\n *   Effect.gen(function*() {\n *     yield* Queue.offer(queue, 1)\n *     yield* Queue.offer(queue, 2)\n *     yield* Queue.offer(queue, 3)\n *     yield* Queue.end(queue)\n *   })\n * )\n * await Effect.runPromise(Channel.runCollect(channel)) // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const callback = (f, options) => fromTransform((_, scope) => Effect.map(asyncQueue(scope, f, options), Queue.take));\n/**\n * Creates a `Channel` that interacts with a callback function using a queue, emitting arrays.\n *\n * **Example** (Creating array channels from callbacks)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect, Queue } from \"effect\"\n *\n * const channel = Channel.callbackArray<number>(Effect.fn(function*(queue) {\n *   yield* Queue.offer(queue, 1)\n *   yield* Queue.offer(queue, 2)\n *   yield* Queue.end(queue)\n * }))\n * await Effect.runPromise(Channel.runCollect(channel)) // => [[1, 2]]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const callbackArray = (f, options) => fromTransform((_, scope) => Effect.map(asyncQueue(scope, f, options), Queue.takeAll));\n/**\n * Creates a `Channel` that lazily evaluates to another channel.\n *\n * **Example** (Suspending channel creation)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const channel = Channel.suspend(() => Channel.succeed(42))\n * Effect.runSync(Channel.runCollect(channel)) // => [42]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const suspend = evaluate => fromTransform((upstream, scope) => Effect.suspend(() => toTransform(evaluate())(upstream, scope)));\n/**\n * Acquires a resource, uses it to build a `Channel`, and guarantees that\n * `release` runs with the channel's `Exit` when the channel completes, fails,\n * or is interrupted.\n *\n * **Details**\n *\n * Acquisition is uninterruptible. If acquisition fails, `use` is not run and\n * `release` is not registered.\n *\n * **Example** (Managing resources with acquire-use-release)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const released: Array<string> = []\n * const channel = Channel.acquireUseRelease(\n *   Effect.succeed(\"resource\"),\n *   (resource) => Channel.succeed(resource.toUpperCase()),\n *   (resource, exit) => Effect.sync(() => released.push(resource))\n * )\n * const observed = [await Effect.runPromise(Channel.runCollect(channel)), released] // => [[\"RESOURCE\"], [\"resource\"]]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const acquireUseRelease = (acquire, use, release) => fromTransformBracket(Effect.fnUntraced(function* (upstream, scope, forkedScope) {\n  let option = Option.none();\n  yield* Scope.addFinalizerExit(forkedScope, exit => Option.isSome(option) ? release(option.value, exit) : Effect.void);\n  const value = yield* Effect.uninterruptible(acquire);\n  option = Option.some(value);\n  return yield* toTransform(use(value))(upstream, scope);\n}));\n/**\n * Acquires a resource, emits the acquired value as a single channel element,\n * and registers `release` in the channel scope.\n *\n * **Details**\n *\n * The release action runs when the channel scope closes and receives the scope\n * exit. If acquisition fails, no element is emitted and `release` is not\n * registered.\n *\n * **Example** (Managing resources with acquire-release)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const released: Array<string> = []\n * const channel = Channel.acquireRelease(\n *   Effect.succeed(\"resource\"),\n *   (resource, exit) => Effect.sync(() => released.push(resource))\n * )\n * const observed = [await Effect.runPromise(Channel.runCollect(channel)), released] // => [[\"resource\"], [\"resource\"]]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const acquireRelease = /*#__PURE__*/dual(2, (self, release) => unwrap(Effect.map(Effect.acquireRelease(self, release), succeed)));\n/**\n * Creates a `Channel` from an iterator.\n *\n * **Example** (Creating channels from iterators)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4, 5]\n * const channel = Channel.fromIterator(() => numbers[Symbol.iterator]())\n * Effect.runSync(Channel.runCollect(channel)) // => [1, 2, 3, 4, 5]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromIterator = iterator => fromPull(Effect.sync(() => {\n  const iter = iterator();\n  return Effect.suspend(() => {\n    const state = iter.next();\n    return state.done ? Cause.done(state.value) : Effect.succeed(state.value);\n  });\n}));\n/**\n * Creates a `Channel` that emits all elements from an array.\n *\n * **Example** (Creating channels from arrays)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const channel = Channel.fromArray([1, 2, 3, 4, 5])\n * Effect.runSync(Channel.runCollect(channel)) // => [1, 2, 3, 4, 5]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromArray = array => fromPull(Effect.sync(() => {\n  let index = 0;\n  return Effect.suspend(() => index >= array.length ? Cause.done() : Effect.succeed(array[index++]));\n}));\n/**\n * Creates a `Channel` that emits all elements from a chunk.\n *\n * **Example** (Creating channels from chunks)\n *\n * ```ts import.meta.vitest\n * import { Channel, Chunk, Effect } from \"effect\"\n *\n * const chunk = Chunk.make(1, 2, 3)\n * const channel = Channel.fromChunk(chunk)\n * Effect.runSync(Channel.runCollect(channel)) // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromChunk = chunk => fromArray(Chunk.toReadonlyArray(chunk));\n/**\n * Creates a `Channel` from an iterator that emits arrays of elements.\n *\n * **Details**\n *\n * Finite fractional `chunkSize` values are rounded down. `NaN` and non-positive\n * values are treated as `1` so every successful pull emits a non-empty array.\n *\n * **Example** (Batching iterator output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * // Create a channel from a simple iterator\n * const numberIterator = (): Iterator<number, string> => {\n *   let count = 0\n *   return {\n *     next: () => {\n *       if (count < 3) {\n *         return { value: count++, done: false }\n *       }\n *       return { value: \"finished\", done: true }\n *     }\n *   }\n * }\n *\n * const channel = Channel.fromIteratorArray(() => numberIterator(), 2)\n * Effect.runSync(Channel.runCollect(channel)) // => [[0, 1], [2]]\n * ```\n *\n * **Example** (Batching generator output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * // Create channel from a generator function\n * function* fibonacci(): Generator<number, void, unknown> {\n *   let a = 0, b = 1\n *   for (let i = 0; i < 5; i++) {\n *     yield a\n *     ;[a, b] = [b, a + b]\n *   }\n * }\n *\n * const fibChannel = Channel.fromIteratorArray(() => fibonacci(), 3)\n * Effect.runSync(Channel.runCollect(fibChannel)) // => [[0, 1, 1], [2, 3]]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromIteratorArray = (iterator, chunkSize = DefaultChunkSize) => {\n  const size = Count.normalizeNonEmpty(chunkSize);\n  return fromPull(Effect.sync(() => {\n    const iter = iterator();\n    let done = Option.none();\n    return Effect.suspend(() => {\n      if (done._tag === \"Some\") return Cause.done(done.value);\n      const buffer = [];\n      while (buffer.length < size) {\n        const state = iter.next();\n        if (state.done) {\n          if (buffer.length === 0) {\n            return Cause.done(state.value);\n          }\n          done = Option.some(state.value);\n          break;\n        }\n        buffer.push(state.value);\n      }\n      return Effect.succeed(buffer);\n    });\n  }));\n};\n/**\n * Creates a `Channel` that emits all elements from an iterable.\n *\n * **Example** (Creating channels from iterables)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const set = new Set([1, 2, 3])\n * const channel = Channel.fromIterable(set)\n * Effect.runSync(Channel.runCollect(channel)) // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromIterable = iterable => fromIterator(() => iterable[Symbol.iterator]());\n/**\n * Creates a `Channel` that emits arrays of elements from an iterable.\n *\n * **Details**\n *\n * Finite fractional `chunkSize` values are rounded down. `NaN` and non-positive\n * values are treated as `1`.\n *\n * **Example** (Batching iterable output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4, 5]\n * const channel = Channel.fromIterableArray(numbers, 4)\n * Effect.runSync(Channel.runCollect(channel)) // => [[1, 2, 3, 4], [5]]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromIterableArray = (iterable, chunkSize = DefaultChunkSize) => fromIteratorArray(() => iterable[Symbol.iterator](), chunkSize);\n/**\n * Creates a `Channel` that emits a single value and then ends.\n *\n * **Example** (Creating channels that succeed)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const channel = Channel.succeed(42)\n * Effect.runSync(Channel.runCollect(channel)) // => [42]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const succeed = value => fromEffect(Effect.succeed(value));\n/**\n * Creates a `Channel` that immediately ends with the specified value.\n *\n * **Example** (Ending with a value)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const channel = Channel.end(\"done\")\n * Effect.runSync(Channel.runCollect(channel)) // => []\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const end = value => fromPull(Effect.succeed(Cause.done(value)));\n/**\n * Creates a `Channel` that immediately ends with the lazily evaluated value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const endSync = evaluate => fromPull(Effect.sync(() => Cause.done(evaluate())));\n/**\n * Creates a `Channel` that emits a single value computed by a lazy evaluation.\n *\n * **Example** (Computing values lazily)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * let requests = 0\n *\n * const channel = Channel.sync(() => {\n *   requests += 1\n *   return `request-${requests}`\n * })\n * Effect.runSync(Channel.runCollect(channel)) // => [\"request-1\"]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const sync = evaluate => fromEffect(Effect.sync(evaluate));\n/**\n * Represents a `Channel` that emits no elements.\n *\n * **Example** (Creating empty channels)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * // Create an empty channel\n * const emptyChannel = Channel.empty\n *\n * // Use empty channel in composition\n * const combined = Channel.concatWith(emptyChannel, () => Channel.succeed(42))\n * // Will immediately provide the second channel's output\n *\n * // Empty channel can be used as a no-op in conditional logic\n * const conditionalChannel = (shouldEmit: boolean) =>\n *   shouldEmit ? Channel.succeed(\"data\") : Channel.empty\n *\n * Effect.runSync(Channel.runCollect(conditionalChannel(true))) // => [\"data\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const empty = /*#__PURE__*/fromPull(/*#__PURE__*/Effect.succeed(/*#__PURE__*/Cause.done()));\n/**\n * Represents a `Channel` that never completes.\n *\n * **Example** (Creating non-terminating channels)\n *\n * ```ts import.meta.vitest\n * import { Channel } from \"effect\"\n *\n * // Create a channel that never completes\n * const neverChannel = Channel.never\n *\n * // Use in conditional logic\n * const withFallback = Channel.concatWith(\n *   neverChannel,\n *   () => Channel.succeed(\"fallback\")\n * )\n *\n * // Never channel is useful for testing or as a placeholder\n * const conditionalChannel = (shouldComplete: boolean) =>\n *   shouldComplete ? Channel.succeed(\"done\") : Channel.never\n *\n * Channel.isChannel(conditionalChannel(false)) // => true\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const never = /*#__PURE__*/fromPull(/*#__PURE__*/Effect.succeed(Effect.never));\n/**\n * Constructs a channel that fails immediately with the specified error.\n *\n * **Example** (Failing with an error)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect, Exit } from \"effect\"\n *\n * const failedChannel = Channel.fail(\"Something went wrong\")\n * Effect.runSync(Effect.exit(Channel.runCollect(failedChannel))) // => Exit.fail(\"Something went wrong\")\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fail = error => fromPull(Effect.succeed(Effect.fail(error)));\n/**\n * Constructs a channel that fails immediately with the specified lazily\n * evaluated error.\n *\n * **When to use**\n *\n * Use when the error value should be computed each time the channel runs instead\n * of when the channel is constructed.\n *\n * **Example** (Failing with a lazy error)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect, Exit } from \"effect\"\n *\n * let attempts = 0\n * const conditionalError = Channel.failSync(() => {\n *   attempts += 1\n *   return `Error after attempt ${attempts}`\n * })\n * const observed = [\n *   Effect.runSync(Effect.exit(Channel.runCollect(conditionalError))),\n *   attempts\n * ] // => [Exit.fail(\"Error after attempt 1\"), 1]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const failSync = evaluate => fromPull(Effect.failSync(evaluate));\n/**\n * Constructs a channel that fails immediately with the specified `Cause`.\n *\n * **When to use**\n *\n * Use when the channel failure must preserve a full `Cause`, such as defects,\n * interruptions, or combined failures.\n *\n * **Example** (Failing with causes)\n *\n * ```ts import.meta.vitest\n * import { Cause, Channel, Effect, Exit } from \"effect\"\n *\n * const simpleCause = Cause.fail(\"Simple error\")\n * const failedChannel = Channel.failCause(simpleCause)\n * Effect.runSync(Effect.exit(Channel.runCollect(failedChannel))) // => Exit.failCause(simpleCause)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const failCause = cause => fromPull(Effect.failCause(cause));\n/**\n * Constructs a channel that fails immediately with the specified lazily\n * evaluated `Cause`.\n *\n * **Example** (Failing with lazy causes)\n *\n * ```ts import.meta.vitest\n * import { Cause, Channel, Effect, Exit } from \"effect\"\n *\n * // Create a channel that fails with a lazily computed cause\n * let attempts = 0\n * const failedChannel = Channel.failCauseSync(() => {\n *   attempts += 1\n *   return Cause.fail(`Runtime error after attempt ${attempts}`)\n * })\n *\n * const observed = [\n *   Effect.runSync(Effect.exit(Channel.runCollect(failedChannel))),\n *   attempts\n * ] // => [Exit.fail(\"Runtime error after attempt 1\"), 1]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const failCauseSync = evaluate => fromPull(Effect.failCauseSync(evaluate));\n/**\n * Constructs a channel that fails immediately with the specified defect.\n *\n * **Example** (Dying with defects)\n *\n * ```ts import.meta.vitest\n * import { Cause, Channel, Effect, Exit } from \"effect\"\n *\n * const defect = \"Unrecoverable error\"\n * const diedChannel = Channel.die(defect)\n * Effect.runSync(Effect.exit(Channel.runCollect(diedChannel))) // => Exit.failCause(Cause.die(defect))\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const die = defect => failCause(Cause.die(defect));\n/**\n * Uses an effect to write a single value to the channel.\n *\n * **Example** (Creating channels from effects)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const successChannel = Channel.fromEffect(\n *   Effect.succeed(\"Hello from effect!\")\n * )\n * Effect.runSync(Channel.runCollect(successChannel)) // => [\"Hello from effect!\"]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromEffect = effect => fromPull(Effect.sync(() => {\n  let done = false;\n  return Effect.suspend(() => {\n    if (done) return Cause.done();\n    done = true;\n    return effect;\n  });\n}));\n/**\n * Creates a channel that evaluates an effect and uses its successful value as\n * the channel's done value without emitting any output elements.\n *\n * **Details**\n *\n * If the effect fails, the channel fails with the effect's error.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromEffectDone = effect => fromPull(Effect.succeed(Effect.flatMap(effect, Cause.done)));\n/**\n * Uses an effect and discards its result.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromEffectDrain = effect => fromPull(Effect.flatMap(effect, () => Cause.done()));\n/**\n * Creates a channel from an effect that produces a `Take`.\n *\n * **Details**\n *\n * A successful `Take` emits a non-empty array of output elements. A failed\n * `Take` fails the channel. A done `Take` completes the channel with its done\n * value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromEffectTake = effect => fromPull(Effect.succeed(Effect.flatMap(effect, Take.toPull)));\n/**\n * Creates a channel from a queue.\n *\n * **Example** (Creating channels from queues)\n *\n * ```ts import.meta.vitest\n * import { Cause, Channel, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<string, Cause.Done>(3)\n *   yield* Queue.offerAll(queue, [\"item1\", \"item2\", \"item3\"])\n *   yield* Queue.end(queue)\n *   const channel = Channel.fromQueue(queue)\n *   return yield* Channel.runCollect(channel)\n * })\n * await Effect.runPromise(program) // => [\"item1\", \"item2\", \"item3\"]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromQueue = queue => fromPull(Effect.succeed(Queue.take(queue)));\n/**\n * Creates a channel from a queue that emits arrays of elements.\n *\n * **Example** (Creating batched channels from queues)\n *\n * ```ts import.meta.vitest\n * import { Cause, Channel, Effect, Queue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<number, Cause.Done>(4)\n *   yield* Queue.offerAll(queue, [1, 2, 3, 4])\n *   yield* Queue.end(queue)\n *   const arrayChannel = Channel.fromQueueArray(queue)\n *   return yield* Channel.runCollect(arrayChannel)\n * })\n * await Effect.runPromise(program) // => [[1, 2, 3, 4]]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromQueueArray = queue => fromPull(Effect.succeed(Queue.takeAll(queue)));\n/**\n * Creates a channel that forwards upstream input elements, input errors, and\n * the upstream done value unchanged.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const identity = () => fromTransform((upstream, _scope) => Effect.succeed(upstream));\n/**\n * Creates a channel from a PubSub subscription.\n *\n * **Example** (Creating channels from subscriptions)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect, Option, PubSub } from \"effect\"\n *\n * class SubscriptionError extends Data.TaggedError(\"SubscriptionError\")<{\n *   readonly reason: string\n * }> {}\n *\n * const program = Effect.gen(function*() {\n *   // Create a PubSub\n *   const pubsub = yield* PubSub.bounded<string>(32)\n *\n *   // Create a subscription\n *   const subscription = yield* PubSub.subscribe(pubsub)\n *\n *   // Publish some messages\n *   yield* PubSub.publish(pubsub, \"Hello\")\n *   yield* PubSub.publish(pubsub, \"World\")\n *   yield* PubSub.publish(pubsub, \"from\")\n *   yield* PubSub.publish(pubsub, \"PubSub\")\n *\n *   // Create a channel from the subscription\n *   const channel = Channel.fromSubscription(subscription)\n *\n *   // The channel will receive all published messages\n *   return channel\n * })\n * const result = Effect.scoped(Effect.flatMap(program, Channel.runHead))\n * await Effect.runPromise(result) // => Option.some(\"Hello\")\n *\n * // Real-time notifications example\n * const notificationChannel = Effect.gen(function*() {\n *   const eventBus = yield* PubSub.unbounded<{ type: string; payload: any }>()\n *   const userSubscription = yield* PubSub.subscribe(eventBus)\n *\n *   return Channel.fromSubscription(userSubscription)\n * })\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromSubscription = subscription => fromPull(Effect.succeed(Effect.onInterrupt(PubSub.take(subscription), () => Cause.done())));\n/**\n * Creates a channel from a PubSub subscription that outputs arrays of values.\n *\n * **Details**\n *\n * This constructor creates a channel that reads from a PubSub subscription and outputs\n * arrays of values in chunks. It's useful when you want to process multiple values at once\n * for better performance.\n *\n * **Example** (Batching subscription values)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect, Option, PubSub } from \"effect\"\n *\n * class StreamError extends Data.TaggedError(\"StreamError\")<{\n *   readonly message: string\n * }> {}\n *\n * const program = Effect.gen(function*() {\n *   const pubsub = yield* PubSub.bounded<number>(16)\n *   const subscription = yield* PubSub.subscribe(pubsub)\n *\n *   // Create a channel that reads arrays of values\n *   const channel = Channel.fromSubscriptionArray(subscription)\n *\n *   // Publish some values\n *   yield* PubSub.publish(pubsub, 1)\n *   yield* PubSub.publish(pubsub, 2)\n *   yield* PubSub.publish(pubsub, 3)\n *   yield* PubSub.publish(pubsub, 4)\n *\n *   // The channel will output arrays like [1, 2, 3] and [4]\n *   return channel\n * })\n * const result = Effect.scoped(Effect.flatMap(program, Channel.runHead))\n * await Effect.runPromise(result) // => Option.some([1, 2, 3, 4])\n * ```\n *\n * **Example** (Processing subscription values in batches)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect, Option, PubSub } from \"effect\"\n *\n * class BatchProcessingError extends Data.TaggedError(\"BatchProcessingError\")<{\n *   readonly reason: string\n * }> {}\n *\n * const batchProcessor = Effect.gen(function*() {\n *   const pubsub = yield* PubSub.bounded<string>(32)\n *   const subscription = yield* PubSub.subscribe(pubsub)\n *\n *   // Create a channel that processes items in batches\n *   const batchChannel = Channel.fromSubscriptionArray(subscription)\n *\n *   // Transform to process each batch\n *   const processedChannel = Channel.map(batchChannel, (batch) =>\n *     batch.map((item) => item.toUpperCase())\n *   )\n *\n *   yield* PubSub.publishAll(pubsub, [\"one\", \"two\"])\n *   return processedChannel\n * })\n * const batch = Effect.scoped(Effect.flatMap(batchProcessor, Channel.runHead))\n * await Effect.runPromise(batch) // => Option.some([\"ONE\", \"TWO\"])\n * ```\n *\n * **Example** (Aggregating subscription metrics)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect, Option, PubSub } from \"effect\"\n *\n * const metricsAggregator = Effect.gen(function*() {\n *   const metricsPubSub = yield* PubSub.bounded<\n *     { timestamp: number; value: number }\n *   >(100)\n *   const subscription = yield* PubSub.subscribe(metricsPubSub)\n *\n *   // Create a channel that collects metrics in chunks\n *   const metricsChannel = Channel.fromSubscriptionArray(subscription)\n *\n *   // Transform to calculate aggregate statistics\n *   const aggregatedChannel = Channel.map(metricsChannel, (metrics) => {\n *     const values = metrics.map((m) => m.value)\n *     const sum = values.reduce((a, b) => a + b, 0)\n *     const avg = sum / values.length\n *     const min = Math.min(...values)\n *     const max = Math.max(...values)\n *\n *     return {\n *       count: values.length,\n *       sum,\n *       average: avg,\n *       min,\n *       max,\n *       firstTimestamp: Math.min(...metrics.map((m) => m.timestamp)),\n *       lastTimestamp: Math.max(...metrics.map((m) => m.timestamp))\n *     }\n *   })\n *\n *   yield* PubSub.publish(metricsPubSub, { timestamp: 1, value: 10 })\n *   return aggregatedChannel\n * })\n * const metric = Effect.scoped(Effect.flatMap(metricsAggregator, Channel.runHead))\n * const result = await Effect.runPromise(metric)\n * Option.map(result, ({ count, sum, average, min, max }) => ({ count, sum, average, min, max })) // => Option.some({ count: 1, sum: 10, average: 10, min: 10, max: 10 })\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromSubscriptionArray = subscription => fromPull(Effect.succeed(Effect.onInterrupt(PubSub.takeAll(subscription), () => Cause.done())));\n/**\n * Creates a channel from a PubSub that outputs individual values.\n *\n * **Details**\n *\n * This constructor creates a channel that reads from a PubSub by automatically\n * subscribing to it. The channel outputs individual values as they are published\n * to the PubSub, making it ideal for real-time streaming scenarios.\n *\n * **Example** (Creating channels from PubSubs)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect, Option, PubSub } from \"effect\"\n *\n * class StreamError extends Data.TaggedError(\"StreamError\")<{\n *   readonly message: string\n * }> {}\n *\n * const program = Effect.gen(function*() {\n *   const pubsub = yield* PubSub.unbounded<number>({ replay: 3 })\n *\n *   // Create a channel that reads individual values\n *   const channel = Channel.fromPubSub(pubsub)\n *\n *   // Publish some values\n *   yield* PubSub.publish(pubsub, 1)\n *   yield* PubSub.publish(pubsub, 2)\n *   yield* PubSub.publish(pubsub, 3)\n *\n *   // The channel will output: 1, 2, 3 (individual values)\n *   return channel\n * })\n * const result = Effect.scoped(Effect.flatMap(program, Channel.runHead))\n * await Effect.runPromise(result) // => Option.some(1)\n * ```\n *\n * **Example** (Streaming PubSub notifications)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect, Option, PubSub } from \"effect\"\n *\n * const notificationService = Effect.gen(function*() {\n *   const notificationPubSub = yield* PubSub.unbounded<string>({ replay: 1 })\n *\n *   // Create a channel for real-time notifications\n *   const notificationChannel = Channel.fromPubSub(notificationPubSub)\n *\n *   // Transform notifications to add timestamps\n *   const receivedAt = \"2024-01-01T00:00:00.000Z\"\n *   const timestampedChannel = Channel.map(notificationChannel, (message) => ({\n *     message,\n *     receivedAt,\n *     id: `notification:${message}`\n *   }))\n *\n *   yield* PubSub.publish(notificationPubSub, \"ready\")\n *   return timestampedChannel\n * })\n * const notification = Effect.scoped(Effect.flatMap(notificationService, Channel.runHead))\n * await Effect.runPromise(notification) // => Option.some({ message: \"ready\", receivedAt: \"2024-01-01T00:00:00.000Z\", id: \"notification:ready\" })\n * ```\n *\n * **Example** (Processing PubSub events)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect, Option, PubSub } from \"effect\"\n *\n * interface DomainEvent {\n *   readonly type: string\n *   readonly payload: unknown\n *   readonly timestamp: number\n * }\n *\n * const eventProcessor = Effect.gen(function*() {\n *   const eventPubSub = yield* PubSub.unbounded<DomainEvent>({ replay: 1 })\n *\n *   // Create a channel for processing domain events\n *   const eventChannel = Channel.fromPubSub(eventPubSub)\n *\n *   // Filter and transform events\n *   const processedChannel = Channel.map(eventChannel, (event) => {\n *     if (event.type === \"user.created\") {\n *       return {\n *         ...event,\n *         processed: true,\n *         processedAt: event.timestamp + 1\n *       }\n *     }\n *     return event\n *   })\n *\n *   yield* PubSub.publish(eventPubSub, { type: \"user.created\", payload: {}, timestamp: 1 })\n *   return processedChannel\n * })\n * const event = Effect.scoped(Effect.flatMap(eventProcessor, Channel.runHead))\n * const result = await Effect.runPromise(event) // => Option.some({ type: \"user.created\", payload: {}, timestamp: 1, processed: true, processedAt: 2 })\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromPubSub = pubsub => unwrap(Effect.map(PubSub.subscribe(pubsub), fromSubscription));\n/**\n * Creates a channel from a PubSub that outputs arrays of values.\n *\n * **Details**\n *\n * This constructor creates a channel that reads from a PubSub by automatically\n * subscribing to it and collecting values into arrays. The channel outputs\n * arrays of values in chunks, making it ideal for batch processing scenarios.\n *\n * **Example** (Batching PubSub values)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect, Option, PubSub } from \"effect\"\n *\n * class BatchError extends Data.TaggedError(\"BatchError\")<{\n *   readonly message: string\n * }> {}\n *\n * const program = Effect.gen(function*() {\n *   const pubsub = yield* PubSub.unbounded<number>({ replay: 4 })\n *\n *   // Create a channel that reads arrays of values\n *   const channel = Channel.fromPubSubArray(pubsub)\n *\n *   // Publish some values\n *   yield* PubSub.publish(pubsub, 1)\n *   yield* PubSub.publish(pubsub, 2)\n *   yield* PubSub.publish(pubsub, 3)\n *   yield* PubSub.publish(pubsub, 4)\n *\n *   // The channel will output arrays like [1, 2, 3] and [4]\n *   return channel\n * })\n * const result = Effect.scoped(Effect.flatMap(program, Channel.runHead))\n * await Effect.runPromise(result) // => Option.some([1, 2, 3, 4])\n * ```\n *\n * **Example** (Processing PubSub orders in batches)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect, Option, PubSub } from \"effect\"\n *\n * interface Order {\n *   readonly id: string\n *   readonly customerId: string\n *   readonly items: ReadonlyArray<string>\n *   readonly total: number\n *   readonly submittedAt: number\n * }\n *\n * const orderBatchProcessor = Effect.gen(function*() {\n *   const orderPubSub = yield* PubSub.unbounded<Order>({ replay: 1 })\n *\n *   // Create a channel that processes orders in batches\n *   const orderChannel = Channel.fromPubSubArray(orderPubSub)\n *\n *   // Transform to process each batch of orders\n *   const processedChannel = Channel.map(orderChannel, (orderBatch) => {\n *     const totalRevenue = orderBatch.reduce((sum, order) => sum + order.total, 0)\n *     const customerCount = new Set(orderBatch.map((order) =>\n *       order.customerId\n *     )).size\n *\n *     return {\n *       batchSize: orderBatch.length,\n *       totalRevenue,\n *       uniqueCustomers: customerCount,\n *       firstSubmittedAt: Math.min(...orderBatch.map((order) => order.submittedAt)),\n *       orders: orderBatch\n *     }\n *   })\n *\n *   yield* PubSub.publish(orderPubSub, {\n *     id: \"1\", customerId: \"a\", items: [\"book\"], total: 10, submittedAt: 1\n *   })\n *   return processedChannel\n * })\n * const order = Effect.scoped(Effect.flatMap(orderBatchProcessor, Channel.runHead))\n * const result = await Effect.runPromise(order)\n * Option.map(result, (batch) => [batch.batchSize, batch.totalRevenue, batch.uniqueCustomers]) // => Option.some([1, 10, 1])\n * ```\n *\n * **Example** (Processing PubSub logs in batches)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect, Option, PubSub } from \"effect\"\n *\n * interface LogEntry {\n *   readonly timestamp: number\n *   readonly level: \"info\" | \"warn\" | \"error\"\n *   readonly message: string\n *   readonly source: string\n * }\n *\n * const logAggregator = Effect.gen(function*() {\n *   const logPubSub = yield* PubSub.unbounded<LogEntry>({ replay: 1 })\n *\n *   // Create a channel that collects logs in batches\n *   const logChannel = Channel.fromPubSubArray(logPubSub)\n *\n *   // Transform to analyze log batches\n *   const analysisChannel = Channel.map(logChannel, (logBatch) => {\n *     const errorCount = logBatch.filter((log) => log.level === \"error\").length\n *     const warnCount = logBatch.filter((log) => log.level === \"warn\").length\n *     const infoCount = logBatch.filter((log) => log.level === \"info\").length\n *\n *     const timeRange = {\n *       start: Math.min(...logBatch.map((log) => log.timestamp)),\n *       end: Math.max(...logBatch.map((log) => log.timestamp))\n *     }\n *\n *     return {\n *       batchId: `${timeRange.start}-${timeRange.end}`,\n *       totalEntries: logBatch.length,\n *       errorCount,\n *       warnCount,\n *       infoCount,\n *       timeRange,\n *       sources: [...new Set(logBatch.map((log) => log.source))]\n *     }\n *   })\n *\n *   yield* PubSub.publish(logPubSub, {\n *     timestamp: 1,\n *     level: \"info\",\n *     message: \"ready\",\n *     source: \"app\"\n *   } satisfies LogEntry)\n *   return analysisChannel\n * })\n * const log = Effect.scoped(Effect.flatMap(logAggregator, Channel.runHead))\n * const result = await Effect.runPromise(log)\n * Option.map(result, (batch) => [batch.batchId, batch.totalEntries, batch.infoCount]) // => Option.some([\"1-1\", 1, 1])\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromPubSubArray = pubsub => unwrap(Effect.map(PubSub.subscribe(pubsub), fromSubscriptionArray));\n/**\n * Subscribes to a `PubSub` of `Take` values and exposes them as a channel.\n *\n * **Details**\n *\n * Output `Take` values are emitted as non-empty arrays. Failed `Take` values\n * fail the channel. Done `Take` values complete the channel.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromPubSubTake = pubsub => unwrap(Effect.map(PubSub.subscribe(pubsub), sub => fromEffectTake(PubSub.take(sub))));\n/**\n * Creates a Channel from a Schedule.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromSchedule = schedule => fromPull(Effect.map(Schedule.toStepWithSleep(schedule), step => step(void 0)));\n/**\n * Creates a channel from a lazily supplied Web `ReadableStream`.\n *\n * **Example** (Reading from a Web stream)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const channel = Channel.fromReadableStream({\n *   evaluate: () => new ReadableStream({\n *     start(controller) {\n *       controller.enqueue(1)\n *       controller.close()\n *     }\n *   }),\n *   onError: (cause) => new Error(String(cause))\n * })\n *\n * await Effect.runPromise(Channel.runCollect(channel)) // => [[1]]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromReadableStream = options => fromTransform((_, scope) => readableStreamToPullUnsafe({\n  scope,\n  readable: options.evaluate(),\n  onError: options.onError,\n  releaseLockOnEnd: options.releaseLockOnEnd\n}));\n/** @internal */\nexport const pullIntoWritableStream = options => Effect.acquireUseRelease(Effect.sync(() => options.writable.getWriter()), writer => {\n  const loop = options.pull.pipe(Effect.flatMap(chunk => Effect.forEach(chunk, value => Effect.tryPromise({\n    try: () => writer.ready.then(() => writer.write(value)),\n    catch: options.onError\n  }), {\n    discard: true\n  })), Effect.forever({\n    disableYield: true\n  }));\n  const withClose = options.closeOnDone !== false ? Pull.catchDone(loop, done => Effect.andThen(Effect.tryPromise({\n    try: () => writer.close(),\n    catch: options.onError\n  }), Cause.done(done))) : loop;\n  return Effect.onError(withClose, cause => Pull.isDoneCause(cause) ? Effect.void : Effect.promise(() => writer.abort(cause).catch(constVoid)));\n}, writer => Effect.sync(() => writer.releaseLock()));\n/**\n * Creates a channel that writes upstream values to a lazily supplied Web\n * `WritableStream`.\n *\n * **Example** (Writing channel input)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const written: Array<number> = []\n * const sink = Channel.fromWritableStream<never, Error, number>({\n *   evaluate: () => new WritableStream({\n *     write(value) {\n *       written.push(value)\n *     }\n *   }),\n *   onError: (cause) => new Error(String(cause))\n * })\n *\n * const program = Channel.fromArray([[1, 2] as [number, number]]).pipe(\n *   Channel.pipeTo(sink),\n *   Channel.runDrain\n * )\n *\n * await Effect.runPromise(program)\n * written // => [1, 2]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromWritableStream = options => fromTransform(pull => {\n  const writable = options.evaluate();\n  return Effect.succeed(pullIntoWritableStream({\n    ...options,\n    writable,\n    pull\n  }));\n});\n/**\n * Creates a channel backed by a Web `TransformStream`, writing upstream values\n * while emitting transformed values from its readable side.\n *\n * **Example** (Transforming channel input)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const transform = Channel.fromTransformStream<never, number, number, Error>({\n *   evaluate: () => new TransformStream({\n *     transform(value, controller) {\n *       controller.enqueue(value * 2)\n *     }\n *   }),\n *   onError: (cause) => new Error(String(cause))\n * })\n *\n * const program = Channel.fromArray([[1, 2] as [number, number]]).pipe(\n *   Channel.pipeTo(transform),\n *   Channel.runCollect\n * )\n *\n * await Effect.runPromise(program) // => [[2], [4]]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromTransformStream = options => fromTransform((upstream, scope) => {\n  const transform = options.evaluate();\n  const exit = MutableRef.make(undefined);\n  return pullIntoWritableStream({\n    pull: upstream,\n    writable: transform.writable,\n    onError: options.onError,\n    closeOnDone: options.closeOnDone\n  }).pipe(Effect.catchCause(cause => {\n    if (!Pull.isDoneCause(cause)) {\n      exit.current = Exit.failCause(cause);\n    }\n    return Effect.void;\n  }), Effect.forkIn(scope), Effect.flatMap(() => readableStreamToPullUnsafe({\n    scope,\n    exit,\n    readable: transform.readable,\n    onError: options.onError,\n    releaseLockOnEnd: options.releaseLockOnEnd\n  })));\n});\nconst readableStreamToPullUnsafe = options => {\n  const reader = options.readable.getReader();\n  const exit = options.exit ?? MutableRef.make(undefined);\n  const pull = Effect.suspend(() => {\n    if (exit.current) return exit.current;\n    return Effect.matchCauseEffect(Effect.tryPromise({\n      try: () => reader.read(),\n      catch: options.onError\n    }), {\n      onFailure: cause => exit.current ?? Effect.failCause(cause),\n      onSuccess: ({\n        done,\n        value\n      }) => {\n        if (exit.current) return exit.current;\n        return done ? Cause.done() : Effect.succeed(Arr.of(value));\n      }\n    });\n  });\n  return Effect.as(Scope.addFinalizer(options.scope, options.releaseLockOnEnd ? Effect.sync(() => reader.releaseLock()) : Effect.promise(() => reader.cancel().catch(constVoid))), pull);\n};\n/**\n * Creates a channel that pulls values from an `AsyncIterable`.\n *\n * **Details**\n *\n * Each yielded value is emitted as an output element. The iterator's return\n * value becomes the channel's done value. Thrown or rejected iterator errors\n * are converted with `onError`. If the channel scope closes early and the\n * iterator has a `return` method, that method is called.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromAsyncIterable = (iterable, onError) => fromTransform(Effect.fnUntraced(function* (_, scope) {\n  const iter = iterable[Symbol.asyncIterator]();\n  if (iter.return) {\n    yield* Scope.addFinalizer(scope, Effect.promise(() => iter.return()));\n  }\n  return Effect.flatMap(Effect.tryPromise({\n    try: () => iter.next(),\n    catch: onError\n  }), result => result.done ? Cause.done(result.value) : Effect.succeed(result.value));\n}));\n/**\n * Creates a channel from an `AsyncIterable`, emitting each yielded value as a\n * single-element non-empty array.\n *\n * **Details**\n *\n * The iterator's return value becomes the channel's done value. Thrown or\n * rejected iterator errors are converted with `onError`. If the channel scope\n * closes early and the iterator has a `return` method, that method is called.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromAsyncIterableArray = (iterable, onError) => map(fromAsyncIterable(iterable, onError), Arr.of);\n/**\n * Maps the output of this channel using the specified function.\n *\n * **Example** (Mapping channel output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class TransformError extends Data.TaggedError(\"TransformError\")<{\n *   readonly reason: string\n * }> {}\n *\n * // Basic mapping of channel values\n * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5])\n * const doubledChannel = Channel.map(numbersChannel, (n) => n * 2)\n * Effect.runSync(Channel.runCollect(doubledChannel)) // => [2, 4, 6, 8, 10]\n *\n * // Transform string data\n * const wordsChannel = Channel.fromIterable([\"hello\", \"world\", \"effect\"])\n * const upperCaseChannel = Channel.map(wordsChannel, (word) => word.toUpperCase())\n * Effect.runSync(Channel.runCollect(upperCaseChannel)) // => [\"HELLO\", \"WORLD\", \"EFFECT\"]\n *\n * // Complex object transformation\n * type User = { id: number; name: string }\n * type UserDisplay = { displayName: string; isActive: boolean }\n *\n * const usersChannel = Channel.fromIterable([\n *   { id: 1, name: \"Alice\" },\n *   { id: 2, name: \"Bob\" }\n * ])\n * const displayChannel = Channel.map(usersChannel, (user): UserDisplay => ({\n *   displayName: `User: ${user.name}`,\n *   isActive: true\n * }))\n * Effect.runSync(Channel.runCollect(displayChannel)) // => [{ displayName: \"User: Alice\", isActive: true }, { displayName: \"User: Bob\", isActive: true }]\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => transformPull(self, pull => Effect.sync(() => {\n  let i = 0;\n  return Effect.map(pull, o => f(o, i++));\n})));\n/**\n * Maps the done value of this channel using the specified function.\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const mapDone = /*#__PURE__*/dual(2, (self, f) => mapDoneEffect(self, o => Effect.succeed(f(o))));\n/**\n * Maps the done value of this channel using the specified effectful function.\n *\n * **When to use**\n *\n * Use when the terminal done value transformation needs services or can fail,\n * while emitted elements should pass through unchanged.\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const mapDoneEffect = /*#__PURE__*/dual(2, (self, f) => transformPull(self, pull => Effect.succeed(Pull.catchDone(pull, done => Effect.flatMap(f(done), Cause.done)))));\nconst concurrencyIsSequential = concurrency => concurrency === undefined || concurrency !== \"unbounded\" && concurrency <= 1;\n/**\n * Maps each output element with an effectful function, preserving the source\n * channel's done value.\n *\n * **When to use**\n *\n * Use when transforming each channel output needs an Effect, service\n * dependency, failure channel, or configured concurrency.\n *\n * **Details**\n *\n * The mapping function receives the output element and its zero-based index.\n * By default elements are mapped sequentially. Use `options.concurrency` to\n * map multiple elements concurrently, and `options.unordered` to allow\n * concurrently mapped outputs to be emitted as soon as they complete.\n *\n * **Example** (Mapping channel output with effects)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5])\n * const processedChannel = Channel.mapEffect(\n *   numbersChannel,\n *   (n) => Effect.succeed(n * n)\n * )\n * await Effect.runPromise(Channel.runCollect(processedChannel)) // => [1, 4, 9, 16, 25]\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const mapEffect = /*#__PURE__*/dual(args => isChannel(args[0]), (self, f, options) => concurrencyIsSequential(options?.concurrency) ? mapEffectSequential(self, f) : mapEffectConcurrent(self, f, options));\nconst mapEffectSequential = (self, f) => fromTransform((upstream, scope) => {\n  let i = 0;\n  return Effect.map(toTransform(self)(upstream, scope), Effect.flatMap(o => f(o, i++)));\n});\nconst mapEffectConcurrent = (self, f, options) => fromTransformBracket(Effect.fnUntraced(function* (upstream, scope, forkedScope) {\n  let i = 0;\n  const pull = yield* toTransform(self)(upstream, scope);\n  const concurrencyN = options.concurrency === \"unbounded\" ? Number.MAX_SAFE_INTEGER : options.concurrency;\n  const queue = yield* Queue.bounded(0);\n  yield* Scope.addFinalizer(forkedScope, Queue.shutdown(queue));\n  const runFork = Effect.runForkWith(yield* Effect.context());\n  const trackFiber = Fiber.runIn(forkedScope);\n  if (options.unordered) {\n    const semaphore = Semaphore.makeUnsafe(concurrencyN);\n    const release = constant(semaphore.release(1));\n    const handle = Effect.matchCauseEffect({\n      onFailure: cause => Effect.flatMap(Queue.failCause(queue, cause), release),\n      onSuccess: value => Effect.flatMap(Queue.offer(queue, value), release)\n    });\n    yield* semaphore.take(1).pipe(Effect.flatMap(() => pull), Effect.flatMap(value => {\n      trackFiber(runFork(handle(f(value, i++))));\n      return Effect.void;\n    }), Effect.forever({\n      disableYield: true\n    }), Effect.catchCause(cause => semaphore.withPermits(concurrencyN - 1)(Queue.failCause(queue, cause))), Effect.forkIn(forkedScope));\n  } else {\n    // capacity is n - 2 because\n    // - 1 for the offer *after* starting a fiber\n    // - 1 for the current processing fiber\n    const effects = yield* Queue.bounded(concurrencyN - 2);\n    yield* Scope.addFinalizer(forkedScope, Queue.shutdown(effects));\n    yield* Queue.take(effects).pipe(Effect.flatten, Effect.flatMap(value => Queue.offer(queue, value)), Effect.forever({\n      disableYield: true\n    }), Effect.catchCause(cause => Queue.failCause(queue, cause)), Effect.forkIn(forkedScope));\n    let errorCause;\n    const onExit = exit => {\n      if (exit._tag === \"Success\") return;\n      errorCause = exit.cause;\n      Queue.failCauseUnsafe(queue, exit.cause);\n    };\n    yield* pull.pipe(Effect.flatMap(value => {\n      if (errorCause) return Effect.failCause(errorCause);\n      const fiber = runFork(f(value, i++));\n      trackFiber(fiber);\n      fiber.addObserver(onExit);\n      return Queue.offer(effects, Fiber.join(fiber));\n    }), Effect.forever({\n      disableYield: true\n    }), Effect.catchCause(cause => Queue.offer(effects, Exit.failCause(cause)).pipe(Effect.andThen(Queue.failCause(effects, cause)))), Effect.forkIn(forkedScope));\n  }\n  return Queue.take(queue);\n}));\n/**\n * Returns a new channel which is the same as this one but applies the given\n * function to the input channel’s input elements.\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const mapInput = /*#__PURE__*/dual(2, (self, f) => fromTransform((upstream, scope) => toTransform(self)(Effect.flatMap(upstream, el => f(el)), scope)));\n/**\n * Returns a new channel which is the same as this one but applies the given\n * function to the input errors.\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const mapInputError = /*#__PURE__*/dual(2, (self, f) => fromTransform((upstream, scope) => toTransform(self)(Effect.catch(upstream, err => {\n  if (Cause.isDone(err)) return Effect.fail(err);\n  return Effect.flatMap(f(err), Effect.fail);\n}), scope)));\n/**\n * Applies a side effect function to each output element of the channel,\n * returning a new channel that emits the same elements.\n *\n * **Details**\n *\n * The `tap` function allows you to perform side effects (like logging or\n * debugging) on each element emitted by a channel without modifying the\n * elements themselves.\n *\n * **Example** (Tapping channel output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class LogError extends Data.TaggedError(\"LogError\")<{\n *   readonly message: string\n * }> {}\n *\n * // Create a channel that outputs numbers\n * const numberChannel = Channel.fromIterable([1, 2, 3])\n *\n * // Tap into each output element to perform side effects\n * const processed: Array<number> = []\n * const tappedChannel = Channel.tap(\n *   numberChannel,\n *   (n) => Effect.sync(() => processed.push(n))\n * )\n *\n * const observed = [await Effect.runPromise(Channel.runCollect(tappedChannel)), processed] // => [[1, 2, 3], [1, 2, 3]]\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const tap = /*#__PURE__*/dual(args => isChannel(args[0]), (self, f, options) => mapEffect(self, a => Effect.as(f(a), a), options));\n/**\n * Maps each output element to a channel and flattens the child channel\n * outputs.\n *\n * **Details**\n *\n * The source channel's done value is preserved. Child channel done values are\n * used only for child-channel completion. By default child channels are run\n * sequentially. Use `options.concurrency` and `options.bufferSize` to run child\n * channels concurrently.\n *\n * **Example** (Flat mapping channel output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class ProcessError extends Data.TaggedError(\"ProcessError\")<{\n *   readonly cause: string\n * }> {}\n *\n * // Create a channel that outputs numbers\n * const numberChannel = Channel.fromIterable([1, 2, 3])\n *\n * // FlatMap each number to create new channels\n * const flatMappedChannel = Channel.flatMap(\n *   numberChannel,\n *   (n) =>\n *     Channel.fromIterable(Array.from({ length: n }, (_, i) => `item-${n}-${i}`))\n * )\n *\n * Effect.runSync(Channel.runCollect(flatMappedChannel)) // => [\"item-1-0\", \"item-2-0\", \"item-2-1\", \"item-3-0\", \"item-3-1\", \"item-3-2\"]\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const flatMap = /*#__PURE__*/dual(args => isChannel(args[0]), (self, f, options) => concurrencyIsSequential(options?.concurrency) ? flatMapSequential(self, f) : flatMapConcurrent(self, f, options));\nconst flatMapSequential = (self, f) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => {\n  let childPull;\n  let childScope;\n  const makePull = Effect.flatMap(pull, value => {\n    childScope ??= Scope.forkUnsafe(scope);\n    return Effect.flatMapEager(toTransform(f(value))(upstream, childScope), pull => {\n      childPull = catchHalt(pull);\n      return childPull;\n    });\n  });\n  const catchHalt = Pull.catchDone(_ => {\n    childPull = undefined;\n    // we can reuse the scope if the only finalizer is the \"fork\" one\n    if (childScope.state._tag === \"Open\" && scopeFinalizerCountUnsafe(childScope) === 1) {\n      return makePull;\n    }\n    const close = Scope.close(childScope, Exit.void);\n    childScope = undefined;\n    return Effect.flatMap(close, () => makePull);\n  });\n  return Effect.suspend(() => childPull ?? makePull);\n}));\nconst flatMapConcurrent = (self, f, options) => self.pipe(map(f), mergeAll(options));\n/**\n * Concatenates this channel with another channel created from the terminal value\n * of this channel. The new channel is created using the provided function.\n *\n * **Example** (Concatenating with completion values)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class ConcatError extends Data.TaggedError(\"ConcatError\")<{\n *   readonly reason: string\n * }> {}\n *\n * // Create a channel that outputs numbers and terminates with sum\n * const numberChannel = Channel.fromIterable([1, 2, 3]).pipe(\n *   Channel.concatWith((sum: void) => Channel.succeed(`Completed processing`))\n * )\n *\n * Effect.runSync(Channel.runCollect(numberChannel)) // => [1, 2, 3, \"Completed processing\"]\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const concatWith = /*#__PURE__*/dual(2, (self, f) => fromTransform((upstream, scope) => Effect.sync(() => {\n  let currentPull;\n  const forkedScope = Scope.forkUnsafe(scope);\n  const makePull = Effect.flatMap(toTransform(self)(upstream, forkedScope), pull => {\n    currentPull = Pull.catchDone(pull, leftover => {\n      return Scope.close(forkedScope, Exit.void).pipe(Effect.flatMap(() => toTransform(f(leftover))(upstream, scope)), Effect.flatMap(pull => {\n        currentPull = pull;\n        return pull;\n      }));\n    });\n    return currentPull;\n  });\n  return Effect.suspend(() => currentPull ?? makePull);\n})));\n/**\n * Concatenates this channel with another channel, so that the second channel\n * starts emitting values after the first channel has completed.\n *\n * **Example** (Concatenating channels)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class ConcatError extends Data.TaggedError(\"ConcatError\")<{\n *   readonly reason: string\n * }> {}\n *\n * // Create two channels\n * const firstChannel = Channel.fromIterable([1, 2, 3])\n * const secondChannel = Channel.fromIterable([\"a\", \"b\", \"c\"])\n *\n * // Concatenate them\n * const concatenatedChannel = Channel.concat(firstChannel, secondChannel)\n *\n * Effect.runSync(Channel.runCollect(concatenatedChannel)) // => [1, 2, 3, \"a\", \"b\", \"c\"]\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const concat = /*#__PURE__*/dual(2, (self, that) => concatWith(self, _ => that));\n/**\n * Combines two channels with a stateful pull function.\n *\n * **When to use**\n *\n * Use to coordinate pulling from two channels when each output element depends\n * on both sides and local state.\n *\n * **Details**\n *\n * The combining function receives the current state and pull functions for the\n * left and right channels. It returns the next output element together with the\n * next state.\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const combine = /*#__PURE__*/dual(4, (self, that, s, f) => fromTransform(Effect.fnUntraced(function* (upstream, scope) {\n  const leftPull = yield* toTransform(self)(upstream, scope);\n  const rightPull = yield* toTransform(that)(upstream, scope);\n  let state = s();\n  return Effect.suspend(() => {\n    const combinedPull = f(state, leftPull, rightPull);\n    return Effect.map(combinedPull, ([a, s1]) => {\n      state = s1;\n      return a;\n    });\n  });\n})));\n/**\n * Runs a fallback channel if this channel completes without emitting any\n * output elements.\n *\n * **Details**\n *\n * If the source emits at least one element, the source is used unchanged. If\n * the source completes before emitting an element, the fallback function\n * receives the source done value and returns the replacement channel.\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const orElseIfEmpty = /*#__PURE__*/dual(2, (self, f) => fromTransform((upstream, scope) => Effect.sync(() => {\n  let currentPull;\n  const forkedScope = Scope.forkUnsafe(scope);\n  const makePull = Effect.flatMap(toTransform(self)(upstream, forkedScope), pull => {\n    const next = pull.pipe(Effect.tap(() => {\n      currentPull = pull;\n      return Effect.void;\n    }), Pull.catchDone(leftover => Scope.close(forkedScope, Exit.succeed(leftover)).pipe(Effect.andThen(toTransform(f(leftover))(upstream, scope)), Effect.flatMap(pull => {\n      currentPull = pull;\n      return pull;\n    }))));\n    currentPull = next;\n    return next;\n  });\n  return Effect.suspend(() => currentPull ?? makePull);\n})));\n/**\n * Flattens a channel of channels.\n *\n * **Example** (Flattening nested channels)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class FlattenError extends Data.TaggedError(\"FlattenError\")<{\n *   readonly cause: string\n * }> {}\n *\n * // Create a channel that outputs channels\n * const nestedChannels = Channel.fromIterable([\n *   Channel.fromIterable([1, 2]),\n *   Channel.fromIterable([3, 4]),\n *   Channel.fromIterable([5, 6])\n * ])\n *\n * // Flatten the nested channels\n * const flattenedChannel = Channel.flatten(nestedChannels)\n *\n * Effect.runSync(Channel.runCollect(flattenedChannel)) // => [1, 2, 3, 4, 5, 6]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const flatten = channels => flatMap(channels, identity_);\n/**\n * Flattens a channel that outputs arrays into a channel that outputs individual elements.\n *\n * **Example** (Flattening arrays of channel output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class FlattenError extends Data.TaggedError(\"FlattenError\")<{\n *   readonly message: string\n * }> {}\n *\n * // Create a channel that outputs arrays\n * const arrayChannel = Channel.fromIterable([\n *   [1, 2, 3],\n *   [4, 5],\n *   [6, 7, 8, 9]\n * ])\n *\n * // Flatten the arrays into individual elements\n * const flattenedChannel = Channel.flattenArray(arrayChannel)\n *\n * Effect.runSync(Channel.runCollect(flattenedChannel)) // => [1, 2, 3, 4, 5, 6, 7, 8, 9]\n * ```\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const flattenArray = self => transformPull(self, pull => {\n  let array;\n  let index = 0;\n  const pump = Effect.suspend(function loop() {\n    if (array === undefined) {\n      return Effect.flatMap(pull, array_ => {\n        switch (array_.length) {\n          case 0:\n            return loop();\n          case 1:\n            return Effect.succeed(array_[0]);\n          default:\n            {\n              array = array_;\n              return Effect.succeed(array_[index++]);\n            }\n        }\n      });\n    }\n    const next = array[index++];\n    if (index >= array.length) {\n      array = undefined;\n      index = 0;\n    }\n    return Effect.succeed(next);\n  });\n  return Effect.succeed(pump);\n});\n/**\n * Flattens a channel that emits `Take` values into a channel that emits the\n * `Take` outputs directly.\n *\n * **Details**\n *\n * Output `Take` values are emitted as non-empty arrays. Failed `Take` values\n * fail the returned channel. Done `Take` values complete the returned channel.\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const flattenTake = self => mapEffectSequential(self, Take.toPull);\n/**\n * Creates a new channel that consumes all output from the source channel\n * but emits nothing, preserving only the completion value.\n *\n * **Example** (Draining channel output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * // Create a channel that outputs values\n * const sourceChannel = Channel.fromIterable([1, 2, 3, 4, 5])\n *\n * // Drain all output, keeping only the completion\n * const drainedChannel = Channel.drain(sourceChannel)\n *\n * Effect.runSync(Channel.runCollect(drainedChannel)) // => []\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const drain = self => transformPull(self, pull => Effect.succeed(Effect.forever(pull, {\n  disableYield: true\n})));\n/**\n * Repeats this channel according to the provided schedule.\n *\n * @category repetition\n * @since 4.0.0\n */\nexport const repeat = /*#__PURE__*/dual(2, (self, schedule) => Schedule.toStepWithMetadata(typeof schedule === \"function\" ? schedule(identity_) : schedule).pipe(Effect.map(step => {\n  let meta = Schedule.CurrentMetadata.defaultValue();\n  const loop = concatWith(provideServiceEffect(self, Schedule.CurrentMetadata, Effect.sync(() => meta)), done => step(done).pipe(Effect.map(meta_ => {\n    meta = meta_;\n    return loop;\n  }), Pull.catchDone(() => Effect.succeed(end(done))), unwrap));\n  return loop;\n}), unwrap));\n/**\n * Repeats this channel forever.\n *\n * @category repetition\n * @since 4.0.0\n */\nexport const forever = self => concatWith(self, () => forever(self));\n/**\n * Runs a schedule step for each output element while preserving the emitted\n * elements.\n *\n * **Details**\n *\n * The schedule receives each output element as input. Schedule delays are\n * applied between emitted elements. If the schedule fails, the returned channel\n * fails. If the schedule finishes, the returned channel completes with the\n * schedule output.\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const schedule = /*#__PURE__*/dual(2, (self, schedule) => transformPull(self, (pull, _scope) => Effect.map(Schedule.toStepWithSleep(schedule), step => {\n  const pullWithStep = Effect.tap(pull, step);\n  return pullWithStep;\n})));\n/**\n * Filters the output elements of a channel using a predicate function.\n * Elements that don't match the predicate are discarded.\n *\n * **Example** (Filtering channel output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * // Create a channel with mixed numbers\n * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5, 6, 7, 8])\n *\n * // Filter to keep only even numbers\n * const evenChannel = Channel.filter(numbersChannel, (n) => n % 2 === 0)\n * Effect.runSync(Channel.runCollect(evenChannel)) // => [2, 4, 6, 8]\n *\n * // Filter with type refinement\n * const mixedChannel = Channel.fromIterable([1, \"hello\", 2, \"world\", 3])\n * const numbersOnlyChannel = Channel.filter(\n *   mixedChannel,\n *   (value): value is number => typeof value === \"number\"\n * )\n * Effect.runSync(Channel.runCollect(numbersOnlyChannel)) // => [1, 2, 3]\n * ```\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filter = /*#__PURE__*/dual(2, (self, predicate) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => Effect.flatMap(pull, function loop(elem) {\n  return predicate(elem) ? Effect.succeed(elem) : Effect.flatMap(pull, loop);\n}))));\n/**\n * Filters and maps output elements using a `Filter`.\n *\n * **When to use**\n *\n * Use to keep only channel output elements accepted by a `Filter` and emit\n * each filter success value.\n *\n * **Details**\n *\n * Successful filter results are emitted as mapped values. Failed filter\n * results are discarded. The source channel's errors and done value are\n * preserved.\n *\n * @see {@link filter} for keeping original output elements with a predicate\n * @see {@link filterMapEffect} for using an effectful `Filter`\n * @see {@link filterMapArray} for filtering arrays of output elements\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterMap = /*#__PURE__*/dual(2, (self, filter) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => Effect.flatMap(pull, function loop(elem) {\n  const result = filter(elem);\n  return Result.isFailure(result) ? Effect.flatMap(pull, loop) : Effect.succeed(result.success);\n}))));\n/**\n * Filters output elements with an effectful predicate.\n *\n * **When to use**\n *\n * Use when the keep/discard decision depends on an Effect or service and\n * predicate failures should fail the returned channel.\n *\n * **Details**\n *\n * Elements for which the predicate succeeds with `true` are emitted. Elements\n * for which the predicate succeeds with `false` are discarded. Predicate\n * failures fail the returned channel.\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterEffect = /*#__PURE__*/dual(2, (self, predicate) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => Effect.flatMap(pull, function loop(elem) {\n  return Effect.flatMap(predicate(elem), passes => passes ? Effect.succeed(elem) : Effect.flatMap(pull, loop));\n}))));\n/**\n * Filters and maps output elements using an effectful `Filter`.\n *\n * **When to use**\n *\n * Use to apply effectful logic that can discard channel output elements and\n * emit transformed values for the elements that pass.\n *\n * **Details**\n *\n * Successful filter results are emitted as mapped values. Failed filter\n * results are discarded. Failures from the effectful filter fail the returned\n * channel.\n *\n * @see {@link filterMap} for using a synchronous `Filter`\n * @see {@link filterEffect} for effectfully keeping original output elements\n * @see {@link mapEffect} for effectfully transforming every output element\n * @see {@link filterMapArrayEffect} for effectful filtering of array outputs\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterMapEffect = /*#__PURE__*/dual(2, (self, filter) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => Effect.flatMap(pull, function loop(elem) {\n  return Effect.flatMap(filter(elem), result => Result.isFailure(result) ? Effect.flatMap(pull, loop) : Effect.succeed(result.success));\n}))));\n/**\n * Filters arrays of elements emitted by a channel, applying the filter\n * to each element within the arrays and only emitting non-empty filtered arrays.\n *\n * **Example** (Filtering array output)\n *\n * ```ts import.meta.vitest\n * import { Array, Channel, Effect } from \"effect\"\n *\n * const nonEmptyArrayPredicate = Array.isReadonlyArrayNonEmpty\n *\n * // Create a channel that outputs arrays of mixed data\n * const arrayChannel = Channel.fromIterable([\n *   Array.make(1, 2, 3, 4, 5),\n *   Array.make(6, 7, 8, 9, 10),\n *   Array.make(11, 12, 13, 14, 15)\n * ]).pipe(Channel.filter(nonEmptyArrayPredicate))\n *\n * // Filter arrays to keep only even numbers\n * const evenArraysChannel = Channel.filterArray(arrayChannel, (n) => n % 2 === 0)\n * Effect.runSync(Channel.runCollect(evenArraysChannel)) // => [[2, 4], [6, 8, 10], [12, 14]]\n * // Note: Only non-empty filtered arrays are emitted\n *\n * // Arrays that would become empty after filtering are discarded entirely\n * const oddChannel = Channel.fromIterable([\n *   Array.make(1, 3, 5),\n *   Array.make(2, 4),\n *   Array.make(7, 9)\n * ]).pipe(Channel.filter(nonEmptyArrayPredicate))\n * const filteredOddChannel = Channel.filterArray(oddChannel, (n) => n % 2 === 0)\n * Effect.runSync(Channel.runCollect(filteredOddChannel)) // => [[2, 4]]\n * ```\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterArray = /*#__PURE__*/dual(2, (self, predicate) => transformPull(self, pull => Effect.succeed(Effect.flatMap(pull, function loop(arr) {\n  const passes = [];\n  for (let i = 0; i < arr.length; i++) {\n    if (predicate(arr[i])) {\n      passes.push(arr[i]);\n    }\n  }\n  return Arr.isReadonlyArrayNonEmpty(passes) ? Effect.succeed(passes) : Effect.flatMap(pull, loop);\n}))));\n/**\n * Filters and maps each element inside emitted non-empty arrays using a\n * `Filter`.\n *\n * **Details**\n *\n * Successful filter results are kept as mapped values. Failed filter results\n * are removed from the array. Arrays that become empty are discarded.\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterMapArray = /*#__PURE__*/dual(2, (self, filter) => transformPull(self, pull => Effect.succeed(Effect.flatMap(pull, function loop(arr) {\n  const passes = [];\n  for (let i = 0; i < arr.length; i++) {\n    const result = filter(arr[i]);\n    if (Result.isSuccess(result)) {\n      passes.push(result.success);\n    }\n  }\n  return Arr.isReadonlyArrayNonEmpty(passes) ? Effect.succeed(passes) : Effect.flatMap(pull, loop);\n}))));\n/**\n * Filters each element inside emitted non-empty arrays with an effectful\n * predicate.\n *\n * **When to use**\n *\n * Use when filtering array-valued channel outputs requires Effects or services,\n * and arrays that become empty should be skipped.\n *\n * **Details**\n *\n * The predicate receives the element and its index within the array. Elements\n * for which the predicate succeeds with `true` are kept. Arrays that become\n * empty are discarded. Predicate failures fail the returned channel.\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterArrayEffect = /*#__PURE__*/dual(2, (self, predicate) => transformPull(self, pull => {\n  const f = Effect.flatMap(pull, arr => Effect.filter(arr, predicate));\n  return Effect.succeed(Effect.flatMap(f, function loop(arr) {\n    return Arr.isReadonlyArrayNonEmpty(arr) ? Effect.succeed(arr) : Effect.flatMap(f, loop);\n  }));\n}));\n/**\n * Filters and maps each element inside emitted non-empty arrays using an\n * effectful `Filter`.\n *\n * **When to use**\n *\n * Use when array-valued channel outputs need an effectful filter-map that can\n * fail and can discard arrays that become empty.\n *\n * **Details**\n *\n * Successful filter results are kept as mapped values. Failed filter results\n * are removed from the array. Arrays that become empty are discarded. Failures\n * from the effectful filter fail the returned channel.\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterMapArrayEffect = /*#__PURE__*/dual(2, (self, filter) => transformPull(self, pull => Effect.succeed(Effect.flatMap(pull, function loop(arr) {\n  return Effect.flatMap(Effect.filterMapEffect(arr, filter), passes => Arr.isReadonlyArrayNonEmpty(passes) ? Effect.succeed(passes) : Effect.flatMap(pull, loop));\n}))));\n/**\n * Maps over a channel statefully with an accumulator, where each element can produce multiple output values.\n *\n * **Example** (Mapping with accumulated state)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * // Create a channel with numbers\n * const numbersChannel = Channel.fromIterable([1, 2, 3, 4])\n *\n * // Use mapAccum to create running sums and emit both current and sum\n * const runningSum = Channel.mapAccum(\n *   numbersChannel,\n *   () => 0, // initial accumulator state\n *   (sum, current) => {\n *     const newSum = sum + current\n *     // Return [newState, outputValues]\n *     return [newSum, [current, newSum]] as const\n *   }\n * )\n * // Using with Effect for async processing\n * const asyncMapAccum = Channel.mapAccum(\n *   numbersChannel,\n *   () => \"\",\n *   (acc, value) =>\n *     Effect.gen(function*() {\n *       const newAcc = acc + value.toString()\n *       return [newAcc, [`${value}-processed`, newAcc]] as const\n *     })\n * )\n * Effect.runSync(Channel.runCollect(runningSum)) // => [1, 1, 2, 3, 3, 6, 4, 10]\n * Effect.runSync(Channel.runCollect(asyncMapAccum)) // => [\"1-processed\", \"1\", \"2-processed\", \"12\", \"3-processed\", \"123\", \"4-processed\", \"1234\"]\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const mapAccum = /*#__PURE__*/dual(args => isChannel(args[0]), (self, initial, f, options) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => {\n  let state = initial();\n  let current;\n  let index = 0;\n  let cause;\n  const pullNext = Effect.matchCauseEffect(pull, {\n    onFailure(cause_) {\n      cause = cause_;\n      const b = options?.onHalt && options.onHalt(state);\n      return b && b.length > 0 ? Effect.succeed([state, b]) : Effect.failCause(cause_);\n    },\n    onSuccess(a) {\n      const b = f(state, a);\n      return Arr.isArray(b) ? Effect.succeed(b) : b;\n    }\n  });\n  const pump = Effect.suspend(function loop() {\n    if (current === undefined) {\n      if (cause) return Effect.failCause(cause);\n      return Effect.flatMap(pullNext, ([newState, values]) => {\n        state = newState;\n        if (values.length === 0) {\n          return loop();\n        } else if (values.length === 1) {\n          return Effect.succeed(values[0]);\n        }\n        current = values;\n        return loop();\n      });\n    }\n    const next = current[index++];\n    if (index >= current.length) {\n      current = undefined;\n      index = 0;\n    }\n    return Effect.succeed(next);\n  });\n  return pump;\n})));\n/**\n * Transforms a channel statefully by scanning over its output with an accumulator function.\n * Emits the intermediate results of the scan operation.\n *\n * **Example** (Scanning channel output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * // Create a channel with numbers\n * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5])\n *\n * // Scan to create running sum\n * const runningSumChannel = Channel.scan(numbersChannel, 0, (sum, n) => sum + n)\n * Effect.runSync(Channel.runCollect(runningSumChannel)) // => [0, 1, 3, 6, 10, 15]\n * // Note: emits the initial value and each intermediate result\n *\n * // Scan with string concatenation\n * const wordsChannel = Channel.fromIterable([\"hello\", \"world\", \"from\", \"effect\"])\n * const sentenceChannel = Channel.scan(\n *   wordsChannel,\n *   \"\",\n *   (sentence, word) => sentence === \"\" ? word : `${sentence} ${word}`\n * )\n * Effect.runSync(Channel.runCollect(sentenceChannel)) // => [\"\", \"hello\", \"hello world\", \"hello world from\", \"hello world from effect\"]\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const scan = /*#__PURE__*/dual(3, (self, initial, f) => scanEffect(self, initial, (s, a) => Effect.succeed(f(s, a))));\n/**\n * Transforms a channel statefully by scanning over its output with an effectful accumulator function.\n * Emits the intermediate results of the scan operation.\n *\n * **When to use**\n *\n * Use when maintaining accumulated state over channel output requires Effects\n * or can fail, while still emitting each intermediate state.\n *\n * **Example** (Scanning channel output with effects)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class ScanError extends Data.TaggedError(\"ScanError\")<{\n *   readonly reason: string\n * }> {}\n *\n * // Create a channel with numbers\n * const numbersChannel = Channel.fromIterable([1, 2, 3, 4])\n *\n * // Effectful scan with async operations\n * const asyncScanChannel = Channel.scanEffect(\n *   numbersChannel,\n *   \"\",\n *   (acc, value) =>\n *     Effect.gen(function*() {\n *       return acc + value.toString()\n *     })\n * )\n * await Effect.runPromise(Channel.runCollect(asyncScanChannel)) // => [\"\", \"1\", \"12\", \"123\", \"1234\"]\n *\n * // Scan with error handling\n * const errorHandlingScan = Channel.scanEffect(\n *   numbersChannel,\n *   0,\n *   (sum, n) => {\n *     if (n < 0) {\n *       return Effect.fail(new ScanError({ reason: \"negative number\" }))\n *     }\n *     return Effect.succeed(sum + n)\n *   }\n * )\n * await Effect.runPromise(Channel.runCollect(errorHandlingScan)) // => [0, 1, 3, 6, 10]\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const scanEffect = /*#__PURE__*/dual(3, (self, initial, f) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => {\n  let state = initial;\n  let isFirst = true;\n  return Effect.suspend(() => {\n    if (isFirst) {\n      isFirst = false;\n      return Effect.succeed(state);\n    }\n    return Effect.map(Effect.flatMap(pull, a => f(state, a)), newState => {\n      state = newState;\n      return state;\n    });\n  });\n})));\n/**\n * Catches any cause of failure from the channel and allows recovery by\n * creating a new channel based on the caught cause.\n *\n * **Example** (Recovering from failure causes)\n *\n * ```ts import.meta.vitest\n * import { Cause, Channel, Data, Effect } from \"effect\"\n *\n * class ProcessError extends Data.TaggedError(\"ProcessError\")<{\n *   readonly reason: string\n * }> {}\n *\n * class RecoveryError extends Data.TaggedError(\"RecoveryError\")<{\n *   readonly message: string\n * }> {}\n *\n * // Create a failing channel\n * const failingChannel = Channel.fail(\n *   new ProcessError({ reason: \"network error\" })\n * )\n *\n * // Catch the cause and provide recovery\n * const recoveredChannel = Channel.catchCause(failingChannel, (cause) => {\n *   if (Cause.hasFails(cause)) {\n *     return Channel.succeed(\"Recovered from failure\")\n *   }\n *   return Channel.succeed(\"Recovered from interruption\")\n * })\n *\n * Effect.runSync(Channel.runCollect(recoveredChannel)) // => [\"Recovered from failure\"]\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const catchCause = /*#__PURE__*/dual(2, (self, f) => fromTransform((upstream, scope) => {\n  let forkedScope = Scope.forkUnsafe(scope);\n  return Effect.map(toTransform(self)(upstream, forkedScope), pull => {\n    let currentPull = pull.pipe(Effect.catchCause(cause => {\n      if (Pull.isDoneCause(cause)) {\n        return Effect.failCause(cause);\n      }\n      const toClose = forkedScope;\n      forkedScope = Scope.forkUnsafe(scope);\n      return Scope.close(toClose, Exit.failCause(cause)).pipe(Effect.andThen(toTransform(f(cause))(upstream, forkedScope)), Effect.flatMap(childPull => {\n        currentPull = childPull;\n        return childPull;\n      }));\n    }));\n    return Effect.suspend(() => currentPull);\n  });\n}));\n/**\n * Recovers from defects using the provided function.\n *\n * **Details**\n *\n * Typed failures and interruptions are not caught.\n *\n * **Example** (Recovering from a defect)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const channel = Channel.fromEffect(Effect.die(\"boom\")).pipe(\n *   Channel.catchDefect((defect) => Channel.succeed(`recovered: ${defect}`))\n * )\n *\n * Effect.runSync(Channel.runCollect(channel)) // => [\"recovered: boom\"]\n * ```\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchDefect = /*#__PURE__*/dual(2, (self, f) => catchCauseFilter(self, Cause.findDefect, f));\n/**\n * Runs an effect with the full failure `Cause` when the channel fails, then\n * fails the returned channel with the original cause.\n *\n * **When to use**\n *\n * Use when observing the full channel failure `Cause` is needed without\n * changing successful output or replacing the original cause.\n *\n * **Details**\n *\n * Use this for observing failures, such as logging or metrics. If the observer\n * effect fails, that failure can fail the returned channel.\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const tapCause = /*#__PURE__*/dual(2, (self, f) => catchCause(self, cause => fromEffectDrain(Effect.flatMap(f(cause), _ => Effect.failCause(cause)))));\n/**\n * Catches causes of failure that match a specific filter, allowing\n * conditional error recovery based on the type of failure.\n *\n * **When to use**\n *\n * Use to recover a channel only when its full `Cause` satisfies a boolean\n * predicate.\n *\n * **Details**\n *\n * When the predicate matches, the recovery function receives the original\n * cause. When it does not match, the returned channel fails with the original\n * cause.\n *\n * @see {@link catchCauseFilter} for selecting causes with a `Filter`\n * @see {@link catchCause} for recovering from every cause\n * @see {@link catchIf} for recovering from typed channel errors\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchCauseIf = /*#__PURE__*/dual(3, (self, predicate, f) => catchCause(self, cause => {\n  return predicate(cause) ? f(cause) : failCause(cause);\n}));\n/**\n * Recovers from channel failures whose full `Cause` is selected by a `Filter`.\n *\n * **When to use**\n *\n * Use when you need to recover a channel 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 * When the filter succeeds, the recovery function receives the selected value\n * and the original cause. When the filter fails, the returned channel fails\n * with the residual cause produced by the filter.\n *\n * @see {@link catchCauseIf} for selecting causes with a predicate\n * @see {@link catchFilter} for selecting typed errors with a `Filter`\n * @see {@link catchCause} for recovering from every cause\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchCauseFilter = /*#__PURE__*/dual(3, (self, filter, f) => catchCause(self, cause => {\n  const result = filter(cause);\n  return Result.isFailure(result) ? failCause(result.failure) : f(result.success, cause);\n}));\nconst catch_ = /*#__PURE__*/dual(2, (self, f) => catchCauseFilter(self, Cause.findError, e => f(e)));\nexport {\n/**\n * Recovers from typed channel errors by running a fallback channel.\n *\n * @category error handling\n * @since 4.0.0\n */\ncatch_ as catch };\n/**\n * Runs an effect when the channel fails with a typed error, then preserves the\n * original channel failure.\n *\n * **Details**\n *\n * The effect is not run for normal channel completion. If the observer effect\n * fails, that failure can fail the returned channel.\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const tapError = /*#__PURE__*/dual(2, (self, f) => transformPull(self, pull => Effect.succeed(Effect.tapError(pull, err => Cause.isDone(err) ? Effect.void : Effect.asVoid(f(err))))));\n/**\n * Recovers from typed channel errors that match a predicate or refinement.\n *\n * **When to use**\n *\n * Use to recover from typed channel errors when a predicate or refinement\n * selects the failures that should switch to a recovery channel.\n *\n * **Details**\n *\n * Matching errors are handled by the recovery function. Non-matching errors\n * are handled by `orElse` when provided. Without `orElse`, non-matching errors\n * are re-failed.\n *\n * @see {@link catch_ catch} for recovering from every typed channel error\n * @see {@link catchFilter} for selecting typed errors with a `Filter`\n * @see {@link catchTag} for selecting tagged typed errors\n * @see {@link catchCauseFilter} for selecting full causes with a `Filter`\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchIf = /*#__PURE__*/dual(args => isChannel(args[0]), (self, predicate, f, orElse) => catch_(self, err => {\n  return predicate(err) ? f(err) : orElse ? orElse(err) : fail(err);\n}));\n/**\n * Recovers from typed channel errors selected by a `Filter`.\n *\n * **When to use**\n *\n * Use to recover from channel errors with a reusable `Filter` when matching\n * can also narrow or transform the error before choosing the recovery channel.\n *\n * **Details**\n *\n * Successful filter results are handled by the recovery function. Failed\n * filter results are handled by `orElse` when provided. Without `orElse`,\n * failed filter results are re-failed.\n *\n * @see {@link catchIf} for selecting typed errors with a predicate\n * @see {@link catchTag} for selecting tagged typed errors\n * @see {@link catchCauseFilter} for selecting full causes with a `Filter`\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchFilter = /*#__PURE__*/dual(args => isChannel(args[0]), (self, filter, f, orElse) => catch_(self, err => {\n  const result = filter(err);\n  return Result.isFailure(result) ? orElse ? orElse(result.failure) : fail(result.failure) : f(result.success);\n}));\n/**\n * Recovers from tagged channel errors whose `_tag` matches one or more tags.\n *\n * **Details**\n *\n * Matching tagged errors are handled by the recovery function. Non-matching\n * errors are handled by `orElse` when provided. Without `orElse`,\n * non-matching errors are re-failed.\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchTag = /*#__PURE__*/dual(args => isChannel(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/**\n * Catches a specific reason within a tagged error.\n *\n * **Example** (Recovering from nested reasons)\n *\n * ```ts import.meta.vitest\n * import { Channel, 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 reason = new RateLimitError({ retryAfter: 60 })\n * const channel = Channel.fail(new AiError({ reason }))\n *\n * const recovered = channel.pipe(\n *   Channel.catchReason(\"AiError\", \"RateLimitError\", (reason) =>\n *     Channel.succeed(`retry: ${reason.retryAfter}`)\n *   )\n * )\n * Effect.runSync(Channel.runCollect(recovered)) // => [\"retry: 60\"]\n * ```\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchReason = /*#__PURE__*/dual(args => isChannel(args[0]), (self, errorTag, reasonTag, f, orElse) => catch_(self, error => {\n  if (isTagged(error, errorTag) && hasProperty(error, \"reason\")) {\n    const reason = error.reason;\n    if (isTagged(reason, reasonTag)) {\n      return f(reason, error);\n    }\n    return orElse ? orElse(reason, error) : fail(error);\n  }\n  return fail(error);\n}));\n/**\n * Catches multiple reasons within a tagged error using an object of handlers.\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchReasons = /*#__PURE__*/dual(args => isChannel(args[0]), (self, errorTag, cases, orElse) => {\n  let keys;\n  return catch_(self, error => {\n    if (isTagged(error, errorTag) && hasProperty(error, \"reason\") && hasProperty(error.reason, \"_tag\") && String.isString(error.reason._tag)) {\n      const reason = error.reason;\n      keys ??= new Set(Object.keys(cases));\n      if (keys.has(reason._tag)) {\n        return cases[reason._tag](reason, error);\n      }\n      return orElse ? orElse(reason, error) : fail(error);\n    }\n    return fail(error);\n  });\n});\n/**\n * Promotes nested reason errors into the channel error, replacing the parent error.\n *\n * **Example** (Promoting nested reasons)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect, Exit } 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 reason = new RateLimitError({ retryAfter: 60 })\n * const channel = Channel.fail(new AiError({ reason }))\n *\n * const unwrapped = channel.pipe(Channel.unwrapReason(\"AiError\"))\n * Effect.runSync(Effect.exit(Channel.runCollect(unwrapped))) // => Exit.fail(reason)\n * ```\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const unwrapReason = /*#__PURE__*/dual(2, (self, errorTag) => catchFilter(self, error => isTagged(error, errorTag) && hasProperty(error, \"reason\") ? Result.succeed(error.reason) : Result.fail(error), fail));\n/**\n * Returns a new channel, which is the same as this one, except the failure\n * value of the returned channel is created by applying the specified function\n * to the failure value of this channel.\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const mapError = /*#__PURE__*/dual(2, (self, f) => catch_(self, err => fail(f(err))));\n/**\n * Converts all errors in the channel to defects (unrecoverable failures).\n * This is useful when you want to treat errors as programming errors.\n *\n * **Example** (Converting failures to defects)\n *\n * ```ts import.meta.vitest\n * import { Cause, Channel, Data, Effect, Exit } from \"effect\"\n *\n * class ValidationError extends Data.TaggedError(\"ValidationError\")<{\n *   readonly field: string\n * }> {}\n *\n * // Create a channel that might fail\n * const error = new ValidationError({ field: \"email\" })\n * const failingChannel = Channel.fail(error)\n *\n * // Convert failures to defects\n * const fatalChannel = Channel.orDie(failingChannel)\n *\n * Effect.runSync(Effect.exit(Channel.runCollect(fatalChannel))) // => Exit.failCause(Cause.die(error))\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const orDie = self => catch_(self, die);\n/**\n * Ignores all errors in the channel, converting them to an empty channel.\n *\n * **Details**\n *\n * Use the `log` option to emit the full {@link Cause} when the channel fails.\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const ignore = /*#__PURE__*/dual(args => isChannel(args[0]), (self, options) => {\n  if (!options?.log) {\n    return catch_(self, () => empty);\n  }\n  const logEffect = Effect.logWithLevel(options.log === true ? undefined : options.log);\n  return catch_(tapCause(self, cause => Cause.hasFails(cause) ? logEffect(cause) : Effect.void), () => empty);\n});\nconst ignoreCause_ = self => catchCause(self, () => empty);\n/**\n * Ignores all errors in the channel including defects, converting them to an empty channel.\n *\n * **When to use**\n *\n * Use when a channel should become best-effort and all failure causes, including\n * defects and interruptions, can be converted to empty output.\n *\n * **Details**\n *\n * Use the `log` option to emit the full {@link Cause} when the channel fails.\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const ignoreCause = /*#__PURE__*/dual(args => isChannel(args[0]), (self, options) => {\n  if (!options?.log) return ignoreCause_(self);\n  const logEffect = Effect.logWithLevel(options.log === true ? undefined : options.log);\n  return ignoreCause_(tapCause(self, cause => logEffect(cause)));\n});\n/**\n * Returns a new channel that retries this channel according to the specified\n * schedule whenever it fails.\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const retry = /*#__PURE__*/dual(2, (self, schedule) => suspend(() => {\n  let step = undefined;\n  let meta = Schedule.CurrentMetadata.defaultValue();\n  const selfWithMeta = provideServiceEffect(self, Schedule.CurrentMetadata, Effect.sync(() => meta));\n  const withReset = onFirst(selfWithMeta, () => {\n    step = undefined;\n    return Effect.void;\n  });\n  const resolvedSchedule = typeof schedule === \"function\" ? schedule(identity_) : schedule;\n  const loop = catch_(withReset, Effect.fnUntraced(function* (error) {\n    if (!step) {\n      step = yield* Schedule.toStepWithMetadata(resolvedSchedule);\n    }\n    meta = yield* step(error);\n    return loop;\n  }, (effect, error) => Pull.catchDone(effect, () => Effect.succeed(fail(error))), unwrap));\n  return loop;\n}));\n/**\n * Maps each output element to a channel and emits values from the most recent\n * active child channels.\n *\n * **Details**\n *\n * With the default concurrency of `1`, starting a new child channel interrupts\n * the previous child channel. Use `options.concurrency` to allow more active\n * child channels. The source channel's done value is preserved.\n *\n * **Example** (Switching mapped channels)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class SwitchError extends Data.TaggedError(\"SwitchError\")<{\n *   readonly reason: string\n * }> {}\n *\n * // Create a channel that outputs numbers\n * const numberChannel = Channel.fromIterable([1, 2, 3])\n *\n * // Switch to new channels based on each value\n * const switchedChannel = Channel.switchMap(\n *   numberChannel,\n *   (n) => Channel.fromIterable([`value-${n}`])\n * )\n *\n * await Effect.runPromise(Channel.runCollect(switchedChannel)) // => [\"value-3\"]\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const switchMap = /*#__PURE__*/dual(args => isChannel(args[0]), (self, f, options) => self.pipe(map(f), mergeAll({\n  ...options,\n  concurrency: options?.concurrency ?? 1,\n  switch: true\n})));\n/**\n * Merges multiple channels with specified concurrency and buffering options.\n *\n * **When to use**\n *\n * Use when channel outputs are themselves channels and multiple inner channels\n * should run with configured concurrency and buffering.\n *\n * **Example** (Merging nested channels)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class MergeAllError extends Data.TaggedError(\"MergeAllError\")<{\n *   readonly reason: string\n * }> {}\n *\n * // Create channels that output other channels\n * const nestedChannels = Channel.fromIterable([\n *   Channel.fromIterable([1, 2]),\n *   Channel.fromIterable([3, 4]),\n *   Channel.fromIterable([5, 6])\n * ])\n *\n * // Merge all channels with bounded concurrency\n * const mergedChannel = Channel.mergeAll({\n *   concurrency: 1,\n *   bufferSize: 16\n * })(nestedChannels)\n *\n * await Effect.runPromise(Channel.runCollect(mergedChannel)) // => [1, 2, 3, 4, 5, 6]\n * ```\n *\n * @category combining\n * @since 2.0.0\n */\nexport const mergeAll = /*#__PURE__*/dual(2, (channels, {\n  bufferSize = 16,\n  concurrency,\n  switch: switch_ = false\n}) => fromTransformBracket(Effect.fnUntraced(function* (upstream, scope, forkedScope) {\n  const concurrencyN = concurrency === \"unbounded\" ? Number.MAX_SAFE_INTEGER : Math.max(1, concurrency);\n  const semaphore = switch_ ? undefined : Semaphore.makeUnsafe(concurrencyN);\n  const doneLatch = yield* Latch.make(true);\n  const fibers = new Set();\n  const queue = yield* Queue.bounded(bufferSize);\n  yield* Scope.addFinalizer(forkedScope, Queue.shutdown(queue));\n  const pull = yield* toTransform(channels)(upstream, scope);\n  yield* Effect.gen(function* () {\n    while (true) {\n      let pullFiber;\n      if (semaphore) {\n        if (fibers.size < concurrencyN) {\n          yield* semaphore.take(1);\n        } else {\n          pullFiber = yield* Effect.forkChild(pull);\n          yield* Effect.raceFirst(semaphore.take(1), Effect.andThen(Fiber.join(pullFiber), Effect.never));\n        }\n      }\n      const channel = pullFiber === undefined ? yield* pull : yield* Fiber.join(pullFiber);\n      const childScope = Scope.forkUnsafe(forkedScope);\n      const childPull = yield* toTransform(channel)(upstream, childScope);\n      while (fibers.size >= concurrencyN) {\n        const fiber = Iterable.headUnsafe(fibers);\n        fibers.delete(fiber);\n        if (fibers.size === 0) yield* doneLatch.open;\n        yield* Fiber.interrupt(fiber);\n      }\n      const fiber = yield* childPull.pipe(Effect.tap(() => Effect.yieldNow), Effect.flatMap(value => Queue.offer(queue, value)), Effect.forever({\n        disableYield: true\n      }), Effect.onError(Effect.fnUntraced(function* (cause) {\n        const halt = Pull.filterDone(cause);\n        yield* Effect.exit(Scope.close(childScope, !Result.isFailure(halt) ? Exit.succeed(halt.success.value) : Exit.failCause(halt.failure)));\n        if (!fibers.has(fiber)) return;\n        fibers.delete(fiber);\n        if (semaphore) yield* semaphore.release(1);\n        if (fibers.size === 0) yield* doneLatch.open;\n        if (Result.isSuccess(halt)) return;\n        return yield* Queue.failCause(queue, cause);\n      })), Effect.forkChild);\n      doneLatch.closeUnsafe();\n      fibers.add(fiber);\n    }\n  }).pipe(Effect.catchCause(cause => {\n    const halt = Pull.filterDone(cause);\n    if (Result.isSuccess(halt)) {\n      return doneLatch.whenOpen(Queue.failCause(queue, cause));\n    }\n    return Queue.failCause(queue, cause);\n  }), Effect.forkIn(forkedScope));\n  return Queue.take(queue);\n})));\n/**\n * Returns a new channel, which is the merge of this channel and the specified\n * channel.\n *\n * **Example** (Merging channels)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * // Create two channels\n * const leftChannel = Channel.fromIterable([1, 2, 3])\n * const rightChannel = Channel.fromIterable([\"a\", \"b\", \"c\"])\n *\n * // The default \"both\" strategy waits for both channels to complete\n * const mergedChannel = Channel.merge(leftChannel, rightChannel)\n *\n * const values = await Effect.runPromise(Channel.runCollect(mergedChannel))\n * values.map(String).sort() // => [\"1\", \"2\", \"3\", \"a\", \"b\", \"c\"]\n * ```\n *\n * @category combining\n * @since 4.0.0\n */\nexport const merge = /*#__PURE__*/dual(args => isChannel(args[0]) && isChannel(args[1]), (left, right, options) => fromTransformBracket(Effect.fnUntraced(function* (upstream, _scope, forkedScope) {\n  const strategy = options?.haltStrategy ?? \"both\";\n  const queue = yield* Queue.bounded(0);\n  yield* Scope.addFinalizer(forkedScope, Queue.shutdown(queue));\n  let done = 0;\n  function onExit(side, cause) {\n    done++;\n    if (!Pull.isDoneCause(cause)) {\n      return Queue.failCause(queue, cause);\n    }\n    switch (strategy) {\n      case \"both\":\n        {\n          return done === 2 ? Queue.failCause(queue, cause) : Effect.void;\n        }\n      case \"left\":\n      case \"right\":\n        {\n          return side === strategy ? Queue.failCause(queue, cause) : Effect.void;\n        }\n      case \"either\":\n        {\n          return Queue.failCause(queue, cause);\n        }\n    }\n  }\n  const runSide = (side, channel, scope) => toTransform(channel)(upstream, scope).pipe(Effect.flatMap(pull => pull.pipe(Effect.flatMap(value => Queue.offer(queue, value)), Effect.forever)), Effect.onError(cause => Effect.andThen(Scope.close(scope, Pull.doneExitFromCause(cause)), onExit(side, cause))), Effect.forkIn(forkedScope));\n  yield* runSide(\"left\", left, Scope.forkUnsafe(forkedScope));\n  yield* runSide(\"right\", right, Scope.forkUnsafe(forkedScope));\n  return Queue.take(queue);\n})));\n/**\n * Runs an effect concurrently with a channel while emitting only the channel's\n * output elements.\n *\n * **When to use**\n *\n * Use when a side effect should run for the lifetime of a channel and only the\n * channel's output elements should be emitted.\n *\n * **Details**\n *\n * The effect's successful value is ignored. If the effect fails while the\n * channel is running, the returned channel fails with that error.\n *\n * @category combining\n * @since 4.0.0\n */\nexport const mergeEffect = /*#__PURE__*/dual(2, (self, effect) => merge(self, fromEffectDrain(effect), {\n  haltStrategy: \"left\"\n}));\n/**\n * Splits upstream string chunks into lines, recognizing `\\n`, `\\r\\n`, and\n * standalone `\\r` as line terminators. The behavior matches\n * `String.linesIterator` regardless of how the input is chunked.\n *\n * **Details**\n *\n * A line terminator at the very end of the stream does **not** produce a\n * trailing empty line (consistent with `String.linesIterator`). Conversely,\n * if the stream ends without a terminator the final partial line is still\n * emitted.\n *\n * **Example** (Splitting string chunks into lines)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const result = await Effect.runPromise(Stream.runCollect(\n *   Stream.splitLines(Stream.make(\"hel\", \"lo\\r\\nwor\", \"ld\\n\"))\n * ))\n * result // => [\"hello\", \"world\"]\n * ```\n *\n * @category splitting\n * @since 2.0.0\n */\nexport const splitLines = () => fromTransform((upstream, _scope) => Effect.sync(() => {\n  // Accumulates text that has not yet been terminated by a line break.\n  // Content is carried across chunks until a terminator is found.\n  let stringBuilder = \"\";\n  // A trailing \\r completes the line immediately. Remember it only to\n  // suppress a leading \\n in the next nonempty string.\n  let midCRLF = false;\n  // Remembers the upstream Done value after the first time the upstream\n  // signals completion, so subsequent pulls return Done immediately\n  // without pulling upstream again.\n  let done = Option.none();\n  function splitLinesArray(chunk) {\n    const chunkBuilder = [];\n    function pushLine(segment) {\n      if (stringBuilder.length === 0) {\n        chunkBuilder.push(segment);\n      } else {\n        chunkBuilder.push(stringBuilder + segment);\n        stringBuilder = \"\";\n      }\n    }\n    for (let i = 0; i < chunk.length; i++) {\n      const str = chunk[i];\n      if (str.length !== 0) {\n        let from = 0;\n        let indexOfCR = str.indexOf(\"\\r\");\n        let indexOfLF = str.indexOf(\"\\n\");\n        if (midCRLF) {\n          if (indexOfLF === 0) {\n            from = 1;\n            indexOfLF = str.indexOf(\"\\n\", from);\n          }\n          midCRLF = false;\n        }\n        while (indexOfCR !== -1 || indexOfLF !== -1) {\n          if (indexOfCR === -1 || indexOfLF !== -1 && indexOfLF < indexOfCR) {\n            pushLine(str.substring(from, indexOfLF));\n            from = indexOfLF + 1;\n            indexOfLF = str.indexOf(\"\\n\", from);\n          } else {\n            pushLine(str.substring(from, indexOfCR));\n            if (str.length === indexOfCR + 1) {\n              midCRLF = true;\n              from = str.length;\n              indexOfCR = -1;\n            } else {\n              from = indexOfCR + (indexOfLF === indexOfCR + 1 ? 2 : 1);\n              indexOfCR = str.indexOf(\"\\r\", from);\n              indexOfLF = str.indexOf(\"\\n\", from);\n            }\n          }\n        }\n        stringBuilder = stringBuilder + str.substring(from);\n      }\n    }\n    return Arr.isReadonlyArrayNonEmpty(chunkBuilder) ? chunkBuilder : null;\n  }\n  const pullOrFlush = Effect.suspend(() => {\n    if (done._tag === \"Some\") {\n      return Cause.done(done.value);\n    }\n    return Pull.matchEffect(upstream, {\n      onSuccess: loop,\n      onFailure: Effect.failCause,\n      onDone: leftover => {\n        done = Option.some(leftover);\n        if (stringBuilder.length > 0) {\n          const last = stringBuilder;\n          stringBuilder = \"\";\n          midCRLF = false;\n          return Effect.succeed([last]);\n        }\n        return Cause.done(leftover);\n      }\n    });\n  });\n  function loop(chunk) {\n    const lines = splitLinesArray(chunk);\n    return lines !== null ? Effect.succeed(lines) : pullOrFlush;\n  }\n  return pullOrFlush;\n}));\n/**\n * Decodes incoming `Uint8Array` chunks into strings using `TextDecoder`.\n *\n * **Details**\n *\n * Input chunks are decoded with streaming enabled so multi-byte characters may\n * span `Uint8Array` boundaries. The optional `encoding` and `options` are\n * passed to `TextDecoder`.\n *\n * @category decoding\n * @since 4.0.0\n */\nexport const decodeText = (encoding, options) => fromTransform((upstream, _scope) => Effect.sync(() => {\n  const decoder = new TextDecoder(encoding, options);\n  const streamOptions = {\n    stream: true\n  };\n  return Effect.map(upstream, Arr.map(line => decoder.decode(line, streamOptions)));\n}));\n/**\n * Encodes incoming string chunks into `Uint8Array` values using `TextEncoder`.\n *\n * **Details**\n *\n * Each string inside an emitted array is encoded independently.\n *\n * @category encoding\n * @since 4.0.0\n */\nexport const encodeText = () => fromTransform((upstream, _scope) => Effect.sync(() => {\n  const encoder = new TextEncoder();\n  return Effect.map(upstream, Arr.map(line => encoder.encode(line)));\n}));\n/**\n * Returns a new channel that pipes the output of this channel into the\n * specified channel. The returned channel has the input type of this channel,\n * and the output type of the specified channel, terminating with the value of\n * the specified channel.\n *\n * **Example** (Piping one channel into another)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class PipeError extends Data.TaggedError(\"PipeError\")<{\n *   readonly stage: string\n * }> {}\n *\n * // Create source and transform channels\n * const sourceChannel = Channel.fromIterable([1, 2, 3])\n * const transformChannel = Channel.map(sourceChannel, (n: number) => n * 2)\n *\n * // Pipe the source into the transform\n * const pipedChannel = Channel.pipeTo(sourceChannel, transformChannel)\n *\n * Effect.runSync(Channel.runCollect(pipedChannel)) // => [2, 4, 6]\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const pipeTo = /*#__PURE__*/dual(2, (self, that) => fromTransform((upstream, scope) => Effect.flatMap(toTransform(self)(upstream, scope), upstream => toTransform(that)(upstream, scope))));\n/**\n * Returns a new channel that pipes the output of this channel into the\n * specified channel and preserves this channel's failures without providing\n * them to the other channel for observation.\n *\n * **Example** (Piping while preserving failures)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect, Exit } from \"effect\"\n *\n * class SourceError extends Data.TaggedError(\"SourceError\")<{\n *   readonly code: number\n * }> {}\n *\n * // Create a failing source channel\n * const error = new SourceError({ code: 404 })\n * const failingSource = Channel.fail(error)\n * const safeTransform = Channel.identity<never, never, never>()\n *\n * // Pipe while preserving source failures\n * const safePipedChannel = Channel.pipeToOrFail(failingSource, safeTransform)\n *\n * Effect.runSync(Effect.exit(Channel.runCollect(safePipedChannel))) // => Exit.fail(error)\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const pipeToOrFail = /*#__PURE__*/dual(2, (self, that) => fromTransform((upstream, scope) => Effect.flatMap(toTransform(self)(upstream, scope), upstream => {\n  const upstreamPull = Effect.catchCause(upstream, cause => Pull.isDoneCause(cause) ? Effect.failCause(cause) : Effect.die(Cause.Done(cause)));\n  return Effect.map(toTransform(that)(upstreamPull, scope), pull => Effect.catchDefect(pull, defect => Cause.isDone(defect) ? Effect.failCause(defect.value) : Effect.die(defect)));\n})));\n/**\n * Constructs a `Channel` from a scoped effect that will result in a\n * `Channel` if successful.\n *\n * **Example** (Unwrapping channel effects)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class UnwrapError extends Data.TaggedError(\"UnwrapError\")<{\n *   readonly reason: string\n * }> {}\n *\n * // Create an effect that produces a channel\n * const channelEffect = Effect.succeed(\n *   Channel.fromIterable([1, 2, 3])\n * )\n *\n * // Unwrap the effect to get the channel\n * const unwrappedChannel = Channel.unwrap(channelEffect)\n *\n * Effect.runSync(Channel.runCollect(unwrappedChannel)) // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const unwrap = channel => fromTransform((upstream, scope) => {\n  let pull;\n  return Effect.succeed(Effect.suspend(() => {\n    if (pull) return pull;\n    return channel.pipe(Scope.provide(scope), Effect.flatMap(channel => toTransform(channel)(upstream, scope)), Effect.flatMap(pull_ => pull = pull_));\n  }));\n});\n/**\n * Runs a channel with a scope provided for the duration of the channel\n * execution, removing the channel's `Scope` requirement.\n *\n * @category resource management\n * @since 2.0.0\n */\nexport const scoped = self => fromTransformBracket((upstream, scope, forkedScope) => Effect.map(Scope.provide(toTransform(self)(upstream, scope), forkedScope), Scope.provide(forkedScope)));\n/**\n * Runs an input handler against the upstream pull while the wrapped channel\n * runs without receiving upstream input directly.\n *\n * **Details**\n *\n * The input handler is forked in the channel scope. The wrapped channel is run\n * with an already-completed input.\n *\n * **Example** (Embedding custom input handling)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * // Create a base channel\n * const baseChannel = Channel.fromIterable([1, 2, 3])\n *\n * // Drain the embedded input while the base channel runs\n * const embeddedChannel = Channel.embedInput(\n *   baseChannel,\n *   (upstream) =>\n *     upstream.pipe(\n *       Effect.forever,\n *       Effect.ignore\n *     )\n * )\n * await Effect.runPromise(Channel.runCollect(embeddedChannel)) // => [1, 2, 3]\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const embedInput = /*#__PURE__*/dual(2, (self, input) => fromTransformBracket((upstream, scope, forkedScope) => Effect.andThen(Effect.forkIn(input(upstream), forkedScope), toTransform(self)(Cause.done(), scope))));\n/**\n * Buffers individual output elements in a queue with the configured `capacity`\n * so a faster producer can progress independently of a slower consumer.\n *\n * **When to use**\n *\n * Use when output elements can be decoupled from downstream demand and the\n * configured backpressure or loss strategy is acceptable.\n *\n * **Details**\n *\n * Finite queues use the `strategy` option. The default `\"suspend\"` strategy\n * applies backpressure, while `\"dropping\"` and `\"sliding\"` can discard output\n * elements when the queue is full. `\"unbounded\"` capacity does not use a finite\n * capacity strategy.\n *\n * **Gotchas**\n *\n * Dropping and sliding strategies can lose output elements under backpressure.\n *\n * @see {@link bufferArray} for buffering elements from array outputs\n *\n * @category buffering\n * @since 2.0.0\n */\nexport const buffer = /*#__PURE__*/dual(2, (self, options) => fromTransform(Effect.fnUntraced(function* (upstream, scope) {\n  const pull = yield* toTransform(self)(upstream, scope);\n  const queue = yield* Queue.make({\n    capacity: options.capacity === \"unbounded\" ? undefined : options.capacity,\n    strategy: options.capacity === \"unbounded\" ? undefined : options.strategy\n  });\n  yield* Scope.addFinalizer(scope, Queue.shutdown(queue));\n  yield* pull.pipe(Effect.flatMap(value => Queue.offer(queue, value)), Effect.forever({\n    disableYield: true\n  }), Effect.onError(cause => Queue.failCause(queue, cause)), Effect.forkIn(scope));\n  return Queue.take(queue);\n})));\n/**\n * Buffers array output elements in a queue with the configured `capacity` so a\n * faster producer can progress independently of a slower consumer.\n *\n * **When to use**\n *\n * Use when emitted arrays are batches of elements and it is acceptable for\n * buffering to flatten and rebuild those batches.\n *\n * **Details**\n *\n * Finite queues use the `strategy` option. The default `\"suspend\"` strategy\n * applies backpressure, while `\"dropping\"` and `\"sliding\"` can discard output\n * elements when the queue is full. `\"unbounded\"` capacity does not use a finite\n * capacity strategy.\n *\n * **Gotchas**\n *\n * Input arrays are offered to the queue element-by-element and outputs are\n * rebuilt from the currently available queued elements, so upstream array\n * boundaries are not preserved.\n *\n * @see {@link buffer} for buffering output elements without flattening arrays\n *\n * @category buffering\n * @since 4.0.0\n */\nexport const bufferArray = /*#__PURE__*/dual(2, (self, options) => fromTransform(Effect.fnUntraced(function* (upstream, scope) {\n  const pull = yield* toTransform(self)(upstream, scope);\n  const queue = yield* Queue.make({\n    capacity: options.capacity === \"unbounded\" ? undefined : options.capacity,\n    strategy: options.capacity === \"unbounded\" ? undefined : options.strategy\n  });\n  yield* Scope.addFinalizer(scope, Queue.shutdown(queue));\n  yield* pull.pipe(Effect.flatMap(value => Queue.offerAll(queue, value)), Effect.forever({\n    disableYield: true\n  }), Effect.onError(cause => Queue.failCause(queue, cause)), Effect.forkIn(scope));\n  return Queue.takeAll(queue);\n})));\n/**\n * Interrupts a channel when another effect completes.\n *\n * **When to use**\n *\n * Use to race channel execution against an external effect whose success can\n * become the channel's done value.\n *\n * **Details**\n *\n * If the effect completes first, its success value becomes the returned\n * channel's done value. If the channel completes first, the original channel's\n * done value is preserved.\n *\n * @category interruption\n * @since 2.0.0\n */\nexport const interruptWhen = /*#__PURE__*/dual(2, (self, effect) => merge(self, fromPull(Effect.succeed(Effect.flatMap(effect, Cause.done))), {\n  haltStrategy: \"either\"\n}));\n/**\n * Stops a channel when the specified effect completes or fails.\n *\n * **Details**\n *\n * If the effect completes before the channel is done, its success value becomes\n * the returned channel's done value. If the effect fails, the returned channel\n * fails with that error. If the channel completes first, the channel's done\n * value is preserved.\n *\n * @category interruption\n * @since 4.0.0\n */\nexport const haltWhen = /*#__PURE__*/dual(2, (self, effect) => fromTransformBracket(Effect.fnUntraced(function* (upstream, scope, forkedScope) {\n  const pull = yield* toTransform(self)(upstream, scope);\n  const fiber = yield* Effect.forkIn(effect, forkedScope, {\n    startImmediately: true\n  });\n  return Effect.suspend(() => {\n    const exit = fiber.pollUnsafe();\n    return exit === undefined ? pull : Exit.match(exit, {\n      onFailure: Effect.failCause,\n      onSuccess: Cause.done\n    });\n  });\n})));\n/**\n * Attaches a finalizer that runs only when the channel exits with failure.\n *\n * **Details**\n *\n * The finalizer receives the failure `Cause`. The original channel failure is\n * preserved. The finalizer itself must not fail.\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const onError = /*#__PURE__*/dual(2, (self, finalizer) => onExit(self, exit => Exit.isFailure(exit) ? finalizer(exit.cause) : Effect.void));\n/**\n * Returns a channel with an exit-aware finalizer that is guaranteed to run once\n * the channel begins execution, whether it succeeds or fails.\n *\n * **Example** (Running exit finalizers)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect, Exit } from \"effect\"\n *\n * class ExitError extends Data.TaggedError(\"ExitError\")<{\n *   readonly stage: string\n * }> {}\n *\n * // Create a channel\n * const dataChannel = Channel.fromIterable([1, 2, 3])\n *\n * // Attach exit handler\n * const exits: Array<Exit.Exit<void, ExitError>> = []\n * const channelWithExit = Channel.onExit(dataChannel, (exit) => {\n *   exits.push(exit)\n *   return Effect.void\n * })\n * const observed = [await Effect.runPromise(Channel.runCollect(channelWithExit)), exits] // => [[1, 2, 3], [Exit.void]]\n * ```\n *\n * @category resource management\n * @since 4.0.0\n */\nexport const onExit = /*#__PURE__*/dual(2, (self, finalizer) => fromTransformBracket((upstream, scope, forkedScope) => Scope.addFinalizerExit(forkedScope, finalizer).pipe(Effect.andThen(toTransform(self)(upstream, scope)))));\n/**\n * Runs an effect before the channel starts.\n *\n * **Details**\n *\n * The effect's successful value is ignored. If the effect fails, the returned\n * channel fails before running the source channel.\n *\n * @category hooks\n * @since 4.0.0\n */\nexport const onStart = /*#__PURE__*/dual(2, (self, onStart) => unwrap(Effect.as(onStart, self)));\n/**\n * Runs an effect the first time the channel emits an output element.\n *\n * **When to use**\n *\n * Use when initialization depends on the first output element rather than only\n * on channel startup.\n *\n * **Details**\n *\n * The effect receives the first emitted element. The first element is still\n * emitted unchanged. The effect is not run if the channel completes without\n * emitting an element.\n *\n * @category hooks\n * @since 4.0.0\n */\nexport const onFirst = /*#__PURE__*/dual(2, (self, onFirst) => transformPull(self, pull => Effect.sync(() => {\n  let isFirst = true;\n  const pullFirst = Effect.tap(pull, element => {\n    isFirst = false;\n    return onFirst(element);\n  });\n  return Effect.suspend(() => isFirst ? pullFirst : pull);\n})));\n/**\n * Runs an effect when the channel completes successfully.\n *\n * **Details**\n *\n * The effect runs before the original done value is propagated. The effect is\n * not run when the channel fails. If the effect fails, the returned channel\n * fails with that error.\n *\n * @category hooks\n * @since 4.0.0\n */\nexport const onEnd = /*#__PURE__*/dual(2, (self, onEnd) => transformPull(self, pull => Effect.succeed(Pull.catchDone(pull, leftover => Effect.flatMap(onEnd, () => Cause.done(leftover))))));\n/**\n * Returns a channel with a finalizer effect that is guaranteed to run once the\n * channel begins execution, whether it succeeds or fails.\n *\n * **Example** (Ensuring cleanup runs)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class EnsureError extends Data.TaggedError(\"EnsureError\")<{\n *   readonly operation: string\n * }> {}\n *\n * // Create a channel\n * const dataChannel = Channel.fromIterable([1, 2, 3])\n *\n * // Ensure cleanup always runs\n * const events: Array<string> = []\n * const channelWithCleanup = Channel.ensuring(\n *   dataChannel,\n *   Effect.sync(() => events.push(\"cleanup\"))\n * )\n * const observed = [await Effect.runPromise(Channel.runCollect(channelWithCleanup)), events] // => [[1, 2, 3], [\"cleanup\"]]\n * ```\n *\n * @category resource management\n * @since 2.0.0\n */\nexport const ensuring = /*#__PURE__*/dual(2, (self, finalizer) => onExit(self, _ => finalizer));\nconst runWith = (self, f, onHalt) => Effect.suspend(() => {\n  const scope = Scope.makeUnsafe();\n  const makePull = toTransform(self)(Cause.done(), scope);\n  return Pull.catchDone(Effect.flatMap(makePull, f), onHalt ? onHalt : Effect.succeed).pipe(Effect.onExit(exit => Scope.close(scope, exit)));\n});\n/**\n * Creates a channel from the specified services.\n *\n * @category accessors\n * @since 2.0.0\n */\nexport const contextWith = f => fromTransform((upstream, scope) => Effect.contextWith(context => toTransform(f(context))(upstream, scope)));\n/**\n * Provides a `Context` to the channel, removing the corresponding service\n * requirements from the returned channel.\n *\n * @category providing services\n * @since 2.0.0\n */\nexport const provideContext = /*#__PURE__*/dual(2, (self, context) => fromTransform((upstream, scope) => Effect.map(Effect.provideContext(toTransform(self)(upstream, scope), context), Effect.provideContext(context))));\n/**\n * Provides a concrete service for a context key, removing that service\n * requirement from the returned channel.\n *\n * @category providing services\n * @since 2.0.0\n */\nexport const provideService = /*#__PURE__*/dual(3, (self, key, service) => fromTransform((upstream, scope) => Effect.map(Effect.provideService(toTransform(self)(upstream, scope), key, service), Effect.provideService(key, service))));\n/**\n * Provides a service to the channel after obtaining it from an effect.\n *\n * **When to use**\n *\n * Use to supply a channel dependency when constructing the service itself is\n * effectful or can fail.\n *\n * **Details**\n *\n * If the service effect fails, the returned channel fails. The provided service\n * removes the corresponding service requirement from the returned channel.\n *\n * @category providing services\n * @since 4.0.0\n */\nexport const provideServiceEffect = /*#__PURE__*/dual(3, (self, key, service) => fromTransform((upstream, scope) => Effect.flatMap(service, s => toTransform(provideService(self, key, s))(upstream, scope))));\n/**\n * Provides a `Layer` or `Context` to the channel, removing the corresponding\n * service requirements.\n *\n * **Details**\n *\n * Providing a `Context` delegates to `provideContext`. Providing a `Layer`\n * builds the layer in the channel scope. Use `options.local` to build a fresh\n * layer instance for this provision.\n *\n * @category providing services\n * @since 4.0.0\n */\nexport const provide = /*#__PURE__*/dual(args => isChannel(args[0]), (self, layer, options) => Context.isContext(layer) ? provideContext(self, layer) : fromTransform((upstream, scope) => Effect.flatMap(options?.local ? Layer.buildWithMemoMap(layer, Layer.makeMemoMapUnsafe(), scope) : Layer.buildWithScope(layer, scope), context => Effect.map(Effect.provideContext(toTransform(self)(upstream, scope), context), Effect.provideContext(context)))));\n/**\n * Transforms the current context before running the channel.\n *\n * **Details**\n *\n * The function receives the surrounding context and returns the context to\n * provide to the channel. The returned channel requires the services needed to\n * build that context.\n *\n * @category providing services\n * @since 4.0.0\n */\nexport const updateContext = /*#__PURE__*/dual(2, (self, f) => fromTransform((upstream, scope) => Effect.contextWith(context => {\n  const toProvide = f(context);\n  return toTransform(provideContext(self, toProvide))(upstream, scope);\n})));\n/**\n * Updates a service in the current context before running the channel.\n *\n * **Details**\n *\n * The existing service is read from the context. The updated service is\n * provided to the channel under the same key.\n *\n * @category providing services\n * @since 2.0.0\n */\nexport const updateService = /*#__PURE__*/dual(3, (self, service, f) => updateContext(self, context => Context.add(context, service, f(Context.get(context, service)))));\n/**\n * Runs the channel inside a tracing span with the specified name and options.\n *\n * **Details**\n *\n * The created span is provided as the current parent span while the channel\n * runs. The span is ended with the channel's exit value.\n *\n * @category tracing\n * @since 2.0.0\n */\nexport const withSpan = function () {\n  const dataFirst = isChannel(arguments[0]);\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 withSpanImpl(self, name, options);\n  }\n  return self => withSpanImpl(self, name, options);\n};\nconst withSpanImpl = (self, name, options) => acquireUseRelease(Effect.makeSpan(name, options), span => provideService(self, ParentSpan, span), (span, exit) => Effect.withFiber(fiber => {\n  const clock = fiber.getRef(ClockRef);\n  const timingEnabled = fiber.getRef(TracerTimingEnabled);\n  return endSpan(span, exit, clock, timingEnabled);\n}));\n/**\n * The starting channel for Do notation, emitting an empty object.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Do = /*#__PURE__*/succeed({});\nconst let_ = /*#__PURE__*/dual(3, (self, name, f) => map(self, elem => ({\n  ...elem,\n  [name]: f(elem)\n})));\nexport {\n/**\n * Adds a computed field to each object emitted by a channel.\n *\n * @category mapping\n * @since 4.0.0\n */\nlet_ as let };\n/**\n * Adds a field to each object emitted by a channel by running another channel\n * derived from that object.\n *\n * **Details**\n *\n * The field name must not already exist on the emitted object. The derived\n * channel's output becomes the value of the new field. `options.concurrency`\n * and `options.bufferSize` control how derived channels are flattened.\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const bind = /*#__PURE__*/dual(args => isChannel(args[0]), (self, name, f, options) => flatMap(self, elem => map(f(elem), b => ({\n  ...elem,\n  [name]: b\n})), options));\n/**\n * Wraps each output element in an object under the specified field name.\n *\n * **When to use**\n *\n * Use when you need to start a Channel Do-notation chain from an existing\n * output value by assigning that value to a field name.\n *\n * @see {@link Do} for starting Do notation from an empty object\n * @see {@link bind} for adding a field produced by another channel\n * @see {@link let_ let} for adding a computed field\n *\n * @category mapping\n * @since 4.0.0\n */\nexport const bindTo = /*#__PURE__*/dual(2, (self, name) => map(self, elem => ({\n  [name]: elem\n})));\n/**\n * Runs a channel and counts the number of elements it outputs.\n *\n * **Example** (Counting channel output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class CountError extends Data.TaggedError(\"CountError\")<{\n *   readonly reason: string\n * }> {}\n *\n * // Create a channel with multiple elements\n * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5])\n *\n * // Count the elements\n * const countEffect = Channel.runCount(numbersChannel)\n *\n * Effect.runSync(countEffect) // => 5\n * ```\n *\n * @category running\n * @since 4.0.0\n */\nexport const runCount = self => runFold(self, () => 0, acc => acc + 1);\n/**\n * Runs a channel and discards all output elements, returning only the final result.\n *\n * **Example** (Draining channel output at runtime)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class DrainError extends Data.TaggedError(\"DrainError\")<{\n *   readonly stage: string\n * }> {}\n *\n * // Create a channel that outputs elements and completes with a result\n * const resultChannel = Channel.fromIterable([1, 2, 3])\n * const completedChannel = Channel.concat(resultChannel, Channel.end(\"completed\"))\n *\n * // Drain all elements and get only the final result\n * const drainEffect = Channel.runDrain(completedChannel)\n *\n * Effect.runSync(drainEffect) // => \"completed\"\n * ```\n *\n * @category running\n * @since 2.0.0\n */\nexport const runDrain = self => runWith(self, pull => Effect.forever(pull, {\n  disableYield: true\n}));\n/**\n * Runs a channel and applies an effect to each output element.\n *\n * **Example** (Running effects for each output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class ForEachError extends Data.TaggedError(\"ForEachError\")<{\n *   readonly element: unknown\n * }> {}\n *\n * // Create a channel with numbers\n * const numbersChannel = Channel.fromIterable([1, 2, 3])\n *\n * // Run forEach to process each element\n * const processed: Array<number> = []\n * const forEachEffect = Channel.runForEach(\n *   numbersChannel,\n *   (n) => Effect.sync(() => processed.push(n))\n * )\n *\n * await Effect.runPromise(forEachEffect)\n * processed // => [1, 2, 3]\n * ```\n *\n * @category running\n * @since 4.0.0\n */\nexport const runForEach = /*#__PURE__*/dual(2, (self, f) => runWith(self, pull => Effect.forever(Effect.flatMap(pull, f), {\n  disableYield: true\n})));\n/**\n * Runs a channel and applies an effectful predicate to each output element\n * until the predicate returns `false`.\n *\n * **Details**\n *\n * Returning `true` continues consuming the channel. Returning `false` stops\n * consumption early. The returned effect completes with `void`.\n *\n * @category running\n * @since 4.0.0\n */\nexport const runForEachWhile = /*#__PURE__*/dual(2, (self, f) => runWith(self, pull => pull.pipe(Effect.flatMap(f), Effect.flatMap(cont => cont ? Effect.void : Cause.done()), Effect.forever({\n  disableYield: true\n}))));\n/**\n * Concatenates a channel's `Uint8Array` chunks into a single `Uint8Array`.\n *\n * **Gotchas**\n *\n * This materializes the full content in memory. The source channel must not\n * reuse or mutate emitted buffers, which are retained until collection completes.\n *\n * **Example** (Joining channel byte chunks)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect } from \"effect\"\n *\n * const channel = Channel.fromArray([\n *   [new Uint8Array([1, 2])],\n *   [new Uint8Array([3, 4])]\n * ] as const)\n *\n * const bytes = Effect.runSync(Channel.mkUint8Array(channel))\n * Array.from(bytes) // => [1, 2, 3, 4]\n * ```\n *\n * @category running\n * @since 4.0.0\n */\nexport const mkUint8Array = self => Effect.map(runFold(self, () => ({\n  bytes: 0,\n  arrays: []\n}), (acc, chunk) => {\n  for (let i = 0; i < chunk.length; i++) {\n    acc.bytes += chunk[i].length;\n    acc.arrays.push(chunk[i]);\n  }\n  return acc;\n}), ({\n  arrays,\n  bytes\n}) => {\n  const result = new Uint8Array(bytes);\n  let offset = 0;\n  for (let i = 0; i < arrays.length; i++) {\n    const array = arrays[i];\n    result.set(array, offset);\n    offset += array.length;\n  }\n  return result;\n});\n/**\n * Runs a channel and collects all output elements into an array.\n *\n * **Example** (Collecting channel output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class CollectError extends Data.TaggedError(\"CollectError\")<{\n *   readonly reason: string\n * }> {}\n *\n * // Create a channel with elements\n * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5])\n *\n * // Collect all elements into an array\n * const collectEffect = Channel.runCollect(numbersChannel)\n *\n * Effect.runSync(collectEffect) // => [1, 2, 3, 4, 5]\n * ```\n *\n * @category running\n * @since 2.0.0\n */\nexport const runCollect = self => runFold(self, () => [], (acc, o) => {\n  acc.push(o);\n  return acc;\n});\n/**\n * Runs a channel until the first output element is available, returning it in\n * an `Option`.\n *\n * **Details**\n *\n * Returns `Option.some` with the first output element, or `Option.none` if the\n * channel completes without emitting output.\n *\n * @category running\n * @since 4.0.0\n */\nexport const runHead = self => Effect.suspend(() => {\n  let head = Option.none();\n  return runWith(self, pull => pull.pipe(Effect.asSome, Effect.flatMap(head_ => {\n    head = head_;\n    return Cause.done();\n  })), () => Effect.succeed(head));\n});\n/**\n * Runs a channel to completion and returns the last output element in an\n * `Option`.\n *\n * **Details**\n *\n * Returns `Option.some` with the last emitted element, or `Option.none` if the\n * channel completes without emitting output.\n *\n * @category running\n * @since 4.0.0\n */\nexport const runLast = self => Effect.suspend(() => {\n  const absent = Symbol(); // Prevent boxing\n  let last = absent;\n  return runWith(self, pull => Effect.forever(Effect.flatMap(pull, item => {\n    last = item;\n    return Effect.void;\n  }), {\n    disableYield: true\n  }), () => last === absent ? Effect.succeedNone : Effect.succeedSome(last));\n});\n/**\n * Runs a channel and folds over all output elements with an accumulator.\n *\n * **Example** (Folding channel output)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class FoldError extends Data.TaggedError(\"FoldError\")<{\n *   readonly operation: string\n * }> {}\n *\n * // Create a channel with numbers\n * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5])\n *\n * // Fold to calculate sum\n * const sumEffect = Channel.runFold(numbersChannel, () => 0, (acc, n) => acc + n)\n *\n * Effect.runSync(sumEffect) // => 15\n * ```\n *\n * @category running\n * @since 4.0.0\n */\nexport const runFold = /*#__PURE__*/dual(3, (self, initial, f) => Effect.suspend(() => {\n  let state = initial();\n  return runWith(self, pull => Effect.whileLoop({\n    while: constTrue,\n    body: () => pull,\n    step: value => {\n      state = f(state, value);\n    }\n  }), () => Effect.succeed(state));\n}));\n/**\n * Runs a channel and effectfully folds all output elements with an accumulator.\n *\n * **When to use**\n *\n * Use when folding channel output needs effects, services, or an additional\n * failure channel during accumulation.\n *\n * **Details**\n *\n * The initial accumulator is evaluated lazily. Each output element is passed to\n * the effectful accumulator function. The returned effect succeeds with the\n * final accumulator value.\n *\n * @category running\n * @since 4.0.0\n */\nexport const runFoldEffect = /*#__PURE__*/dual(3, (self, initial, f) => Effect.suspend(() => {\n  let state = initial();\n  return runWith(self, pull => Effect.whileLoop({\n    while: constTrue,\n    body: constant(pull.pipe(Effect.flatMap(o => f(state, o)), Effect.map(s => {\n      state = s;\n    }))),\n    step: constVoid\n  }), () => Effect.succeed(state));\n}));\n/**\n * Converts a channel to a scoped `Pull` for low-level consumption.\n *\n * **Details**\n *\n * The effect requires a `Scope`. The returned pull should be consumed only\n * while that scope remains open. Pulls are serialized so only one pull is\n * evaluated at a time.\n *\n * **Example** (Converting channels to pulls)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect } from \"effect\"\n *\n * class PullError extends Data.TaggedError(\"PullError\")<{\n *   readonly step: string\n * }> {}\n *\n * // Create a channel\n * const numbersChannel = Channel.fromIterable([1, 2, 3])\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n *   const pull = yield* Channel.toPull(numbersChannel)\n *   return [yield* pull, yield* pull, yield* pull]\n * }))\n * await Effect.runPromise(program) // => [1, 2, 3]\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const toPull = /*#__PURE__*/Effect.fnUntraced(function* (self) {\n  const semaphore = Semaphore.makeUnsafe(1);\n  const context = yield* Effect.context();\n  const scope = Context.get(context, Scope.Scope);\n  const pull = yield* toTransform(self)(Cause.done(), scope);\n  return pull.pipe(Effect.provideContext(context), semaphore.withPermits(1));\n},\n/*#__PURE__*/\n// ensure errors are redirected to the pull effect\nEffect.catchCause(cause => Effect.succeed(Effect.failCause(cause))));\n/**\n * Converts a channel to a Pull within an existing scope.\n *\n * **Example** (Converting channels to scoped pulls)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect, Scope } from \"effect\"\n *\n * class ScopedPullError extends Data.TaggedError(\"ScopedPullError\")<{\n *   readonly reason: string\n * }> {}\n *\n * // Create a channel\n * const numbersChannel = Channel.fromIterable([1, 2, 3])\n *\n * // Convert to Pull with explicit scope\n * const scopedPullEffect = Effect.gen(function*() {\n *   const scope = yield* Effect.scope\n *   const pull = yield* Channel.toPullScoped(numbersChannel, scope)\n *   return [yield* pull, yield* pull, yield* pull]\n * })\n * await Effect.runPromise(Effect.scoped(scopedPullEffect)) // => [1, 2, 3]\n * ```\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const toPullScoped = (self, scope) => toTransform(self)(Cause.done(), scope);\n/**\n * Runs a channel and offers each output element into a queue.\n *\n * **Details**\n *\n * When the channel completes, the queue is ended. When the channel fails, the\n * queue is failed with the channel's cause. The returned effect itself\n * completes with `void`.\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const runIntoQueue = /*#__PURE__*/dual(args => isChannel(args[0]), (self, queue) => Effect.uninterruptibleMask(restore => runForEach(self, value => Queue.offer(queue, value)).pipe(restore, Effect.exit, Effect.flatMap(exit => {\n  if (Exit.isSuccess(exit)) {\n    Queue.endUnsafe(queue);\n  } else {\n    Queue.failCauseUnsafe(queue, exit.cause);\n  }\n  return Effect.void;\n}))));\n/**\n * Runs a channel that emits non-empty arrays and offers each array element into\n * a queue.\n *\n * **Details**\n *\n * When the channel completes, the queue is ended. When the channel fails, the\n * queue is failed with the channel's cause. The returned effect itself\n * completes with `void`.\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const runIntoQueueArray = /*#__PURE__*/dual(args => isChannel(args[0]), (self, queue) => Effect.uninterruptibleMask(restore => runForEach(self, value => Queue.offerAll(queue, value)).pipe(restore, Effect.exit, Effect.flatMap(exit => {\n  if (Exit.isSuccess(exit)) {\n    Queue.endUnsafe(queue);\n  } else {\n    Queue.failCauseUnsafe(queue, exit.cause);\n  }\n  return Effect.void;\n}))));\n/**\n * Creates a scoped queue and forks the channel to feed it for concurrent\n * consumption.\n *\n * **Details**\n *\n * Output elements are offered to the queue. Channel completion and failure are\n * signaled through the queue. The queue is shut down when the surrounding scope\n * closes.\n *\n * **Example** (Converting channels to queues)\n *\n * ```ts import.meta.vitest\n * import { Channel, Data, Effect, Queue } from \"effect\"\n *\n * class QueueError extends Data.TaggedError(\"QueueError\")<{\n *   readonly operation: string\n * }> {}\n *\n * // Create a channel with data\n * const dataChannel = Channel.fromIterable([1, 2, 3, 4, 5])\n *\n * // Convert to queue for concurrent processing\n * const program = Effect.scoped(Effect.gen(function*() {\n *   const queue = yield* Channel.toQueue(dataChannel, { capacity: 32 })\n *   return yield* Queue.takeBetween(queue, 5, 5)\n * }))\n * await Effect.runPromise(program) // => [1, 2, 3, 4, 5]\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const toQueue = /*#__PURE__*/dual(args => isChannel(args[0]), /*#__PURE__*/Effect.fnUntraced(function* (self, options) {\n  const scope = yield* Effect.scope;\n  const queue = yield* Queue.make({\n    capacity: typeof options.capacity === \"number\" ? options.capacity : undefined,\n    strategy: typeof options.capacity === \"number\" ? options.strategy : undefined\n  });\n  yield* Scope.addFinalizer(scope, Queue.shutdown(queue));\n  yield* Effect.forkIn(runIntoQueue(self, queue), scope);\n  return queue;\n}));\n/**\n * Creates a scoped queue and forks an array-emitting channel to feed it.\n *\n * **Details**\n *\n * Each element inside emitted non-empty arrays is offered to the queue. Channel\n * completion and failure are signaled through the queue. The queue is shut down\n * when the surrounding scope closes.\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const toQueueArray = /*#__PURE__*/dual(args => isChannel(args[0]), /*#__PURE__*/Effect.fnUntraced(function* (self, options) {\n  const scope = yield* Effect.scope;\n  const queue = yield* Queue.make({\n    capacity: typeof options.capacity === \"number\" ? options.capacity : undefined,\n    strategy: typeof options.capacity === \"number\" ? options.strategy : undefined\n  });\n  yield* Scope.addFinalizer(scope, Queue.shutdown(queue));\n  yield* Effect.forkIn(runIntoQueueArray(self, queue), scope);\n  return queue;\n}));\n/**\n * Converts a channel to a PubSub for concurrent consumption.\n *\n * **Details**\n *\n * `shutdownOnEnd` indicates whether the PubSub should be shut down when the\n * channel ends. By default this is `true`.\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const toPubSub = /*#__PURE__*/dual(2, /*#__PURE__*/Effect.fnUntraced(function* (self, options) {\n  const pubsub = yield* makePubSub(options);\n  yield* Effect.forkScoped(runIntoPubSub(self, pubsub, {\n    shutdownOnEnd: options.shutdownOnEnd !== false\n  }));\n  return pubsub;\n}));\n/**\n * Runs a channel and publishes each output element to a `PubSub`.\n *\n * **Details**\n *\n * The channel's output values are published as individual PubSub messages. Use\n * `options.shutdownOnEnd` to shut down the PubSub when channel execution ends.\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const runIntoPubSub = /*#__PURE__*/dual(args => isChannel(args[0]), (self, pubsub, options) => runForEach(self, value => PubSub.publish(pubsub, value)).pipe(options?.shutdownOnEnd === true ? Effect.ensuring(PubSub.shutdown(pubsub)) : identity_));\nconst makePubSub = options => Effect.acquireRelease(options.capacity === \"unbounded\" ? PubSub.unbounded(options) : options.strategy === \"dropping\" ? PubSub.dropping(options) : options.strategy === \"sliding\" ? PubSub.sliding(options) : PubSub.bounded(options), PubSub.shutdown);\n/**\n * Converts an array-emitting channel to a scoped `PubSub` for concurrent\n * consumption.\n *\n * **Details**\n *\n * Each element inside emitted non-empty arrays is published as an individual\n * PubSub message. `shutdownOnEnd` indicates whether the PubSub should be shut\n * down when the channel ends. By default this is `true`.\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const toPubSubArray = /*#__PURE__*/dual(2, /*#__PURE__*/Effect.fnUntraced(function* (self, options) {\n  const pubsub = yield* makePubSub(options);\n  yield* Effect.forkScoped(runIntoPubSubArray(self, pubsub, {\n    shutdownOnEnd: options.shutdownOnEnd !== false\n  }));\n  return pubsub;\n}));\n/**\n * Runs an array-emitting channel and publishes each array element to a\n * `PubSub`.\n *\n * **Details**\n *\n * Each element inside emitted non-empty arrays is published as an individual\n * PubSub message. Use `options.shutdownOnEnd` to shut down the PubSub when\n * channel execution ends.\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const runIntoPubSubArray = /*#__PURE__*/dual(args => isChannel(args[0]), (self, pubsub, options) => runForEach(self, value => PubSub.publishAll(pubsub, value)).pipe(options?.shutdownOnEnd === true ? Effect.ensuring(PubSub.shutdown(pubsub)) : identity_));\n/**\n * Converts a channel to a scoped `PubSub` of `Take` values.\n *\n * **Details**\n *\n * Emitted non-empty arrays are published as output `Take` values. When the\n * channel ends, its final `Exit` is published so subscribers can observe\n * completion or failure.\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const toPubSubTake = /*#__PURE__*/dual(2, /*#__PURE__*/Effect.fnUntraced(function* (self, options) {\n  const pubsub = yield* makePubSub(options);\n  yield* runForEach(self, value => PubSub.publish(pubsub, value)).pipe(Effect.onExit(exit => PubSub.publish(pubsub, exit)), Effect.forkScoped);\n  return pubsub;\n}));\n//# sourceMappingURL=Channel.js.map","import { identity } from \"../Function.js\";\nimport { pipeArguments } from \"../Pipeable.js\";\nconst TypeId = \"~effect/Stream\";\nconst streamVariance = {\n  _R: identity,\n  _E: identity,\n  _A: identity\n};\nconst Stream = function (channel) {\n  this.channel = channel;\n};\nStream.prototype = {\n  [TypeId]: streamVariance,\n  pipe() {\n    return pipeArguments(this, arguments);\n  }\n};\n/** @internal */\nexport const fromChannel = channel => new Stream(channel);\n//# sourceMappingURL=stream.js.map","import * as Arr from \"./Array.js\";\nimport * as Cause from \"./Cause.js\";\nimport * as Channel from \"./Channel.js\";\nimport * as Clock from \"./Clock.js\";\nimport * as Duration from \"./Duration.js\";\nimport * as Effect from \"./Effect.js\";\nimport * as Exit from \"./Exit.js\";\nimport { constant, constFalse, constTrue, constVoid, dual, identity, pipe } from \"./Function.js\";\nimport * as Count from \"./internal/count.js\";\nimport * as internalStream from \"./internal/stream.js\";\nimport * as Option from \"./Option.js\";\nimport { pipeArguments } from \"./Pipeable.js\";\nimport { hasProperty } from \"./Predicate.js\";\nimport * as PubSub from \"./PubSub.js\";\nimport * as Pull from \"./Pull.js\";\nimport * as Queue from \"./Queue.js\";\nimport * as Result from \"./Result.js\";\nimport * as Scope from \"./Scope.js\";\nconst TypeId = \"~effect/Sink\";\nconst endVoid = /*#__PURE__*/Effect.succeed([void 0]);\nconst sinkVariance = {\n  _A: identity,\n  _In: identity,\n  _L: identity,\n  _E: identity,\n  _R: identity\n};\nconst SinkProto = {\n  [TypeId]: sinkVariance,\n  pipe() {\n    return pipeArguments(this, arguments);\n  }\n};\n/**\n * Checks whether a value is a Sink.\n *\n * **Example** (Checking for a sink)\n *\n * ```ts import.meta.vitest\n * import { Sink } from \"effect\"\n *\n * const sink = Sink.never\n * const notStream = { data: [1, 2, 3] }\n *\n * Sink.isSink(sink) // => true\n * Sink.isSink(notStream) // => false\n * ```\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isSink = u => hasProperty(u, TypeId);\n/**\n * Creates a sink from a `Channel`.\n *\n * **When to use**\n *\n * Use to create a `Sink` from a `Channel` that processes non-empty arrays of\n * input values.\n *\n * **Example** (Using channel completion as the sink result)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect, Sink, Stream } from \"effect\"\n *\n * const channel = Channel.identity<readonly [number, ...Array<number>], never, void>().pipe(\n *   Channel.drain,\n *   Channel.mapDone(() => [\"consumed\"] as const)\n * )\n * const sink = Sink.fromChannel(channel)\n *\n * await Effect.runPromise(Stream.run(Stream.make(1, 2, 3), sink)) // => \"consumed\"\n * ```\n *\n * @see {@link toChannel} for converting a `Sink` back to a `Channel`\n * @category constructors\n * @since 2.0.0\n */\nexport const fromChannel = channel => fromTransform((upstream, scope) => Channel.toTransform(channel)(upstream, scope).pipe(Effect.flatMap(Effect.forever({\n  disableYield: true\n})), Pull.catchDone(Effect.succeed)));\n/**\n * Creates a sink that writes its input to a Web `WritableStream`.\n *\n * **Example** (Collecting values in a Web stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Sink, Stream } from \"effect\"\n *\n * const written: Array<number> = []\n * const sink = Sink.fromWritableStream({\n *   evaluate: () => new WritableStream<number>({\n *     write(value) {\n *       written.push(value)\n *     }\n *   }),\n *   onError: (cause) => new Error(String(cause))\n * })\n *\n * await Effect.runPromise(Stream.run(Stream.make(1, 2, 3), sink))\n * written // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromWritableStream = options => fromChannel(Channel.mapDone(Channel.fromWritableStream(options), _ => [_]));\n/**\n * Creates a `Sink` from a low-level transform function.\n *\n * **Details**\n *\n * The transform receives the upstream pull of non-empty input arrays and the\n * active scope, and returns an effect that completes with the sink's `End`\n * value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromTransform = transform => {\n  const self = Object.create(SinkProto);\n  self.transform = transform;\n  return self;\n};\n/**\n * Creates a `Channel` from a Sink.\n *\n * **Example** (Running a sink as a channel)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect, Sink, Stream } from \"effect\"\n *\n * const channel = Stream.toChannel(Stream.make(1, 2, 3)).pipe(\n *   Channel.pipeTo(Sink.toChannel(Sink.sum))\n * )\n *\n * await Effect.runPromise(Channel.runDrain(channel)) // => [6]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const toChannel = self => Channel.fromTransform((upstream, scope) => Effect.succeed(Effect.flatMap(self.transform(upstream, scope), Cause.done)));\n/**\n * Creates a pipe-style constructor for sinks over input type `In`.\n *\n * **Details**\n *\n * The returned function exposes the sink input as a `Stream<In>`, applies the\n * provided pipeline, and uses the final effect's success value as the sink\n * result.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = () => (...fns) => fromTransform((upstream, scope) => pipe(internalStream.fromChannel(Channel.fromPull(Effect.succeed(upstream))), ...fns, Effect.flatMap(a => Cause.done([a])), Scope.provide(scope)));\n/**\n * Creates a sink that ignores upstream input and completes from an effect that\n * already returns an `End`.\n *\n * **When to use**\n *\n * Use when you need to create a sink from an effect that returns both the sink\n * result value and optional leftovers.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromEffectEnd = effect => fromTransform(() => effect);\n/**\n * Creates a sink that ignores upstream input and completes with the success\n * value of the provided effect.\n *\n * **Details**\n *\n * If the effect fails, the sink fails with the same error.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromEffect = effect => fromEffectEnd(Effect.map(effect, a => [a]));\n/**\n * Creates a sink that offers every consumed input element to a queue.\n *\n * **Details**\n *\n * When the upstream stream ends, the sink ends the queue and completes with\n * `void`.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromQueue = queue => fromTransform(upstream => upstream.pipe(Effect.flatMap(arr => Queue.offerAll(queue, arr)), Effect.forever({\n  disableYield: true\n}), Pull.catchDone(_ => {\n  Queue.endUnsafe(queue);\n  return endVoid;\n})));\n/**\n * Creates a sink that publishes every consumed input element to a `PubSub`.\n *\n * **Details**\n *\n * The sink completes with `void` when the upstream stream ends.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromPubSub = pubsub => forEachArray(arr => PubSub.publishAll(pubsub, arr));\n/**\n * A sink that immediately ends with the specified value.\n *\n * **Example** (Succeeding with a value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Sink, Stream } from \"effect\"\n *\n * // Create a sink that always yields the same value\n * const sink = Sink.succeed(42)\n *\n * // Use it with a stream\n * const stream = Stream.make(1, 2, 3)\n * await Effect.runPromise(Stream.run(stream, sink)) // => 42\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const succeed = (a, leftovers) => fromEffectEnd(Effect.succeed([a, leftovers]));\n/**\n * A sink that immediately ends with the specified lazily evaluated value.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const sync = a => fromEffect(Effect.sync(a));\n/**\n * A sink that is created from a lazily evaluated sink.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const suspend = evaluate => fromTransform((upstream, scope) => evaluate().transform(upstream, scope));\n/**\n * A sink that always fails with the specified error.\n *\n * **Example** (Failing with an error)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Sink, Stream } from \"effect\"\n *\n * // Create a sink that always fails\n * const sink = Sink.fail(\"Sink failed\")\n *\n * // Use it with a stream\n * const stream = Stream.make(1, 2, 3)\n * await Effect.runPromiseExit(Stream.run(stream, sink)) // => Exit.fail(\"Sink failed\")\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fail = e => fromEffectEnd(Effect.fail(e));\n/**\n * A sink that always fails with the specified lazily evaluated error.\n *\n * **Example** (Failing with a lazy error)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Sink, Stream } from \"effect\"\n *\n * // Create a sink that fails with a lazy error\n * const sink = Sink.failSync(() => \"Lazy error\")\n *\n * // Use it with a stream\n * const stream = Stream.make(1, 2, 3)\n * await Effect.runPromiseExit(Stream.run(stream, sink)) // => Exit.fail(\"Lazy error\")\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const failSync = evaluate => fromEffectEnd(Effect.failSync(evaluate));\n/**\n * Creates a sink halting with a specified `Cause`.\n *\n * **Example** (Failing with a cause)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Exit, Sink, Stream } from \"effect\"\n *\n * // Create a sink that fails with a specific cause\n * const sink = Sink.failCause(Cause.fail(\"Custom cause\"))\n *\n * // Use it with a stream\n * const stream = Stream.make(1, 2, 3)\n * await Effect.runPromiseExit(Stream.run(stream, sink)) // => Exit.fail(\"Custom cause\")\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const failCause = cause => fromEffectEnd(Effect.failCause(cause));\n/**\n * Creates a sink halting with a specified lazily evaluated `Cause`.\n *\n * **Example** (Failing with a lazy cause)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Exit, Sink, Stream } from \"effect\"\n *\n * // Create a sink that fails with a lazy cause\n * const sink = Sink.failCauseSync(() => Cause.fail(\"Lazy cause\"))\n *\n * // Use it with a stream\n * const stream = Stream.make(1, 2, 3)\n * await Effect.runPromiseExit(Stream.run(stream, sink)) // => Exit.fail(\"Lazy cause\")\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const failCauseSync = evaluate => fromEffectEnd(Effect.failCauseSync(evaluate));\n/**\n * Creates a sink halting with a specified defect.\n *\n * **Example** (Dying with a defect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Sink, Stream } from \"effect\"\n *\n * // Create a sink that dies with a defect\n * const sink = Sink.die(\"Defect error\")\n *\n * // Use it with a stream\n * const stream = Stream.make(1, 2, 3)\n * await Effect.runPromiseExit(Stream.run(stream, sink)) // => Exit.die(\"Defect error\")\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const die = defect => fromEffectEnd(Effect.die(defect));\n/**\n * A sink that never completes.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const never = /*#__PURE__*/fromEffectEnd(Effect.never);\n/**\n * Drops leftovers produced by a sink.\n *\n * **Details**\n *\n * The sink result is preserved, but any leftover elements are discarded\n * instead of being returned to downstream sink composition. This does not\n * continue pulling additional elements from the upstream stream.\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const ignoreLeftover = self => mapEnd(self, ([a]) => [a]);\n/**\n * Consumes and ignores all stream inputs.\n *\n * **When to use**\n *\n * Use to consume all upstream input and complete with void when the input\n * values and any aggregate result are not needed.\n *\n * @see {@link count} for consuming all input while returning the number of elements\n * @see {@link forEach} for consuming all input while running an effect for each element\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const drain = /*#__PURE__*/fromTransform(upstream => Pull.catchDone(Effect.forever(upstream, {\n  disableYield: true\n}), () => endVoid));\n/**\n * A sink that folds its inputs with the provided function, termination\n * predicate and initial state.\n *\n * **When to use**\n *\n * Use to accumulate stream input element by element with an effectful step and\n * stop based on the accumulated state.\n *\n * **Details**\n *\n * The initial state is evaluated lazily. Each input element is folded with the\n * effectful function, and the sink continues while `contFn` returns `true`. If\n * the sink stops in the middle of a pulled array, the remaining elements from\n * that array are returned as leftovers.\n *\n * @see {@link foldArray} for folding each pulled non-empty input array at once\n * @see {@link foldUntil} for folding until a fixed maximum number of elements is consumed\n *\n * @category folding\n * @since 2.0.0\n */\nexport const fold = (s, contFn, f) => fromTransform(upstream => {\n  let state = s();\n  return Effect.gen(function* () {\n    while (true) {\n      const arr = yield* upstream;\n      for (let i = 0; i < arr.length; i++) {\n        state = yield* f(state, arr[i]);\n        if (contFn(state)) continue;\n        return [state, i + 1 < arr.length ? arr.slice(i + 1) : undefined];\n      }\n    }\n  }).pipe(Pull.catchDone(() => Effect.succeed([state])));\n});\n/**\n * Folds non-empty input arrays into state with an effectful function.\n *\n * **When to use**\n *\n * Use to update state with an effectful function once per pulled non-empty\n * input array when batch-level processing is the natural unit.\n *\n * **Details**\n *\n * The initial state is evaluated lazily. After each pulled array is folded,\n * the sink continues while `contFn` returns `true`; otherwise it completes\n * with the current state.\n *\n * @see {@link fold} for folding element by element and returning leftovers when stopping mid-array\n * @see {@link reduceWhileArrayEffect} for array-level effectful reducing that checks the predicate before consuming input\n *\n * @category folding\n * @since 4.0.0\n */\nexport const foldArray = (s, contFn, f) => fromTransform(upstream => {\n  let state = s();\n  return Effect.gen(function* () {\n    while (true) {\n      const arr = yield* upstream;\n      state = yield* f(state, arr);\n      if (contFn(state)) continue;\n      return [state];\n    }\n  }).pipe(Pull.catchDone(() => Effect.succeed([state])));\n});\n/**\n * Folds input elements into state until the specified maximum number of\n * elements has been consumed or the upstream stream ends.\n *\n * **Details**\n *\n * Finite fractional values of `max` are rounded down. If `max` is `NaN` or\n * non-positive, the sink completes with the initial state without consuming\n * input.\n *\n * If the sink stops in the middle of a pulled array, the remaining elements\n * from that array are returned as leftovers.\n *\n * @category folding\n * @since 2.0.0\n */\nexport const foldUntil = (s, max, f) => {\n  const count = Count.normalize(max);\n  if (count === 0) return sync(s);\n  return fold(() => [s(), 0], tuple => tuple[1] < count, ([output, consumed], input) => Effect.map(f(output, input), s => [s, consumed + 1])).pipe(map(tuple => tuple[0]));\n};\n/**\n * A sink that returns whether all elements satisfy the specified predicate.\n *\n * **When to use**\n *\n * Use to reduce a stream to a boolean that is true only when every input\n * satisfies a pure predicate.\n *\n * @see {@link some} for the dual any-match check\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const every = predicate => fold(constTrue, identity, (_, a) => Effect.succeed(predicate(a)));\n/**\n * A sink that returns whether an element satisfies the specified predicate.\n *\n * **When to use**\n *\n * Use to reduce a stream to a boolean that is true when any input satisfies a\n * pure predicate.\n *\n * @see {@link every} for the all-match check\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const some = predicate => fold(constFalse, b => !b, (_, a) => Effect.succeed(predicate(a)));\n/**\n * Transforms this sink's result.\n *\n * **When to use**\n *\n * Use to compute a new result from the original sink result while preserving\n * the sink's input consumption behavior.\n *\n * **Details**\n *\n * The transformed sink preserves the original sink's input type, leftovers,\n * errors, and requirements.\n *\n * @see {@link mapEffect} for effectful result transformations\n * @see {@link as} for replacing the result with a constant value\n * @see {@link mapEnd} for transforming both the result and leftovers\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => mapEnd(self, ([a, l]) => [f(a), l]));\n/**\n * Sets the sink's result to a constant value.\n *\n * **When to use**\n *\n * Use to keep a sink's input consumption, errors, requirements, and leftovers\n * while replacing only its result with a known value.\n *\n * @see {@link map} for computing the replacement from the original result\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const as = /*#__PURE__*/dual(2, (self, a2) => map(self, () => a2));\n/**\n * Transforms this sink's input elements.\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const mapInput = /*#__PURE__*/dual(2, (self, f) => mapInputArray(self, Arr.map(f)));\n/**\n * Transforms this sink's input elements effectfully.\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const mapInputEffect = /*#__PURE__*/dual(2, (self, f) => mapInputArrayEffect(self, Effect.forEach(f)));\n/**\n * Transforms each non-empty array of upstream input before it is fed to this\n * sink.\n *\n * @category mapping\n * @since 4.0.0\n */\nexport const mapInputArray = /*#__PURE__*/dual(2, (self, f) => fromTransform((upstream, scope) => self.transform(Effect.map(upstream, f), scope)));\n/**\n * Transforms each non-empty array of upstream input effectfully before it is\n * fed to this sink.\n *\n * @category mapping\n * @since 4.0.0\n */\nexport const mapInputArrayEffect = /*#__PURE__*/dual(2, (self, f) => fromTransform((upstream, scope) => self.transform(Effect.flatMap(upstream, f), scope)));\n/**\n * Transforms the full `End` produced by this sink.\n *\n * **Details**\n *\n * This can change both the result value and the optional leftovers.\n *\n * @category mapping\n * @since 4.0.0\n */\nexport const mapEnd = /*#__PURE__*/dual(2, (self, f) => fromTransform((upstream, scope) => Effect.map(self.transform(upstream, scope), f)));\nconst transformEffect = (self, f) => fromTransform((upstream, scope) => f(self.transform(upstream, scope)));\n/**\n * Transforms the full `End` produced by this sink effectfully.\n *\n * **Details**\n *\n * This can change both the result value and the optional leftovers, and the\n * transformation can fail or require services.\n *\n * @category mapping\n * @since 4.0.0\n */\nexport const mapEffectEnd = /*#__PURE__*/dual(2, (self, f) => transformEffect(self, Effect.flatMap(f)));\n/**\n * Transforms this sink's result effectfully.\n *\n * **When to use**\n *\n * Use when you need a sink result transformation that is effectful, can fail,\n * or requires services.\n *\n * **Details**\n *\n * The transformed sink preserves the original sink's input consumption and\n * leftovers while adding the errors and requirements of the transformation.\n *\n * @see {@link map} for pure result transformations\n * @see {@link mapEffectEnd} for effectfully transforming both the result and leftovers\n * @see {@link flatMap} for continuing with another sink based on the result\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const mapEffect = /*#__PURE__*/dual(2, (self, f) => mapEffectEnd(self, ([a, l]) => Effect.map(f(a), a2 => [a2, l])));\n/**\n * Transforms the errors emitted by this sink using `f`.\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const mapError = /*#__PURE__*/dual(2, (self, f) => transformEffect(self, Effect.mapError(f)));\n/**\n * Transforms the leftovers emitted by this sink using `f`.\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const mapLeftover = /*#__PURE__*/dual(2, (self, f) => mapEnd(self, ([a, l]) => [a, l && Arr.map(l, f)]));\n/**\n * Collects up to `n` input elements into an array.\n *\n * **Details**\n *\n * Finite fractional values of `n` are rounded down. If `n` is `NaN` or\n * non-positive, the sink completes with an empty array. If more elements are\n * pulled than needed, the remaining elements from the same array are returned\n * as leftovers.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const take = n => {\n  const count = Count.normalize(n);\n  return fromTransform(upstream => {\n    const taken = [];\n    if (count === 0) {\n      return Effect.succeed([taken]);\n    }\n    let leftover = undefined;\n    return upstream.pipe(Effect.flatMap(arr => {\n      if (taken.length + arr.length <= count) {\n        taken.push(...arr);\n        if (taken.length === count) {\n          return Cause.done();\n        }\n        return Effect.void;\n      }\n      for (let i = 0; i < arr.length; i++) {\n        taken.push(arr[i]);\n        if (taken.length === count) {\n          if (i + 1 < arr.length) {\n            leftover = arr.slice(i + 1);\n          }\n          return Cause.done();\n        }\n      }\n      return Effect.void;\n    }), Effect.forever({\n      disableYield: true\n    }), Pull.catchDone(() => Effect.succeed([taken, leftover])));\n  });\n};\n/**\n * Runs this sink until it yields a result, then uses that result to create\n * another sink from the provided function which will continue to run until it\n * yields a result.\n *\n * **When to use**\n *\n * Use to compose sinks when the next sink depends on the result produced by the\n * previous sink.\n *\n * **Details**\n *\n * Leftovers from the first sink are fed to the sink returned by `f` before more\n * upstream input is pulled.\n *\n * @see {@link map} for transforming the result without switching sinks\n * @see {@link mapEffect} for effectfully transforming the result without switching sinks\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const flatMap = /*#__PURE__*/dual(2, (self, f) => fromTransform((upstream, scope) => {\n  let upstreamDone = false;\n  const pull = Effect.catchCause(upstream, cause => {\n    upstreamDone = true;\n    return Effect.failCause(cause);\n  });\n  return Effect.flatMap(self.transform(pull, scope), ([a, leftover]) => f(a).transform(Effect.suspend(() => {\n    if (leftover) {\n      const arr = leftover;\n      leftover = undefined;\n      return Effect.succeed(arr);\n    } else if (upstreamDone) {\n      return Cause.done();\n    }\n    return upstream;\n  }), scope).pipe(Effect.map(end => {\n    if (!leftover) {\n      return end;\n    }\n    return [end[0], end[1] ? [...end[1], ...leftover] : leftover];\n  })));\n}));\n/**\n * A sink that reduces input elements from the provided `initial` state with\n * `f` while the specified `predicate` returns `true`.\n *\n * @category folding\n * @since 4.0.0\n */\nexport const reduceWhile = (initial, predicate, f) => fromTransform(upstream => {\n  let state = initial();\n  let leftover = undefined;\n  if (!predicate(state)) {\n    return Effect.succeed([state]);\n  }\n  return upstream.pipe(Effect.flatMap(arr => {\n    for (let i = 0; i < arr.length; i++) {\n      state = f(state, arr[i]);\n      if (!predicate(state)) {\n        if (i + 1 < arr.length) {\n          leftover = arr.slice(i + 1);\n        }\n        return Cause.done();\n      }\n    }\n    return Effect.void;\n  }), Effect.forever({\n    disableYield: true\n  }), Pull.catchDone(() => Effect.succeed([state, leftover])));\n});\n/**\n * A sink that effectfully reduces input elements from the provided `initial`\n * state with `f` while the specified `predicate` returns `true`.\n *\n * @category folding\n * @since 4.0.0\n */\nexport const reduceWhileEffect = (initial, predicate, f) => fromTransform(upstream => {\n  let state = initial();\n  let leftover = undefined;\n  if (!predicate(state)) {\n    return Effect.succeed([state]);\n  }\n  return upstream.pipe(Effect.flatMap(arr => {\n    let i = 0;\n    return Effect.whileLoop({\n      while: () => i < arr.length,\n      body: constant(Effect.flatMap(Effect.suspend(() => f(state, arr[i++])), s => {\n        state = s;\n        if (!predicate(state)) {\n          if (i < arr.length) {\n            leftover = arr.slice(i);\n          }\n          return Cause.done();\n        }\n        return Effect.void;\n      })),\n      step: constVoid\n    });\n  }), Effect.forever({\n    disableYield: true\n  }), Pull.catchDone(() => Effect.succeed([state, leftover])));\n});\n/**\n * A sink that reduces non-empty input arrays from the provided `initial` state\n * with `f` while the specified `predicate` returns `true`.\n *\n * @category folding\n * @since 4.0.0\n */\nexport const reduceWhileArray = (initial, contFn, f) => fromTransform(upstream => {\n  let state = initial();\n  if (!contFn(state)) {\n    return Effect.succeed([state]);\n  }\n  return upstream.pipe(Effect.flatMap(arr => {\n    state = f(state, arr);\n    if (!contFn(state)) {\n      return Cause.done();\n    }\n    return Effect.void;\n  }), Effect.forever({\n    disableYield: true\n  }), Pull.catchDone(() => Effect.succeed([state])));\n});\n/**\n * A sink that effectfully reduces non-empty input arrays from the provided\n * `initial` state with `f` while the specified `predicate` returns `true`.\n *\n * @category folding\n * @since 4.0.0\n */\nexport const reduceWhileArrayEffect = (initial, predicate, f) => fromTransform(upstream => {\n  let state = initial();\n  if (!predicate(state)) {\n    return Effect.succeed([state]);\n  }\n  return upstream.pipe(Effect.flatMap(arr => f(state, arr)), Effect.flatMap(s => {\n    state = s;\n    if (!predicate(state)) {\n      return Cause.done();\n    }\n    return Effect.void;\n  }), Effect.forever({\n    disableYield: true\n  }), Pull.catchDone(() => Effect.succeed([state])));\n});\n/**\n * A sink that reduces its inputs using the provided function `f` starting from\n * the provided `initial` state.\n *\n * @category folding\n * @since 4.0.0\n */\nexport const reduce = (initial, f) => reduceArray(initial, (s, arr) => {\n  for (let i = 0; i < arr.length; i++) {\n    s = f(s, arr[i]);\n  }\n  return s;\n});\n/**\n * A sink that reduces its inputs using the provided function `f` starting from\n * the specified `initial` state.\n *\n * @category folding\n * @since 4.0.0\n */\nexport const reduceArray = (initial, f) => fromTransform(upstream => {\n  let state = initial();\n  return upstream.pipe(Effect.flatMap(arr => {\n    state = f(state, arr);\n    return Effect.void;\n  }), Effect.forever({\n    disableYield: true\n  }), Pull.catchDone(() => Effect.succeed([state])));\n});\n/**\n * A sink that reduces its inputs using the provided effectful function `f`\n * starting from the specified `initial` state.\n *\n * @category folding\n * @since 4.0.0\n */\nexport const reduceEffect = (initial, f) => reduceWhileEffect(initial, constTrue, f);\nconst head_ = /*#__PURE__*/reduceWhile(Option.none, Option.isNone, (_, in_) => Option.some(in_));\n/**\n * Creates a sink containing the first value.\n *\n * **Details**\n *\n * Returns `Option.some(first)` for non-empty input, or `Option.none` when the\n * upstream ends without input. The first element is consumed; later elements\n * from the same pulled array are emitted as leftovers.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const head = () => head_;\nconst last_ = /*#__PURE__*/reduceArray(Option.none, (_, arr) => Arr.last(arr));\n/**\n * Creates a sink containing the last value.\n *\n * **When to use**\n *\n * Use when you need to consume all upstream input and keep only the final\n * element.\n *\n * **Details**\n *\n * Returns `Option.some(last)` with the final input value, or `Option.none` when\n * the upstream ends without input.\n *\n * **Gotchas**\n *\n * This sink produces a result only when the upstream ends, so it does not\n * complete for a stream that does not end.\n *\n * @see {@link head} for taking the first input value instead\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const last = () => last_;\n/**\n * Creates a sink containing the first value matched by a synchronous predicate.\n *\n * **When to use**\n *\n * Use to scan stream input until the first matching element is found and return\n * that element as an `Option`.\n *\n * **Details**\n *\n * Returns `Option.none` if the upstream stream ends before a match is found.\n * Refinement predicates narrow the returned value type. The matching input is\n * consumed; any later elements from the same pulled array are returned as\n * leftovers.\n *\n * @see {@link findEffect} for an effectful predicate that can fail or require services\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const find = predicate => reduceWhile(Option.none, Option.isNone, (acc, in_) => predicate(in_) ? Option.some(in_) : acc);\n/**\n * Creates a sink containing the first value matched by an effectful predicate.\n *\n * **When to use**\n *\n * Use when you need to run effects, fail, or use services while searching for\n * the first matching input.\n *\n * **Details**\n *\n * Returns `Option.some` with the first input whose predicate result is `true`,\n * or `Option.none` if the upstream stream ends first. If the predicate effect\n * fails, the sink fails with the same error.\n *\n * @see {@link find} for the synchronous predicate variant\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const findEffect = predicate => reduceWhileEffect(Option.none, Option.isNone, (acc, in_) => Effect.map(predicate(in_), b => b ? Option.some(in_) : acc));\n/**\n * Creates a sink which sums up its inputs.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const sum = /*#__PURE__*/reduceArray(() => 0, (s, arr) => {\n  for (let i = 0; i < arr.length; i++) {\n    s += arr[i];\n  }\n  return s;\n});\n/**\n * A sink that counts the number of elements fed to it.\n *\n * **When to use**\n *\n * Use to consume input and return only the number of elements received.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const count = /*#__PURE__*/reduceArray(() => 0, (s, arr) => s + arr.length);\n/**\n * Accumulates incoming elements into an array.\n *\n * **When to use**\n *\n * Use when you need a sink result containing all upstream input elements.\n *\n * @see {@link take} for collecting only a fixed number of input elements\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const collect = () => reduceArray(Arr.empty, (s, arr) => {\n  s.push(...arr);\n  return s;\n});\n/**\n * Collects the longest input prefix whose elements satisfy the predicate or\n * refinement.\n *\n * **Details**\n *\n * The first failing input is consumed and excluded from the result. Any later\n * elements from the same pulled array are returned as leftovers.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const takeWhile = predicate => fromTransform(upstream => {\n  const out = Arr.empty();\n  return upstream.pipe(Effect.flatMap(arr => {\n    for (let i = 0; i < arr.length; i++) {\n      if (!predicate(arr[i])) {\n        const leftover = i + 1 < arr.length ? arr.slice(i + 1) : undefined;\n        return Cause.done([out, leftover]);\n      }\n      out.push(arr[i]);\n    }\n    return Effect.void;\n  }), Effect.forever({\n    disableYield: true\n  }), Pull.catchDone(end => Effect.succeed(end ?? [out])));\n});\n/**\n * Applies a `Filter` to input elements while it succeeds, collecting each\n * successful output.\n *\n * **Details**\n *\n * The first input for which the filter fails is consumed and excluded from the\n * result. Any later elements from the same pulled array are returned as\n * leftovers.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const takeWhileFilter = filter => fromTransform(upstream => {\n  const out = Arr.empty();\n  return upstream.pipe(Effect.flatMap(arr => {\n    for (let i = 0; i < arr.length; i++) {\n      const result = filter(arr[i]);\n      if (Result.isFailure(result)) {\n        const leftover = i + 1 < arr.length ? arr.slice(i + 1) : undefined;\n        return Cause.done([out, leftover]);\n      }\n      out.push(result.success);\n    }\n    return Effect.void;\n  }), Effect.forever({\n    disableYield: true\n  }), Pull.catchDone(end => Effect.succeed(end ?? [out])));\n});\n/**\n * Collects input elements effectfully while the predicate succeeds.\n *\n * **Details**\n *\n * The first input for which the predicate returns `false` is consumed and\n * excluded from the result. Any later elements from the same pulled array are\n * returned as leftovers.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const takeWhileEffect = predicate => fromTransform(upstream => {\n  const out = Arr.empty();\n  let leftover = undefined;\n  return upstream.pipe(Effect.flatMap(arr => {\n    let i = 0;\n    return Effect.whileLoop({\n      while: () => i < arr.length,\n      body: constant(Effect.flatMap(Effect.suspend(() => {\n        const input = arr[i++];\n        return Effect.map(predicate(input), passes => [input, passes]);\n      }), ([input, passes]) => {\n        if (!passes) {\n          if (i < arr.length) {\n            leftover = arr.slice(i);\n          }\n          return Cause.done();\n        }\n        out.push(input);\n        return Effect.void;\n      })),\n      step: constVoid\n    });\n  }), Effect.forever({\n    disableYield: true\n  }), Pull.catchDone(() => Effect.succeed([out, leftover])));\n});\n/**\n * Applies a `FilterEffect` to input elements effectfully while it succeeds,\n * collecting each successful output.\n *\n * **Details**\n *\n * The first input for which the filter fails is consumed and excluded from the\n * result. Any later elements from the same pulled array are returned as\n * leftovers.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const takeWhileFilterEffect = filter => fromTransform(upstream => {\n  const out = Arr.empty();\n  let leftover = undefined;\n  return upstream.pipe(Effect.flatMap(arr => {\n    let i = 0;\n    return Effect.whileLoop({\n      while: () => i < arr.length,\n      body: constant(Effect.flatMap(Effect.suspend(() => filter(arr[i++])), result => {\n        if (Result.isFailure(result)) {\n          if (i < arr.length) {\n            leftover = arr.slice(i);\n          }\n          return Cause.done();\n        }\n        out.push(result.success);\n        return Effect.void;\n      })),\n      step: constVoid\n    });\n  }), Effect.forever({\n    disableYield: true\n  }), Pull.catchDone(() => Effect.succeed([out, leftover])));\n});\n/**\n * Collects input elements until the predicate returns `true`, including the\n * matching element in the result.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const takeUntil = predicate => suspend(() => {\n  let done = false;\n  return takeWhile(i => {\n    if (done) return false;\n    done = predicate(i);\n    return true;\n  });\n});\n/**\n * Collects input elements effectfully until the predicate returns `true`,\n * including the matching element in the result.\n *\n * **Details**\n *\n * If the predicate effect fails, the sink fails with the same error.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const takeUntilEffect = predicate => suspend(() => {\n  let done = false;\n  return takeWhileEffect(input => {\n    if (done) {\n      return Effect.succeed(false);\n    }\n    return Effect.map(predicate(input), b => {\n      done = b;\n      return true;\n    });\n  });\n});\n/**\n * A sink that executes the provided effectful function for every item fed\n * to it.\n *\n * **Example** (Running effects for each item)\n *\n * ```ts import.meta.vitest\n * import { Effect, Sink, Stream } from \"effect\"\n *\n * const processed: Array<number> = []\n * const sink = Sink.forEach((item: number) => Effect.sync(() => processed.push(item)))\n *\n * // Use it with a stream\n * const stream = Stream.make(1, 2, 3)\n * await Effect.runPromise(Stream.run(stream, sink))\n * processed // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const forEach = f => forEachArray(Effect.forEach(_ => f(_), {\n  discard: true\n}));\n/**\n * A sink that executes the provided effectful function for every Chunk fed\n * to it.\n *\n * **Example** (Running effects for each chunk)\n *\n * ```ts import.meta.vitest\n * import { Effect, Sink, Stream } from \"effect\"\n *\n * const processed: Array<Array<number>> = []\n * const sink = Sink.forEachArray((chunk: ReadonlyArray<number>) => Effect.sync(() => processed.push([...chunk])))\n *\n * // Use it with a stream\n * const stream = Stream.make(1, 2, 3, 4, 5)\n * await Effect.runPromise(Stream.run(stream, sink))\n * processed // => [[1, 2, 3, 4, 5]]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const forEachArray = f => fromTransform(upstream => upstream.pipe(Effect.flatMap(f), Effect.forever({\n  disableYield: true\n}), Pull.catchDone(() => endVoid)));\n/**\n * Runs an effectful function for each input element while it returns `true`.\n *\n * **Details**\n *\n * The sink stops consuming input when the function returns `false` or when the\n * upstream stream ends, and completes with `void`.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const forEachWhile = f => forEachWhileArray(Effect.fnUntraced(function* (input) {\n  for (let i = 0; i < input.length; i++) {\n    const cont = yield* f(input[i]);\n    if (!cont) return false;\n  }\n  return true;\n}));\n/**\n * Runs an effectful function for each non-empty input array while it returns\n * `true`.\n *\n * **Details**\n *\n * The sink stops consuming input when the function returns `false` or when the\n * upstream stream ends, and completes with `void`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const forEachWhileArray = f => fromTransform(upstream => upstream.pipe(Effect.flatMap(f), Effect.flatMap(cont => cont ? Effect.void : Cause.done()), Effect.forever({\n  disableYield: true\n}), Pull.catchDone(() => endVoid)));\n/**\n * Creates a sink produced from a scoped effect.\n *\n * **Example** (Unwrapping a sink effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Sink, Stream } from \"effect\"\n *\n * // Create a sink from an effect that produces a sink\n * const processed: Array<number> = []\n * const sinkEffect = Effect.succeed(\n *   Sink.forEach((item: number) => Effect.sync(() => processed.push(item)))\n * )\n * const sink = Sink.unwrap(sinkEffect)\n *\n * // Use it with a stream\n * const stream = Stream.make(1, 2, 3)\n * await Effect.runPromise(Stream.run(stream, sink))\n * processed // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const unwrap = effect => fromChannel(Channel.unwrap(Effect.map(effect, toChannel)));\n/**\n * Runs a summary effect when the sink starts and again when it completes.\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const summarized = /*#__PURE__*/dual(3, (self, summary, f) => fromTransform(Effect.fnUntraced(function* (upstream, scope) {\n  const start = yield* summary;\n  const [done, leftover] = yield* self.transform(upstream, scope);\n  const end = yield* summary;\n  return [[done, f(start, end)], leftover];\n})));\n/**\n * Returns the sink that executes this one and times its execution.\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const withDuration = self => summarized(self, Clock.monotonicTimeNanos, (start, end) => Duration.nanos(end - start));\n/**\n * A sink that drains all input and returns the elapsed duration.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const timed = /*#__PURE__*/map(/*#__PURE__*/withDuration(drain), ([, duration]) => duration);\n/**\n * Provides a `Context` to this sink.\n *\n * **Details**\n *\n * Services contained in the provided context are removed from the sink's\n * service requirements.\n *\n * @category providing services\n * @since 2.0.0\n */\nexport const provideContext = /*#__PURE__*/dual(2, (self, context) => fromTransform((upstream, scope) => self.transform(upstream, scope).pipe(Effect.provideContext(context))));\n/**\n * Provides a single service implementation to this sink.\n *\n * **Details**\n *\n * The service identified by `key` is removed from the sink's service\n * requirements.\n *\n * @category providing services\n * @since 4.0.0\n */\nexport const provideService = /*#__PURE__*/dual(3, (self, key, value) => fromTransform((upstream, scope) => self.transform(upstream, scope).pipe(Effect.provideService(key, value))));\n/**\n * Runs a fallback sink if this sink fails with a typed error.\n *\n * **Details**\n *\n * The fallback is built from the error and continues consuming from the same\n * upstream stream. If the upstream stream had already ended, the fallback sees\n * the upstream end instead.\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const orElse = /*#__PURE__*/dual(2, (self, f) => fromTransform((upstream, scope) => {\n  let upstreamDone = false;\n  const pull = Effect.catchCause(upstream, cause => {\n    upstreamDone = true;\n    return Effect.failCause(cause);\n  });\n  return Effect.catch(self.transform(pull, scope), error => f(error).transform(Effect.suspend(() => {\n    if (upstreamDone) {\n      return Cause.done();\n    }\n    return upstream;\n  }), scope));\n}));\n/**\n * Handles failures from this sink by inspecting the full `Cause`.\n *\n * **When to use**\n *\n * Use to recover from a sink failure based on the full `Cause` instead of only\n * the typed error value.\n *\n * **Details**\n *\n * When this sink fails, the handler effect is run and its success value\n * becomes the sink result. If the handler fails, the returned sink fails with\n * that error.\n *\n * @see {@link catch_ catch} for recovering from typed errors only\n * @see {@link orElse} for recovering by switching to another sink\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchCause = /*#__PURE__*/dual(2, (self, f) => transformEffect(self, Effect.catchCause(cause => Effect.map(f(cause), a2 => [a2]))));\nconst catch_ = /*#__PURE__*/dual(2, (self, f) => transformEffect(self, Effect.catch(error => Effect.map(f(error), a2 => [a2]))));\nexport {\n/**\n * Handles typed errors from this sink with an effectful fallback value.\n *\n * **When to use**\n *\n * Use to recover from a typed sink failure by producing the replacement\n * result with an `Effect`.\n *\n * @see {@link catchCause} for recovering from the full failure cause\n * @see {@link orElse} for recovering by switching to another sink\n *\n * @category error handling\n * @since 4.0.0\n */\ncatch_ as catch };\n/**\n * Runs an effect after this sink completes, fails, or is interrupted.\n *\n * **Details**\n *\n * The effect receives the sink's `Exit` for the result value. The original\n * sink result and leftovers are preserved unless the finalizer itself fails.\n *\n * @category resource management\n * @since 4.0.0\n */\nexport const onExit = /*#__PURE__*/dual(2, (self, f) => transformEffect(self, Effect.onExit(exit => f(Exit.map(exit, ([a]) => a)))));\n/**\n * Runs a finalizer effect after this sink completes, fails, or is interrupted.\n *\n * **Details**\n *\n * The original sink result and leftovers are preserved unless the finalizer\n * itself fails.\n *\n * @category resource management\n * @since 2.0.0\n */\nexport const ensuring = /*#__PURE__*/dual(2, (self, effect) => onExit(self, () => effect));\n//# sourceMappingURL=Sink.js.map","import * as Context from \"../Context.js\";\nimport * as Duration from \"../Duration.js\";\nimport * as Effect from \"../Effect.js\";\nimport * as Exit from \"../Exit.js\";\nimport * as Fiber from \"../Fiber.js\";\nimport { identity } from \"../Function.js\";\nimport { pipeArguments } from \"../Pipeable.js\";\nimport * as Scope from \"../Scope.js\";\nimport * as Semaphore from \"../Semaphore.js\";\nconst TypeId = \"~effect/RcRef\";\nconst stateEmpty = {\n  _tag: \"Empty\"\n};\nconst stateClosed = {\n  _tag: \"Closed\"\n};\nconst variance = {\n  _A: identity,\n  _E: identity\n};\nclass RcRefImpl {\n  [TypeId] = variance;\n  pipe() {\n    return pipeArguments(this, arguments);\n  }\n  state = stateEmpty;\n  semaphore = /*#__PURE__*/Semaphore.makeUnsafe(1);\n  acquire;\n  context;\n  scope;\n  idleTimeToLive;\n  constructor(acquire, context, scope, idleTimeToLive) {\n    this.acquire = acquire;\n    this.context = context;\n    this.scope = scope;\n    this.idleTimeToLive = idleTimeToLive;\n  }\n}\n/** @internal */\nexport const make = options => Effect.withFiber(fiber => {\n  const context = fiber.context;\n  const scope = Context.get(context, Scope.Scope);\n  const ref = new RcRefImpl(options.acquire, context, scope, options.idleTimeToLive ? Duration.fromInputUnsafe(options.idleTimeToLive) : undefined);\n  return Effect.as(Scope.addFinalizerExit(scope, () => {\n    const close = ref.state._tag === \"Acquired\" ? Scope.close(ref.state.scope, Exit.void) : Effect.void;\n    ref.state = stateClosed;\n    return close;\n  }), ref);\n});\nconst getState = self => Effect.uninterruptibleMask(function loop(restore) {\n  switch (self.state._tag) {\n    case \"Closed\":\n      {\n        return Effect.interrupt;\n      }\n    case \"Acquired\":\n      {\n        self.state.refCount++;\n        return self.state.fiber ? Effect.as(Fiber.interrupt(self.state.fiber), self.state) : Effect.succeed(self.state);\n      }\n    case \"Empty\":\n      {\n        const scope = Scope.makeUnsafe();\n        return self.semaphore.withPermit(Effect.suspend(() => {\n          if (self.state._tag !== \"Empty\") {\n            return loop(restore);\n          }\n          return restore(Effect.provideContext(self.acquire, Context.add(self.context, Scope.Scope, scope))).pipe(Effect.flatMap(value => {\n            if (self.state._tag === \"Closed\") {\n              return Effect.interrupt;\n            }\n            const state = {\n              _tag: \"Acquired\",\n              value,\n              scope,\n              fiber: undefined,\n              refCount: 1,\n              invalidated: false\n            };\n            self.state = state;\n            return Effect.succeed(state);\n          }), Effect.onExit(exit => Exit.isFailure(exit) ? Scope.close(scope, exit) : Effect.void));\n        }));\n      }\n  }\n});\n/** @internal */\nexport const get = /*#__PURE__*/Effect.fnUntraced(function* (self_) {\n  const self = self_;\n  const state = yield* getState(self);\n  const scope = yield* Effect.scope;\n  const isFinite = self.idleTimeToLive !== undefined && Duration.isFinite(self.idleTimeToLive);\n  yield* Scope.addFinalizerExit(scope, () => {\n    state.refCount--;\n    if (state.refCount > 0) {\n      return Effect.void;\n    }\n    if (self.idleTimeToLive === undefined || state.invalidated) {\n      if (self.state === state) {\n        self.state = stateEmpty;\n      }\n      return Scope.close(state.scope, Exit.void);\n    } else if (!isFinite) {\n      return Effect.void;\n    }\n    state.fiber = Effect.sleep(self.idleTimeToLive).pipe(Effect.flatMap(() => {\n      if (self.state === state && state.refCount === 0) {\n        self.state = stateEmpty;\n        return Scope.close(state.scope, Exit.void);\n      }\n      return Effect.void;\n    }), Effect.ensuring(Effect.sync(() => {\n      state.fiber = undefined;\n    })), Effect.runForkWith(self.context), Fiber.runIn(self.scope));\n    return Effect.void;\n  });\n  return state.value;\n});\n/** @internal */\nexport const invalidate = self_ => {\n  const self = self_;\n  return Effect.uninterruptible(Effect.suspend(() => {\n    if (self.state._tag !== \"Acquired\") {\n      return Effect.void;\n    }\n    const state = self.state;\n    self.state = stateEmpty;\n    state.invalidated = true;\n    if (state.refCount > 0) {\n      return Effect.void;\n    }\n    state.fiber?.interruptUnsafe();\n    return Scope.close(state.scope, Exit.void);\n  }));\n};\n//# sourceMappingURL=rcRef.js.map","import * as internal from \"./internal/rcRef.js\";\nconst TypeId = \"~effect/RcRef\";\n/**\n * Creates an `RcRef` from an acquire effect.\n *\n * **When to use**\n *\n * Use to create a lazily acquired, reference-counted resource from an acquire\n * effect.\n *\n * **Details**\n *\n * The resource is acquired lazily on the first `get` and shared by subsequent\n * gets while it remains cached. Each `get` adds a reference to the current\n * `Scope`. When the last reference is released, the resource is closed\n * immediately by default, or after `idleTimeToLive` when that option is\n * provided.\n *\n * **Example** (Creating a reference-counted resource)\n *\n * ```ts import.meta.vitest\n * import { Effect, RcRef } from \"effect\"\n *\n * const events: Array<string> = []\n *\n * const program = Effect.gen(function*() {\n *   const ref = yield* RcRef.make({\n *     acquire: Effect.acquireRelease(\n *       Effect.succeed(\"foo\"),\n *       () => Effect.sync(() => events.push(\"released foo\"))\n *     )\n *   })\n *\n *   // will only acquire the resource once, and release it\n *   // when the scope is closed\n *   yield* RcRef.get(ref).pipe(\n *     Effect.andThen(RcRef.get(ref)),\n *     Effect.scoped\n *   )\n * })\n *\n * await Effect.runPromise(Effect.scoped(program))\n * events // => [\"released foo\"]\n * ```\n *\n * @category constructors\n * @since 3.5.0\n */\nexport const make = internal.make;\n/**\n * Gets the value from an `RcRef`, acquiring it first if needed.\n *\n * **When to use**\n *\n * Use to borrow the current resource within a `Scope`, acquiring it first if\n * necessary.\n *\n * **Details**\n *\n * The reference count is incremented for the current `Scope`, and a release\n * finalizer is added to that scope. When the current scope closes, the\n * reference is released; the resource is closed when the final reference is\n * released, subject to any configured idle time-to-live.\n *\n * **Example** (Sharing one acquired value)\n *\n * ```ts import.meta.vitest\n * import { Effect, RcRef } from \"effect\"\n *\n * const events: Array<string> = []\n *\n * const program = Effect.gen(function*() {\n *   // Create an RcRef with a resource\n *   const ref = yield* RcRef.make({\n *     acquire: Effect.acquireRelease(\n *       Effect.succeed(\"shared resource\"),\n *       (resource) => Effect.sync(() => events.push(`released ${resource}`))\n *     )\n *   })\n *\n *   // Get the value from the RcRef\n *   const value1 = yield* RcRef.get(ref)\n *   const value2 = yield* RcRef.get(ref)\n *\n *   return [value1 === value2, events] as const\n * })\n *\n * await Effect.runPromise(Effect.scoped(program)) // => [true, [\"released shared resource\"]]\n * ```\n *\n * @category combinators\n * @since 3.5.0\n */\nexport const get = internal.get;\n/**\n * Invalidates the currently cached resource, if one has been acquired.\n *\n * **When to use**\n *\n * Use to force future `RcRef.get` calls to acquire a fresh resource when the\n * currently cached resource should no longer be reused.\n *\n * **Details**\n *\n * After invalidation, the next `get` acquires a fresh resource.\n *\n * **Gotchas**\n *\n * Invalidation does not revoke resources already borrowed by active scopes;\n * those remain usable until their scopes close.\n *\n * @see {@link get} for acquiring the current cached resource or the fresh resource after invalidation\n *\n * @category combinators\n * @since 3.19.6\n */\nexport const invalidate = internal.invalidate;\n//# sourceMappingURL=RcRef.js.map","/**\n * Describes effectful sources that emit values over time.\n *\n * A `Stream<A, E, R>` can emit many `A` values, fail with `E`, and require\n * services `R` while it is being consumed. Streams are useful for data that is\n * pulled in steps, such as values from collections, queues, pubsubs, schedules,\n * callbacks, async iterables, or platform streams. The APIs here cover the full\n * stream lifecycle: create a stream, transform or combine it, control buffering\n * and timing, handle failures, and finally consume it.\n *\n * @since 2.0.0\n */\n// @effect-diagnostics returnEffectInGen:off\nimport * as Arr from \"./Array.js\";\nimport * as ByteSize from \"./ByteSize.js\";\nimport * as Cause from \"./Cause.js\";\nimport * as Channel from \"./Channel.js\";\nimport { Clock } from \"./Clock.js\";\nimport * as Context from \"./Context.js\";\nimport * as Duration from \"./Duration.js\";\nimport * as Effect from \"./Effect.js\";\nimport * as Equal from \"./Equal.js\";\nimport * as ExecutionPlan from \"./ExecutionPlan.js\";\nimport * as Exit from \"./Exit.js\";\nimport * as Fiber from \"./Fiber.js\";\nimport { constant, constTrue, constVoid, dual, identity } from \"./Function.js\";\nimport * as Count from \"./internal/count.js\";\nimport * as internalExecutionPlan from \"./internal/executionPlan.js\";\nimport * as internal from \"./internal/stream.js\";\nimport { addSpanStackTrace } from \"./internal/tracer.js\";\nimport * as Iterable from \"./Iterable.js\";\nimport * as Latch from \"./Latch.js\";\nimport * as MutableHashMap from \"./MutableHashMap.js\";\nimport * as MutableList from \"./MutableList.js\";\nimport * as Option from \"./Option.js\";\nimport { hasProperty, isNotUndefined, isTagged } from \"./Predicate.js\";\nimport * as PubSub from \"./PubSub.js\";\nimport * as Pull from \"./Pull.js\";\nimport * as Queue from \"./Queue.js\";\nimport * as RcMap from \"./RcMap.js\";\nimport * as RcRef from \"./RcRef.js\";\nimport * as Result from \"./Result.js\";\nimport * as Schedule from \"./Schedule.js\";\nimport * as Scope from \"./Scope.js\";\nimport * as Sink from \"./Sink.js\";\nimport { isString } from \"./String.js\";\n/**\n * Runtime identifier stored on `Stream` values and used by `isStream` to\n * recognize them.\n *\n * **Details**\n *\n * This marker is part of the runtime representation of `Stream` values. Prefer\n * `isStream` when narrowing unknown values.\n *\n * @see {@link isStream} for the public guard that checks this identifier\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const TypeId = \"~effect/Stream\";\n/**\n * Checks whether a value is a Stream.\n *\n * **Example** (Checking whether a value is a Stream)\n *\n * ```ts import.meta.vitest\n * import { Stream } from \"effect\"\n *\n * Stream.isStream(Stream.make(1, 2, 3)) // => true\n * Stream.isStream({ data: [1, 2, 3] }) // => false\n * ```\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isStream = u => hasProperty(u, TypeId);\n/**\n * The default chunk size used by Stream constructors and combinators.\n *\n * **Example** (Reading the default chunk size)\n *\n * ```ts import.meta.vitest\n * import { Stream } from \"effect\"\n *\n * Stream.DefaultChunkSize // => 4096\n * ```\n *\n * @category constants\n * @since 2.0.0\n */\nexport const DefaultChunkSize = Channel.DefaultChunkSize;\n/**\n * Creates a stream from a array-emitting `Channel`.\n *\n * **Example** (Creating a stream from an array-emitting channel)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect, Stream } from \"effect\"\n *\n * const channel = Channel.succeed([1, 2, 3] as const)\n * const stream = Stream.fromChannel(channel)\n * await Effect.runPromise(Stream.runCollect(stream)) // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromChannel = internal.fromChannel;\n/**\n * Creates a stream from an effect.\n *\n * **Example** (Creating a stream from an effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.fromEffect(Effect.succeed(42))\n * await Effect.runPromise(Stream.runCollect(stream)) // => [42]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromEffect = effect => fromChannel(Channel.fromEffect(Effect.map(effect, Arr.of)));\n/**\n * Accesses a service from the context and emits it as a single element.\n *\n * **Example** (Accessing a service as a stream)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Stream } from \"effect\"\n *\n * class Greeter extends Context.Service<Greeter, {\n *   readonly greet: (name: string) => string\n * }>()(\"Greeter\") {}\n *\n * const stream = Stream.service(Greeter).pipe(\n *   Stream.map((greeter) => greeter.greet(\"World\"))\n * )\n *\n * await Effect.runPromise(\n *   stream.pipe(\n *     Stream.provideService(Greeter, {\n *       greet: (name) => `Hello, ${name}!`\n *     }),\n *     Stream.runCollect\n *   )\n * ) // => [\"Hello, World!\"]\n * ```\n *\n * @category accessors\n * @since 4.0.0\n */\nexport const service = service => fromEffect(Effect.service(service));\n/**\n * Optionally accesses a service from the context and emits the result as a\n * single element.\n *\n * **When to use**\n *\n * Use when you need a stream that emits an optional service from the context\n * without requiring that service to be present.\n *\n * **Example** (Accessing an optional service as a stream)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Option, Stream } from \"effect\"\n *\n * class Greeter extends Context.Service<Greeter, {\n *   readonly greet: (name: string) => string\n * }>()(\"Greeter\") {}\n *\n * const stream = Stream.serviceOption(Greeter).pipe(\n *   Stream.map((maybeGreeter) =>\n *     Option.match(maybeGreeter, {\n *       onNone: () => \"No greeter\",\n *       onSome: (greeter) => greeter.greet(\"World\")\n *     })\n *   )\n * )\n *\n * await Effect.runPromise(\n *   stream.pipe(\n *     Stream.provideService(Greeter, {\n *       greet: (name) => `Hello, ${name}!`\n *     }),\n *     Stream.runCollect\n *   )\n * ) // => [\"Hello, World!\"]\n * ```\n *\n * @category accessors\n * @since 4.0.0\n */\nexport const serviceOption = service => fromEffect(Effect.serviceOption(service));\n/**\n * Creates a stream that runs the effect and emits no elements.\n *\n * **Example** (Draining an effect into a stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * let drained = false\n * await Effect.runPromise(\n *   Stream.fromEffectDrain(Effect.sync(() => {\n *     drained = true\n *   })).pipe(Stream.runDrain)\n * )\n * drained // => true\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromEffectDrain = effect => fromPull(Effect.succeed(Effect.flatMap(effect, () => Cause.done())));\n/**\n * Creates a stream from an effect producing a value of type `A` which repeats forever.\n *\n * **Example** (Repeating an effect forever)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * let n = 0\n * const stream = Stream.fromEffectRepeat(Effect.sync(() => ++n)).pipe(Stream.take(5))\n * await Effect.runPromise(Stream.runCollect(stream)) // => [1, 2, 3, 4, 5]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromEffectRepeat = effect => fromPull(Effect.succeed(Effect.map(effect, Arr.of)));\n/**\n * Creates a stream from an effect producing a value of type `A`, which is\n * repeated using the specified schedule.\n *\n * **Example** (Repeating an effect with a schedule)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schedule, Stream } from \"effect\"\n *\n * const stream = Stream.fromEffectSchedule(Effect.succeed(\"ping\"), Schedule.recurs(2))\n * await Effect.runPromise(Stream.runCollect(stream)) // => [\"ping\", \"ping\", \"ping\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromEffectSchedule = (effect, schedule) => fromPull(Effect.gen(function* () {\n  const step = yield* Schedule.toStepWithMetadata(schedule);\n  let s = yield* Effect.provideService(effect, Schedule.CurrentMetadata, Schedule.CurrentMetadata.defaultValue());\n  let initial = true;\n  const pull = Effect.suspend(() => step(s)).pipe(Effect.flatMap(meta => Effect.provideService(effect, Schedule.CurrentMetadata, meta)), Effect.map(next => {\n    s = next;\n    return Arr.of(next);\n  }));\n  return Effect.suspend(() => {\n    if (initial) {\n      initial = false;\n      return Effect.succeed(Arr.of(s));\n    }\n    return pull;\n  });\n}));\n/**\n * Creates a stream that emits `void` immediately once, then emits another\n * `void` after each specified interval.\n *\n * **Example** (Emitting ticks on an interval)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * await Effect.runPromise(Stream.tick(0).pipe(Stream.take(3), Stream.runCollect)) // => [undefined, undefined, undefined]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const tick = interval => fromPull(Effect.sync(() => {\n  let first = true;\n  const effect = Effect.succeed(Arr.of(undefined));\n  const delayed = Effect.delay(effect, interval);\n  return Effect.suspend(() => {\n    if (first) {\n      first = false;\n      return effect;\n    }\n    return delayed;\n  });\n}));\n/**\n * Creates a stream from a pull effect, such as one produced by `Stream.toPull`.\n *\n * **Details**\n *\n * A pull effect yields chunks on demand and completes when the upstream stream ends.\n * See `Stream.toPull` for a matching producer.\n *\n * **Example** (Creating a stream from a pull effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.scoped(\n *   Effect.gen(function*() {\n *     const source = Stream.make(1, 2, 3)\n *     const pull = yield* Stream.toPull(source)\n *     const stream = Stream.fromPull(Effect.succeed(pull))\n *     return yield* Stream.runCollect(stream)\n *   })\n * )\n *\n * await Effect.runPromise(program) // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromPull = pull => fromChannel(Channel.fromPull(pull));\n/**\n * Derives a stream by transforming its pull effect.\n *\n * **Example** (Transforming a pull effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3)\n *\n * const transformed = Stream.transformPull(stream, (pull) => Effect.succeed(pull))\n *\n * await Effect.runPromise(Stream.runCollect(transformed)) // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const transformPull = (self, f) => fromChannel(Channel.fromTransform((_, scope) => Effect.flatMap(Channel.toPullScoped(self.channel, scope), pull => f(pull, scope))));\n/**\n * Transforms a stream by effectfully transforming its pull effect.\n *\n * **Details**\n *\n * A forked scope is also provided to the transformation function, which is\n * closed once the resulting stream has finished processing.\n *\n * **Example** (Transforming a stream by effectfully transforming its pull effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Scope, Stream } from \"effect\"\n *\n * const finalized: Array<boolean> = []\n * const stream = Stream.make(1, 2, 3)\n *\n * const transformed = Stream.transformPullBracket(\n *   stream,\n *   (pull, _scope, forkedScope) =>\n *     Effect.gen(function*() {\n *       yield* Scope.addFinalizer(forkedScope, Effect.sync(() => finalized.push(true)))\n *       return pull\n *     })\n * )\n *\n * await Effect.runPromise(Stream.runCollect(transformed)) // => [1, 2, 3]\n * finalized // => [true]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const transformPullBracket = (self, f) => fromChannel(Channel.fromTransformBracket((_, scope, forkedScope) => Effect.flatMap(Channel.toPullScoped(self.channel, scope), pull => f(pull, scope, forkedScope))));\n/**\n * Creates a channel from a stream.\n *\n * **Example** (Converting a stream to a channel)\n *\n * ```ts import.meta.vitest\n * import { Channel, Effect, Stream } from \"effect\"\n *\n * const channel = Stream.toChannel(Stream.make(1, 2, 3))\n * const values = await Effect.runPromise(Channel.runCollect(channel))\n * values.flat() // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const toChannel = stream => stream.channel;\n/**\n * Creates a stream from a callback that can emit values into a queue.\n *\n * **When to use**\n *\n * Use when you need callback-based code to emit stream values by offering to a\n * `Queue`, or signal stream completion through the `Queue` module APIs.\n *\n * By default it uses an \"unbounded\" buffer size.\n * You can customize the buffer size and strategy by passing an object as the\n * second argument with the `bufferSize` and `strategy` fields.\n *\n * **Example** (Creating a stream from a callback that can emit values into a queue)\n *\n * ```ts import.meta.vitest\n * import { Effect, Queue, Stream } from \"effect\"\n *\n * const stream = Stream.callback<number>((queue) =>\n *   Effect.sync(() => {\n *     // Emit values to the stream\n *     Queue.offerUnsafe(queue, 1)\n *     Queue.offerUnsafe(queue, 2)\n *     Queue.offerUnsafe(queue, 3)\n *     // Signal completion\n *     Queue.endUnsafe(queue)\n *   })\n * )\n *\n * await Effect.runPromise(Stream.runCollect(stream)) // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const callback = (f, options) => fromChannel(Channel.callbackArray(f, options));\n/**\n * Creates an empty stream.\n *\n * **Example** (Creating an empty stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * await Effect.runPromise(Stream.runCollect(Stream.empty)) // => []\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const empty = /*#__PURE__*/fromChannel(Channel.empty);\n/**\n * Creates a single-valued pure stream.\n *\n * **Example** (Creating a single-valued pure stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * await Effect.runPromise(Stream.runCollect(Stream.succeed(3))) // => [3]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const succeed = value => fromChannel(Channel.succeed(Arr.of(value)));\n/**\n * Creates a stream from a sequence of values.\n *\n * **Example** (Creating a stream from a sequence of values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3)\n *\n * await Effect.runPromise(Stream.runCollect(stream)) // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const make = (...values) => fromArray(values);\n/**\n * Creates a stream that synchronously evaluates a function and emits the result as a single value.\n *\n * **Details**\n *\n * The function is evaluated each time the stream is run.\n *\n * **Example** (Evaluating a value synchronously)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * await Effect.runPromise(Stream.sync(() => 2 + 1).pipe(Stream.runCollect)) // => [3]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const sync = evaluate => fromChannel(Channel.sync(() => Arr.of(evaluate())));\n/**\n * Creates a lazily constructed stream.\n *\n * **Details**\n *\n * The stream factory is evaluated each time the stream is run.\n *\n * **Example** (Creating a lazily constructed stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * await Effect.runPromise(Stream.suspend(() => Stream.make(1, 2, 3)).pipe(Stream.runCollect)) // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const suspend = stream => fromChannel(Channel.suspend(() => stream().channel));\n/**\n * Terminates with the specified error.\n *\n * **Example** (Failing a stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Stream } from \"effect\"\n *\n * await Effect.runPromise(Effect.exit(Stream.runCollect(Stream.fail(\"Uh oh!\")))) // => Exit.fail(\"Uh oh!\")\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fail = error => fromChannel(Channel.fail(error));\n/**\n * Terminates with the specified lazily evaluated error.\n *\n * **Example** (Failing a stream lazily)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Stream } from \"effect\"\n *\n * const stream = Stream.failSync(() => \"Uh oh!\")\n *\n * await Effect.runPromise(Stream.runCollect(stream).pipe(Effect.exit)) // => Exit.fail(\"Uh oh!\")\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const failSync = evaluate => fromChannel(Channel.failSync(evaluate));\n/**\n * Creates a stream that fails with the specified `Cause`.\n *\n * **Example** (Failing with a cause)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Stream } from \"effect\"\n *\n * const stream = Stream.failCause(Cause.fail(\"Database connection failed\")).pipe(\n *   Stream.catchCause(() => Stream.succeed(\"recovered\"))\n * )\n *\n * await Effect.runPromise(Stream.runCollect(stream)) // => [\"recovered\"]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const failCause = cause => fromChannel(Channel.failCause(cause));\n/**\n * The stream that dies with the specified defect.\n *\n * **Example** (Dying with a defect)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Exit, Stream } from \"effect\"\n *\n * const defect = new Error(\"Boom\")\n * const stream = Stream.die(defect)\n *\n * await Effect.runPromise(Effect.exit(Stream.runCollect(stream))) // => Exit.failCause(Cause.die(defect))\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const die = defect => fromChannel(Channel.die(defect));\n/**\n * The stream that always fails with the specified lazily evaluated `Cause`.\n *\n * **Example** (Failing with a lazy cause)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Exit, Stream } from \"effect\"\n *\n * const stream = Stream.failCauseSync(() =>\n *   Cause.fail(\"Connection timeout after retries\")\n * )\n *\n * await Effect.runPromise(Stream.runCollect(stream).pipe(Effect.exit)) // => Exit.fail(\"Connection timeout after retries\")\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const failCauseSync = evaluate => fromChannel(Channel.failCauseSync(evaluate));\n/**\n * Creates a stream that consumes values from an iterator.\n *\n * **Details**\n *\n * The `maxChunkSize` parameter controls how many values are pulled per chunk.\n * Finite fractional values are rounded down, while `NaN` and non-positive\n * values are treated as `1`.\n *\n * **Example** (Consuming values from an iterator)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * function* numbers() {\n *   yield 1\n *   yield 2\n *   yield 3\n * }\n *\n * const stream = Stream.fromIteratorSucceed(numbers())\n *\n * const program = Effect.gen(function* () {\n *   const values = yield* Stream.runCollect(stream)\n *   values // => [1, 2, 3]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromIteratorSucceed = (iterator, maxChunkSize) => fromChannel(Channel.fromIteratorArray(() => iterator, maxChunkSize));\n/**\n * Creates a new `Stream` from an iterable collection of values.\n *\n * **Details**\n *\n * - `chunkSize`: Maximum number of values emitted per chunk. Finite fractional\n *   values are rounded down, while `NaN` and non-positive values are treated as\n *   `1`.\n *\n * **Example** (Creating a stream from an iterable)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const numbers = [1, 2, 3]\n *\n * const program = Effect.gen(function*() {\n *   const stream = Stream.fromIterable(numbers)\n *   const values = yield* Stream.runCollect(stream)\n *   values // => [1, 2, 3]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromIterable = (iterable, options) => Array.isArray(iterable) && options?.chunkSize === undefined ? fromArray(iterable) : fromChannel(Channel.fromIterableArray(iterable, options?.chunkSize));\n/**\n * Creates a stream from an effect producing an iterable of values.\n *\n * **When to use**\n *\n * Use when the iterable must be acquired from an Effect before the stream emits,\n * and acquisition services or failures should be part of the stream.\n *\n * **Example** (Creating a stream from an iterable effect)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Stream } from \"effect\"\n *\n * class UserRepo extends Context.Service<UserRepo, {\n *   readonly list: Effect.Effect<ReadonlyArray<string>>\n * }>()(\"UserRepo\") {}\n *\n * const listUsers = Effect.service(UserRepo).pipe(\n *   Effect.andThen((repo) => repo.list)\n * )\n *\n * const stream = Stream.fromIterableEffect(listUsers)\n *\n * const program = Effect.gen(function*() {\n *   const users = yield* stream.pipe(\n *     Stream.provideService(UserRepo, {\n *       list: Effect.succeed([\"user1\", \"user2\"])\n *     }),\n *     Stream.runCollect\n *   )\n *   users // => [\"user1\", \"user2\"]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromIterableEffect = iterable => unwrap(Effect.map(iterable, fromIterable));\n/**\n * Creates a stream by repeatedly running an effect that yields an iterable of values.\n *\n * **Example** (Repeating an iterable effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const stream = Stream.fromIterableEffectRepeat(Effect.succeed([1, 2])).pipe(\n *     Stream.take(5)\n *   )\n *   const values = yield* Stream.runCollect(stream)\n *   values // => [1, 2, 1, 2, 1]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromIterableEffectRepeat = iterable => flatMap(fromEffectRepeat(iterable), fromIterable);\n/**\n * Creates a stream from an array of values.\n *\n * **Example** (Creating a stream from an array of values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const stream = Stream.fromArray([1, 2, 3])\n *   const values = yield* Stream.runCollect(stream)\n *   values // => [1, 2, 3]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromArray = array => Arr.isReadonlyArrayNonEmpty(array) ? fromChannel(Channel.succeed(array)) : empty;\n/**\n * Creates a stream from an effect that produces an array of values.\n *\n * **When to use**\n *\n * Use when the array must be acquired from an Effect before the stream emits,\n * and acquisition services or failures should be part of the stream.\n *\n * **Example** (Creating a stream from an effect that produces an array of values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const stream = Stream.fromArrayEffect(Effect.succeed([\"Ada\", \"Grace\"]))\n *   const values = yield* Stream.runCollect(stream)\n *   values // => [\"Ada\", \"Grace\"]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromArrayEffect = effect => unwrap(Effect.map(effect, fromArray));\n/**\n * Creates a stream from an arbitrary number of arrays.\n *\n * **Example** (Creating a stream from an arbitrary number of arrays)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const stream = Stream.fromArrays([1, 2], [3, 4])\n *   const values = yield* Stream.runCollect(stream)\n *   values // => [1, 2, 3, 4]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromArrays = (...arrays) => fromChannel(Channel.fromArray(Arr.filter(arrays, Arr.isReadonlyArrayNonEmpty)));\n/**\n * Creates a stream that pulls values from a `Queue.Dequeue`.\n *\n * **Details**\n *\n * The stream emits non-empty batches of queued values and ends when the queue\n * fails with `Cause.Done`; other queue failures are propagated.\n *\n * **Example** (Creating a stream from a queue of values)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.unbounded<number, Cause.Done>()\n *   yield* Queue.offer(queue, 1)\n *   yield* Queue.offer(queue, 2)\n *   yield* Queue.offer(queue, 3)\n *   yield* Queue.end(queue)\n *\n *   const stream = Stream.fromQueue(queue)\n *   const values = yield* Stream.runCollect(stream)\n *   values // => [1, 2, 3]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromQueue = queue => fromChannel(Channel.fromQueueArray(queue));\n/**\n * Creates a stream from a subscription to a `PubSub`.\n *\n * **Example** (Creating a stream from a subscription to a PubSub)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber, PubSub, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const pubsub = yield* PubSub.unbounded<number>({ replay: 3 })\n *\n *   const fiber = yield* Stream.fromPubSub(pubsub).pipe(\n *     Stream.take(3),\n *     Stream.runCollect,\n *     Effect.forkChild\n *   )\n *\n *   yield* PubSub.publish(pubsub, 1)\n *   yield* PubSub.publish(pubsub, 2)\n *   yield* PubSub.publish(pubsub, 3)\n *\n *   const values = yield* Fiber.join(fiber)\n *   values // => [1, 2, 3]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromPubSub = pubsub => fromChannel(Channel.fromPubSubArray(pubsub));\n/**\n * Creates a stream from a PubSub of `Take` values.\n *\n * **Details**\n *\n * `Take` values include end and failure signals.\n *\n * **Example** (Creating a stream from PubSub takes)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, PubSub, Stream, Take } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const pubsub = yield* PubSub.unbounded<Take.Take<number, string>>({\n *     replay: 3\n *   })\n *\n *   yield* PubSub.publish(pubsub, [1])\n *   yield* PubSub.publish(pubsub, [2])\n *   yield* PubSub.publish(pubsub, Exit.succeed<void>(undefined))\n *\n *   const values = yield* Stream.fromPubSubTake(pubsub).pipe(Stream.runCollect)\n *   values // => [1, 2]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromPubSubTake = pubsub => fromChannel(Channel.fromPubSubTake(pubsub));\n/**\n * Creates a stream from a lazily supplied Web `ReadableStream`.\n *\n * **Details**\n *\n * The stream reads from a `ReadableStreamDefaultReader`, maps read failures\n * with `onError`, and closes the reader when the stream finalizes. By default\n * the reader is canceled; set `releaseLockOnEnd` to release the lock instead.\n *\n * **Example** (Creating a stream from a ReadableStream)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect, Stream } from \"effect\"\n *\n * class StreamError extends Data.TaggedError(\"StreamError\")<{ readonly cause: unknown }> {}\n *\n * const readableStream = new ReadableStream({\n *   start(controller) {\n *     controller.enqueue(1)\n *     controller.enqueue(2)\n *     controller.enqueue(3)\n *     controller.close()\n *   }\n * })\n *\n * const program = Effect.gen(function*() {\n *   const stream = Stream.fromReadableStream({\n *     evaluate: () => readableStream,\n *     onError: (cause) => new StreamError({ cause })\n *   })\n *   const values = yield* Stream.runCollect(stream)\n *   values // => [1, 2, 3]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromReadableStream = options => fromChannel(Channel.fromReadableStream(options));\n/**\n * Creates a stream from an AsyncIterable.\n *\n * **Example** (Creating a stream from an AsyncIterable)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect, Stream } from \"effect\"\n *\n * class StreamError extends Data.TaggedError(\"StreamError\")<{ readonly cause: unknown }> {}\n *\n * const iterable = (async function*() {\n *   yield 1\n *   yield 2\n *   yield 3\n * })()\n *\n * await Effect.runPromise(Effect.gen(function*() {\n *   const stream = Stream.fromAsyncIterable(iterable, (cause) => new StreamError({ cause }))\n *   const values = yield* Stream.runCollect(stream)\n *   values // => [1, 2, 3]\n * }))\n *\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromAsyncIterable = (iterable, onError) => fromChannel(Channel.fromAsyncIterableArray(iterable, onError));\n/**\n * Creates a stream that emits each output of a schedule that does not require input,\n * for as long as the schedule continues.\n *\n * **Example** (Creating a stream from a schedule)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schedule, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const schedule = Schedule.recurs(3)\n *   const stream = Stream.fromSchedule(schedule)\n *   const values = yield* Stream.runCollect(stream)\n *   values // => [0, 1, 2]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromSchedule = schedule => fromPull(Effect.map(Schedule.toStepWithSleep(schedule), step => Pull.catchDone(Effect.map(step(void 0), Arr.of), () => Cause.done())));\n/**\n * Creates a stream from a PubSub subscription.\n *\n * **When to use**\n *\n * Use when you already have a `PubSub.Subscription` and want to expose its\n * messages as a `Stream`, with `Stream.take` or cancellation controlling how\n * many values are consumed.\n *\n * **Example** (Creating a stream from a PubSub subscription)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub, Stream } from \"effect\"\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n *   const pubsub = yield* PubSub.unbounded<number>()\n *   const subscription = yield* PubSub.subscribe(pubsub)\n *\n *   yield* PubSub.publish(pubsub, 1)\n *   yield* PubSub.publish(pubsub, 2)\n *\n *   const stream = Stream.fromSubscription(subscription)\n *   const values = yield* stream.pipe(Stream.take(2), Stream.runCollect)\n *   values // => [1, 2]\n * }))\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromSubscription = pubsub => fromChannel(Channel.fromSubscriptionArray(pubsub));\n/**\n * Creates a stream from an event listener.\n *\n * **Example** (Creating a stream from an event listener)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * class NumberTarget implements Stream.EventListener<number> {\n *   addEventListener(event: string, f: (event: number) => void) {\n *     if (event === \"data\") {\n *       f(1)\n *       f(2)\n *       f(3)\n *     }\n *   }\n *   removeEventListener(_event: string, _f: (event: number) => void) {}\n * }\n *\n * await Effect.runPromise(Effect.gen(function*() {\n *   const stream = Stream.fromEventListener(new NumberTarget(), \"data\").pipe(\n *     Stream.take(3)\n *   )\n *   const values = yield* Stream.runCollect(stream)\n *   values // => [1, 2, 3]\n * }))\n *\n * ```\n *\n * @category constructors\n * @since 3.1.0\n */\nexport const fromEventListener = (target, type, options) => callback(queue => {\n  const once = typeof options === \"object\" && options.once;\n  function emit(event) {\n    Queue.offerUnsafe(queue, event);\n    if (once) Queue.endUnsafe(queue);\n  }\n  return Effect.acquireRelease(Effect.sync(() => target.addEventListener(type, emit, options)), () => Effect.sync(() => target.removeEventListener(type, emit, options)));\n}, {\n  bufferSize: typeof options === \"object\" ? options.bufferSize : undefined\n});\n/**\n * Creates a stream by repeatedly applying an effectful step function to a\n * state.\n *\n * **Details**\n *\n * Each `readonly [value, nextState]` result emits `value` and continues with\n * `nextState`; returning `undefined` ends the stream.\n *\n * **Example** (Unfolding stream state)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const stream = Stream.unfold(1, (n) => Effect.succeed([n, n + 1] as const))\n *   const values = yield* Stream.runCollect(stream.pipe(Stream.take(5)))\n *   values // => [ 1, 2, 3, 4, 5 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const unfold = (s, f) => fromPull(Effect.sync(() => {\n  let state = s;\n  return Effect.flatMap(Effect.suspend(() => f(state)), next => {\n    if (next === undefined) return Cause.done();\n    state = next[1];\n    return Effect.succeed(Arr.of(next[0]));\n  });\n}));\n/**\n * Creates a stream by repeatedly evaluating an effectful page function.\n *\n * **When to use**\n *\n * Use to consume paginated APIs where each step returns a batch of values\n * together with an optional next state.\n *\n * **Details**\n *\n * This is similar to {@link unfold}, but each step can emit zero or more values\n * and independently decide whether another state should be requested.\n *\n * **Example** (Paginating stream state)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, Stream } from \"effect\"\n *\n * const stream = Stream.paginate(0, (n: number) =>\n *   Effect.succeed(\n *     [\n *       [n],\n *       n < 3 ? Option.some(n + 1) : Option.none<number>()\n *     ] as const\n *   ))\n *\n * await Effect.runPromise(Stream.runCollect(stream)) // => [0, 1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const paginate = (s, f) => fromPull(Effect.sync(() => {\n  let state = s;\n  let done = false;\n  return Effect.suspend(function loop() {\n    if (done) return Cause.done();\n    return Effect.flatMap(f(state), ([a, s]) => {\n      if (Option.isNone(s)) {\n        done = true;\n      } else {\n        state = s.value;\n      }\n      if (!Arr.isReadonlyArrayNonEmpty(a)) return loop();\n      return Effect.succeed(a);\n    });\n  });\n}));\n/**\n * Creates an infinite stream by repeatedly applying a function to a seed value.\n *\n * **Example** (Iterating from a seed value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.iterate(1, (n) => n + 1).pipe(Stream.take(3))\n *\n * const program = Effect.gen(function* () {\n *   const values = yield* Stream.runCollect(stream)\n *   values // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const iterate = (value, next) => unfold(value, a => Effect.succeed([a, next(a)]));\n/**\n * Constructs a stream from a range of integers, including both endpoints.\n *\n * **Details**\n *\n * If the provided `min` is greater than `max`, the stream will not emit any\n * values. Finite fractional `chunkSize` values are rounded down, while `NaN`\n * and non-positive values are treated as `1`.\n *\n * **Example** (Creating a numeric range)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.range(1, 5).pipe(Stream.runCollect)\n *   values // => [ 1, 2, 3, 4, 5 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const range = (min, max, chunkSize = Channel.DefaultChunkSize) => min > max ? empty : fromPull(Effect.sync(() => {\n  const size = Count.normalizeNonEmpty(chunkSize);\n  let start = min;\n  let done = false;\n  return Effect.suspend(() => {\n    if (done) return Cause.done();\n    const remaining = max - start + 1;\n    if (remaining > size) {\n      const chunk = Arr.range(start, start + size - 1);\n      start += size;\n      return Effect.succeed(chunk);\n    }\n    const chunk = Arr.range(start, start + remaining - 1);\n    done = true;\n    return Effect.succeed(chunk);\n  });\n}));\n/**\n * The stream that never produces any value or fails with any error.\n *\n * **Example** (Creating a never-ending stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Stream.never.pipe(\n *   Stream.take(0),\n *   Stream.runCollect\n * )\n *\n * await Effect.runPromise(program) // => []\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const never = /*#__PURE__*/fromChannel(Channel.never);\n/**\n * Creates a stream produced from an `Effect`.\n *\n * **Example** (Unwrapping a stream effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const effect = Effect.succeed(Stream.make(1, 2, 3))\n *\n * const stream = Stream.unwrap(effect)\n *\n * const program = Effect.gen(function*() {\n *   const chunk = yield* Stream.runCollect(stream)\n *   chunk // => [ 1, 2, 3 ]\n * })\n * await Effect.runPromise(program)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const unwrap = effect => fromChannel(Channel.unwrap(Effect.map(effect, toChannel)));\n/**\n * Runs a stream that requires `Scope` in a managed scope, ensuring its\n * finalizers are run when the stream completes.\n *\n * **Example** (Scoping a stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const events: Array<string> = []\n * const stream = Stream.scoped(\n *   Stream.fromEffect(\n *     Effect.acquireRelease(\n *       Effect.sync(() => {\n *         events.push(\"acquire\")\n *         return \"resource\"\n *       }),\n *       () => Effect.sync(() => events.push(\"release\"))\n *     )\n *   )\n * )\n *\n * await Effect.runPromise(Stream.runCollect(stream)) // => [\"resource\"]\n * events // => [\"acquire\", \"release\"]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const scoped = self => fromChannel(Channel.scoped(self.channel));\n/**\n * Transforms the elements of this stream using the supplied function.\n *\n * **Example** (Mapping stream values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, Stream } from \"effect\"\n *\n * const stream = Stream.fromArray([1, 2, 3]).pipe(Stream.map((n, i) => n + i))\n * await Effect.runPromise(Stream.runCollect(stream)) // => [1, 3, 5]\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => suspend(() => {\n  let i = 0;\n  return fromChannel(Channel.map(self.channel, Arr.map(o => f(o, i++))));\n}));\n/**\n * Maps both the failure and success channels of a stream.\n *\n * **Example** (Mapping both the failure and success channels of a stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const mapper = {\n *   onFailure: (error: string) => `error: ${error}`,\n *   onSuccess: (value: number) => value * 2\n * }\n *\n * const program = Effect.gen(function*() {\n *   const success = yield* Stream.make(1, 2).pipe(\n *     Stream.mapBoth(mapper),\n *     Stream.runCollect\n *   )\n *   success // => [ 2, 4 ]\n *\n *   const failure = yield* Stream.fail(\"boom\").pipe(\n *     Stream.mapBoth(mapper),\n *     Stream.catch((error: string) => Stream.succeed(error)),\n *     Stream.runCollect\n *   )\n *   failure // => [ 'error: boom' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const mapBoth = /*#__PURE__*/dual(2, (self, options) => self.pipe(map(options.onSuccess), mapError(options.onFailure)));\n/**\n * Transforms each emitted chunk using the provided function, which receives the chunk and its index.\n *\n * **Example** (Mapping stream chunks)\n *\n * ```ts import.meta.vitest\n * import { Array, Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.make(1, 2, 3, 4).pipe(\n *     Stream.rechunk(2),\n *     Stream.mapArray((chunk, index) => Array.map(chunk, (n) => n + index)),\n *     Stream.runCollect\n *   )\n *   result // => [ 1, 2, 4, 5 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category mapping\n * @since 4.0.0\n */\nexport const mapArray = /*#__PURE__*/dual(2, (self, f) => fromChannel(Channel.map(self.channel, f)));\n/**\n * Maps over elements of the stream with the specified effectful function.\n *\n * **When to use**\n *\n * Use when each stream element transformation needs an Effect, service\n * dependency, failure channel, or configured concurrency.\n *\n * **Example** (Effectfully mapping stream values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const events: Array<string> = []\n * const stream = Stream.make(1, 2, 3)\n *\n * const mappedStream = stream.pipe(\n *   Stream.mapEffect((n) =>\n *     Effect.sync(() => {\n *       events.push(`Processing: ${n}`)\n *       return n * 2\n *     })\n *   )\n * )\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.runCollect(mappedStream)\n *   result // => [2, 4, 6]\n * })\n *\n * await Effect.runPromise(program)\n * events // => [\"Processing: 1\", \"Processing: 2\", \"Processing: 3\"]\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const mapEffect = /*#__PURE__*/dual(args => isStream(args[0]), (self, f, options) => self.channel.pipe(Channel.flattenArray, Channel.mapEffect(f, options), Channel.map(Arr.of), fromChannel));\n/**\n * Flattens a stream of `Effect` values into a stream of their results.\n *\n * **When to use**\n *\n * Use when stream elements already are effects and their successes should become\n * stream elements while their failures enter the stream error channel.\n *\n * **Example** (Flattening a stream of Effect values into a stream of their results)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(Effect.succeed(1), Effect.succeed(2), Effect.succeed(3))\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.runCollect(stream.pipe(Stream.flattenEffect()))\n *   result // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const flattenEffect = /*#__PURE__*/dual(args => isStream(args[0]), (self, options) => mapEffect(self, identity, options));\n/**\n * Maps over non-empty array chunks emitted by the stream effectfully.\n *\n * **When to use**\n *\n * Use when transformation needs to see and replace each non-empty emitted chunk\n * effectfully instead of mapping individual stream elements.\n *\n * **Example** (Effectfully mapping stream chunks)\n *\n * ```ts import.meta.vitest\n * import { Array, Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.fromArray([1, 2, 3, 4]).pipe(\n *     Stream.rechunk(2),\n *     Stream.mapArrayEffect((chunk, index) =>\n *       Effect.succeed(Array.map(chunk, (n) => n + index * 10))\n *     ),\n *     Stream.runCollect\n *   )\n *   result // => [ 1, 2, 13, 14 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category mapping\n * @since 4.0.0\n */\nexport const mapArrayEffect = /*#__PURE__*/dual(2, (self, f) => fromChannel(Channel.mapEffect(self.channel, f)));\n/**\n * Lifts failures and successes into a `Result`, yielding a stream that cannot fail.\n *\n * **Details**\n *\n * The stream ends after the first failure, emitting a `Result.fail` value.\n *\n * **Example** (Converting failures to results)\n *\n * ```ts import.meta.vitest\n * import { Effect, Result, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const results = yield* Stream.make(1, 2).pipe(\n *     Stream.concat(Stream.fail(\"boom\")),\n *     Stream.result,\n *     Stream.map(Result.match({\n *       onFailure: (error) => `failure: ${error}`,\n *       onSuccess: (value) => `success: ${value}`\n *     })),\n *     Stream.runCollect\n *   )\n *   results // => [ 'success: 1', 'success: 2', 'failure: boom' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const result = self => self.pipe(map(Result.succeed), catch_(e => succeed(Result.fail(e))));\n/**\n * Runs the provided effect for each element while preserving the elements.\n *\n * **Example** (Tapping stream values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const events: Array<string> = []\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.fromArray([1, 2, 3]).pipe(\n *     Stream.tap((n) => Effect.sync(() => events.push(`before mapping: ${n}`))),\n *     Stream.map((n) => n * 2),\n *     Stream.tap((n) => Effect.sync(() => events.push(`after mapping: ${n}`))),\n *     Stream.runCollect\n *   )\n *\n *   result // => [2, 4, 6]\n * })\n *\n * await Effect.runPromise(program)\n * events // => [\"before mapping: 1\", \"after mapping: 2\", \"before mapping: 2\", \"after mapping: 4\", \"before mapping: 3\", \"after mapping: 6\"]\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const tap = /*#__PURE__*/dual(args => isStream(args[0]), (self, f, options) => mapEffect(self, a => Effect.as(f(a), a), options));\n/**\n * Returns a stream that effectfully \"peeks\" at elements and failures.\n *\n * **Example** (Tapping values and errors)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const events: Array<string> = []\n * const program = Effect.gen(function*() {\n *   const stream = Stream.make(1, 2).pipe(\n *     Stream.concat(Stream.fail(\"boom\")),\n *     Stream.tapBoth({\n *       onElement: (value) => Effect.sync(() => events.push(`seen: ${value}`)),\n *       onError: (error) => Effect.sync(() => events.push(`error: ${error}`))\n *     }),\n *     Stream.catch(() => Stream.make(3))\n *   )\n *   const result = yield* Stream.runCollect(stream)\n *   result // => [1, 2, 3]\n * })\n *\n * await Effect.runPromise(program)\n * events // => [\"seen: 1\", \"seen: 2\", \"error: boom\"]\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const tapBoth = /*#__PURE__*/dual(2, (self, options) => self.pipe(tapError(options.onError), tap(options.onElement, {\n  concurrency: options.concurrency\n})));\n/**\n * Runs a sink for all stream elements while still emitting them downstream.\n *\n * **Example** (Tapping values with a sink)\n *\n * ```ts import.meta.vitest\n * import { Effect, Ref, Sink, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const seen = yield* Ref.make<Array<number>>([])\n *   const sink = Sink.forEach((value: number) =>\n *     Ref.update(seen, (items) => [...items, value])\n *   )\n *   const result = yield* Stream.make(1, 2, 3).pipe(\n *     Stream.tapSink(sink),\n *     Stream.runCollect\n *   )\n *   const tapped = yield* Ref.get(seen)\n *   tapped // => [ 1, 2, 3 ]\n *   result // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const tapSink = /*#__PURE__*/dual(2, (self, sink) => transformPullBracket(self, Effect.fnUntraced(function* (pull, _, scope) {\n  const upstreamLatch = Latch.makeUnsafe();\n  const sinkLatch = Latch.makeUnsafe();\n  let chunk = undefined;\n  let causeSink = undefined;\n  let sinkDone = false;\n  let streamDone = false;\n  const sinkUpstream = upstreamLatch.whenOpen(Effect.suspend(() => {\n    if (chunk) {\n      const arr = chunk;\n      chunk = undefined;\n      if (!streamDone) upstreamLatch.closeUnsafe();\n      return Effect.as(sinkLatch.open, arr);\n    }\n    return Cause.done();\n  }));\n  yield* Effect.suspend(() => sink.transform(sinkUpstream, scope)).pipe(eff => Effect.onExitPrimitive(eff, exit => {\n    sinkDone = true;\n    if (Exit.isFailure(exit)) {\n      causeSink = exit.cause;\n    }\n    return sinkLatch.open;\n  }, true), Effect.forkIn(scope));\n  const pullAndOffer = pull.pipe(Effect.flatMap(chunk_ => {\n    chunk = chunk_;\n    sinkLatch.closeUnsafe();\n    upstreamLatch.openUnsafe();\n    return Effect.as(sinkLatch.await, chunk_);\n  }), Pull.catchDone(() => {\n    streamDone = true;\n    sinkLatch.closeUnsafe();\n    upstreamLatch.openUnsafe();\n    return Effect.flatMap(sinkLatch.await, () => Cause.done());\n  }));\n  return Effect.suspend(() => {\n    if (causeSink) {\n      return Effect.failCause(causeSink);\n    } else if (sinkDone) {\n      return pull;\n    }\n    return pullAndOffer;\n  });\n})));\n/**\n * Maps each element to a stream and flattens the resulting streams.\n *\n * **Details**\n *\n * With the default sequential concurrency, inner streams are concatenated in\n * input order. When `concurrency` is greater than `1` or `\"unbounded\"`,\n * multiple inner streams may run at the same time and their outputs are merged\n * as they arrive.\n *\n * **Example** (Flat mapping stream values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.make(1, 2, 3).pipe(\n *     Stream.flatMap((n) => Stream.make(n, n * 2)),\n *     Stream.runCollect\n *   )\n *   values // => [ 1, 2, 2, 4, 3, 6 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const flatMap = /*#__PURE__*/dual(args => isStream(args[0]), (self, f, options) => self.channel.pipe(Channel.flattenArray, Channel.flatMap(a => f(a).channel, options), fromChannel));\n/**\n * Switches to the latest stream produced by the mapping function, interrupting\n * the previous stream when a new element arrives.\n *\n * **Example** (Switching to the latest stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Stream.make(1, 2, 3).pipe(\n *   Stream.switchMap((n) => (n === 3 ? Stream.make(n) : Stream.never)),\n *   Stream.runCollect\n * )\n *\n * await Effect.runPromise(Effect.gen(function*() {\n *   const result = yield* program\n *   result // => [ 3 ]\n * }))\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const switchMap = /*#__PURE__*/dual(args => isStream(args[0]), (self, f, options) => self.channel.pipe(Channel.flattenArray, Channel.switchMap(a => f(a).channel, options), fromChannel));\n/**\n * Flattens a stream of streams into a single stream.\n *\n * **Details**\n *\n * With the default sequential concurrency, inner streams are concatenated in\n * strict order. When `concurrency` is greater than `1` or `\"unbounded\"`,\n * multiple inner streams may run at the same time and their outputs are merged\n * as they arrive.\n *\n * **Example** (Flattening nested streams)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const streamOfStreams = Stream.make(\n *   Stream.make(1, 2),\n *   Stream.make(3, 4),\n *   Stream.make(5, 6)\n * )\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.runCollect(Stream.flatten(streamOfStreams))\n *   values // => [ 1, 2, 3, 4, 5, 6 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const flatten = /*#__PURE__*/dual(args => isStream(args[0]), (self, options) => flatMap(self, identity, options));\n/**\n * Flattens a stream of non-empty arrays into a stream of elements.\n *\n * **Example** (Flattening a stream of non-empty arrays into a stream of elements)\n *\n * ```ts import.meta.vitest\n * import { Array, Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(Array.make(1, 2), Array.make(3))\n *\n * const program = Effect.gen(function* () {\n *   const result = yield* Stream.runCollect(Stream.flattenArray(stream))\n *   result // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const flattenArray = self => fromChannel(Channel.flattenArray(self.channel));\n/**\n * Converts this stream to one that runs its effects but emits no elements.\n *\n * **Example** (Draining stream values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.range(1, 6).pipe(Stream.drain, Stream.runCollect)\n *   result // => []\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const drain = self => fromChannel(Channel.drain(self.channel));\n/**\n * Runs the provided stream in the background while this stream runs, interrupting it\n * when this stream completes and failing if the background stream fails or defects.\n *\n * **Example** (Draining a stream in the background)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const events: Array<string> = []\n * const foreground = Stream.make(1, 2)\n * const background = Stream.fromEffect(Effect.sync(() => events.push(\"background task\")))\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* foreground.pipe(\n *     Stream.drainFork(background),\n *     Stream.runCollect\n *   )\n *   values // => [1, 2]\n * })\n *\n * await Effect.runPromise(program)\n * events // => [\"background task\"]\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const drainFork = /*#__PURE__*/dual(2, (self, that) => mergeEffect(self, runDrain(that)));\n/**\n * Repeats the entire stream according to the provided schedule.\n *\n * **Example** (Repeating a stream on a schedule)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schedule, Stream } from \"effect\"\n *\n * const program = Effect.gen(function* () {\n *   const result = yield* Stream.make(1).pipe(\n *     Stream.repeat(Schedule.recurs(4)),\n *     Stream.runCollect\n *   )\n *\n *   result // => [ 1, 1, 1, 1, 1 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const repeat = /*#__PURE__*/dual(2, (self, schedule) => fromChannel(Channel.repeat(self.channel, schedule)));\n/**\n * Schedules the stream's elements according to the provided schedule.\n *\n * **Example** (Scheduling stream elements)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schedule, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.make(1, 2, 3).pipe(\n *     Stream.schedule(Schedule.recurs(3)),\n *     Stream.runCollect\n *   )\n *\n *   result // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category rate limiting\n * @since 2.0.0\n */\nexport const schedule = /*#__PURE__*/dual(2, (self, schedule) => self.channel.pipe(Channel.flattenArray, Channel.schedule(schedule), Channel.map(Arr.of), fromChannel));\n/**\n * Ends the stream if it does not produce a value within the specified duration.\n *\n * **Example** (Timing out a stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.make(1).pipe(\n *     Stream.concat(Stream.never),\n *     Stream.timeout(\"1 second\"),\n *     Stream.runCollect\n *   )\n *   values // => [ 1 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category delays & timeouts\n * @since 2.0.0\n */\nexport const timeout = /*#__PURE__*/dual(2, (self, duration) => timeoutOrElse(self, {\n  duration,\n  orElse: () => empty\n}));\n/**\n * Switches to a fallback stream if this stream does not emit a value within\n * the specified duration.\n *\n * **When to use**\n *\n * Use when a stream should continue with another stream if an upstream pull\n * waits longer than the allowed duration.\n *\n * **Details**\n *\n * The timeout is checked for each pull. A zero duration uses `orElse`\n * immediately, while an infinite duration leaves the original stream\n * unchanged.\n *\n * **Gotchas**\n *\n * The fallback stream is not timed after the switch.\n *\n * @see {@link timeout} for ending the stream instead of switching to a fallback stream\n *\n * @category delays & timeouts\n * @since 4.0.0\n */\nexport const timeoutOrElse = /*#__PURE__*/dual(2, (self, options) => {\n  const duration = Duration.fromInputUnsafe(options.duration);\n  if (!Duration.isFinite(duration)) return self;\n  if (Duration.isZero(duration)) return suspend(options.orElse);\n  const timeoutSymbol = Symbol();\n  return catchCause(suspend(() => {\n    const parent = Fiber.getCurrent();\n    const clock = parent.getRef(Clock);\n    const durationMs = Duration.toMillis(duration);\n    let deadline = undefined;\n    const latch = Latch.makeUnsafe(false);\n    return merge(transformPull(self, (pull, _scope) => Effect.suspend(() => {\n      deadline = clock.currentTimeMillisUnsafe() + durationMs;\n      latch.openUnsafe();\n      return pull;\n    }).pipe(Effect.map(arr => {\n      latch.closeUnsafe();\n      deadline = undefined;\n      return arr;\n    }), Effect.succeed)), fromEffectDrain(Effect.gen(function* () {\n      while (true) {\n        yield* latch.await;\n        if (deadline === undefined) continue;\n        yield* Effect.sleep(deadline - clock.currentTimeMillisUnsafe());\n        if (deadline === undefined) continue;\n        const remaining = deadline - clock.currentTimeMillisUnsafe();\n        if (remaining > 0) continue;\n        return yield* Effect.die(timeoutSymbol);\n      }\n    })), {\n      haltStrategy: \"left\"\n    });\n  }), cause => {\n    const isTimeout = cause.reasons.find(r => r._tag === \"Die\" && r.defect === timeoutSymbol);\n    if (isTimeout) return options.orElse();\n    return failCause(cause);\n  });\n});\n/**\n * Repeats each element of the stream according to the provided schedule,\n * including the original emission.\n *\n * **Example** (Repeating stream elements)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schedule, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.make(\"A\", \"B\", \"C\").pipe(\n *     Stream.repeatElements(Schedule.recurs(1)),\n *     Stream.runCollect\n *   )\n *   values // => [ 'A', 'A', 'B', 'B', 'C', 'C' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const repeatElements = /*#__PURE__*/dual(2, (self, schedule) => fromChannel(Channel.fromTransform((upstream, scope) => Effect.map(Channel.toTransform(Channel.flattenArray(self.channel))(upstream, scope), pullElement => {\n  let pullRepeat = undefined;\n  const pull = Effect.gen(function* () {\n    const element = yield* pullElement;\n    const chunk = Arr.of(element);\n    const step = yield* Schedule.toStepWithSleep(schedule);\n    pullRepeat = step(element).pipe(Effect.as(chunk), Pull.catchDone(_ => {\n      pullRepeat = undefined;\n      return pull;\n    }));\n    return chunk;\n  });\n  return Effect.suspend(() => pullRepeat ?? pull);\n}))));\n/**\n * Repeats this stream forever.\n *\n * **Example** (Repeating a stream forever)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(\"A\", \"B\").pipe(\n *   Stream.forever,\n *   Stream.take(5)\n * )\n *\n * const program = Effect.gen(function*() {\n *   const output = yield* Stream.runCollect(stream)\n *   output // => [ 'A', 'B', 'A', 'B', 'A' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const forever = self => fromChannel(Channel.forever(self.channel));\n/**\n * Flattens the iterables emitted by this stream into the stream's structure.\n *\n * **Example** (Flattening iterable values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const stream = Stream.make([1, 2], [3, 4]).pipe(Stream.flattenIterable)\n *   const values = yield* Stream.runCollect(stream)\n *   values // => [ 1, 2, 3, 4 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category mapping\n * @since 4.0.0\n */\nexport const flattenIterable = self => flatMap(self, fromIterable);\n/**\n * Unwraps `Take` values, emitting elements from non-empty arrays and ending or\n * failing when the `Exit` signals completion.\n *\n * **Example** (Flattening Take values)\n *\n * ```ts import.meta.vitest\n * import { Array, Effect, Exit, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const takes = Stream.make(\n *     Array.make(1, 2),\n *     Array.make(3),\n *     Exit.succeed<void>(undefined)\n *   )\n *\n *   const values = yield* Stream.flattenTake(takes).pipe(Stream.runCollect)\n *   values // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const flattenTake = self => self.channel.pipe(Channel.flattenArray, Channel.flattenTake, fromChannel);\n/**\n * Concatenates two streams, emitting all elements from the first stream\n * followed by all elements from the second stream.\n *\n * **Example** (Concatenating streams)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.concat(Stream.make(1, 2, 3), Stream.make(4, 5, 6))\n *\n * await Effect.runPromise(Effect.gen(function*() {\n *   const values = yield* Stream.runCollect(stream)\n *   values // => [ 1, 2, 3, 4, 5, 6 ]\n * }))\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const concat = /*#__PURE__*/dual(2, (self, that) => flatten(fromArray([self, that])));\n/**\n * Prepends the values from the provided iterable before the stream's elements.\n *\n * **Example** (Prepending values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.make(3, 4).pipe(\n *     Stream.prepend([1, 2]),\n *     Stream.runCollect\n *   )\n *\n *   values // => [ 1, 2, 3, 4 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const prepend = /*#__PURE__*/dual(2, (self, values) => concat(fromIterable(values), self));\n/**\n * Merges two streams, emitting elements from both as they arrive.\n *\n * **Details**\n *\n * By default, the merged stream ends when both streams end. Use\n * `haltStrategy` to change the termination behavior.\n *\n * **Example** (Merging stream values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const fast = Stream.make(1, 2, 3)\n * const slow = Stream.fromEffect(Effect.delay(Effect.succeed(4), \"50 millis\"))\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.runCollect(Stream.merge(fast, slow))\n *   result // => [ 1, 2, 3, 4 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category merging\n * @since 2.0.0\n */\nexport const merge = /*#__PURE__*/dual(args => isStream(args[0]) && isStream(args[1]), (self, that, options) => fromChannel(Channel.merge(toChannel(self), toChannel(that), options)));\n/**\n * Merges this stream with a background effect, keeping the stream's elements.\n *\n * **When to use**\n *\n * Use when an effect should run concurrently for the lifetime of a stream while\n * only the stream's elements remain in the output.\n *\n * **Details**\n *\n * The effect runs concurrently, fails the stream if it fails, and is interrupted\n * when the stream completes.\n *\n * **Example** (Merging with a background effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const events: Array<string> = []\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.make(1, 2, 3).pipe(\n *     Stream.mergeEffect(Effect.sync(() => events.push(\"side task\"))),\n *     Stream.runCollect\n *   )\n *\n *   values // => [1, 2, 3]\n * })\n *\n * await Effect.runPromise(program)\n * events // => [\"side task\"]\n * ```\n *\n * @category merging\n * @since 4.0.0\n */\nexport const mergeEffect = /*#__PURE__*/dual(2, (self, effect) => self.channel.pipe(Channel.mergeEffect(effect), fromChannel));\n/**\n * Merges this stream and the specified stream together, tagging values from the\n * left stream as `Result.succeed` and values from the right stream as `Result.fail`.\n *\n * **When to use**\n *\n * Use when values from both streams should be emitted and downstream code needs\n * left values wrapped as successful `Result` values and right values wrapped as\n * failed `Result` values.\n *\n * **Example** (Merging streams into results)\n *\n * ```ts import.meta.vitest\n * import { Effect, Result, Stream } from \"effect\"\n *\n * const left = Stream.fromEffect(Effect.succeed(\"left\"))\n * const right = Stream.fromEffect(Effect.delay(Effect.succeed(\"right\"), \"10 millis\"))\n *\n * const merged = left.pipe(\n *   Stream.mergeResult(right),\n *   Stream.map(\n *     Result.match({\n *       onFailure: (value) => `right:${value}`,\n *       onSuccess: (value) => `left:${value}`\n *     })\n *   )\n * )\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.runCollect(merged)\n *   result // => [ 'left:left', 'right:right' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category merging\n * @since 4.0.0\n */\nexport const mergeResult = /*#__PURE__*/dual(2, (self, that) => merge(map(self, Result.succeed), map(that, Result.fail)));\n/**\n * Merges two streams while emitting only the values from the left stream.\n *\n * **When to use**\n *\n * Use when the right stream is needed for its effects or failures, but downstream\n * consumers should only receive values from the left stream.\n *\n * **Details**\n *\n * The right stream still runs for its effects, and any failures from the right\n * stream are propagated. The merged stream completes when the left stream\n * completes, interrupting the right stream.\n *\n * **Example** (Merging streams while keeping left values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const left = Stream.make(1, 2)\n *   const right = Stream.make(\"a\", \"b\")\n *   const values = yield* left.pipe(Stream.mergeLeft(right), Stream.runCollect)\n *   values // => [ 1, 2 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category merging\n * @since 2.0.0\n */\nexport const mergeLeft = /*#__PURE__*/dual(2, (left, right) => mergeEffect(left, runDrain(right)));\n/**\n * Merges this stream and the specified stream together, emitting only the\n * values from the right stream while the left stream runs for its effects.\n *\n * **When to use**\n *\n * Use when the left stream is needed for its effects or failures, but downstream\n * consumers should only receive values from the right stream.\n *\n * **Details**\n *\n * The merged stream ends when the right stream completes, interrupting the\n * left stream. Failures from the left stream still fail the merged stream.\n *\n * **Example** (Merging streams while keeping right values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const left = Stream.make(\"left-1\", \"left-2\").pipe(\n *   Stream.tap(() => Effect.sync(() => undefined))\n * )\n * const right = Stream.make(1, 2)\n *\n * const merged = Stream.mergeRight(left, right)\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.runCollect(merged)\n *   result // => [ 1, 2 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category merging\n * @since 2.0.0\n */\nexport const mergeRight = /*#__PURE__*/dual(2, (left, right) => mergeEffect(right, runDrain(left)));\n/**\n * Merges a collection of streams, running up to the specified number concurrently.\n *\n * **When to use**\n *\n * Use to merge an iterable of already-created streams while bounding how many\n * inner streams may run at the same time.\n *\n * **Details**\n *\n * The `concurrency` option is required and may be a number or `\"unbounded\"`.\n * `bufferSize` controls buffering between inner streams, and outputs are\n * emitted as they arrive under concurrent merging.\n *\n * **Example** (Merging streams with bounded concurrency)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const streams = [\n *   Stream.fromEffect(Effect.delay(Effect.succeed(\"A\"), \"20 millis\")),\n *   Stream.fromEffect(Effect.delay(Effect.succeed(\"B\"), \"10 millis\"))\n * ]\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.mergeAll(streams, { concurrency: 2 }).pipe(\n *     Stream.runCollect\n *   )\n *   values // => [ 'B', 'A' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @see {@link merge} for merging exactly two streams and choosing a halt strategy\n * @see {@link flatten} for flattening a stream that already emits streams\n *\n * @category merging\n * @since 2.0.0\n */\nexport const mergeAll = /*#__PURE__*/dual(2, (streams, options) => flatten(fromIterable(streams), options));\n/**\n * Creates the cartesian product of two streams, running the `right` stream for\n * each element in the `left` stream.\n *\n * **Details**\n *\n * See also `Stream.zip` for the more common point-wise variant.\n *\n * **Example** (Computing cartesian products)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const left = Stream.make(1, 2)\n *   const right = Stream.make(\"a\", \"b\")\n *   const values = yield* Stream.runCollect(Stream.cross(left, right))\n *   values // => [ [ 1, 'a' ], [ 1, 'b' ], [ 2, 'a' ], [ 2, 'b' ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const cross = /*#__PURE__*/dual(2, (left, right) => crossWith(left, right, (l, r) => [l, r]));\n/**\n * Creates a cartesian product of elements from two streams using a function.\n *\n * **Details**\n *\n * The `right` stream is rerun for every element in the `left` stream.\n *\n * See also `Stream.zipWith` for the more common point-wise variant.\n *\n * **Example** (Combining cartesian products)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const left = Stream.make(1, 2)\n *   const right = Stream.make(\"a\", \"b\")\n *   const combined = Stream.crossWith(left, right, (n, s) => `${n}-${s}`)\n *   const result = yield* Stream.runCollect(combined)\n *   result // => [ '1-a', '1-b', '2-a', '2-b' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const crossWith = /*#__PURE__*/dual(3, (left, right, f) => flatMap(left, l => map(right, r => f(l, r))));\n/**\n * Zips two streams point-wise with a combining function, ending when either stream ends.\n *\n * **Example** (Zipping streams with a function)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream1 = Stream.make(1, 2, 3, 4, 5, 6)\n * const stream2 = Stream.make(\"a\", \"b\", \"c\")\n *\n * const zipped = Stream.zipWith(stream1, stream2, (n, s) => `${n}-${s}`)\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.runCollect(zipped)\n *   result // => [ '1-a', '2-b', '3-c' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipWith = /*#__PURE__*/dual(3, (left, right, f) => zipWithArray(left, right, zipArrays(f)));\nconst zipArrays = f => (leftArr, rightArr) => {\n  const minLength = Math.min(leftArr.length, rightArr.length);\n  const result = [];\n  for (let i = 0; i < minLength; i++) {\n    result.push(f(leftArr[i], rightArr[i]));\n  }\n  return [result, leftArr.slice(minLength), rightArr.slice(minLength)];\n};\n/**\n * Zips two streams by applying a function to non-empty arrays of elements.\n *\n * **Details**\n *\n * The function returns output plus leftover arrays that carry into the next pull.\n *\n * **Example** (Zipping stream chunks)\n *\n * ```ts import.meta.vitest\n * import { Array, Effect, Stream } from \"effect\"\n *\n * const left = Stream.fromArrays([1, 2, 3], [4, 5])\n * const right = Stream.fromArrays([\"a\", \"b\"], [\"c\", \"d\", \"e\"])\n *\n * const zipped = Stream.zipWithArray(left, right, (leftChunk, rightChunk) => {\n *   const minLength = Math.min(leftChunk.length, rightChunk.length)\n *   const output = Array.makeBy(minLength, (i) => [leftChunk[i], rightChunk[i]] as const)\n *\n *   return [output, leftChunk.slice(minLength), rightChunk.slice(minLength)]\n * })\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.runCollect(zipped)\n *   result // => [ [ 1, 'a' ], [ 2, 'b' ], [ 3, 'c' ], [ 4, 'd' ], [ 5, 'e' ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category zipping\n * @since 4.0.0\n */\nexport const zipWithArray = /*#__PURE__*/dual(3, (left, right, f) => fromChannel(Channel.fromTransformBracket(Effect.fnUntraced(function* (_, scope) {\n  const pullLeft = yield* Channel.toPullScoped(left.channel, scope);\n  const pullRight = yield* Channel.toPullScoped(right.channel, scope);\n  const pullBoth = Effect.gen(function* () {\n    const fiberLeft = yield* Effect.forkIn(pullLeft, scope);\n    const fiberRight = yield* Effect.forkIn(pullRight, scope);\n    return yield* Fiber.joinAll([fiberLeft, fiberRight]);\n  });\n  let state = {\n    _tag: \"PullBoth\"\n  };\n  const pull = Effect.gen(function* () {\n    const [left, right] = state._tag === \"PullBoth\" ? yield* pullBoth : state._tag === \"PullLeft\" ? [yield* pullLeft, state.rightArray] : [state.leftArray, yield* pullRight];\n    const result = f(left, right);\n    if (Arr.isReadonlyArrayNonEmpty(result[1])) {\n      state = {\n        _tag: \"PullRight\",\n        leftArray: result[1]\n      };\n    } else if (Arr.isReadonlyArrayNonEmpty(result[2])) {\n      state = {\n        _tag: \"PullLeft\",\n        rightArray: result[2]\n      };\n    } else {\n      state = {\n        _tag: \"PullBoth\"\n      };\n    }\n    return result[0];\n  });\n  return pull;\n}))));\n/**\n * Zips this stream with another point-wise and emits tuples of elements from\n * both streams. The new stream ends when either stream ends.\n *\n * **Example** (Zipping streams)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream1 = Stream.make(1, 2, 3)\n * const stream2 = Stream.make(\"a\", \"b\", \"c\")\n *\n * const zipped = Stream.zip(stream1, stream2)\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.runCollect(zipped)\n *   result // => [ [ 1, 'a' ], [ 2, 'b' ], [ 3, 'c' ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zip = /*#__PURE__*/dual(2, (self, that) => zipWith(self, that, (a, a2) => [a, a2]));\n/**\n * Zips this stream with another point-wise and keeps only the values from\n * the left stream.\n *\n * **Details**\n *\n * The resulting stream ends when either side ends.\n *\n * **Example** (Zipping streams while keeping left values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream1 = Stream.make(1, 2, 3, 4)\n * const stream2 = Stream.make(\"a\", \"b\")\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.zipLeft(stream1, stream2).pipe(Stream.runCollect)\n *   result // => [ 1, 2 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipLeft = /*#__PURE__*/dual(2, (left, right) => zipWithArray(left, right, (leftArr, rightArr) => {\n  const minLength = Math.min(leftArr.length, rightArr.length);\n  const output = leftArr.slice(0, minLength);\n  const leftoverLeft = leftArr.slice(minLength);\n  const leftoverRight = rightArr.slice(minLength);\n  return [output, leftoverLeft, leftoverRight];\n}));\n/**\n * Zips this stream with another point-wise, keeping only right values and ending when either stream ends.\n *\n * **Example** (Zipping streams while keeping right values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream1 = Stream.make(1, 2)\n * const stream2 = Stream.make(\"a\", \"b\", \"c\", \"d\")\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.zipRight(stream1, stream2).pipe(Stream.runCollect)\n *   result // => [ 'a', 'b' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipRight = /*#__PURE__*/dual(2, (left, right) => zipWithArray(left, right, (leftArr, rightArr) => {\n  const minLength = Math.min(leftArr.length, rightArr.length);\n  const output = rightArr.slice(0, minLength);\n  const leftoverLeft = leftArr.slice(minLength);\n  const leftoverRight = rightArr.slice(minLength);\n  return [output, leftoverLeft, leftoverRight];\n}));\n/**\n * Zips this stream with another point-wise and emits tuples of elements from\n * both streams, flattening the left tuple.\n *\n * **Details**\n *\n * The new stream will end when one of the sides ends.\n *\n * **Example** (Zipping and flattening tuples)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const stream1 = Stream.make(\n *     [1, \"a\"] as const,\n *     [2, \"b\"] as const,\n *     [3, \"c\"] as const\n *   )\n *   const stream2 = Stream.make(\"x\", \"y\", \"z\")\n *   const result = yield* Stream.zipFlatten(stream1, stream2).pipe(Stream.runCollect)\n *\n *   result // => [ [ 1, 'a', 'x' ], [ 2, 'b', 'y' ], [ 3, 'c', 'z' ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipFlatten = /*#__PURE__*/dual(2, (self, that) => zipWith(self, that, (a, a2) => [...a, a2]));\n/**\n * Zips this stream together with the index of elements.\n *\n * **Example** (Zipping elements with indices)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const indexed = yield* Stream.make(\"a\", \"b\", \"c\", \"d\").pipe(\n *     Stream.zipWithIndex,\n *     Stream.runCollect\n *   )\n *   indexed // => [ [ 'a', 0 ], [ 'b', 1 ], [ 'c', 2 ], [ 'd', 3 ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipWithIndex = self => map(self, (a, i) => [a, i]);\n/**\n * Zips each element with the next element, pairing the final element with\n * `Option.none()`.\n *\n * **Example** (Zipping elements with next values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, Stream } from \"effect\"\n *\n * const stream = Stream.zipWithNext(Stream.make(1, 2, 3, 4))\n *\n * await Effect.runPromise(Effect.gen(function*() {\n *   const values = yield* Stream.runCollect(stream)\n *   values // => [[1, Option.some(2)], [2, Option.some(3)], [3, Option.some(4)], [4, Option.none()]]\n * }))\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipWithNext = self => mapAccumArray(self, Option.none, (acc, arr) => {\n  let i = 0;\n  if (acc._tag === \"None\") {\n    i = 1;\n    acc = Option.some(arr[0]);\n  }\n  const pairs = Arr.empty();\n  for (; i < arr.length; i++) {\n    const value = acc.value;\n    acc = Option.some(arr[i]);\n    pairs.push([value, acc]);\n  }\n  return [acc, pairs];\n}, {\n  onHalt(state) {\n    return state._tag === \"Some\" ? [[state.value, Option.none()]] : [];\n  }\n});\n/**\n * Zips each element with its previous element, starting with `None`.\n *\n * **Example** (Zipping elements with previous values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, Stream } from \"effect\"\n *\n * const stream = Stream.zipWithPrevious(Stream.make(1, 2, 3, 4))\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.runCollect(stream)\n *   result // => [[Option.none(), 1], [Option.some(1), 2], [Option.some(2), 3], [Option.some(3), 4]]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipWithPrevious = self => mapAccumArray(self, Option.none, (acc, arr) => {\n  const pairs = Arr.empty();\n  for (let i = 0; i < arr.length; i++) {\n    const value = arr[i];\n    pairs.push([acc, value]);\n    acc = Option.some(arr[i]);\n  }\n  return [acc, pairs];\n});\n/**\n * Zips each element with its previous and next values.\n *\n * **Example** (Zipping elements with neighbors)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect, Option, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.make(1, 2, 3).pipe(\n *     Stream.zipWithPreviousAndNext,\n *     Stream.runCollect\n *   )\n *   values // => [[Option.none(), 1, Option.some(2)], [Option.some(1), 2, Option.some(3)], [Option.some(2), 3, Option.none()]]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipWithPreviousAndNext = self => mapAccumArray(self, () => ({\n  prev: Option.none(),\n  current: Option.none()\n}), (acc, arr) => {\n  let i = 0;\n  let current;\n  if (acc.current._tag === \"None\") {\n    i = 1;\n    current = arr[0];\n    acc.current = Option.some(current);\n  } else {\n    current = acc.current.value;\n  }\n  const pairs = Arr.empty();\n  for (; i < arr.length; i++) {\n    const element = arr[i];\n    acc.current = Option.some(element);\n    pairs.push([acc.prev, current, acc.current]);\n    acc.prev = Option.some(current);\n    current = element;\n  }\n  return [acc, pairs];\n}, {\n  onHalt(acc) {\n    return acc.current._tag === \"Some\" ? [[acc.prev, acc.current.value, Option.none()]] : [];\n  }\n});\n/**\n * Zips multiple streams so that when a value is emitted by any stream, it is\n * combined with the latest values from the other streams to produce a result.\n *\n * **When to use**\n *\n * Use when each stream should contribute its latest value after all streams have\n * emitted at least once.\n *\n * **Gotchas**\n *\n * Note: tracking the latest value is done on a per-array basis. That means\n * that emitted elements that are not the last value in arrays will never be\n * used for zipping.\n *\n * **Example** (Zipping latest values from many streams)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.zipLatestAll(\n *   Stream.make(1, 2, 3).pipe(Stream.rechunk(1)),\n *   Stream.make(\"a\", \"b\", \"c\").pipe(Stream.rechunk(1)),\n *   Stream.make(true, false, true).pipe(Stream.rechunk(1))\n * )\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.runCollect(stream)\n *   result // => [[1, \"a\", true], [2, \"a\", true], [2, \"b\", true], [2, \"b\", false], [3, \"b\", false], [3, \"c\", false], [3, \"c\", true]]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category zipping\n * @since 3.3.0\n */\nexport const zipLatestAll = (...streams) => fromChannel(Channel.suspend(() => {\n  const latest = [];\n  const emitted = new Set();\n  const readyLatch = Latch.makeUnsafe();\n  return Channel.mergeAll(Channel.fromArray(streams.map((s, i) => s.channel.pipe(Channel.flattenArray, Channel.mapEffect(a => {\n    latest[i] = a;\n    if (!emitted.has(i)) {\n      emitted.add(i);\n      if (emitted.size < streams.length) {\n        return readyLatch.await;\n      }\n      return Effect.as(readyLatch.open, Arr.of(latest.slice()));\n    }\n    return Effect.succeed(Arr.of(latest.slice()));\n  }), Channel.filter(isNotUndefined)))), {\n    concurrency: \"unbounded\",\n    bufferSize: 0\n  });\n}));\n/**\n * Combines two streams by emitting each new element with the latest value from the other stream.\n *\n * **When to use**\n *\n * Use when two streams should start emitting combined pairs after both have\n * produced at least one value.\n *\n * **Gotchas**\n *\n * Note: tracking the latest value is done on a per-array basis. That means\n * that emitted elements that are not the last value in arrays will never be\n * used for zipping.\n *\n * **Example** (Zipping latest values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.zipLatest(\n *     Stream.make(1),\n *     Stream.make(\"a\")\n *   ).pipe(Stream.runCollect)\n *\n *   result // => [ [ 1, 'a' ] ]\n * })\n * await Effect.runPromise(program)\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipLatest = /*#__PURE__*/dual(2, (left, right) => zipLatestAll(left, right));\n/**\n * Combines the latest values from both streams whenever either emits, using\n * the provided function.\n *\n * **When to use**\n *\n * Use when two streams should start emitting custom combined values after both\n * have produced at least one value.\n *\n * **Gotchas**\n *\n * Note: tracking the latest value is done on a per-array basis. That means\n * that emitted elements that are not the last value in arrays will never be\n * used for zipping.\n *\n * **Example** (Zipping latest values with a function)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * await Effect.runPromise(Effect.gen(function*() {\n *   const result = yield* Stream.make(1, 2, 3).pipe(\n *     Stream.rechunk(1),\n *     Stream.zipLatestWith(\n *       Stream.make(10, 20).pipe(Stream.rechunk(1)),\n *       (n, m) => n + m\n *     ),\n *     Stream.runCollect\n *   )\n *\n *   result // => [ 11, 12, 22, 23 ]\n * }))\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipLatestWith = /*#__PURE__*/dual(3, (left, right, f) => map(zipLatestAll(left, right), ([a, a2]) => f(a, a2)));\n/**\n * Runs all streams concurrently until one stream emits its first value, then\n * mirrors that winning stream and interrupts the rest.\n *\n * **Details**\n *\n * Failures or completion from losing streams before a winner is chosen are\n * ignored unless every stream fails or completes before emitting. After a\n * winner is chosen, that stream's later failures are propagated.\n *\n * **Example** (Racing multiple streams)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schedule, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.raceAll(\n *     Stream.empty,\n *     Stream.make(0, 1, 2)\n *   ).pipe(Stream.runCollect)\n *   result // => [ 0, 1, 2 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category racing\n * @since 3.5.0\n */\nexport const raceAll = (...streams) => fromChannel(Channel.fromTransform((_, scope) => Effect.sync(() => {\n  let winner;\n  const race = Effect.raceAll(streams.map(stream => {\n    const childScope = Scope.forkUnsafe(scope);\n    return Channel.toPullScoped(stream.channel, childScope).pipe(Effect.flatMap(pull => Effect.zip(Effect.succeed(pull), pull)), Effect.onExit(exit => {\n      if (exit._tag === \"Success\") {\n        if (winner) {\n          return Scope.close(childScope, exit);\n        }\n        winner = exit.value[0];\n        return Effect.void;\n      }\n      return Scope.close(childScope, exit);\n    }), Effect.map(([, chunk]) => chunk));\n  }));\n  return Effect.suspend(() => winner ?? race);\n})));\n/**\n * Runs both streams concurrently until one stream emits its first value, then\n * mirrors that winning stream and interrupts the other.\n *\n * **Details**\n *\n * A failure or completion from one side before the other side emits does not\n * win the race unless both sides fail or complete before emitting. After a\n * winner is chosen, that stream's later failures are propagated.\n *\n * **Example** (Racing two streams)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.race(\n *   Stream.empty,\n *   Stream.make(0, 1, 2)\n * )\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.runCollect(stream)\n *   result // => [ 0, 1, 2 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category racing\n * @since 3.7.0\n */\nexport const race = /*#__PURE__*/dual(2, (left, right) => raceAll(left, right));\n/**\n * Filters a stream to the elements that satisfy a predicate.\n *\n * **Example** (Filtering stream values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const stream = Stream.make(1, 2, 3, 4).pipe(\n *     Stream.filter((n) => n % 2 === 0)\n *   )\n *   const values = yield* Stream.runCollect(stream)\n *   values // => [ 2, 4 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const filter = /*#__PURE__*/dual(2, (self, predicate) => fromChannel(Channel.filterArray(toChannel(self), predicate)));\n/**\n * Filters and maps stream elements in one pass using a `Filter`.\n *\n * **When to use**\n *\n * Use to keep only stream elements accepted by a `Filter` and emit each filter\n * success value.\n *\n * **Details**\n *\n * `Result.succeed` values are emitted and `Result.fail` values are skipped.\n *\n * @see {@link filter} for keeping original elements with a boolean predicate or refinement\n * @see {@link filterMapEffect} for an effectful `Filter`\n * @see {@link partition} for consuming both filter success and failure values\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const filterMap = /*#__PURE__*/dual(2, (self, filter) => fromChannel(Channel.filterMapArray(toChannel(self), filter)));\n/**\n * Filters elements in a single pass effectfully.\n *\n * **Example** (Effectfully filtering stream values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3, 4).pipe(Stream.filterEffect((n) => Effect.succeed(n > 2)))\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.runCollect(stream)\n *   result // => [ 3, 4 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const filterEffect = /*#__PURE__*/dual(2, (self, predicate) => fromChannel(Channel.filterArrayEffect(toChannel(self), predicate)));\n/**\n * Filters and maps elements in one pass effectfully using a `FilterEffect`.\n *\n * **When to use**\n *\n * Use to apply effectful logic that can reject stream elements or emit\n * transformed values before they continue downstream.\n *\n * **Details**\n *\n * `Result.succeed` values are emitted, `Result.fail` values are skipped, and\n * effect failures fail the stream.\n *\n * @see {@link filterMap} for the synchronous `Filter` variant\n * @see {@link filterEffect} for effectfully keeping original elements\n * @see {@link mapEffect} for effectfully transforming every element\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const filterMapEffect = /*#__PURE__*/dual(2, (self, filter) => fromChannel(Channel.filterMapArrayEffect(toChannel(self), filter)));\n/**\n * Partitions a stream using a `Filter` and exposes passing and failing values\n * as scoped queues.\n *\n * **Details**\n *\n * The queues are backed by a fiber in the current scope and should be consumed\n * while that scope remains open. Each queue fails with the stream error or\n * `Cause.Done` when the source ends.\n *\n * **Example** (Partitioning a stream into queues)\n *\n * ```ts import.meta.vitest\n * import { Effect, Result, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const [passes, fails] = yield* Stream.make(1, 2, 3, 4).pipe(\n *     Stream.partitionQueue((n) => n % 2 === 0 ? Result.succeed(n) : Result.fail(n))\n *   )\n *\n *   const passValues = yield* Stream.fromQueue(passes).pipe(Stream.runCollect)\n *   const failValues = yield* Stream.fromQueue(fails).pipe(Stream.runCollect)\n *\n *   passValues // => [ 2, 4 ]\n *   failValues // => [ 1, 3 ]\n * })\n *\n * await Effect.runPromise(Effect.scoped(program))\n * ```\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const partitionQueue = /*#__PURE__*/dual(args => isStream(args[0]), /*#__PURE__*/Effect.fnUntraced(function* (self, filter, options) {\n  const scope = yield* Effect.scope;\n  const pull = yield* Channel.toPullScoped(self.channel, scope);\n  const capacity = options?.capacity === \"unbounded\" ? undefined : options?.capacity ?? DefaultChunkSize;\n  const passes = yield* Queue.make({\n    capacity\n  });\n  const fails = yield* Queue.make({\n    capacity\n  });\n  yield* Effect.gen(function* () {\n    while (true) {\n      const chunk = yield* pull;\n      const excluded = [];\n      const satisfying = [];\n      for (let i = 0; i < chunk.length; i++) {\n        const result = filter(chunk[i]);\n        if (Result.isFailure(result)) {\n          excluded.push(result.failure);\n        } else {\n          satisfying.push(result.success);\n        }\n      }\n      let passFiber = undefined;\n      if (satisfying.length > 0) {\n        const leftover = Queue.offerAllUnsafe(passes, satisfying);\n        if (leftover.length > 0) {\n          passFiber = yield* Effect.forkChild(Queue.offerAll(passes, leftover));\n        }\n      }\n      if (excluded.length > 0) {\n        const leftover = Queue.offerAllUnsafe(fails, excluded);\n        if (leftover.length > 0) {\n          yield* Queue.offerAll(fails, leftover);\n        }\n      }\n      if (passFiber) yield* Fiber.join(passFiber);\n    }\n  }).pipe(Effect.onError(cause => {\n    Queue.failCauseUnsafe(passes, cause);\n    Queue.failCauseUnsafe(fails, cause);\n    return Effect.void;\n  }), Effect.forkIn(scope));\n  return [passes, fails];\n}));\n/**\n * Splits a stream with an effectful `Filter`, returning scoped streams for\n * filter successes and failures.\n *\n * **When to use**\n *\n * Use when you need to classify each stream element with an effectful `Filter`\n * and consume both passing and failing mapped values as streams.\n *\n * **Details**\n *\n * The returned streams are backed by queues in the current scope and should be\n * consumed while that scope remains open. The first stream emits success values\n * from the filter, and the second emits failure values.\n *\n * @see {@link partition} for the pure `Filter` variant, which returns the failing stream before the passing stream\n * @see {@link partitionQueue} for the lower-level queue result\n * @see {@link filterMapEffect} for effectful filtering that discards failed filter results\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const partitionEffect = /*#__PURE__*/dual(args => isStream(args[0]), (self, filter, options) => Effect.map(partitionQueue(mapEffect(self, a => filter(a), options), result => result, options), ([passes, fails]) => [fromQueue(passes), fromQueue(fails)]));\n/**\n * Splits a stream into scoped excluded and satisfying substreams using a\n * `Filter`.\n *\n * **Details**\n *\n * The returned streams are backed by queues in the current scope and should be\n * consumed while that scope remains open. The faster stream may advance up to\n * `bufferSize` elements ahead of the slower one.\n *\n * **Example** (Partitioning a stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Result, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const [excluded, satisfying] = yield* Stream.partition(\n *     Stream.make(1, 2, 3, 4),\n *     (n) => n % 2 === 0 ? Result.succeed(n) : Result.fail(n)\n *   )\n *   const left = yield* Stream.runCollect(excluded)\n *   const right = yield* Stream.runCollect(satisfying)\n *   left // => [ 1, 3 ]\n *   right // => [ 2, 4 ]\n * })\n * await Effect.runPromise(Effect.scoped(program))\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const partition = /*#__PURE__*/dual(args => isStream(args[0]), (self, filter, options) => Effect.map(partitionQueue(self, filter, {\n  capacity: options?.bufferSize ?? 16\n}), ([passes, fails]) => [fromQueue(fails), fromQueue(passes)]));\n/**\n * Returns the specified stream if the given condition is satisfied, otherwise\n * returns an empty stream.\n *\n * **Example** (Conditionally keeping a stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.runCollect(\n *     Stream.when(Stream.make(1, 2, 3), Effect.succeed(false))\n *   )\n *   result // => []\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const when = /*#__PURE__*/dual(2, (self, test) => test.pipe(Effect.map(pass => pass ? self : empty), unwrap));\n/**\n * Runs a sink to peel off enough elements to produce a value and returns that\n * value with the remaining stream in a scope.\n *\n * **Details**\n *\n * The returned stream is only valid within the scope.\n *\n * **Example** (Peeling a stream with a sink)\n *\n * ```ts import.meta.vitest\n * import { Effect, Sink, Stream } from \"effect\"\n *\n * const stream = Stream.fromArrays([1, 2, 3], [4, 5, 6])\n * const sink = Sink.take<number>(3)\n *\n * const program = Effect.scoped(\n *   Effect.gen(function*() {\n *     const [peeled, rest] = yield* Stream.peel(stream, sink)\n *     const remaining = yield* Stream.runCollect(rest)\n *     const result = [peeled, remaining] // => [[1, 2, 3], [4, 5, 6]]\n *   })\n * )\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const peel = /*#__PURE__*/dual(2, /*#__PURE__*/Effect.fnUntraced(function* (self, sink) {\n  let cause = undefined;\n  const originalPull = yield* Channel.toPull(self.channel);\n  const pull = Effect.catchCause(originalPull, cause_ => {\n    cause = cause_;\n    return Effect.failCause(cause_);\n  });\n  let stream = fromPull(Effect.succeed(pull));\n  const leftover = yield* run(stream, sink);\n  if (cause) return [leftover, empty];\n  stream = fromPull(Effect.succeed(originalPull));\n  return [leftover, stream];\n}));\n/**\n * Buffers up to `capacity` elements so a faster producer can progress\n * independently of a slower consumer.\n *\n * **Details**\n *\n * Finite buffers use the configured queue strategy: `\"suspend\"` applies\n * backpressure, while `\"dropping\"` and `\"sliding\"` may discard elements when\n * the buffer is full. This combinator destroys chunking; use `Stream.rechunk`\n * afterward if you need fixed chunk sizes.\n *\n * **Example** (Buffering stream elements)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.make(1, 2, 3).pipe(\n *     Stream.buffer({ capacity: 1 }),\n *     Stream.runCollect\n *   )\n *   values // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category buffering\n * @since 2.0.0\n */\nexport const buffer = /*#__PURE__*/dual(2, (self, options) => fromChannel(Channel.bufferArray(self.channel, options)));\n/**\n * Allows a faster producer to progress independently of a slower consumer by\n * buffering up to `capacity` chunks in a queue.\n *\n * **Details**\n *\n * Finite buffers use the configured queue strategy: `\"suspend\"` applies\n * backpressure, while `\"dropping\"` and `\"sliding\"` may discard chunks when the\n * buffer is full. This combinator preserves chunking and is best with\n * power-of-2 capacities.\n *\n * **Example** (Buffering stream chunks)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.fromArrays([1, 2], [3, 4]).pipe(\n *     Stream.bufferArray({ capacity: 2 }),\n *     Stream.runCollect\n *   )\n *   result // => [ 1, 2, 3, 4 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category buffering\n * @since 4.0.0\n */\nexport const bufferArray = /*#__PURE__*/dual(2, (self, options) => fromChannel(Channel.buffer(self.channel, options)));\n/**\n * Switches over to the stream produced by the provided function in case this\n * one fails. Allows recovery from all causes of failure, including\n * interruption if the stream is uninterruptible.\n *\n * **Example** (Catching stream causes)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2).pipe(\n *   Stream.concat(Stream.fail(\"Oops!\")),\n *   Stream.concat(Stream.make(3, 4))\n * )\n *\n * const recovered = stream.pipe(\n *   Stream.catchCause(() => Stream.make(999))\n * )\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.runCollect(recovered)\n *   values // => [ 1, 2, 999 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const catchCause = /*#__PURE__*/dual(2, (self, f) => self.channel.pipe(Channel.catchCause(cause => f(cause).channel), fromChannel));\n/**\n * Recovers from defects using the provided function.\n *\n * **Details**\n *\n * Typed failures and interruptions are not caught.\n *\n * **Example** (Recovering from a defect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.die(\"boom\").pipe(\n *   Stream.catchDefect((defect) => Stream.succeed(`recovered: ${defect}`))\n * )\n *\n * const result = Effect.runSync(Stream.runCollect(stream))\n * result // => [\"recovered: boom\"]\n * ```\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchDefect = /*#__PURE__*/dual(2, (self, f) => self.channel.pipe(Channel.catchDefect(defect => f(defect).channel), fromChannel));\n/**\n * Runs an effect when the stream fails without changing its values or error,\n * unless the tap effect itself fails.\n *\n * **Example** (Tapping stream causes)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Stream } from \"effect\"\n *\n * const observations: Array<boolean> = []\n * const stream = Stream.make(1, 2).pipe(\n *   Stream.concat(Stream.fail(\"boom\")),\n *   Stream.tapCause((cause) => Effect.sync(() => observations.push(Cause.isReason(cause)))),\n *   Stream.catch(() => Stream.succeed(0))\n * )\n *\n * const program = Effect.gen(function* () {\n *   const result = yield* Stream.runCollect(stream)\n *   result // => [1, 2, 0]\n * })\n *\n * await Effect.runPromise(program)\n * observations // => [false]\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const tapCause = /*#__PURE__*/dual(2, (self, f) => self.channel.pipe(Channel.tapCause(f), fromChannel));\nconst catch_ = /*#__PURE__*/dual(2, (self, f) => fromChannel(Channel.catch(self.channel, error => f(error).channel)));\nexport {\n/**\n * Switches over to the stream produced by the provided function if this one fails.\n *\n * **Example** (Catching stream failures)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2).pipe(\n *   Stream.concat(Stream.fail(\"Oops!\")),\n *   Stream.catch(() => Stream.make(999))\n * )\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.runCollect(stream)\n *   values // => [ 1, 2, 999 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 4.0.0\n */\ncatch_ as catch };\n/**\n * Peeks at errors effectfully without changing the stream unless the tap fails.\n *\n * **Example** (Effectfully peeking at errors)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const errors: Array<string> = []\n * const stream = Stream.make(1, 2).pipe(\n *   Stream.concat(Stream.fail(\"boom\")),\n *   Stream.tapError((error) => Effect.sync(() => errors.push(error))),\n *   Stream.catch(() => Stream.make(999))\n * )\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.runCollect(stream)\n *   values // => [1, 2, 999]\n * })\n *\n * await Effect.runPromise(program)\n * errors // => [\"boom\"]\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const tapError = /*#__PURE__*/dual(2, (self, f) => self.channel.pipe(Channel.tapError(f), fromChannel));\n/**\n * Recovers from errors that match a predicate by switching to a recovery stream.\n *\n * **Details**\n *\n * When a failure matches the filter, the stream switches to the recovery\n * stream. Non-matching failures propagate downstream, so the error type is\n * preserved unless the filter narrows it.\n *\n * **Example** (Catching matching failures)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2).pipe(\n *   Stream.concat(Stream.fail(42)),\n *   Stream.catchIf(\n *     (error): error is 42 => error === 42,\n *     () => Stream.make(999)\n *   )\n * )\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.runCollect(stream)\n *   values // => [ 1, 2, 999 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchIf = /*#__PURE__*/dual(args => isStream(args[0]), (self, predicate, f, orElse) => fromChannel(Channel.catchIf(toChannel(self), predicate, e => f(e).channel, orElse && (e => orElse(e).channel))));\n/**\n * Recovers from errors that match a `Filter` by switching to a recovery\n * stream.\n *\n * **When to use**\n *\n * Use to recover from stream errors with a reusable `Filter` when matching can\n * also narrow or transform the error before choosing the recovery stream.\n *\n * **Details**\n *\n * Successful filter results are passed to `f`. Failed filter results go to\n * `orElse` when provided; otherwise the filter failure is re-failed.\n *\n * @see {@link catchIf} for predicate or refinement based recovery\n * @see {@link catchTag} for `_tag` based recovery from one tagged error\n * @see {@link catchTags} for `_tag` based recovery from multiple tagged errors\n * @see {@link catchCauseFilter} for filtering full causes\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchFilter = /*#__PURE__*/dual(args => isStream(args[0]), (self, filter, f, orElse) => fromChannel(Channel.catchFilter(toChannel(self), filter, e => f(e).channel, orElse && (e => orElse(e).channel))));\n/**\n * Recovers from failures whose `_tag` matches the provided value by switching to\n * the stream returned by `f`.\n *\n * **When to use**\n *\n * Use when you need to handle a specific error case from a stream whose error\n * type is a tagged union with a readonly `_tag` field.\n *\n * **Example** (Catching tagged failures)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect, Stream } from \"effect\"\n *\n * class HttpError extends Data.TaggedError(\"HttpError\")<{ message: string }> {}\n *\n * const stream = Stream.fail(new HttpError({ message: \"timeout\" }))\n *\n * const recovered = Stream.catchTag(stream, \"HttpError\", (error) =>\n *   Stream.make(`Recovered: ${error.message}`)\n * )\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.runCollect(recovered)\n *   values // => [ 'Recovered: timeout' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const catchTag = /*#__PURE__*/dual(args => isStream(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/**\n * Switches to a recovery stream based on matching `_tag` handlers.\n *\n * **Example** (Catching tagged failures with handlers)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * class NotFound {\n *   readonly _tag = \"NotFound\"\n *   constructor(readonly resource: string) {}\n * }\n *\n * class Unauthorized {\n *   readonly _tag = \"Unauthorized\"\n *   constructor(readonly user: string) {}\n * }\n *\n * const stream = Stream.fail(new NotFound(\"profile\"))\n *\n * const program = Effect.gen(function* () {\n *   const result = yield* stream.pipe(\n *     Stream.catchTags({\n *       NotFound: () => Stream.succeed(\"fallback\"),\n *       Unauthorized: () => Stream.succeed(\"login\")\n *     }),\n *     Stream.runCollect\n *   )\n *   result // => [ 'fallback' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const catchTags = /*#__PURE__*/dual(args => isStream(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 => cases[e[\"_tag\"]](e), orElse);\n});\n/**\n * Catches a specific reason within a tagged error.\n *\n * **When to use**\n *\n * Use to handle nested error causes without removing the parent error\n * from the error channel.\n *\n * **Details**\n *\n * The handler receives the unwrapped reason.\n *\n * **Example** (Catching a tagged error reason)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect, Stream } 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 stream = Stream.fail(\n *   new AiError({ reason: new RateLimitError({ retryAfter: 60 }) })\n * )\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* stream.pipe(\n *     Stream.catchReason(\"AiError\", \"RateLimitError\", (reason) =>\n *       Stream.succeed(`retry: ${reason.retryAfter}`)\n *     ),\n *     Stream.runCollect\n *   )\n *   values // => [ 'retry: 60' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchReason = /*#__PURE__*/dual(args => isStream(args[0]), (self, errorTag, reasonTag, f, orElse) => fromChannel(Channel.catchReason(toChannel(self), errorTag, reasonTag, (reason, error) => f(reason, error).channel, orElse && ((reason, error) => orElse(reason, error).channel))));\n/**\n * Catches multiple reasons within a tagged error using an object of handlers.\n *\n * **Example** (Catching tagged error reasons)\n *\n * ```ts import.meta.vitest\n * import { Data, Effect, Stream } 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 stream = Stream.fail(\n *   new AiError({ reason: new RateLimitError({ retryAfter: 60 }) })\n * )\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* stream.pipe(\n *     Stream.catchReasons(\"AiError\", {\n *       RateLimitError: (reason) => Stream.succeed(`retry: ${reason.retryAfter}`),\n *       QuotaExceededError: (reason) => Stream.succeed(`quota: ${reason.limit}`)\n *     }),\n *     Stream.runCollect\n *   )\n *   values // => [ 'retry: 60' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchReasons = /*#__PURE__*/dual(args => isStream(args[0]), (self, errorTag, cases, orElse) => {\n  const handlers = Object.create(null);\n  for (const key of Object.keys(cases)) {\n    const handler = cases[key];\n    handlers[key] = (reason, error) => handler(reason, error).channel;\n  }\n  const orElseHandler = orElse && ((reason, error) => orElse(reason, error).channel);\n  return fromChannel(Channel.catchReasons(self.channel, errorTag, handlers, orElseHandler));\n});\n/**\n * Transforms the errors emitted by this stream using `f`.\n *\n * **Example** (Mapping stream errors)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.fail(\"bad\").pipe(\n *     Stream.mapError((error) => `mapped: ${error}`),\n *     Stream.catch((error) => Stream.make(`recovered from ${error}`)),\n *     Stream.runCollect\n *   )\n *   result // => [ 'recovered from mapped: bad' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const mapError = /*#__PURE__*/dual(2, (self, f) => fromChannel(Channel.mapError(self.channel, f)));\n/**\n * Recovers from stream failures by filtering the `Cause` and switching to a recovery stream.\n * Non-matching causes are re-emitted as failures.\n *\n * **Example** (Catching matching causes)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const failingStream = Stream.fail(\"NetworkError\")\n *   const recovered = Stream.catchCauseIf(\n *     failingStream,\n *     (cause) => Cause.hasFails(cause),\n *     (cause) => Stream.make(`Recovered: ${Cause.squash(cause)}`)\n *   )\n *\n *   const output = yield* Stream.runCollect(recovered)\n *   output // => [ 'Recovered: NetworkError' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const catchCauseIf = /*#__PURE__*/dual(3, (self, predicate, f) => fromChannel(Channel.catchCauseIf(self.channel, predicate, cause => f(cause).channel)));\n/**\n * Recovers from stream failures by filtering the `Cause` and switching to a\n * recovery stream.\n *\n * **When to use**\n *\n * Use when you need to recover a stream 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`. A successful filter result is\n * passed to `f` together with the original cause; a failed filter result\n * re-fails with the residual cause.\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 = /*#__PURE__*/dual(3, (self, filter, f) => fromChannel(Channel.catchCauseFilter(self.channel, filter, (failure, cause) => f(failure, cause).channel)));\n/**\n * Switches to a fallback stream if this stream is empty.\n *\n * **Example** (Switching on empty streams)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.empty.pipe(\n *     Stream.orElseIfEmpty(() => Stream.make(1, 2)),\n *     Stream.runCollect\n *   )\n *   values // => [ 1, 2 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const orElseIfEmpty = /*#__PURE__*/dual(2, (self, orElse) => fromChannel(Channel.orElseIfEmpty(self.channel, _ => toChannel(orElse()))));\n/**\n * Returns a stream that emits a fallback value when this stream fails.\n *\n * **Example** (Recovering with a fallback value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const stream = Stream.fail(\"NetworkError\").pipe(\n *     Stream.orElseSucceed((error) => `Recovered: ${error}`)\n *   )\n *\n *   const values = yield* Stream.runCollect(stream)\n *   values // => [ 'Recovered: NetworkError' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const orElseSucceed = /*#__PURE__*/dual(2, (self, f) => catch_(self, e => succeed(f(e))));\n/**\n * Turns typed failures into defects, making the stream infallible.\n *\n * **Example** (Turning failures into defects)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.make(1, 2, 3).pipe(\n *     Stream.orDie,\n *     Stream.runCollect\n *   )\n *\n *   values // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const orDie = self => fromChannel(Channel.orDie(self.channel));\n/**\n * Ignores failures and ends the stream on error.\n *\n * **When to use**\n *\n * Use when you want a failing stream to end gracefully rather than propagate\n * the error.\n *\n * **Details**\n *\n * The `log` option controls whether the failure is logged before the stream\n * terminates.\n *\n * **Example** (Ignoring stream failures)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.make(1, 2, 3).pipe(\n *     Stream.concat(Stream.fail(\"boom\")),\n *     Stream.ignore,\n *     Stream.runCollect\n *   )\n *   values // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * **Example** (Configuring ignore logging)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * await Effect.runPromise(Effect.gen(function*() {\n *   const values = yield* Stream.fail(\"boom\").pipe(\n *     Stream.ignore({ log: false }),\n *     Stream.runCollect\n *   )\n *   values // => []\n * }))\n *\n * ```\n *\n * @see {@link ignoreCause} for a variant that also ignores defects, not just typed failures\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const ignore = /*#__PURE__*/dual(args => isStream(args[0]), (self, options) => fromChannel(Channel.ignore(self.channel, options)));\n/**\n * Ignores the stream's failure cause, including defects, and ends the stream.\n *\n * **When to use**\n *\n * Use when you need to silently suppress a stream's entire failure cause,\n * including both typed errors and defects, rather than propagate it downstream.\n *\n * **Example** (Ignoring stream failure causes)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * await Effect.runPromise(Effect.gen(function*() {\n *   const values = yield* Stream.make(1, 2).pipe(\n *     Stream.concat(Stream.die(\"boom\")),\n *     Stream.ignoreCause({ log: false }),\n *     Stream.runCollect\n *   )\n *   values // => [1, 2]\n * }))\n *\n * ```\n *\n * @see {@link ignore} to ignore only typed failures without suppressing defects\n *\n * @category error handling\n * @since 4.0.0\n */\nexport const ignoreCause = /*#__PURE__*/dual(args => isStream(args[0]), (self, options) => fromChannel(Channel.ignoreCause(self.channel, options)));\n/**\n * Retries the stream according to the given schedule when it fails.\n *\n * **Details**\n *\n * This retries the entire stream, so will re-execute all of the stream's\n * acquire operations.\n *\n * The schedule is reset as soon as the first element passes through the\n * stream again.\n *\n * **Example** (Retrying stream failures)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schedule, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.make(1).pipe(\n *     Stream.concat(Stream.fail(\"boom\")),\n *     Stream.retry(Schedule.recurs(1)),\n *     Stream.take(2),\n *     Stream.runCollect\n *   )\n *\n *   values // => [ 1, 1 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const retry = /*#__PURE__*/dual(2, (self, policy) => fromChannel(Channel.retry(self.channel, policy)));\nconst retryWithoutReset = (self, schedule) => unwrap(Effect.map(Schedule.toStepWithMetadata(schedule), step => {\n  let meta = Schedule.CurrentMetadata.defaultValue();\n  const loop = () => catch_(provideServiceEffect(self, Schedule.CurrentMetadata, Effect.sync(() => meta)), error => unwrap(Pull.catchDone(Effect.map(step(error), meta_ => {\n    meta = meta_;\n    return unwrap(Effect.as(Effect.yieldNow, loop()));\n  }), () => Effect.succeed(fail(error)))));\n  return loop();\n}));\n/**\n * Applies an `ExecutionPlan` to a stream, retrying with step-provided resources\n * until it succeeds or the plan is exhausted.\n *\n * **Details**\n *\n * By default, a failing step can fallback even after emitting elements; set\n * `preventFallbackOnPartialStream` to fail instead of mixing partial output with\n * a later fallback.\n *\n * Attempts can be observed from outside the stream by passing\n * `options.onEvent`, which receives an `ExecutionPlan.Event` before each\n * attempt and after it settles; see `Effect.withExecutionPlan` for the handler\n * semantics. When a downstream consumer stops pulling early (for example\n * `Stream.take` outside the plan), the truncated attempt reports\n * `AttemptSuccess`: the consumer stopped, not the source.\n *\n * **Example** (Applying an execution plan)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, ExecutionPlan, Layer, Stream } from \"effect\"\n *\n * class Service extends Context.Service<Service>()(\"Service\", {\n *   make: Effect.succeed({\n *     stream: Stream.fail(\"A\") as Stream.Stream<number, string>\n *   })\n * }) {\n *   static Bad = Layer.succeed(Service, Service.of({ stream: Stream.fail(\"A\") }))\n *   static Good = Layer.succeed(Service, Service.of({ stream: Stream.make(1, 2, 3) }))\n * }\n *\n * const plan = ExecutionPlan.make(\n *   { provide: Service.Bad },\n *   { provide: Service.Good }\n * )\n *\n * const stream = Stream.unwrap(Effect.map(Service, (_) => _.stream))\n *\n * const program = Effect.gen(function*() {\n *   const items = yield* stream.pipe(Stream.withExecutionPlan(plan), Stream.runCollect)\n *   items // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category error handling\n * @since 3.16.0\n */\nexport const withExecutionPlan = /*#__PURE__*/dual(args => isStream(args[0]), (self, policy, options) => suspend(() => {\n  const preventFallbackOnPartialStream = options?.preventFallbackOnPartialStream ?? false;\n  let i = 0;\n  let meta = {\n    attempt: 0,\n    stepIndex: 0\n  };\n  const provideMeta = provideServiceEffect(ExecutionPlan.CurrentMetadata, Effect.sync(() => {\n    meta = {\n      attempt: meta.attempt + 1,\n      stepIndex: i\n    };\n    return meta;\n  }));\n  const emitter = options?.onEvent === undefined ? undefined : internalExecutionPlan.makeEventEmitter(options.onEvent, () => meta);\n  let attemptState;\n  const instrument = emitter === undefined ? identity : attempt => onExit(onStart(attempt, Effect.map(emitter.begin, state => {\n    attemptState = state;\n  })), exit => Effect.suspend(() => {\n    if (attemptState === undefined) return Effect.void;\n    const state = attemptState;\n    attemptState = undefined;\n    return emitter.end(state, exit);\n  }));\n  let lastError = Option.none();\n  const loop = suspend(() => {\n    const step = policy.steps[i];\n    if (!step) {\n      return fail(Option.getOrThrow(lastError));\n    }\n    let nextStream = provideMeta(instrument(provide(self, step.provide)));\n    let receivedElements = false;\n    if (Option.isSome(lastError)) {\n      const error = lastError.value;\n      let attempted = false;\n      const wrapped = nextStream;\n      // ensure the schedule is applied at least once\n      nextStream = suspend(() => {\n        if (attempted) return wrapped;\n        attempted = true;\n        return fail(error);\n      });\n      nextStream = retryWithoutReset(nextStream, internalExecutionPlan.scheduleFromStep(step, false));\n    } else {\n      const schedule = internalExecutionPlan.scheduleFromStep(step, true);\n      nextStream = schedule ? retryWithoutReset(nextStream, schedule) : nextStream;\n    }\n    return catch_(preventFallbackOnPartialStream ? onFirst(nextStream, _ => {\n      receivedElements = true;\n      return Effect.void;\n    }) : nextStream, error => {\n      i++;\n      if (preventFallbackOnPartialStream && receivedElements) {\n        return fail(error);\n      }\n      lastError = Option.some(error);\n      return loop;\n    });\n  });\n  return loop;\n}));\n/**\n * Takes the first `n` elements from this stream.\n *\n * **Details**\n *\n * Finite fractional values of `n` are rounded down. `NaN` and non-positive\n * values return `Stream.empty` without evaluating the source stream.\n *\n * **Example** (Taking values from the left)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.make(1, 2, 3, 4, 5).pipe(\n *     Stream.take(3),\n *     Stream.runCollect\n *   )\n *   values // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const take = /*#__PURE__*/dual(2, (self, n) => {\n  const count = Count.normalize(n);\n  return count === 0 ? empty : takeUntil(self, (_, i) => i === count - 1);\n});\n/**\n * Emits byte chunks until the configured limit would be exceeded, then drops\n * the crossing chunk and switches to a fallback stream.\n *\n * **Example** (Truncating at a byte limit)\n *\n * ```ts import.meta.vitest\n * import { ByteSize, Effect, Stream } from \"effect\"\n *\n * const program = Stream.make(\n *   new Uint8Array([1, 2]),\n *   new Uint8Array([3, 4, 5])\n * ).pipe(\n *   Stream.limitBytes(ByteSize.bytes(4), () => Stream.empty),\n *   Stream.runCollect,\n *   Effect.map((chunks) => chunks.map((chunk) => [...chunk]))\n * )\n *\n * await Effect.runPromise(program) // => [[1, 2]]\n * ```\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const limitBytes = /*#__PURE__*/dual(3, (self, bytes, onLimitReached) => suspend(() => {\n  const limit = ByteSize.fromInputUnsafe(bytes);\n  let size = BigInt(0);\n  let limitReached = false;\n  return concat(takeWhile(self, chunk => {\n    const nextSize = size + BigInt(chunk.length);\n    if (nextSize > limit) {\n      limitReached = true;\n      return false;\n    }\n    size = nextSize;\n    return true;\n  }), suspend(() => limitReached ? onLimitReached() : empty));\n}));\n/**\n * Keeps the last `n` elements from this stream.\n *\n * **Details**\n *\n * Finite fractional values of `n` are rounded down. `NaN` and non-positive\n * values return `Stream.empty` without evaluating the source stream.\n *\n * **Example** (Taking elements from the right)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.range(1, 6).pipe(\n *     Stream.takeRight(3),\n *     Stream.runCollect\n *   )\n *   values // => [ 4, 5, 6 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const takeRight = /*#__PURE__*/dual(2, (self, n) => {\n  const count = Count.normalize(n);\n  if (count === 0) return empty;\n  return mapAccumArray(self, MutableList.make, (list, arr) => {\n    MutableList.appendAll(list, arr);\n    if (list.length > count) {\n      MutableList.takeNVoid(list, list.length - count);\n    }\n    return [list, emptyArr];\n  }, {\n    onHalt(list) {\n      return MutableList.takeAll(list);\n    }\n  });\n});\n/**\n * Takes elements until the predicate matches.\n *\n * **Details**\n *\n * When `excludeLast` is `true`, the matching element is dropped.\n *\n * **Example** (Taking until a predicate matches)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.range(1, 5)\n *\n * const program = Effect.gen(function*() {\n *   const inclusive = yield* stream.pipe(\n *     Stream.takeUntil((n) => n % 3 === 0),\n *     Stream.runCollect\n *   )\n *   inclusive // => [ 1, 2, 3 ]\n *\n *   const exclusive = yield* stream.pipe(\n *     Stream.takeUntil((n) => n % 3 === 0, { excludeLast: true }),\n *     Stream.runCollect\n *   )\n *   exclusive // => [ 1, 2 ]\n * })\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const takeUntil = /*#__PURE__*/dual(args => isStream(args[0]), (self, predicate, options) => transformPull(self, (pull, _scope) => Effect.sync(() => {\n  let i = 0;\n  let done = false;\n  const pump = Effect.flatMap(Effect.suspend(() => done ? Cause.done() : pull), chunk => {\n    const index = chunk.findIndex(a => predicate(a, i++));\n    if (index >= 0) {\n      done = true;\n      const arr = chunk.slice(0, options?.excludeLast ? index : index + 1);\n      return Arr.isReadonlyArrayNonEmpty(arr) ? Effect.succeed(arr) : Cause.done();\n    }\n    return Effect.succeed(chunk);\n  });\n  return pump;\n})));\n/**\n * Takes stream elements until an effectful predicate returns `true`.\n *\n * **When to use**\n *\n * Use when the stopping condition needs an Effect or service and predicate\n * failure should fail the stream.\n *\n * **Example** (Taking until an effectful predicate matches)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.range(1, 5).pipe(\n *     Stream.takeUntilEffect((n) => Effect.succeed(n % 3 === 0)),\n *     Stream.runCollect\n *   )\n *   result // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const takeUntilEffect = /*#__PURE__*/dual(args => isStream(args[0]), (self, predicate, options) => transformPull(self, (pull, _scope) => Effect.sync(() => {\n  let i = 0;\n  let done = false;\n  return Effect.gen(function* () {\n    if (done) return yield* Cause.done();\n    const chunk = yield* pull;\n    for (let j = 0; j < chunk.length; j++) {\n      if (yield* predicate(chunk[j], i++)) {\n        done = true;\n        const arr = chunk.slice(0, options?.excludeLast ? j : j + 1);\n        return Arr.isReadonlyArrayNonEmpty(arr) ? arr : yield* Cause.done();\n      }\n    }\n    return chunk;\n  });\n})));\n/**\n * Takes the longest initial prefix of elements that satisfy the predicate.\n *\n * **Example** (Taking while a predicate holds)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.range(1, 5).pipe(\n *   Stream.takeWhile((n) => n % 3 !== 0)\n * )\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.runCollect(stream)\n *   result // => [ 1, 2 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const takeWhile = /*#__PURE__*/dual(2, (self, predicate) => transformPull(self, (pull, _scope) => Effect.sync(() => {\n  let i = 0;\n  let done = false;\n  const pump = Effect.flatMap(Effect.suspend(() => done ? Cause.done() : pull), chunk => {\n    const out = [];\n    for (let j = 0; j < chunk.length; j++) {\n      if (!predicate(chunk[j], i++)) {\n        done = true;\n        break;\n      }\n      out.push(chunk[j]);\n    }\n    return Arr.isReadonlyArrayNonEmpty(out) ? Effect.succeed(out) : done ? Cause.done() : pump;\n  });\n  return pump;\n})));\n/**\n * Takes the longest initial prefix accepted by a `Filter` and emits the\n * filter's success values.\n *\n * **When to use**\n *\n * Use to keep the leading stream elements that a `Filter` accepts, emit the\n * filter's success values, and stop at the first filter failure.\n *\n * **Details**\n *\n * The stream stops at the first `Result.fail` returned by the filter.\n *\n * @see {@link takeWhile} for keeping original elements with a boolean predicate or refinement\n * @see {@link filterMap} for filtering across the whole stream instead of only the leading prefix\n * @see {@link dropWhileFilter} for dropping the accepted prefix and keeping the remaining original elements\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const takeWhileFilter = /*#__PURE__*/dual(2, (self, filter) => transformPull(self, (pull, _scope) => Effect.sync(() => {\n  let done = false;\n  const pump = Effect.flatMap(Effect.suspend(() => done ? Cause.done() : pull), chunk => {\n    const out = [];\n    for (let j = 0; j < chunk.length; j++) {\n      const result = filter(chunk[j]);\n      if (Result.isFailure(result)) {\n        done = true;\n        break;\n      }\n      out.push(result.success);\n    }\n    return Arr.isReadonlyArrayNonEmpty(out) ? Effect.succeed(out) : done ? Cause.done() : pump;\n  });\n  return pump;\n})));\n/**\n * Takes elements from the stream while the effectful predicate is `true`.\n *\n * **When to use**\n *\n * Use when the leading-prefix predicate needs an Effect or service and the\n * stream should stop before the first false result.\n *\n * **Example** (Effectfully taking while a predicate holds)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.range(1, 5).pipe(\n *     Stream.takeWhileEffect((n) => Effect.succeed(n % 3 !== 0)),\n *     Stream.runCollect\n *   )\n *   result // => [ 1, 2 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const takeWhileEffect = /*#__PURE__*/dual(2, (self, predicate) => takeUntilEffect(self, (a, n) => Effect.map(predicate(a, n), b => !b), {\n  excludeLast: true\n}));\n/**\n * Drops the first `n` elements from this stream.\n *\n * **Details**\n *\n * Finite fractional values of `n` are rounded down. `NaN` and non-positive\n * values return the source stream unchanged.\n *\n * **Example** (Dropping values from the left)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3, 4, 5)\n * const result = Stream.drop(stream, 2)\n *\n * const program = Effect.gen(function*() {\n *   const items = yield* Stream.runCollect(result)\n *   items // => [ 3, 4, 5 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const drop = /*#__PURE__*/dual(2, (self, n) => {\n  const count = Count.normalize(n);\n  if (count === 0) return self;\n  return transformPull(self, (pull, _scope) => Effect.sync(() => {\n    let dropped = 0;\n    const pump = pull.pipe(Effect.flatMap(chunk => {\n      if (dropped >= count) return Effect.succeed(chunk);\n      dropped += chunk.length;\n      if (dropped <= count) return pump;\n      return Effect.succeed(chunk.slice(count - dropped));\n    }));\n    return pump;\n  }));\n});\n/**\n * Drops elements until the specified predicate evaluates to `true`, then drops\n * that matching element.\n *\n * **Example** (Dropping until a predicate matches)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3, 4, 5)\n * const result = Stream.dropUntil(stream, (n) => n >= 3)\n *\n * await Effect.runPromise(Effect.gen(function*() {\n *   const output = yield* Stream.runCollect(result)\n *   output // => [ 4, 5 ]\n * }))\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const dropUntil = /*#__PURE__*/dual(2, (self, predicate) => drop(dropWhile(self, (a, i) => !predicate(a, i)), 1));\n/**\n * Drops all elements of the stream until the specified effectful predicate\n * evaluates to `true`.\n *\n * **When to use**\n *\n * Use when dropping the leading prefix requires an Effect or service and the\n * first matching element should also be dropped.\n *\n * **Example** (Dropping until an effectful predicate matches)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.range(1, 5).pipe(\n *     Stream.dropUntilEffect((n) => Effect.succeed(n % 3 === 0)),\n *     Stream.runCollect\n *   )\n *   result // => [ 4, 5 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const dropUntilEffect = /*#__PURE__*/dual(2, (self, predicate) => drop(dropWhileEffect(self, (a, i) => Effect.map(predicate(a, i), b => !b)), 1));\n/**\n * Drops elements from the stream while the specified predicate evaluates to `true`.\n *\n * **Example** (Dropping while a predicate holds)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.make(1, 2, 3, 4, 5).pipe(\n *     Stream.dropWhile((n) => n < 3),\n *     Stream.runCollect\n *   )\n *   values // => [ 3, 4, 5 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const dropWhile = /*#__PURE__*/dual(2, (self, predicate) => transformPull(self, (pull, _scope) => Effect.sync(() => {\n  let dropping = true;\n  let index = 0;\n  const filtered = Effect.flatMap(pull, arr => {\n    const found = arr.findIndex(a => !predicate(a, index++));\n    if (found === -1) return filtered;\n    dropping = false;\n    return Effect.succeed(arr.slice(found));\n  });\n  return Effect.suspend(() => dropping ? filtered : pull);\n})));\n/**\n * Drops elements while the filter succeeds.\n *\n * **When to use**\n *\n * Use when you need to remove a leading stream prefix based on a synchronous\n * `Filter` result while preserving the remaining original stream elements.\n *\n * **Details**\n *\n * `Result.succeed` drops the current element. The first `Result.fail` stops\n * dropping, emits that original element, and the rest of the source stream is\n * emitted without further filtering.\n *\n * @see {@link dropWhile} for boolean predicate prefix dropping\n * @see {@link takeWhileFilter} for keeping the accepted prefix as filter success values\n * @see {@link dropWhileEffect} for effectful predicate prefix dropping\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const dropWhileFilter = /*#__PURE__*/dual(2, (self, filter) => transformPull(self, (pull, _scope) => Effect.sync(() => {\n  let dropping = true;\n  const filtered = Effect.flatMap(pull, arr => {\n    const found = arr.findIndex(a => Result.isFailure(filter(a)));\n    if (found === -1) return filtered;\n    dropping = false;\n    return Effect.succeed(arr.slice(found));\n  });\n  return Effect.suspend(() => dropping ? filtered : pull);\n})));\n/**\n * Drops elements while the specified effectful predicate evaluates to `true`.\n *\n * **Example** (Effectfully dropping while a predicate holds)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.make(1, 2, 3, 4, 5).pipe(\n *     Stream.dropWhileEffect((n) => Effect.succeed(n < 3)),\n *     Stream.runCollect\n *   )\n *   result // => [ 3, 4, 5 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const dropWhileEffect = /*#__PURE__*/dual(2, (self, predicate) => transformPull(self, (pull, _scope) => Effect.sync(() => {\n  let dropping = true;\n  let index = 0;\n  const filtered = Effect.gen(function* () {\n    while (true) {\n      const arr = yield* pull;\n      for (let i = 0; i < arr.length; i++) {\n        const drop = yield* predicate(arr[i], index++);\n        if (drop) continue;\n        dropping = false;\n        return arr.slice(i);\n      }\n    }\n  });\n  return Effect.suspend(() => dropping ? filtered : pull);\n})));\n/**\n * Drops the last specified number of elements from this stream.\n *\n * **Details**\n *\n * Keeps the last `n` elements in memory to drop them on completion. Finite\n * fractional values of `n` are rounded down. `NaN` and non-positive values\n * return the source stream unchanged.\n *\n * **Example** (Dropping values from the right)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.make(1, 2, 3, 4, 5).pipe(\n *     Stream.dropRight(2),\n *     Stream.runCollect\n *   )\n *   result // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const dropRight = /*#__PURE__*/dual(2, (self, n) => {\n  const count = Count.normalize(n);\n  if (count === 0) return self;\n  return transformPull(self, (pull, _scope) => Effect.sync(() => {\n    const list = MutableList.make();\n    const emit = Effect.flatMap(pull, arr => {\n      MutableList.appendAllUnsafe(list, arr);\n      const toTake = list.length - count;\n      const items = MutableList.takeN(list, toTake);\n      return Arr.isArrayNonEmpty(items) ? Effect.succeed(items) : emit;\n    });\n    return emit;\n  }));\n});\n/**\n * Exposes the underlying chunks as a stream of non-empty arrays.\n *\n * **Example** (Exposing stream chunks)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const chunks = yield* Stream.make(1, 2, 3, 4).pipe(\n *     Stream.rechunk(2),\n *     Stream.chunks,\n *     Stream.runCollect\n *   )\n *   chunks // => [ [ 1, 2 ], [ 3, 4 ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const chunks = self => self.channel.pipe(Channel.map(Arr.of), fromChannel);\n/**\n * Groups the stream into arrays of the specified size, preserving element order.\n *\n * **Details**\n *\n * Finite fractional sizes are rounded down. `NaN` and non-positive sizes are\n * treated as `1`.\n *\n * **Example** (Rechunking stream elements)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.make(1, 2, 3, 4, 5).pipe(\n *     Stream.rechunk(2),\n *     Stream.chunks,\n *     Stream.runCollect\n *   )\n *   result // => [ [ 1, 2 ], [ 3, 4 ], [ 5 ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const rechunk = /*#__PURE__*/dual(2, (self, target) => {\n  target = Count.normalizeNonEmpty(target);\n  return transformPull(self, (pull, _scope) => Effect.sync(() => {\n    let chunk = Arr.empty();\n    let index = 0;\n    let current;\n    let done = false;\n    return Effect.suspend(function loop() {\n      if (done) return Cause.done();else if (current === undefined) {\n        return Effect.flatMap(pull, arr => {\n          if (chunk.length === 0 && arr.length === target) {\n            return Effect.succeed(arr);\n          } else if (chunk.length + arr.length < target) {\n            for (let i = 0; i < arr.length; i++) {\n              chunk.push(arr[i]);\n            }\n            return loop();\n          }\n          current = arr;\n          return loop();\n        });\n      }\n      for (; index < current.length;) {\n        chunk.push(current[index++]);\n        if (chunk.length === target) {\n          const result = chunk;\n          chunk = [];\n          return Effect.succeed(result);\n        }\n      }\n      index = 0;\n      current = undefined;\n      return loop();\n    }).pipe(Pull.catchDone(() => {\n      if (chunk.length === 0) return Cause.done();\n      const result = chunk;\n      done = true;\n      chunk = [];\n      return Effect.succeed(result);\n    }));\n  }));\n});\n/**\n * Emits a sliding window of `n` elements.\n *\n * **Details**\n *\n * Finite fractional window sizes are rounded down. `NaN` and non-positive\n * sizes are treated as `1`.\n *\n * **Example** (Emitting sliding windows)\n *\n * ```ts import.meta.vitest\n * import { Effect, pipe, Stream } from \"effect\"\n *\n * await Effect.runPromise(Effect.gen(function*() {\n *   const result = yield* pipe(\n *     Stream.make(1, 2, 3, 4, 5),\n *     Stream.sliding(2),\n *     Stream.runCollect\n *   )\n *   result // => [ [ 1, 2 ], [ 2, 3 ], [ 3, 4 ], [ 4, 5 ] ]\n * }))\n * ```\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const sliding = /*#__PURE__*/dual(2, (self, chunkSize) => slidingSize(self, chunkSize, 1));\n/**\n * Emits sliding windows of `chunkSize` elements, advancing by `stepSize`.\n *\n * **Details**\n *\n * Finite fractional window and step sizes are rounded down. `NaN` and\n * non-positive sizes are treated as `1`.\n *\n * **Example** (Emitting sliding windows with a step size)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const chunks = yield* Stream.make(1, 2, 3, 4, 5).pipe(\n *     Stream.slidingSize(3, 2),\n *     Stream.runCollect\n *   )\n *   chunks // => [ [ 1, 2, 3 ], [ 3, 4, 5 ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const slidingSize = /*#__PURE__*/dual(3, (self, chunkSize, stepSize) => {\n  const windowSize = Count.normalizeNonEmpty(chunkSize);\n  const step = Count.normalizeNonEmpty(stepSize);\n  return transformPull(self, (upstream, _scope) => Effect.sync(() => {\n    let cause = null;\n    const list = MutableList.make();\n    let emitted = false;\n    let skip = 0;\n    const pull = Effect.matchCauseEffect(upstream, {\n      onSuccess(arr) {\n        MutableList.appendAllUnsafe(list, arr);\n        if (skip > 0) {\n          const length = list.length;\n          MutableList.takeNVoid(list, skip);\n          skip = Math.max(0, skip - length);\n        }\n        if (list.length < windowSize) return pull;\n        emitted = true;\n        const chunks = [];\n        while (list.length >= windowSize) {\n          if (windowSize === step) {\n            chunks.push(MutableList.takeN(list, windowSize));\n          } else {\n            chunks.push(MutableList.toArrayN(list, windowSize));\n            const length = list.length;\n            MutableList.takeNVoid(list, step);\n            skip = Math.max(0, step - length);\n          }\n        }\n        return Effect.succeed(chunks);\n      },\n      onFailure(cause_) {\n        if (emitted) MutableList.takeNVoid(list, windowSize - step);\n        if (list.length === 0) return Effect.failCause(cause_);\n        cause = cause_;\n        return Effect.succeed(Arr.of(MutableList.takeAll(list)));\n      }\n    });\n    return Effect.suspend(() => cause ? Effect.failCause(cause) : pull);\n  }));\n});\n/**\n * Splits the stream into non-empty groups whenever the predicate matches.\n *\n * **Details**\n *\n * Matching elements act as delimiters and are not included in the output.\n *\n * **Example** (Splitting on matching values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.range(0, 9).pipe(\n *     Stream.split((n) => n % 4 === 0),\n *     Stream.runCollect\n *   )\n *   result // => [ [ 1, 2, 3 ], [ 5, 6, 7 ], [ 9 ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const split = /*#__PURE__*/dual(2, (self, predicate) => mapAccumArray(self, Arr.empty, (acc, arr) => {\n  const out = Arr.empty();\n  for (let i = 0; i < arr.length; i++) {\n    if (predicate(arr[i])) {\n      if (Arr.isArrayNonEmpty(acc)) {\n        out.push(acc);\n        acc = [];\n      }\n    } else {\n      acc.push(arr[i]);\n    }\n  }\n  return [acc, out];\n}, {\n  onHalt(arr) {\n    return Arr.isArrayNonEmpty(arr) ? Arr.of(arr) : emptyArr;\n  }\n}));\n/**\n * Combines elements from this stream and the specified stream by repeatedly\n * applying a stateful function that can pull from either side.\n *\n * **Details**\n *\n * Where possible, prefer `Stream.combineArray` for a more efficient\n * implementation.\n *\n * **Example** (Combining streams with state)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.combine(\n *   Stream.make(\"A\", \"B\", \"C\"),\n *   Stream.make(1, 2, 3),\n *   () => true,\n *   (takeLeft, pullLeft, pullRight) =>\n *     takeLeft\n *       ? Effect.map(pullLeft, (value) => [`L:${value}`, false] as const)\n *       : Effect.map(pullRight, (value) => [`R:${value}`, true] as const)\n * )\n *\n * const program = Effect.gen(function*() {\n *   const output = yield* Stream.runCollect(stream)\n *   output // => [ 'L:A', 'R:1', 'L:B', 'R:2', 'L:C', 'R:3' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category merging\n * @since 2.0.0\n */\nexport const combine = /*#__PURE__*/dual(4, (self, that, s, f) => Channel.combine(Channel.flattenArray(self.channel), Channel.flattenArray(that.channel), s, f).pipe(Channel.map(Arr.of), fromChannel));\n/**\n * Combines two streams chunk-by-chunk with a stateful pull function.\n *\n * **When to use**\n *\n * Use to coordinate pulling chunks from two streams when each emitted chunk\n * depends on both sides and local state.\n *\n * **Details**\n *\n * The combining function receives the current state and pull functions for the\n * left and right streams. It returns the next non-empty chunk together with the\n * next state.\n *\n * **Example** (Combining stream chunks with state)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2).pipe(\n *   Stream.combineArray(\n *     Stream.make(10, 20),\n *     () => true,\n *     (useLeft, pullLeft, pullRight) =>\n *       Effect.gen(function*() {\n *         const array = useLeft ? yield* pullLeft : yield* pullRight\n *         return [array, !useLeft] as const\n *       })\n *   )\n * )\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.runCollect(stream)\n *   values // => [ 1, 2, 10, 20 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const combineArray = /*#__PURE__*/dual(4, (self, that, s, f) => fromChannel(Channel.combine(self.channel, that.channel, s, f)));\n/**\n * Maps elements statefully, emitting zero or more outputs per input.\n *\n * **Example** (Statefully mapping stream values)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const totals = yield* Stream.make(0, 1, 2, 3, 4, 5, 6).pipe(\n *     Stream.mapAccum(() => 0, (total, n) => {\n *       const next = total + n\n *       return [next, [next]] as const\n *     }),\n *     Stream.runCollect\n *   )\n *\n *   totals // => [0, 1, 3, 6, 10, 15, 21]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const mapAccum = /*#__PURE__*/dual(args => isStream(args[0]), (self, initial, f, options) => fromChannel(Channel.mapAccum(self.channel, initial, (state, arr) => {\n  const acc = Arr.empty();\n  for (let index = 0; index < arr.length; index++) {\n    const [newState, values] = f(state, arr[index]);\n    state = newState;\n    acc.push(...values);\n  }\n  return [state, Arr.isArrayNonEmpty(acc) ? Arr.of(acc) : emptyArr];\n}, options?.onHalt ? {\n  onHalt(state) {\n    const arr = options.onHalt(state);\n    return Arr.isReadonlyArrayNonEmpty(arr) ? Arr.of(arr) : emptyArr;\n  }\n} : undefined)));\n/**\n * Maps over non-empty chunk arrays statefully, emitting zero or more values per chunk.\n *\n * **Details**\n *\n * The mapping function runs once per chunk and the state is threaded across chunks.\n *\n * **Example** (Statefully mapping stream chunks)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const output = yield* Stream.make(1, 2, 3, 4, 5, 6).pipe(\n *     Stream.rechunk(2),\n *     Stream.mapAccumArray(() => 0, (sum: number, chunk) => {\n *       const next = chunk.reduce((acc, n) => acc + n, sum)\n *       return [next, [next]]\n *     }),\n *     Stream.runCollect\n *   )\n *   output // => [ 3, 10, 21 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category mapping\n * @since 4.0.0\n */\nexport const mapAccumArray = /*#__PURE__*/dual(args => isStream(args[0]), (self, initial, f, options) => fromChannel(Channel.mapAccum(self.channel, initial, (state, arr) => {\n  const [newState, values] = f(state, arr);\n  state = newState;\n  return [state, Arr.isReadonlyArrayNonEmpty(values) ? Arr.of(values) : emptyArr];\n}, options?.onHalt ? {\n  onHalt(state) {\n    const arr = options.onHalt(state);\n    return Arr.isReadonlyArrayNonEmpty(arr) ? Arr.of(arr) : emptyArr;\n  }\n} : undefined)));\nconst emptyArr = /*#__PURE__*/Arr.empty();\n/**\n * Maps each element statefully and effectfully, emitting zero or more output\n * values per input.\n *\n * **When to use**\n *\n * Use when stateful element mapping needs Effects or can fail while emitting\n * zero or more values per input element.\n *\n * **Details**\n *\n * The mapping effect receives the current state and element, then returns the\n * next state plus the values to emit. The state is threaded through the\n * stream.\n *\n * **Example** (Effectfully mapping stream values with state)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.make(1, 1, 1).pipe(\n *     Stream.mapAccumEffect(() => 0, (total, n) =>\n *       Effect.succeed([total + n, [total + n]])\n *     ),\n *     Stream.runCollect\n *   )\n *\n *   result // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const mapAccumEffect = /*#__PURE__*/dual(args => isStream(args[0]), (self, initial, f, options) => self.channel.pipe(Channel.flattenArray, Channel.mapAccum(initial, (state, a) => Effect.map(f(state, a), ([state, values]) => [state, Arr.isReadonlyArrayNonEmpty(values) ? Arr.of(values) : Arr.empty()]), options?.onHalt ? {\n  onHalt(state) {\n    const arr = options.onHalt(state);\n    return Arr.isReadonlyArrayNonEmpty(arr) ? Arr.of(arr) : emptyArr;\n  }\n} : undefined), fromChannel));\n/**\n * Maps each non-empty input chunk statefully and effectfully, emitting zero or\n * more output values per chunk.\n *\n * **When to use**\n *\n * Use when stateful mapping should process each emitted non-empty chunk with an\n * Effect instead of each element separately.\n *\n * **Details**\n *\n * The mapping effect receives the current state and chunk, then returns the\n * next state plus the values to emit. The state is threaded across chunks.\n *\n * **Example** (Effectfully mapping stream chunks with state)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const totals = yield* Stream.make(1, 2, 3, 4).pipe(\n *     Stream.rechunk(2),\n *     Stream.mapAccumArrayEffect(() => 0, (total, chunk) =>\n *       Effect.gen(function*() {\n *         const next = chunk.reduce((sum, value) => sum + value, total)\n *         return [next, [next]] as const\n *       })\n *     ),\n *     Stream.runCollect\n *   )\n *   totals // => [ 3, 10 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category mapping\n * @since 4.0.0\n */\nexport const mapAccumArrayEffect = /*#__PURE__*/dual(args => isStream(args[0]), (self, initial, f, options) => self.channel.pipe(Channel.mapAccum(initial, (state, a) => Effect.map(f(state, a), ([state, values]) => [state, Arr.isReadonlyArrayNonEmpty(values) ? Arr.of(values) : emptyArr]), options?.onHalt ? {\n  onHalt(state) {\n    const arr = options.onHalt(state);\n    return Arr.isReadonlyArrayNonEmpty(arr) ? Arr.of(arr) : emptyArr;\n  }\n} : undefined), fromChannel));\n/**\n * Accumulates state across the stream, emitting the initial state and each updated state.\n *\n * **Example** (Scanning stream state)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.make(1, 2, 3).pipe(\n *     Stream.scan(0, (acc, n) => acc + n),\n *     Stream.runCollect\n *   )\n *   values // => [ 0, 1, 3, 6 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category accumulation\n * @since 2.0.0\n */\nexport const scan = /*#__PURE__*/dual(3, (self, initial, f) => suspend(() => {\n  let isFirst = true;\n  return fromChannel(Channel.mapAccum(self.channel, constant(initial), (state, arr) => {\n    const states = Arr.empty();\n    if (isFirst) {\n      isFirst = false;\n      states.push(state);\n    }\n    for (let index = 0; index < arr.length; index++) {\n      state = f(state, arr[index]);\n      states.push(state);\n    }\n    return [state, Arr.of(states)];\n  }));\n}));\n/**\n * Accumulates state effectfully and emits the initial state plus each accumulated state.\n *\n * **Example** (Effectfully scanning stream state)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const states = yield* Stream.make(1, 2, 3).pipe(\n *     Stream.scanEffect(0, (sum, n) => Effect.succeed(sum + n)),\n *     Stream.runCollect\n *   )\n *   states // => [ 0, 1, 3, 6 ]\n * })\n * await Effect.runPromise(program)\n * ```\n *\n * @category accumulation\n * @since 2.0.0\n */\nexport const scanEffect = /*#__PURE__*/dual(3, (self, initial, f) => self.channel.pipe(Channel.flattenArray, Channel.scanEffect(initial, f), Channel.map(Arr.of), fromChannel));\n/**\n * Drops earlier elements within the debounce window and emits only the latest element after the pause.\n *\n * **Example** (Debouncing stream elements)\n *\n * ```ts import.meta.vitest\n * import { Duration, Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3).pipe(Stream.debounce(Duration.zero))\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.runCollect(stream)\n *   values // => [ 3 ]\n * })\n * await Effect.runPromise(program)\n * ```\n *\n * @category rate limiting\n * @since 2.0.0\n */\nexport const debounce = /*#__PURE__*/dual(2, (self, duration) => transformPull(self, Effect.fnUntraced(function* (pull, scope) {\n  const clock = yield* Clock;\n  const durationMs = Duration.toMillis(Duration.fromInputUnsafe(duration));\n  let lastArr;\n  let cause;\n  let emitAtMs = Infinity;\n  const pullLatch = Latch.makeUnsafe();\n  const emitLatch = Latch.makeUnsafe();\n  const endLatch = Latch.makeUnsafe();\n  yield* pull.pipe(pullLatch.whenOpen, Effect.flatMap(arr => {\n    emitLatch.openUnsafe();\n    lastArr = arr;\n    emitAtMs = clock.currentTimeMillisUnsafe() + durationMs;\n    return Effect.void;\n  }), Effect.forever({\n    disableYield: true\n  }), Effect.onError(cause_ => {\n    cause = cause_;\n    emitAtMs = clock.currentTimeMillisUnsafe();\n    emitLatch.openUnsafe();\n    endLatch.openUnsafe();\n    return Effect.void;\n  }), Effect.forkIn(scope));\n  const sleepLoop = Effect.suspend(function loop() {\n    const now = clock.currentTimeMillisUnsafe();\n    const timeMs = emitAtMs < now ? durationMs : Math.min(durationMs, emitAtMs - now);\n    return Effect.flatMap(Effect.raceFirst(Effect.sleep(timeMs), endLatch.await), () => {\n      const now = clock.currentTimeMillisUnsafe();\n      if (now < emitAtMs) {\n        return loop();\n      } else if (lastArr) {\n        emitLatch.closeUnsafe();\n        pullLatch.closeUnsafe();\n        const eff = Effect.succeed(Arr.of(Arr.lastNonEmpty(lastArr)));\n        lastArr = undefined;\n        return eff;\n      } else if (cause) {\n        return Effect.failCause(cause);\n      }\n      return loop();\n    });\n  });\n  return Effect.suspend(() => {\n    if (cause) {\n      if (lastArr) {\n        const eff = Effect.succeed(Arr.of(Arr.lastNonEmpty(lastArr)));\n        lastArr = undefined;\n        return eff;\n      }\n      return Effect.failCause(cause);\n    }\n    pullLatch.openUnsafe();\n    return emitLatch.whenOpen(sleepLoop);\n  });\n})));\n/**\n * Rate-limits stream chunks with an effectful cost function.\n *\n * **When to use**\n *\n * Use to throttle chunks when computing each chunk's cost requires an effect.\n *\n * **Details**\n *\n * Uses a token bucket. The bucket can accumulate up to `units + burst` tokens,\n * and each chunk consumes the cost returned by the effectful `cost` function.\n *\n * If using the \"enforce\" strategy, arrays that do not meet the bandwidth\n * constraints are dropped. If using the \"shape\" strategy, arrays are delayed\n * until they can be emitted without exceeding the bandwidth constraints.\n *\n * Defaults to the \"shape\" strategy.\n *\n * **Example** (Throttling stream chunks effectfully)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.range(0, 5).pipe(\n *   Stream.rechunk(1),\n *   Stream.throttleEffect({\n *     cost: (arr) => Effect.succeed(arr.length),\n *     units: 1,\n *     duration: 0,\n *     strategy: \"shape\"\n *   })\n * )\n *\n * await Effect.runPromise(Effect.gen(function*() {\n *   const result = yield* Stream.runCollect(stream)\n *   result // => [ 0, 1, 2, 3, 4, 5 ]\n * }))\n * ```\n *\n * @category rate limiting\n * @since 2.0.0\n */\nexport const throttleEffect = /*#__PURE__*/dual(2, (self, options) => {\n  const burst = options.burst ?? 0;\n  if (options.strategy === \"enforce\") {\n    return throttleEnforceEffect(self, options.cost, options.units, options.duration, burst);\n  }\n  return throttleShapeEffect(self, options.cost, options.units, options.duration, burst);\n});\nconst throttleEnforceEffect = (self, cost, units, duration, burst) => transformPull(self, pull => Effect.clockWith(clock => {\n  const durationMs = Duration.toMillis(Duration.fromInputUnsafe(duration));\n  const max = units + burst < 0 ? Number.POSITIVE_INFINITY : units + burst;\n  let tokens = units;\n  let timestampMs = clock.currentTimeMillisUnsafe();\n  return Effect.succeed(Effect.flatMap(pull, function loop(arr) {\n    return Effect.flatMap(cost(arr), weight => {\n      const currentMs = clock.currentTimeMillisUnsafe();\n      const elapsed = currentMs - timestampMs;\n      const cycles = elapsed / durationMs;\n      const sum = tokens + cycles * units;\n      const available = sum < 0 ? max : Math.min(sum, max);\n      if (weight <= available) {\n        tokens = available - weight;\n        timestampMs = currentMs;\n        return Effect.succeed(arr);\n      }\n      // Drop the array and continue\n      return Effect.flatMap(pull, loop);\n    });\n  }));\n}));\nconst throttleShapeEffect = (self, cost, units, duration, burst) => transformPull(self, pull => Effect.clockWith(clock => {\n  const durationMs = Duration.toMillis(Duration.fromInputUnsafe(duration));\n  const max = units + burst < 0 ? Number.POSITIVE_INFINITY : units + burst;\n  let tokens = units;\n  let timestampMs = clock.currentTimeMillisUnsafe();\n  return Effect.succeed(Effect.flatMap(pull, arr => Effect.flatMap(cost(arr), weight => {\n    const currentMs = clock.currentTimeMillisUnsafe();\n    const elapsed = currentMs - timestampMs;\n    const cycles = elapsed / durationMs;\n    const sum = tokens + cycles * units;\n    const available = sum < 0 ? max : Math.min(sum, max);\n    const remaining = available - weight;\n    if (remaining >= 0) {\n      tokens = remaining;\n      timestampMs = currentMs;\n      return Effect.succeed(arr);\n    }\n    // Calculate delay needed\n    const waitCycles = -remaining / units;\n    const delayMs = Math.max(0, waitCycles * durationMs);\n    if (delayMs > 0) {\n      return Effect.flatMap(Effect.sleep(delayMs), () => {\n        tokens = remaining;\n        timestampMs = currentMs;\n        return Effect.succeed(arr);\n      });\n    }\n    tokens = remaining;\n    timestampMs = currentMs;\n    return Effect.succeed(arr);\n  })));\n}));\n/**\n * Rate-limits stream chunks with a synchronous cost function.\n *\n * **When to use**\n *\n * Use to throttle chunks when each chunk's cost can be computed synchronously.\n *\n * **Details**\n *\n * Uses a token bucket. The bucket can accumulate up to `units + burst` tokens,\n * and each chunk consumes the cost returned by `cost`.\n *\n * If using the \"enforce\" strategy, arrays that do not meet the bandwidth\n * constraints are dropped. If using the \"shape\" strategy, arrays are delayed\n * until they can be emitted without exceeding the bandwidth constraints.\n *\n * Defaults to the \"shape\" strategy.\n *\n * **Example** (Throttling stream chunks)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.range(0, 5).pipe(\n *   Stream.rechunk(1),\n *   Stream.throttle({\n *     cost: (arr) => arr.length,\n *     units: 1,\n *     duration: 0,\n *     strategy: \"shape\"\n *   })\n * )\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.runCollect(stream)\n *   values // => [ 0, 1, 2, 3, 4, 5 ]\n * })\n * await Effect.runPromise(program)\n * ```\n *\n * @category rate limiting\n * @since 2.0.0\n */\nexport const throttle = /*#__PURE__*/dual(2, (self, options) => throttleEffect(self, {\n  ...options,\n  cost: arr => Effect.succeed(options.cost(arr))\n}));\n/**\n * Partitions the stream into non-empty arrays of the specified size.\n *\n * **Details**\n *\n * The final array may be smaller if there are not enough elements to fill it.\n * Finite fractional sizes are rounded down. `NaN` and non-positive sizes are\n * treated as `1`.\n *\n * **Example** (Grouping elements by size)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const grouped = yield* Stream.range(1, 8).pipe(\n *     Stream.grouped(3),\n *     Stream.runCollect\n *   )\n *   grouped // => [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8 ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const grouped = /*#__PURE__*/dual(2, (self, n) => chunks(rechunk(self, n)));\n/**\n * Partitions the stream into arrays, emitting when the chunk size is reached\n * or the duration passes.\n *\n * **Details**\n *\n * Finite fractional chunk sizes are rounded down. `NaN` and non-positive sizes\n * are treated as `1`.\n *\n * **Example** (Grouping elements by size or time)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.make(1, 2, 3).pipe(\n *     Stream.groupedWithin(2, \"5 seconds\"),\n *     Stream.runCollect\n *   )\n *   values // => [ [ 1, 2 ], [ 3 ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const groupedWithin = /*#__PURE__*/dual(3, (self, chunkSize, duration) => aggregateWithin(self, Sink.take(Count.normalizeNonEmpty(chunkSize)), Schedule.spaced(duration)));\n/**\n * Groups elements into keyed substreams using an effectful classifier.\n *\n * **Example** (Grouping elements into keyed substreams using an effectful classifier)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const grouped = yield* Stream.make(1, 2, 3, 4, 5).pipe(\n *     Stream.groupBy((n) =>\n *       Effect.succeed([n % 2 === 0 ? \"even\" : \"odd\", n] as const)\n *     ),\n *     Stream.mapEffect(\n *       Effect.fnUntraced(function*([key, stream]) {\n *         return [key, yield* Stream.runCollect(stream)] as const\n *       }),\n *       { concurrency: \"unbounded\" }\n *     ),\n *     Stream.runCollect\n *   )\n *\n *   grouped // => [ [ 'odd', [ 1, 3, 5 ] ], [ 'even', [ 2, 4 ] ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const groupBy = /*#__PURE__*/dual(args => isStream(args[0]), (self, f, options) => groupByImpl(self, Effect.fnUntraced(function* (arr, queues, queueMap) {\n  for (let i = 0; i < arr.length; i++) {\n    const [key, value] = yield* f(arr[i]);\n    const oentry = MutableHashMap.get(queueMap, key);\n    const queue = Option.isSome(oentry) ? oentry.value : yield* Effect.scoped(RcMap.get(queues, key));\n    yield* RcMap.touch(queues, key);\n    yield* Queue.offer(queue, value);\n  }\n}), options));\n/**\n * Groups elements by a key and emits a stream per key.\n *\n * **Example** (Grouping elements by key)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const grouped = yield* Stream.make(1, 2, 3, 4, 5).pipe(\n *     Stream.groupByKey((n) => n % 2 === 0 ? \"even\" : \"odd\"),\n *     Stream.mapEffect(\n *       ([key, stream]) =>\n *         Stream.runCollect(stream).pipe(\n *           Effect.map((values) => [key, values] as const)\n *         ),\n *       { concurrency: \"unbounded\" }\n *     ),\n *     Stream.runCollect\n *   )\n *   grouped // => [ [ 'odd', [ 1, 3, 5 ] ], [ 'even', [ 2, 4 ] ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const groupByKey = /*#__PURE__*/dual(args => isStream(args[0]), (self, f, options) => suspend(() => {\n  const batch = MutableHashMap.empty();\n  return groupByImpl(self, Effect.fnUntraced(function* (arr, queues, queueMap) {\n    for (let i = 0; i < arr.length; i++) {\n      const key = f(arr[i]);\n      const ovalues = MutableHashMap.get(batch, key);\n      if (Option.isNone(ovalues)) {\n        MutableHashMap.set(batch, key, [arr[i]]);\n      } else {\n        ovalues.value.push(arr[i]);\n      }\n    }\n    for (const [key, values] of batch) {\n      const oentry = MutableHashMap.get(queueMap, key);\n      const queue = Option.isSome(oentry) ? oentry.value : yield* Effect.scoped(RcMap.get(queues, key));\n      yield* RcMap.touch(queues, key);\n      yield* Queue.offerAll(queue, values);\n    }\n    MutableHashMap.clear(batch);\n  }), options);\n}));\nconst groupByImpl = (self, f, options) => transformPullBracket(self, Effect.fnUntraced(function* (pull, scope, forkedScope) {\n  const out = yield* Queue.unbounded();\n  yield* Scope.addFinalizer(scope, Queue.shutdown(out));\n  const queueMap = MutableHashMap.empty();\n  const queues = yield* RcMap.make({\n    lookup: key => Effect.acquireRelease(Queue.make({\n      capacity: options?.bufferSize ?? 4096\n    }).pipe(Effect.tap(queue => {\n      MutableHashMap.set(queueMap, key, queue);\n      return Queue.offer(out, [key, fromQueue(queue)]);\n    })), queue => {\n      MutableHashMap.remove(queueMap, key);\n      return Queue.end(queue);\n    }),\n    idleTimeToLive: options?.idleTimeToLive ?? Duration.infinity\n  }).pipe(Scope.provide(forkedScope));\n  yield* Effect.whileLoop({\n    while: constTrue,\n    body: constant(Effect.flatMap(pull, arr => f(arr, queues, queueMap))),\n    step: constVoid\n  }).pipe(Effect.catchCause(cause => Queue.failCause(out, cause)), Effect.forkIn(scope));\n  return Queue.takeAll(out);\n}));\n/**\n * Groups consecutive elements that have equal keys into non-empty arrays.\n *\n * **When to use**\n *\n * Use when you already have a stream ordered by the grouping key and want to\n * emit each consecutive run as a non-empty array while keeping later\n * non-adjacent runs separate.\n *\n * **Details**\n *\n * The key is computed with `f`; adjacent elements whose keys are equal by\n * `Equal.equals` are emitted as one `[key, group]`. Later non-adjacent runs\n * with the same key are emitted separately.\n *\n * @see {@link groupByKey} for grouping all elements with the same key across the stream\n * @see {@link groupBy} for custom grouped stream construction\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const groupAdjacentBy = /*#__PURE__*/dual(2, (self, f) => transformPull(self, (pull, _scope) => Effect.sync(() => {\n  let currentKey = undefined;\n  let group;\n  let toEmit = Arr.empty();\n  const loop = pull.pipe(Effect.flatMap(chunk => {\n    for (let i = 0; i < chunk.length; i++) {\n      const item = chunk[i];\n      const key = f(item);\n      if (group === undefined) {\n        currentKey = key;\n        group = [item];\n        continue;\n      } else if (Equal.equals(key, currentKey)) {\n        group.push(item);\n        continue;\n      }\n      toEmit.push([currentKey, group]);\n      currentKey = key;\n      group = [item];\n    }\n    if (Arr.isArrayNonEmpty(toEmit)) {\n      const out = toEmit;\n      toEmit = [];\n      return Effect.succeed(out);\n    }\n    return loop;\n  }));\n  let done = false;\n  return Pull.catchDone(Effect.suspend(() => done ? Cause.done() : loop), () => {\n    done = true;\n    const out = group;\n    group = undefined;\n    return out && Arr.isArrayNonEmpty(out) ? Effect.succeed(Arr.of([currentKey, out])) : Cause.done();\n  });\n})));\n/**\n * Applies a sink transducer to the stream and emits each sink result.\n *\n * **Example** (Transducing with a sink)\n *\n * ```ts import.meta.vitest\n * import { Effect, Sink, Stream } from \"effect\"\n *\n * const program = Effect.gen(function* () {\n *   const result = yield* Stream.make(1, 2, 3, 4).pipe(\n *     Stream.transduce(Sink.take(2)),\n *     Stream.runCollect\n *   )\n *\n *   result // => [ [ 1, 2 ], [ 3, 4 ], [] ]\n * })\n * await Effect.runPromise(program)\n * ```\n *\n * @category aggregation\n * @since 2.0.0\n */\nexport const transduce = /*#__PURE__*/dual(2, (self, sink) => transformPull(self, (upstream, scope) => Effect.sync(() => {\n  let done;\n  let leftover;\n  const upstreamWithLeftover = Effect.suspend(() => {\n    if (leftover !== undefined) {\n      const chunk = leftover;\n      leftover = undefined;\n      return Effect.succeed(chunk);\n    }\n    return upstream;\n  }).pipe(Effect.catch(error => {\n    done = Exit.fail(error);\n    return Cause.done();\n  }));\n  const pull = Effect.map(Effect.suspend(() => sink.transform(upstreamWithLeftover, scope)), ([value, leftover_]) => {\n    leftover = leftover_;\n    return Arr.of(value);\n  });\n  return Effect.suspend(() => done ? done : pull);\n})));\n/**\n * Aggregates elements using the provided sink and emits each sink result as a stream element.\n *\n * **Details**\n *\n * The stream runs the upstream and downstream in separate fibers, so the sink can keep\n * consuming input while downstream is busy processing the previous output.\n *\n * **Example** (Aggregating with a sink)\n *\n * ```ts import.meta.vitest\n * import { Effect, Sink, Stream } from \"effect\"\n *\n * await Effect.runPromise(Effect.gen(function* () {\n *   const aggregated = yield* Stream.runCollect(\n *     Stream.make(1, 2, 3, 4, 5, 6).pipe(\n *       Stream.aggregate(\n *         Sink.foldUntil(() => 0, 3, (sum, n) => Effect.succeed(sum + n))\n *       )\n *     )\n *   )\n *   aggregated // => [ 6, 15 ]\n * }))\n * ```\n *\n * @category aggregation\n * @since 2.0.0\n */\nexport const aggregate = /*#__PURE__*/dual(2, (self, sink) => aggregateWithin(self, sink, Schedule.forever));\n/**\n * Aggregates elements with a sink, emitting each result when the sink completes or the schedule triggers.\n *\n * **Details**\n *\n * The schedule can flush the current aggregation even if the sink has not finished.\n *\n * **Example** (Aggregating with a sink and schedule)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schedule, Sink, Stream } from \"effect\"\n *\n * await Effect.runPromise(Effect.gen(function* () {\n *   const aggregated = yield* Stream.runCollect(\n *     Stream.make(1, 2, 3, 4, 5, 6).pipe(\n *       Stream.aggregateWithin(\n *         Sink.foldUntil(() => 0, 3, (sum, n) => Effect.succeed(sum + n)),\n *         Schedule.forever\n *       )\n *     )\n *   )\n *   aggregated // => [ 6, 15 ]\n * }))\n * ```\n *\n * @category aggregation\n * @since 2.0.0\n */\nexport const aggregateWithin = /*#__PURE__*/dual(3, (self, sink, schedule) => fromChannel(Channel.fromTransformBracket(Effect.fnUntraced(function* (_upstream, _, scope) {\n  const pull = yield* Channel.toPullScoped(self.channel, _);\n  const pullLatch = Latch.makeUnsafe(false);\n  const scheduleStep = Symbol();\n  const buffer = yield* Queue.make({\n    capacity: 0\n  });\n  // upstream -> buffer\n  yield* pull.pipe(pullLatch.whenOpen, Effect.flatMap(arr => {\n    pullLatch.closeUnsafe();\n    return Queue.offer(buffer, arr);\n  }), Effect.forever,\n  // don't disable autoYield to prevent choking the schedule\n  Effect.catchCause(cause => Queue.failCause(buffer, cause)), Effect.forkIn(scope));\n  // schedule -> buffer\n  let lastOutput = Option.none();\n  let leftover;\n  let sinkHasInput = false;\n  const step = yield* Schedule.toStepWithSleep(schedule);\n  const stepLoop = Effect.suspend(function loop() {\n    return Effect.flatMap(step(lastOutput), () => !sinkHasInput ? loop() : Queue.offer(buffer, scheduleStep));\n  });\n  const stepToBuffer = stepLoop.pipe(Effect.flatMap(() => Effect.never), Pull.catchDone(() => Cause.done()));\n  // buffer -> sink\n  const pullFromBuffer = Queue.take(buffer).pipe(Effect.flatMap(arr => {\n    if (arr === scheduleStep) {\n      return Cause.done();\n    }\n    sinkHasInput = true;\n    return Effect.succeed(arr);\n  }));\n  const sinkUpstream = Effect.suspend(() => {\n    if (leftover !== undefined) {\n      const chunk = leftover;\n      leftover = undefined;\n      sinkHasInput = true;\n      return Effect.succeed(chunk);\n    }\n    pullLatch.openUnsafe();\n    return pullFromBuffer;\n  });\n  const catchSinkHalt = Effect.flatMap(([value, leftover_]) => {\n    // ignore the last output if the upstream only pulled a halt\n    if (!sinkHasInput && buffer.state._tag === \"Done\") return Cause.done();\n    lastOutput = Option.some(value);\n    leftover = leftover_;\n    return Effect.succeed(Arr.of(value));\n  });\n  return Effect.suspend(() => {\n    // if the buffer has exited and there is no more data to process\n    if (buffer.state._tag === \"Done\" && leftover === undefined) {\n      return buffer.state.exit;\n    }\n    sinkHasInput = leftover !== undefined;\n    return Effect.succeed(Effect.suspend(() => sink.transform(sinkUpstream, scope)));\n  }).pipe(Effect.flatMap(pull => Effect.raceFirst(catchSinkHalt(pull), stepToBuffer)));\n}))));\n/**\n * Creates a fixed-size tuple of streams that each emit\n * the same elements as the source stream.\n *\n * **Details**\n *\n * The source stream starts after all downstream streams have been subscribed.\n * With the default suspend strategy, the source can only advance `capacity`\n * chunks ahead of the slowest downstream stream. If a downstream stream is\n * interrupted, it unsubscribes from the broadcast so it no longer contributes\n * backpressure. Finite fractional values of `n` are rounded down. `NaN` and\n * non-positive values create no downstream streams.\n *\n * **Example** (Broadcasting to two consumers)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.scoped(\n *   Effect.gen(function*() {\n *     const [left, right] = yield* Stream.make(1, 2, 3).pipe(\n *       Stream.broadcastN({ n: 2, capacity: 8 })\n *     )\n *\n *     const values = yield* Effect.all([\n *       Stream.runCollect(left),\n *       Stream.runCollect(right)\n *     ], { concurrency: \"unbounded\" })\n *\n *     values // => [ [ 1, 2, 3 ], [ 1, 2, 3 ] ]\n *   })\n * )\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category broadcasting\n * @since 4.0.0\n */\nexport const broadcastN = /*#__PURE__*/dual(2, /*#__PURE__*/Effect.fnUntraced(function* (self, options) {\n  const n = Count.normalize(options.n);\n  const pubsub = yield* makePubSub(options);\n  const streams = new Array(n);\n  const parentScope = yield* Scope.Scope;\n  for (let i = 0; i < n; i++) {\n    const scope = Scope.forkUnsafe(parentScope);\n    const subscription = yield* PubSub.subscribe(pubsub).pipe(Effect.provideService(Scope.Scope, scope));\n    streams[i] = Channel.fromEffectTake(PubSub.take(subscription)).pipe(Channel.onExit(exit => Scope.close(scope, exit)), fromChannel);\n  }\n  yield* Channel.runForEach(self.channel, value => PubSub.publish(pubsub, value)).pipe(Effect.onExit(exit => PubSub.publish(pubsub, exit)), Effect.forkScoped);\n  return streams;\n}));\nconst makePubSub = options => Effect.acquireRelease(options.capacity === \"unbounded\" ? PubSub.unbounded(options) : options.strategy === \"dropping\" ? PubSub.dropping(options) : options.strategy === \"sliding\" ? PubSub.sliding(options) : PubSub.bounded(options), PubSub.shutdown);\n/**\n * Creates a PubSub-backed stream that multicasts the source to all subscribers.\n *\n * **Details**\n *\n * The returned stream is scoped and uses the provided PubSub capacity and replay settings.\n *\n * **Example** (Broadcasting a stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.scoped(\n *   Effect.gen(function* () {\n *     const broadcasted = yield* Stream.broadcast(Stream.fromArray([1, 2, 3]), {\n *       capacity: 8,\n *       replay: 3\n *     })\n *\n *     const [left, right] = yield* Effect.all([\n *       Stream.runCollect(broadcasted),\n *       Stream.runCollect(broadcasted)\n *     ], { concurrency: \"unbounded\" })\n *\n *     const result = [left, right] // => [[1, 2, 3], [1, 2, 3]]\n *   })\n * )\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category broadcasting\n * @since 2.0.0\n */\nexport const broadcast = /*#__PURE__*/dual(2, (self, options) => Effect.map(toPubSubTake(self, options), fromPubSubTake));\n/**\n * Returns a new Stream that multicasts the original stream, subscribing when the first consumer starts.\n *\n * **Details**\n *\n * The upstream continues running while there is at least one consumer and is finalized after the last one exits.\n * If `idleTimeToLive` is set, the upstream is kept alive for that duration so a later subscriber can continue from\n * the next element instead of restarting.\n *\n * **Example** (Sharing a stream)\n *\n * ```ts import.meta.vitest\n * import { Deferred, Effect, Ref, Stream } from \"effect\"\n *\n * const result = await Effect.runPromise(\n *   Effect.scoped(\n *     Effect.gen(function*() {\n *       const firstReady = yield* Deferred.make<void>()\n *       const secondReady = yield* Deferred.make<void>()\n *       const acquisitions = yield* Ref.make(0)\n *       const source = Stream.fromEffect(Ref.update(acquisitions, (n) => n + 1)).pipe(\n *         Stream.drain,\n *         Stream.concat(Stream.make(0)),\n *         Stream.concat(\n *           Stream.fromEffect(Effect.all([Deferred.await(firstReady), Deferred.await(secondReady)])).pipe(Stream.drain)\n *         ),\n *         Stream.concat(Stream.make(1, 2, 3))\n *       )\n *       const shared = yield* Stream.share(source, { capacity: 16, replay: 1 })\n *       const consume = (ready: Deferred.Deferred<void>) =>\n *         shared.pipe(\n *           Stream.tap((value) => value === 0 ? Deferred.succeed(ready, void 0) : Effect.void),\n *           Stream.filter((value) => value !== 0),\n *           Stream.runCollect\n *         )\n *\n *       const values = yield* Effect.all([consume(firstReady), consume(secondReady)], { concurrency: \"unbounded\" })\n *       return { values, acquisitions: yield* Ref.get(acquisitions) }\n *     })\n *   )\n * )\n * result // => { values: [[1, 2, 3], [1, 2, 3]], acquisitions: 1 }\n * ```\n *\n * @category broadcasting\n * @since 3.8.0\n */\nexport const share = /*#__PURE__*/dual(2, (self, options) => Effect.map(RcRef.make({\n  acquire: broadcast(self, options),\n  idleTimeToLive: options.idleTimeToLive\n}), ref => unwrap(RcRef.get(ref))));\n/**\n * Pipes this stream through a channel that consumes and emits chunked elements.\n *\n * **Details**\n *\n * The channel receives `NonEmptyReadonlyArray` chunks and can transform both the\n * output elements and error type.\n *\n * **Example** (Piping through a channel)\n *\n * ```ts import.meta.vitest\n * import { Array, Channel, Effect, Stream } from \"effect\"\n *\n * type NumberChunk = readonly [number, ...Array<number>]\n *\n * const doubleChunks = Channel.identity<NumberChunk, never, unknown>().pipe(\n *   Channel.map((chunk) => Array.map(chunk, (n) => n * 2))\n * )\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.fromArray([1, 2, 3]).pipe(\n *     Stream.rechunk(2),\n *     Stream.pipeThroughChannel(doubleChunks),\n *     Stream.runCollect\n *   )\n *   result // => [ 2, 4, 6 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const pipeThroughChannel = /*#__PURE__*/dual(2, (self, channel) => fromChannel(Channel.pipeTo(self.channel, channel)));\n/**\n * Pipes values through the provided channel while preserving this stream's\n * failures alongside any channel failures.\n *\n * **Details**\n *\n * Upstream failures are not passed to the channel, so the resulting stream can\n * fail with either the original stream error or the channel error.\n *\n * **Example** (Piping through a channel with failures)\n *\n * ```ts import.meta.vitest\n * import { Array, Channel, Effect, Stream } from \"effect\"\n *\n * type NumberChunk = readonly [number, ...Array<number>]\n *\n * const stringifyChunks = Channel.identity<NumberChunk, \"StreamError\", unknown>().pipe(\n *   Channel.map((chunk) => Array.map(chunk, String))\n * )\n *\n * await Effect.runPromise(Effect.gen(function*() {\n *   const result = yield* Stream.make(1, 2, 3).pipe(\n *     Stream.rechunk(2),\n *     Stream.pipeThroughChannelOrFail(stringifyChunks),\n *     Stream.runCollect\n *   )\n *\n *   result // => [\"1\", \"2\", \"3\"]\n * }))\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const pipeThroughChannelOrFail = /*#__PURE__*/dual(2, (self, channel) => fromChannel(Channel.pipeToOrFail(self.channel, channel)));\n/**\n * Pipes the stream through `Sink.toChannel`, emitting only the sink leftovers.\n *\n * **Details**\n *\n * If the sink completes mid-chunk, the remaining elements become the output stream.\n *\n * **Example** (Piping through a sink)\n *\n * ```ts import.meta.vitest\n * import { Effect, Sink, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const leftovers = yield* Stream.make(1, 2, 3, 4).pipe(\n *     Stream.pipeThrough(Sink.take(2)),\n *     Stream.runCollect\n *   )\n *\n *   leftovers // => [ 3, 4 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const pipeThrough = /*#__PURE__*/dual(2, (self, sink) => self.channel.pipe(Channel.pipeToOrFail(Sink.toChannel(sink)), Channel.concatWith(([_, leftover]) => leftover ? Channel.succeed(leftover) : Channel.empty), fromChannel));\n/**\n * Collects all elements into an array and emits it as a single element.\n *\n * **Example** (Collecting values into a stream element)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3)\n *\n * const program = Effect.gen(function*() {\n *   const collected = yield* stream.pipe(Stream.collect, Stream.runCollect)\n *   collected[0] // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category accumulation\n * @since 4.0.0\n */\nexport const collect = self => fromEffect(runCollect(self));\n/**\n * Accumulates elements into a growing array, emitting the cumulative array for each input chunk.\n *\n * **Example** (Accumulating stream elements)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const accumulated = yield* Stream.runCollect(\n *     Stream.fromArray([1, 2, 3]).pipe(\n *       Stream.rechunk(1),\n *       Stream.accumulate\n *     )\n *   )\n *   accumulated // => [ [ 1 ], [ 1, 2 ], [ 1, 2, 3 ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category accumulation\n * @since 2.0.0\n */\nexport const accumulate = self => mapAccumArray(self, Arr.empty, (acc, as) => {\n  const combined = Arr.appendAll(acc, as);\n  return [combined, [combined]];\n});\n/**\n * Emits only elements that differ from the previous one.\n *\n * **Example** (Emitting changed values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.fromIterable([1, 1, 2, 2, 3]).pipe(\n *     Stream.changes,\n *     Stream.runCollect\n *   )\n *\n *   values // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category deduplication\n * @since 2.0.0\n */\nexport const changes = self => changesWith(self, Equal.equals);\n/**\n * Returns a stream that only emits elements that are not equal to the previously emitted element, as determined by the specified predicate.\n *\n * **Example** (Emitting values that changed by equivalence)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(\"A\", \"a\", \"B\", \"b\", \"b\").pipe(\n *   Stream.changesWith((left, right) => left.toLowerCase() === right.toLowerCase())\n * )\n *\n * await Effect.runPromise(\n *   Effect.gen(function*() {\n *     const values = yield* Stream.runCollect(stream)\n *     values // => [ 'A', 'B' ]\n *   })\n * )\n * ```\n *\n * @category deduplication\n * @since 2.0.0\n */\nexport const changesWith = /*#__PURE__*/dual(2, (self, f) => transformPull(self, (pull, _scope) => Effect.sync(() => {\n  let first = true;\n  let last;\n  return Effect.flatMap(pull, function loop(arr) {\n    const out = [];\n    let i = 0;\n    if (first) {\n      first = false;\n      last = arr[0];\n      i = 1;\n      out.push(last);\n    }\n    for (; i < arr.length; i++) {\n      const a = arr[i];\n      if (f(a, last)) continue;\n      last = a;\n      out.push(a);\n    }\n    return Arr.isArrayNonEmpty(out) ? Effect.succeed(out) : Effect.flatMap(pull, loop);\n  });\n})));\n/**\n * Emits only elements that differ from the previous element, using an effectful equality check.\n *\n * **Details**\n *\n * The predicate runs for each element after the first; returning `true` treats it as equal and skips it.\n *\n * **Example** (Effectfully emitting changed values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const stream = Stream.make(1, 1, 2, 2, 3, 3).pipe(\n *     Stream.changesWithEffect((a, b) => Effect.succeed(a === b))\n *   )\n *   const result = yield* Stream.runCollect(stream)\n *   result // => [ 1, 2, 3 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category deduplication\n * @since 2.0.0\n */\nexport const changesWithEffect = /*#__PURE__*/dual(2, (self, f) => transformPull(self, (pull, _scope) => Effect.sync(() => {\n  let first = true;\n  let last;\n  return Effect.flatMap(pull, Effect.fnUntraced(function* loop(arr) {\n    const out = [];\n    let i = 0;\n    if (first) {\n      first = false;\n      last = arr[0];\n      i = 1;\n      out.push(last);\n    }\n    for (; i < arr.length; i++) {\n      const a = arr[i];\n      if (yield* f(a, last)) continue;\n      last = a;\n      out.push(a);\n    }\n    return Arr.isArrayNonEmpty(out) ? out : yield* Effect.flatMap(pull, Effect.fnUntraced(loop));\n  }));\n})));\n/**\n * Decodes Uint8Array chunks into strings using TextDecoder with an optional encoding.\n *\n * **Example** (Decoding Uint8Array chunks into strings using TextDecoder with an optional encoding)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const encoder = new TextEncoder()\n * const stream = Stream.make(\n *   encoder.encode(\"Hello\"),\n *   encoder.encode(\" World\")\n * )\n *\n * const program = Effect.gen(function*() {\n *   const decoded = yield* stream.pipe(\n *     Stream.decodeText,\n *     Stream.runCollect\n *   )\n *   decoded // => [ 'Hello', ' World' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category decoding\n * @since 2.0.0\n */\nexport const decodeText = /*#__PURE__*/dual(args => isStream(args[0]), (self, options) => suspend(() => {\n  const decoder = new TextDecoder(options?.encoding);\n  return map(self, chunk => decoder.decode(chunk, {\n    stream: true\n  }));\n}));\n/**\n * Encodes a stream of strings into UTF-8 `Uint8Array` chunks.\n *\n * **Example** (Encoding a stream of strings into UTF-8 Uint8Array chunks)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(\"Hello\", \" \", \"World\")\n * const program = Effect.gen(function*() {\n *   const encoded = Stream.encodeText(stream)\n *   const chunks = yield* Stream.runCollect(encoded)\n *   const bytes = chunks.map((chunk) => [...chunk])\n *   bytes // => [ [ 72, 101, 108, 108, 111 ], [ 32 ], [ 87, 111, 114, 108, 100 ] ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category encoding\n * @since 2.0.0\n */\nexport const encodeText = self => suspend(() => {\n  const encoder = new TextEncoder();\n  return map(self, chunk => encoder.encode(chunk));\n});\n/**\n * Splits a stream of strings into lines, handling `\\n`, `\\r`, and `\\r\\n` delimiters across chunks.\n *\n * **Example** (Splitting streamed text into lines)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * await Effect.runPromise(Effect.gen(function* () {\n *   const lines = yield* Stream.runCollect(\n *     Stream.make(\"a\\nb\\r\\n\", \"c\\n\").pipe(Stream.splitLines)\n *   )\n *   lines // => [ 'a', 'b', 'c' ]\n * }))\n * ```\n *\n * @category splitting\n * @since 2.0.0\n */\nexport const splitLines = self => self.channel.pipe(Channel.pipeTo(Channel.splitLines()), fromChannel);\n/**\n * Inserts the provided element between emitted elements.\n *\n * **Example** (Interspersing stream elements)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const stream = Stream.make(1, 2, 3, 4).pipe(Stream.intersperse(0))\n *   const result = yield* Stream.runCollect(stream)\n *   result // => [1, 0, 2, 0, 3, 0, 4]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const intersperse = /*#__PURE__*/dual(2, (self, element) => mapArray(self, (arr, i) => {\n  const out = i === 0 ? [] : [element];\n  const lastIndex = arr.length - 1;\n  for (let j = 0; j < arr.length; j++) {\n    if (j === lastIndex) {\n      out.push(arr[j]);\n    } else {\n      out.push(arr[j], element);\n    }\n  }\n  return out;\n}));\n/**\n * Adds a start value, middle value, and end value around stream elements.\n *\n * **Details**\n *\n * The start and end values are always emitted, even when the stream is empty.\n *\n * **Example** (Interspersing stream affixes)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(\"a\", \"b\", \"c\").pipe(\n *   Stream.intersperseAffixes({ start: \"[\", middle: \",\", end: \"]\" })\n * )\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.runCollect(stream)\n *   result // => [\"[\", \"a\", \",\", \"b\", \",\", \"c\", \"]\"]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const intersperseAffixes = /*#__PURE__*/dual(2, (self, options) => succeed(options.start).pipe(concat(intersperse(self, options.middle)), concat(succeed(options.end))));\n/**\n * Interleaves this stream with the specified stream by alternating pulls from\n * each stream; when one ends, the remaining values from the other stream are\n * emitted.\n *\n * **Example** (Interleaving streams)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.interleave(\n *   Stream.make(2, 3),\n *   Stream.make(5, 6, 7)\n * )\n *\n * const program = Effect.gen(function*() {\n *   const collected = yield* Stream.runCollect(stream)\n *   collected // => [ 2, 5, 3, 6, 7 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category merging\n * @since 2.0.0\n */\nexport const interleave = /*#__PURE__*/dual(2, (self, that) => interleaveWith(self, that, fromIterable(Iterable.forever([true, false]))));\n/**\n * Interleaves two streams deterministically by following a boolean decider stream.\n *\n * **Details**\n *\n * The decider controls how many elements are pulled; if one side ends, pulls for\n * that side are ignored.\n *\n * **Example** (Interleaving two streams deterministically by following a boolean decider stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const left = Stream.make(1, 3, 5)\n *   const right = Stream.make(2, 4, 6)\n *   const decider = Stream.make(true, false, false, true, true)\n *\n *   const values = yield* Stream.runCollect(\n *     Stream.interleaveWith(left, right, decider)\n *   )\n *\n *   values // => [ 1, 2, 4, 3, 5 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category merging\n * @since 2.0.0\n */\nexport const interleaveWith = /*#__PURE__*/dual(3, (self, that, decider) => fromChannel(Channel.fromTransform(Effect.fnUntraced(function* (upstream, scope) {\n  const pullDecider = yield* Channel.toTransform(Channel.flattenArray(decider.channel))(upstream, scope);\n  const retry = Symbol();\n  let leftDone = false;\n  let rightDone = false;\n  const pullLeft = (yield* Channel.toTransform(Channel.flattenArray(self.channel))(upstream, scope)).pipe(Pull.catchDone(() => {\n    leftDone = true;\n    return Effect.succeed(retry);\n  }));\n  const pullRight = (yield* Channel.toTransform(Channel.flattenArray(that.channel))(upstream, scope)).pipe(Pull.catchDone(() => {\n    rightDone = true;\n    return Effect.succeed(retry);\n  }));\n  return Effect.gen(function* () {\n    while (true) {\n      if (leftDone && rightDone) {\n        return yield* Cause.done();\n      }\n      const side = yield* pullDecider;\n      if (side && leftDone) continue;\n      if (!side && rightDone) continue;\n      const elem = yield* side ? pullLeft : pullRight;\n      if (elem === retry) continue;\n      return Arr.of(elem);\n    }\n  });\n}))));\n/**\n * Interrupts the evaluation of this stream when the provided effect\n * completes. The given effect will be forked as part of this stream, and its\n * success will be discarded. This combinator will also interrupt any\n * in-progress element being pulled from upstream.\n *\n * **Details**\n *\n * If the effect completes with a failure before the stream completes, the\n * returned stream will emit that failure.\n *\n * **Example** (Interrupting when an effect completes)\n *\n * ```ts import.meta.vitest\n * import { Deferred, Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const interrupt = yield* Deferred.make<void>()\n *   const stream = Stream.make(1, 2, 3).pipe(\n *     Stream.tap((value) =>\n *       value === 2\n *         ? Deferred.succeed(interrupt, void 0)\n *         : Effect.void\n *     ),\n *     Stream.interruptWhen(Deferred.await(interrupt))\n *   )\n *\n *   const result = yield* Stream.runCollect(stream)\n *   result // => [ 1 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category interruption\n * @since 2.0.0\n */\nexport const interruptWhen = /*#__PURE__*/dual(2, (self, effect) => fromChannel(Channel.interruptWhen(self.channel, effect)));\n/**\n * Stops a stream after the current pull when an effect completes.\n *\n * **When to use**\n *\n * Use to stop before the next pull after an external signal completes.\n *\n * **Details**\n *\n * The effect is forked, its success value is discarded, and its failure fails\n * the stream.\n *\n * **Gotchas**\n *\n * This does not interrupt or truncate an in-progress pull. A pull may emit\n * multiple elements in a single chunk, in which case the entire chunk is\n * emitted. Use {@link interruptWhen} when the stream should be interrupted\n * immediately.\n *\n * **Example** (Halting a stream after an effect completes)\n *\n * ```ts import.meta.vitest\n * import { Deferred, Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const halt = yield* Deferred.make<void>()\n *   const values = yield* Stream.fromArray([1, 2, 3]).pipe(\n *     Stream.tap((value) => value === 2 ? Deferred.succeed(halt, void 0) : Effect.void),\n *     Stream.haltWhen(Deferred.await(halt)),\n *     Stream.runCollect\n *   )\n *   values // => [ 1, 2 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category interruption\n * @since 2.0.0\n */\nexport const haltWhen = /*#__PURE__*/dual(2, (self, effect) => fromChannel(Channel.haltWhen(self.channel, effect)));\n/**\n * Runs the provided finalizer when the stream exits, passing the exit value.\n *\n * **Example** (Running a finalizer on exit)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Stream } from \"effect\"\n *\n * const exits: Array<string> = []\n * const stream = Stream.make(1, 2, 3).pipe(\n *   Stream.onExit((exit) =>\n *     Exit.isSuccess(exit)\n *       ? Effect.sync(() => exits.push(\"success\"))\n *       : Effect.sync(() => exits.push(\"failure\"))\n *   )\n * )\n *\n * await Effect.runPromise(Effect.gen(function*() {\n *   yield* Stream.runCollect(stream)\n * }))\n * exits // => [\"success\"]\n * ```\n *\n * @category resource management\n * @since 4.0.0\n */\nexport const onExit = /*#__PURE__*/dual(2, (self, finalizer) => fromChannel(Channel.onExit(self.channel, finalizer)));\n/**\n * Runs the provided effect when the stream fails, passing the failure cause.\n *\n * **Gotchas**\n *\n * Note: Unlike `Effect.onError` there is no guarantee that the provided\n * effect will not be interrupted.\n *\n * **Example** (Running an effect on errors)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Stream } from \"effect\"\n *\n * const errors: Array<string> = []\n * const program = Effect.gen(function*() {\n *   const stream = Stream.make(1, 2, 3).pipe(\n *     Stream.concat(Stream.fail(\"boom\")),\n *     Stream.onError((cause) => Effect.sync(() => errors.push(String(Cause.squash(cause)))))\n *   )\n *\n *   yield* Stream.runCollect(stream)\n * })\n *\n * await Effect.runPromise(Effect.exit(program))\n * errors // => [\"boom\"]\n * ```\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const onError = /*#__PURE__*/dual(2, (self, cleanup) => fromChannel(Channel.onError(self.channel, cleanup)));\n/**\n * Runs the provided effect before this stream starts.\n *\n * **Example** (Running an effect on start)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const events: Array<string> = []\n * const program = Effect.gen(function*() {\n *   const stream = Stream.fromArray([1, 2, 3]).pipe(\n *     Stream.onStart(Effect.sync(() => events.push(\"started\")))\n *   )\n *\n *   const values = yield* Stream.runCollect(stream)\n *   values // => [1, 2, 3]\n * })\n *\n * await Effect.runPromise(program)\n * events // => [\"started\"]\n * ```\n *\n * @category sequencing\n * @since 3.6.0\n */\nexport const onStart = /*#__PURE__*/dual(2, (self, onStart) => fromChannel(Channel.onStart(self.channel, onStart)));\n/**\n * Runs the provided effect with the first element emitted by the stream.\n *\n * **Example** (Running an effect on the first value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const first: Array<number> = []\n * await Effect.runPromise(Effect.gen(function* () {\n *   yield* Stream.fromArray([1, 2, 3]).pipe(\n *     Stream.onFirst((value) => Effect.sync(() => first.push(value))),\n *     Stream.runDrain\n *   )\n * }))\n * first // => [1]\n * ```\n *\n * @category sequencing\n * @since 4.0.0\n */\nexport const onFirst = /*#__PURE__*/dual(2, (self, onFirst) => fromChannel(Channel.onFirst(self.channel, arr => onFirst(arr[0]))));\n/**\n * Runs the provided effect when the stream ends successfully.\n *\n * **Example** (Running an effect on end)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const events: Array<string> = []\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.make(1, 2, 3).pipe(\n *     Stream.onEnd(Effect.sync(() => events.push(\"ended\"))),\n *     Stream.runCollect\n *   )\n *   values // => [1, 2, 3]\n * })\n *\n * await Effect.runPromise(program)\n * events // => [\"ended\"]\n * ```\n *\n * @category sequencing\n * @since 3.6.0\n */\nexport const onEnd = /*#__PURE__*/dual(2, (self, onEnd) => fromChannel(Channel.onEnd(self.channel, onEnd)));\n/**\n * Executes the provided finalizer after this stream's finalizers run.\n *\n * **Example** (Ensuring finalization)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const events: Array<string> = []\n * const stream = Stream.fromArray([1, 2]).pipe(\n *   Stream.ensuring(Effect.sync(() => events.push(\"cleanup\")))\n * )\n *\n * const program = Effect.gen(function*() {\n *   const collected = yield* Stream.runCollect(stream)\n *   collected // => [1, 2]\n * })\n *\n * await Effect.runPromise(program)\n * events // => [\"cleanup\"]\n * ```\n *\n * @category resource management\n * @since 2.0.0\n */\nexport const ensuring = /*#__PURE__*/dual(2, (self, finalizer) => fromChannel(Channel.ensuring(self.channel, finalizer)));\n/**\n * Provides a layer or context to the stream, removing the corresponding\n * service requirements. Use `options.local` to build the layer every time; by\n * default, layers are shared between provide calls.\n *\n * **Example** (Providing stream requirements)\n *\n * ```ts import.meta.vitest\n * import { Console, Context, Effect, Layer, Stream } from \"effect\"\n *\n * class Env extends Context.Service<Env, { readonly name: string }>()(\"Env\") {}\n *\n * const layer = Layer.succeed(Env)({ name: \"Ada\" })\n *\n * const stream = Stream.fromEffect(\n *   Effect.gen(function*() {\n *     const env = yield* Effect.service(Env)\n *     return `Hello, ${env.name}`\n *   })\n * )\n *\n * const withEnv = stream.pipe(Stream.provide(layer))\n *\n * await Effect.runPromise(Stream.runCollect(withEnv)) // => [\"Hello, Ada\"]\n * ```\n *\n * @category providing services\n * @since 4.0.0\n */\nexport const provide = /*#__PURE__*/dual(args => isStream(args[0]), (self, layer, options) => fromChannel(Channel.provide(self.channel, layer, options)));\n/**\n * Provides multiple services to the stream using a context.\n *\n * **Example** (Providing multiple services to the stream using a context)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Stream } from \"effect\"\n *\n * class Config extends Context.Service<Config, { readonly prefix: string }>()(\"Config\") {}\n * class Greeter extends Context.Service<Greeter, { greet: (name: string) => string }>()(\"Greeter\") {}\n *\n * const context = Context.make(Config, { prefix: \"Hello\" }).pipe(\n *   Context.add(Greeter, { greet: (name: string) => `${name}!` })\n * )\n *\n * const stream = Stream.fromEffect(\n *   Effect.gen(function*() {\n *     const config = yield* Effect.service(Config)\n *     const greeter = yield* Effect.service(Greeter)\n *     return greeter.greet(config.prefix)\n *   })\n * )\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.runCollect(Stream.provideContext(stream, context))\n *   result // => [ 'Hello!' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category providing services\n * @since 2.0.0\n */\nexport const provideContext = /*#__PURE__*/dual(2, (self, context) => fromChannel(Channel.provideContext(self.channel, context)));\n/**\n * Provides the stream with a single required service, eliminating that\n * requirement from its environment.\n *\n * **Example** (Providing a stream service)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Stream } from \"effect\"\n *\n * class Greeter extends Context.Service<Greeter, {\n *   greet: (name: string) => string\n * }>()(\"Greeter\") {}\n *\n * const stream = Stream.fromEffect(\n *   Effect.service(Greeter).pipe(\n *     Effect.map((greeter) => greeter.greet(\"Ada\"))\n *   )\n * )\n *\n * const program = Effect.gen(function*() {\n *   const collected = yield* Stream.runCollect(\n *     stream.pipe(\n *       Stream.provideService(Greeter, {\n *         greet: (name) => `Hello, ${name}`\n *       })\n *     )\n *   )\n *   collected // => [ 'Hello, Ada' ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category providing services\n * @since 2.0.0\n */\nexport const provideService = /*#__PURE__*/dual(3, (self, key, service) => fromChannel(Channel.provideService(self.channel, key, service)));\n/**\n * Provides a service to the stream using an effect, removing the requirement and adding the effect's error and environment.\n *\n * **Example** (Providing a stream service effectfully)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Stream } from \"effect\"\n *\n * class ApiConfig extends Context.Service<ApiConfig, { readonly baseUrl: string }>()(\"ApiConfig\") {}\n *\n * const stream = Stream.fromEffect(\n *   Effect.gen(function*() {\n *     const config = yield* Effect.service(ApiConfig)\n *     return config.baseUrl\n *   })\n * )\n *\n * const events: Array<string> = []\n * const withConfig = stream.pipe(\n *   Stream.provideServiceEffect(\n *     ApiConfig,\n *     Effect.succeed({ baseUrl: \"https://example.com\" }).pipe(\n *       Effect.tap(() => Effect.sync(() => events.push(\"loading\")))\n *     )\n *   )\n * )\n *\n * await Effect.runPromise(Stream.runCollect(withConfig)) // => [\"https://example.com\"]\n * events // => [\"loading\"]\n * ```\n *\n * @category providing services\n * @since 2.0.0\n */\nexport const provideServiceEffect = /*#__PURE__*/dual(3, (self, key, service) => fromChannel(Channel.provideServiceEffect(self.channel, key, service)));\n/**\n * Transforms the stream's required services by mapping the current context\n * to a new one.\n *\n * **Example** (Updating the stream context)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Stream } from \"effect\"\n *\n * class Logger extends Context.Service<Logger, { prefix: string }>()(\"Logger\") {}\n * class Config extends Context.Service<Config, { name: string }>()(\"Config\") {}\n *\n * const stream = Stream.fromEffect(\n *   Effect.gen(function*() {\n *     const logger = yield* Effect.service(Logger)\n *     const config = yield* Effect.service(Config)\n *     return `${logger.prefix}${config.name}`\n *   })\n * )\n *\n * const updated = stream.pipe(\n *   Stream.updateContext((context: Context.Context<Logger>) =>\n *     Context.add(context, Config, { name: \"World\" })\n *   )\n * )\n *\n * const program = Effect.gen(function*() {\n *   const values = yield* Stream.runCollect(updated)\n *   values // => [ 'Hello World' ]\n * })\n *\n * await Effect.runPromise(\n *   Effect.provideService(program, Logger, { prefix: \"Hello \" })\n * )\n * ```\n *\n * @category providing services\n * @since 4.0.0\n */\nexport const updateContext = /*#__PURE__*/dual(2, (self, f) => fromChannel(Channel.updateContext(self.channel, f)));\n/**\n * Updates a single service in the stream environment by applying a function.\n *\n * **Example** (Updating a stream service)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Stream } from \"effect\"\n *\n * class Counter extends Context.Service<Counter, { count: number }>()(\"Counter\") {}\n *\n * const stream = Stream.fromEffect(Effect.service(Counter)).pipe(\n *   Stream.updateService(Counter, (counter) => ({ count: counter.count + 1 }))\n * )\n *\n * const program = Effect.gen(function*() {\n *   const counters = yield* Stream.runCollect(stream)\n *   const message = `Updated count: ${counters[0].count}` // => \"Updated count: 1\"\n * })\n *\n * await Effect.runPromise(Effect.provideService(program, Counter, { count: 0 }))\n * ```\n *\n * @category providing services\n * @since 2.0.0\n */\nexport const updateService = /*#__PURE__*/dual(3, (self, service, f) => updateContext(self, context => Context.add(context, service, f(Context.get(context, service)))));\n/**\n * Wraps the stream with a new span for tracing.\n *\n * **Example** (Wrapping a stream in a span)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.fromArray([1, 2, 3]).pipe(Stream.withSpan(\"numbers\"))\n *\n * await Effect.runPromise(\n *   Effect.gen(function*() {\n *     const values = yield* Stream.runCollect(stream)\n *     values // => [ 1, 2, 3 ]\n *   })\n * )\n * ```\n *\n * @category tracing\n * @since 2.0.0\n */\nexport const withSpan = function () {\n  const dataFirst = isStream(arguments[0]);\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 fromChannel(Channel.withSpan(self.channel, name, options));\n  }\n  return self => fromChannel(Channel.withSpan(self.channel, name, options));\n};\n/**\n * Provides the entry point for do-notation style stream composition.\n *\n * **Example** (Starting stream do notation)\n *\n * ```ts import.meta.vitest\n * import { Effect, pipe, Stream } from \"effect\"\n *\n * const program = pipe(\n *   Stream.Do,\n *   Stream.bind(\"value\", () => Stream.fromArray([1, 2])),\n *   Stream.let(\"next\", ({ value }) => value + 1)\n * )\n *\n * const effect = Effect.gen(function*() {\n *   const collected = yield* Stream.runCollect(program)\n *   collected // => [ { value: 1, next: 2 }, { value: 2, next: 3 } ]\n * })\n *\n * await Effect.runPromise(effect)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const Do = /*#__PURE__*/succeed({});\nconst let_ = /*#__PURE__*/dual(3, (self, name, f) => map(self, a => ({\n  ...a,\n  [name]: f(a)\n})));\nexport {\n/**\n * Adds a computed field to the current Do-notation record.\n *\n * **Example** (Adding a computed field)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.Do.pipe(\n *   Stream.let(\"x\", () => 2),\n *   Stream.let(\"y\", ({ x }) => x * 3)\n * )\n *\n * const program = Effect.gen(function*() {\n *   const records = yield* Stream.runCollect(stream)\n *   records // => [ { x: 2, y: 6 } ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nlet_ as let };\n/**\n * Binds the result of a stream to a field in the do-notation record.\n *\n * **Example** (Binding a stream value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Stream.Do.pipe(\n *   Stream.bind(\"a\", () => Stream.make(1, 2)),\n *   Stream.bind(\"b\", ({ a }) => Stream.succeed(a + 1))\n * )\n *\n * const result = Stream.runCollect(program)\n *\n * await Effect.runPromise(result) // => [{ a: 1, b: 2 }, { a: 2, b: 3 }]\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const bind = /*#__PURE__*/dual(args => isStream(args[0]), (self, tag, f, options) => flatMap(self, a => map(f(a), b => ({\n  ...a,\n  [tag]: b\n})), options));\n/**\n * Binds an Effect-produced value into the do-notation record for each stream element.\n *\n * **Example** (Binding an effect value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.Do.pipe(\n *   Stream.bind(\"value\", () => Stream.make(1, 2)),\n *   Stream.bindEffect(\"double\", ({ value }) => Effect.succeed(value * 2))\n * )\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Stream.runCollect(stream)\n *   result // => [ { value: 1, double: 2 }, { value: 2, double: 4 } ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const bindEffect = /*#__PURE__*/dual(args => isStream(args[0]), (self, tag, f, options) => mapEffect(self, a => Effect.map(f(a), b => ({\n  ...a,\n  [tag]: b\n})), options));\n/**\n * Maps each element into a record keyed by the provided name.\n *\n * **Example** (Binding values to a record key)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3).pipe(Stream.bindTo(\"value\"))\n *\n * await Effect.runPromise(Stream.runCollect(stream)) // => [{ value: 1 }, { value: 2 }, { value: 3 }]\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const bindTo = /*#__PURE__*/dual(2, (self, name) => map(self, a => ({\n  [name]: a\n})));\n/**\n * Runs a stream with a sink and returns the sink result.\n *\n * **Example** (Running a stream with a sink)\n *\n * ```ts import.meta.vitest\n * import { Effect, Sink, Stream } from \"effect\"\n *\n * const program = Stream.run(Stream.make(1, 2, 3), Sink.sum)\n *\n * await Effect.runPromise(program) // => 6\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const run = /*#__PURE__*/dual(2, (self, sink) => Effect.scopedWith(scope => Channel.toPullScoped(self.channel, scope).pipe(Effect.flatMap(upstream => sink.transform(upstream, scope)), Effect.map(([a]) => a))));\n/**\n * Runs the stream and collects all elements into an array.\n *\n * **Example** (Collecting stream values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3, 4, 5)\n *\n * const program = Effect.gen(function*() {\n *   const collected = yield* Stream.runCollect(stream)\n *   collected // => [ 1, 2, 3, 4, 5 ]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const runCollect = self => Channel.runFold(self.channel, () => [], (acc, chunk) => {\n  for (let i = 0; i < chunk.length; i++) {\n    acc.push(chunk[i]);\n  }\n  return acc;\n});\n/**\n * Runs the stream and returns the number of elements emitted.\n *\n * **Example** (Counting stream values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3, 4, 5)\n *\n * const program = Effect.gen(function* () {\n *   const count = yield* Stream.runCount(stream)\n *   count // => 5\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const runCount = self => Channel.runFold(self.channel, () => 0, (acc, chunk) => acc + chunk.length);\n/**\n * Runs the stream and returns the numeric sum of its elements.\n *\n * **Example** (Summing stream values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const total = yield* Stream.runSum(Stream.make(1, 2, 3))\n *   total // => 6\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const runSum = self => Channel.runFold(self.channel, () => 0, (acc, chunk) => {\n  for (let i = 0; i < chunk.length; i++) {\n    acc += chunk[i];\n  }\n  return acc;\n});\n/**\n * Runs the stream and folds elements using a pure reducer.\n *\n * **Example** (Folding stream values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const total = yield* Stream.runFold(\n *     Stream.make(1, 2, 3),\n *     () => 0,\n *     (acc, n) => acc + n\n *   )\n *   total // => 6\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const runFold = /*#__PURE__*/dual(3, (self, initial, f) => Channel.runFold(self.channel, initial, (acc, arr) => {\n  for (let i = 0; i < arr.length; i++) {\n    acc = f(acc, arr[i]);\n  }\n  return acc;\n}));\n/**\n * Runs the stream and folds elements using an effectful reducer.\n *\n * **When to use**\n *\n * Use when reducing stream elements needs Effects, services, or failures in the\n * reducer.\n *\n * **Example** (Effectfully folding stream values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const total = yield* Stream.runFoldEffect(\n *     Stream.make(1, 2, 3),\n *     () => 0,\n *     (acc, n) => Effect.succeed(acc + n)\n *   )\n *   total // => 6\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const runFoldEffect = /*#__PURE__*/dual(3, (self, initial, f) => Channel.runFoldEffect(self.channel, initial, (acc, arr) => {\n  let i = 0;\n  let s = acc;\n  return Effect.map(Effect.whileLoop({\n    while: () => i < arr.length,\n    body: () => f(s, arr[i]),\n    step(z) {\n      s = z;\n      i++;\n    }\n  }), () => s);\n}));\n/**\n * Runs the stream and returns the first element as an `Option`.\n *\n * **Example** (Getting the first stream value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const head = yield* Stream.runHead(Stream.make(1, 2, 3))\n *   Option.getOrThrow(head) // => 1\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const runHead = self => Effect.map(Channel.runHead(self.channel), Option.map(Arr.getUnsafe(0)));\n/**\n * Runs the stream and returns the last element as an `Option`.\n *\n * **When to use**\n *\n * Use to consume a finite stream when only the final emitted element matters.\n *\n * **Details**\n *\n * `Option.some` contains the last emitted element. `Option.none` means the\n * stream completed without emitting.\n *\n * **Gotchas**\n *\n * The returned effect waits for the stream to complete before it can produce a\n * value.\n *\n * @see {@link runHead} for consuming only the first emitted element\n * @see {@link runCollect} for collecting every emitted element\n * @see {@link runDrain} for consuming the stream while discarding emitted elements\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const runLast = self => Effect.map(Channel.runLast(self.channel), Option.map(Arr.lastNonEmpty));\n/**\n * Runs the provided effectful callback for each element of the stream.\n *\n * **Example** (Running an effect for each value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3)\n * const values: Array<string> = []\n *\n * const program = Effect.gen(function*() {\n *   yield* Stream.runForEach(stream, (n) => Effect.sync(() => values.push(`Processing: ${n}`)))\n * })\n *\n * await Effect.runPromise(program)\n * values // => [\"Processing: 1\", \"Processing: 2\", \"Processing: 3\"]\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const runForEach = /*#__PURE__*/dual(2, (self, f) => Channel.runForEach(self.channel, arr => {\n  let i = 0;\n  return Effect.whileLoop({\n    while: () => i < arr.length,\n    body: () => f(arr[i++]),\n    step: constVoid\n  });\n}));\n/**\n * Runs the stream, applying the effectful predicate to each element and\n * stopping when it returns `false`.\n *\n * **Example** (Running effects while a predicate holds)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const values: Array<number> = []\n * const program = Effect.gen(function*() {\n *   const stream = Stream.make(1, 2, 3, 4, 5)\n *\n *   yield* Stream.runForEachWhile(stream, (n) =>\n *     Effect.gen(function*() {\n *       yield* Effect.sync(() => values.push(n))\n *       return n < 3\n *     })\n *   )\n * })\n *\n * await Effect.runPromise(program)\n * values // => [1, 2, 3]\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const runForEachWhile = /*#__PURE__*/dual(2, (self, f) => Channel.runForEachWhile(self.channel, arr => {\n  let done = false;\n  let i = 0;\n  return Effect.map(Effect.whileLoop({\n    while: () => !done && i < arr.length,\n    body: () => f(arr[i]),\n    step(b) {\n      i++;\n      if (!b) done = true;\n    }\n  }), () => !done);\n}));\n/**\n * Consumes the stream in chunks, passing each non-empty array to the callback.\n *\n * **Example** (Consuming stream chunks)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3, 4, 5)\n * const chunks: Array<string> = []\n * const program = Effect.gen(function*() {\n *   yield* Stream.runForEachArray(\n *     stream,\n *     (chunk) => Effect.sync(() => chunks.push(chunk.join(\", \")))\n *   )\n * })\n *\n * await Effect.runPromise(program)\n * chunks // => [\"1, 2, 3, 4, 5\"]\n * ```\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const runForEachArray = /*#__PURE__*/dual(2, (self, f) => Channel.runForEach(self.channel, f));\n/**\n * Runs the stream for its effects, discarding emitted elements.\n *\n * **Example** (Draining a stream run)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const values: Array<number> = []\n * const program = Effect.gen(function*() {\n *   const stream = Stream.make(1, 2, 3).pipe(\n *     Stream.mapEffect((n) => Effect.sync(() => values.push(n)))\n *   )\n *\n *   yield* Stream.runDrain(stream)\n * })\n *\n * await Effect.runPromise(program)\n * values // => [1, 2, 3]\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const runDrain = self => Channel.runDrain(self.channel);\n/**\n * Returns a scoped pull for manually consuming the stream's output chunks.\n *\n * **Details**\n *\n * The pull fails with `Cause.Done` when the stream ends and with the stream\n * error on failure.\n *\n * **Example** (Creating a scoped pull)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3)\n *\n * const program = Effect.scoped(\n *   Effect.gen(function*() {\n *     const pull = yield* Stream.toPull(stream)\n *     const chunk = yield* pull\n *     chunk // => [ 1, 2, 3 ]\n *   })\n * )\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const toPull = self => Channel.toPull(self.channel);\n/**\n * Concatenates all emitted strings into a single string.\n *\n * **Example** (Joining strings from a stream)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(\"Hello\", \" \", \"World\", \"!\")\n * const program = Effect.gen(function*() {\n *   const text = yield* Stream.mkString(stream)\n *   text // => \"Hello World!\"\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const mkString = self => Channel.runFold(self.channel, () => \"\", (acc, chunk) => acc + chunk.join(\"\"));\n/**\n * Concatenates the stream's `Uint8Array` chunks into a single `ArrayBuffer`.\n *\n * **Gotchas**\n *\n * This materializes the full content in memory. The source stream must not\n * reuse or mutate emitted buffers, which are retained until collection completes.\n *\n * **Example** (Joining byte chunks into an ArrayBuffer)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const program = Stream.make(\n *   new Uint8Array([1, 2]),\n *   new Uint8Array([3, 4])\n * ).pipe(\n *   Stream.mkArrayBuffer,\n *   Effect.map((buffer) => [...new Uint8Array(buffer)])\n * )\n *\n * await Effect.runPromise(program) // => [1, 2, 3, 4]\n * ```\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const mkArrayBuffer = self => Effect.map(Channel.mkUint8Array(self.channel), bytes => bytes.buffer);\n/**\n * Concatenates the stream's `Uint8Array` chunks into a single `Uint8Array`.\n *\n * **Gotchas**\n *\n * This materializes the full content in memory. The source stream must not\n * reuse or mutate emitted buffers, which are retained until collection completes.\n *\n * **Example** (Joining Uint8Array chunks)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(new Uint8Array([1, 2]), new Uint8Array([3, 4]))\n * const program = Effect.gen(function*() {\n *   const bytes = yield* Stream.mkUint8Array(stream)\n *   const values = Array.from(bytes) // => [1, 2, 3, 4]\n * })\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const mkUint8Array = self => Channel.mkUint8Array(self.channel);\n/**\n * Converts the stream to a `ReadableStream` using the provided services.\n *\n * **When to use**\n *\n * Use when bridging to Web Streams and you already have the `Context` required\n * to run the stream outside an `Effect`.\n *\n * **Details**\n *\n * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream.\n *\n * **Example** (Converting to a ReadableStream with services)\n *\n * ```ts import.meta.vitest\n * import { Context, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3, 4, 5)\n * const readableStream = Stream.toReadableStreamWith(stream, Context.empty())\n * const values = await Array.fromAsync(readableStream)\n * values // => [ 1, 2, 3, 4, 5 ]\n * ```\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const toReadableStreamWith = /*#__PURE__*/dual(args => isStream(args[0]), (self, context, options) => {\n  let currentResolve = undefined;\n  let fiber = undefined;\n  const latch = Latch.makeUnsafe(false);\n  return new ReadableStream({\n    start(controller) {\n      fiber = Effect.runFork(Effect.provideContext(runForEachArray(self, chunk => latch.whenOpen(Effect.sync(() => {\n        latch.closeUnsafe();\n        for (let i = 0; i < chunk.length; i++) {\n          controller.enqueue(chunk[i]);\n        }\n        currentResolve();\n        currentResolve = undefined;\n      }))), context));\n      fiber.addObserver(exit => {\n        if (exit._tag === \"Failure\") {\n          controller.error(Cause.squash(exit.cause));\n        } else {\n          controller.close();\n        }\n      });\n    },\n    pull() {\n      return new Promise(resolve => {\n        currentResolve = resolve;\n        latch.openUnsafe();\n      });\n    },\n    cancel() {\n      if (!fiber) return;\n      return Effect.runPromise(Effect.asVoid(Fiber.interrupt(fiber)));\n    }\n  }, options?.strategy);\n});\n/**\n * Converts a stream to a `ReadableStream`.\n *\n * **Details**\n *\n * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream.\n *\n * **Example** (Converting a stream to a ReadableStream)\n *\n * ```ts import.meta.vitest\n * import { Stream } from \"effect\"\n *\n * const readableStream = Stream.toReadableStream(Stream.make(1, 2, 3))\n * const values = await Array.fromAsync(readableStream)\n * values // => [ 1, 2, 3 ]\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const toReadableStream = /*#__PURE__*/dual(args => isStream(args[0]), (self, options) => toReadableStreamWith(self, Context.empty(), options));\n/**\n * Creates an Effect that builds a ReadableStream from the stream.\n *\n * **When to use**\n *\n * Use when bridging to Web Streams from inside an `Effect` so the required\n * services can be captured from the current context.\n *\n * **Details**\n *\n * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream.\n *\n * **Example** (Creating a ReadableStream effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3, 4, 5)\n *\n * const effect = Effect.gen(function*() {\n *   const readableStream = yield* Stream.toReadableStreamEffect(stream)\n *   readableStream instanceof ReadableStream // => true\n * })\n *\n * await Effect.runPromise(effect)\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const toReadableStreamEffect = /*#__PURE__*/dual(args => isStream(args[0]), (self, options) => Effect.map(Effect.context(), context => toReadableStreamWith(self, context, options)));\n/**\n * Converts the stream to an `AsyncIterable` using the provided services.\n *\n * **When to use**\n *\n * Use when converting outside an Effect and you already have the `Context`\n * needed to run the stream.\n *\n * **Example** (Converting to an AsyncIterable with services)\n *\n * ```ts import.meta.vitest\n * import { Context, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3)\n * const iterable = Stream.toAsyncIterableWith(stream, Context.empty())\n *\n * await Array.fromAsync(iterable) // => [1, 2, 3]\n * ```\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const toAsyncIterableWith = /*#__PURE__*/dual(2, (self, context) => ({\n  [Symbol.asyncIterator]() {\n    const runPromise = Effect.runPromiseWith(context);\n    const runFork = Effect.runForkWith(context);\n    const scope = Scope.makeUnsafe();\n    let pull;\n    let currentIter;\n    let currentFiber;\n    let closePromise;\n    const close = exit => {\n      if (closePromise) return closePromise;\n      const fiber = currentFiber;\n      closePromise = runPromise(Effect.as(Effect.andThen(fiber ? Fiber.interrupt(fiber) : Effect.void, Scope.close(scope, exit)), {\n        done: true,\n        value: undefined\n      }));\n      return closePromise;\n    };\n    const closeAndReportError = async exit => {\n      try {\n        await close(exit);\n      } catch (error) {\n        await runPromise(Effect.logError(\"Suppressed error while closing Stream async iterator\", error));\n      }\n    };\n    return {\n      async next() {\n        if (closePromise) return closePromise;\n        if (currentIter) {\n          const next = currentIter.next();\n          if (!next.done) return next;\n          currentIter = undefined;\n        }\n        const fiber = runFork(pull ?? Effect.flatMap(Channel.toPullScoped(self.channel, scope), nextPull => {\n          pull = nextPull;\n          return nextPull;\n        }));\n        currentFiber = fiber;\n        const exit = await runPromise(Fiber.await(fiber));\n        if (currentFiber === fiber) {\n          currentFiber = undefined;\n        }\n        if (Exit.isSuccess(exit)) {\n          currentIter = exit.value[Symbol.iterator]();\n          return currentIter.next();\n        } else if (Pull.isDoneCause(exit.cause)) {\n          return close(Exit.void);\n        }\n        if (closePromise && Cause.hasInterruptsOnly(exit.cause)) {\n          return closePromise;\n        }\n        await closeAndReportError(exit);\n        throw Cause.squash(exit.cause);\n      },\n      return() {\n        return close(Exit.void);\n      },\n      async throw(error) {\n        await closeAndReportError(Exit.die(error));\n        throw error;\n      }\n    };\n  }\n}));\n/**\n * Creates an effect that yields an `AsyncIterable` using the current services.\n *\n * **When to use**\n *\n * Use when the `AsyncIterable` should be created inside Effect with the current\n * context supplying the stream's services.\n *\n * **Example** (Creating an AsyncIterable effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3)\n *\n * const program = Effect.gen(function*() {\n *   const iterable = yield* Stream.toAsyncIterableEffect(stream)\n *   return yield* Effect.promise(() => Array.fromAsync(iterable))\n * })\n *\n * await Effect.runPromise(program) // => [1, 2, 3]\n * ```\n *\n * @category destructors\n * @since 3.15.0\n */\nexport const toAsyncIterableEffect = self => Effect.map(Effect.context(), context => toAsyncIterableWith(self, context));\n/**\n * Converts a stream to an `AsyncIterable` for `for await...of` consumption.\n *\n * **Example** (Converting to an async iterable)\n *\n * ```ts import.meta.vitest\n * import { Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3)\n *\n * await Array.fromAsync(Stream.toAsyncIterable(stream)) // => [1, 2, 3]\n * ```\n *\n * @category destructors\n * @since 3.15.0\n */\nexport const toAsyncIterable = self => toAsyncIterableWith(self, Context.empty());\n/**\n * Runs the stream, publishing elements into the provided PubSub.\n *\n * **Details**\n *\n * `shutdownOnEnd` controls whether the PubSub is shut down when the stream ends.\n * It only shuts down when set to `true`.\n *\n * **Example** (Running a stream into a PubSub)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub, Stream } from \"effect\"\n *\n * const program = Effect.scoped(Effect.gen(function* () {\n *   const pubsub = yield* PubSub.unbounded<number>()\n *   const subscription = yield* PubSub.subscribe(pubsub)\n *\n *   yield* Stream.runIntoPubSub(Stream.fromIterable([1, 2]), pubsub)\n *\n *   const first = yield* PubSub.take(subscription)\n *   const second = yield* PubSub.take(subscription)\n *\n *   first // => 1\n *   second // => 2\n * }))\n *\n * await Effect.runPromise(program)\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const runIntoPubSub = /*#__PURE__*/dual(args => isStream(args[0]), (self, pubsub, options) => Channel.runIntoPubSubArray(self.channel, pubsub, options));\n/**\n * Converts a stream to a PubSub of emitted values for concurrent consumption.\n *\n * **Details**\n *\n * `shutdownOnEnd` indicates whether the PubSub should be shut down when the\n * stream ends. By default this is `true`.\n *\n * **Example** (Converting a stream to a PubSub for concurrent consumption)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub, Stream } from \"effect\"\n *\n * const program = Effect.scoped(Effect.gen(function* () {\n *   const pubsub = yield* Stream.fromArray([1, 2]).pipe(\n *     Stream.toPubSub({ capacity: 8 })\n *   )\n *   const subscription = yield* PubSub.subscribe(pubsub)\n *   const first = yield* PubSub.take(subscription)\n *\n *   first // => 1\n * }))\n * await Effect.runPromise(program)\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const toPubSub = /*#__PURE__*/dual(2, (self, options) => Channel.toPubSubArray(self.channel, options));\n/**\n * Converts a stream to a PubSub of `Take` values for concurrent consumption.\n *\n * **Details**\n *\n * `Take` values include the stream's end and failure signals.\n *\n * **Example** (Converting to a PubSub of takes)\n *\n * ```ts import.meta.vitest\n * import { Effect, PubSub, Stream } from \"effect\"\n *\n * const program = Effect.gen(function* () {\n *   const pubsub = yield* Stream.fromArray([1, 2, 3]).pipe(\n *     Stream.toPubSubTake({ capacity: 8 })\n *   )\n *   const subscription = yield* PubSub.subscribe(pubsub)\n *   const take = yield* PubSub.take(subscription)\n *\n *   if (Array.isArray(take)) {\n *     take // => [ 1, 2, 3 ]\n *   }\n * })\n * await Effect.runPromise(Effect.scoped(program))\n * ```\n *\n * @category destructors\n * @since 4.0.0\n */\nexport const toPubSubTake = /*#__PURE__*/dual(2, (self, options) => Channel.toPubSubTake(self.channel, options));\n/**\n * Creates a scoped dequeue that is fed by the stream for concurrent\n * consumption.\n *\n * **Details**\n *\n * Elements are offered to the queue as the stream runs. Stream completion is\n * signaled with `Cause.Done`, stream failures fail the queue, and the queue is\n * shut down when the surrounding scope closes.\n *\n * **Example** (Converting a stream to a Queue for concurrent consumption)\n *\n * ```ts import.meta.vitest\n * import { Effect, Queue, Stream } from \"effect\"\n *\n * const program = Effect.gen(function* () {\n *   const queue = yield* Stream.toQueue(Stream.fromIterable([1, 2, 3]), { capacity: 8 })\n *   const chunk = yield* Queue.takeBetween(queue, 1, 3)\n *   chunk // => [ 1, 2, 3 ]\n * })\n * await Effect.runPromise(Effect.scoped(program))\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const toQueue = /*#__PURE__*/dual(2, (self, options) => Channel.toQueueArray(self.channel, options));\n/**\n * Runs the stream, offering each element to the provided queue and ending it\n * with `Cause.Done` when the stream completes.\n *\n * **Example** (Running a stream into a queue)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Queue, Stream } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* Queue.bounded<number, Cause.Done>(4)\n *\n *   yield* Effect.forkChild(\n *     Stream.runIntoQueue(Stream.fromIterable([1, 2, 3]), queue)\n *   )\n *\n *   const values = [\n *     yield* Queue.take(queue),\n *     yield* Queue.take(queue),\n *     yield* Queue.take(queue)\n *   ]\n *   const done = yield* Effect.flip(Queue.take(queue))\n *\n *   values // => [ 1, 2, 3 ]\n *   done._tag === \"Done\" // => true\n * })\n * await Effect.runPromise(program)\n * ```\n *\n * @category destructors\n * @since 2.0.0\n */\nexport const runIntoQueue = /*#__PURE__*/dual(2, (self, queue) => Channel.runIntoQueueArray(self.channel, queue));\n//# sourceMappingURL=Stream.js.map","/**\n * Defines the portable file system service for Effect programs.\n *\n * `FileSystem` is the boundary between Effect code and the host file system.\n * Platform packages provide concrete layers, while this module defines the\n * operations for reading, writing, inspecting, streaming, and watching files.\n * Operations return `Effect`, `Stream`, or `Sink` values and fail with\n * `PlatformError`. The module also includes file handles, open flags, watch\n * events, and the watch backend service.\n *\n * @since 4.0.0\n */\nimport * as Arr from \"./Array.js\";\nimport * as ByteSize from \"./ByteSize.js\";\nimport * as Cause from \"./Cause.js\";\nimport * as Context from \"./Context.js\";\nimport * as Effect from \"./Effect.js\";\nimport { pipe } from \"./Function.js\";\nimport * as Layer from \"./Layer.js\";\nimport * as Option from \"./Option.js\";\nimport { badArgument, systemError } from \"./PlatformError.js\";\nimport { hasProperty } from \"./Predicate.js\";\nimport * as Sink from \"./Sink.js\";\nimport * as Stream from \"./Stream.js\";\nconst TypeId = \"~effect/FileSystem\";\n/**\n * Service tag for platform file-system operations.\n *\n * **When to use**\n *\n * Use to access or provide operations for files, directories, permissions,\n * streams, and sinks through the Effect context.\n *\n * **Details**\n *\n * This key is used to provide and access the FileSystem service in the Effect context.\n *\n * **Example** (Accessing and providing FileSystem)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem } from \"effect\"\n *\n * const customFs = FileSystem.makeNoop({\n *   exists: () => Effect.succeed(true),\n *   readFileString: () => Effect.succeed(\"contents\")\n * })\n *\n * // Access the FileSystem service\n * const program = Effect.gen(function*() {\n *   const fs = yield* FileSystem.FileSystem\n *\n *   const exists = yield* fs.exists(\"./data.txt\")\n *   return exists ? yield* fs.readFileString(\"./data.txt\") : undefined\n * })\n *\n * const withCustomFs = Effect.provideService(\n *   program,\n *   FileSystem.FileSystem,\n *   customFs\n * )\n * Effect.runSync(withCustomFs) // => \"contents\"\n * ```\n *\n * @category services\n * @since 4.0.0\n */\nexport const FileSystem = /*#__PURE__*/Context.Service(\"effect/FileSystem\");\n/**\n * Creates a FileSystem implementation from a partial implementation.\n *\n * **When to use**\n *\n * Use to build a concrete `FileSystem` service from platform-specific core\n * operations while deriving the convenience methods that can be implemented\n * from them.\n *\n * **Details**\n *\n * This function takes a partial FileSystem implementation and automatically provides\n * default implementations for `exists`, `readFileString`, `stream`, `sink`, and\n * `writeFileString` methods based on the provided core methods.\n *\n * @see {@link makeNoop} for a testing stub that accepts method overrides without requiring a complete implementation\n * @see {@link layerNoop} for providing a no-op `FileSystem` as a `Layer` in tests\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = impl => FileSystem.of({\n  ...impl,\n  [TypeId]: TypeId,\n  exists: path => pipe(impl.access(path), Effect.as(true), Effect.catchTag(\"PlatformError\", e => e.reason._tag === \"NotFound\" ? Effect.succeed(false) : Effect.fail(e))),\n  readFileString: (path, encoding) => Effect.flatMap(impl.readFile(path), _ => Effect.try({\n    try: () => new TextDecoder(encoding).decode(_),\n    catch: cause => badArgument({\n      module: \"FileSystem\",\n      method: \"readFileString\",\n      description: \"invalid encoding\",\n      cause\n    })\n  })),\n  stream: Effect.fnUntraced(function* (path, options) {\n    const file = yield* impl.open(path, {\n      flag: \"r\"\n    });\n    const offset = options?.offset === undefined ? undefined : ByteSize.fromInputUnsafe(options.offset);\n    if (offset) {\n      yield* file.seek(offset, \"start\");\n    }\n    const bytesToRead = options?.bytesToRead === undefined ? undefined : ByteSize.fromInputUnsafe(options.bytesToRead);\n    let totalBytesRead = BigInt(0);\n    // Validate chunk sizes even for zero-byte reads.\n    const chunkSize = Number(BigInt(options?.chunkSize ?? 64 * 1024));\n    const readChunk = file.readAlloc(chunkSize);\n    return Stream.fromPull(Effect.succeed(Effect.flatMap(Effect.suspend(() => {\n      if (bytesToRead !== undefined && bytesToRead <= totalBytesRead) {\n        return Cause.done();\n      }\n      return bytesToRead !== undefined && bytesToRead - totalBytesRead < chunkSize ? file.readAlloc(Number(bytesToRead - totalBytesRead)) : readChunk;\n    }), Option.match({\n      onNone: () => Cause.done(),\n      onSome: buf => {\n        totalBytesRead += BigInt(buf.length);\n        return Effect.succeed(Arr.of(buf));\n      }\n    }))));\n  }, Stream.unwrap),\n  sink: (path, options) => pipe(impl.open(path, {\n    ...options,\n    flag: options?.flag ?? \"w\"\n  }), Effect.map(file => Sink.forEach(_ => file.writeAll(_))), Sink.unwrap),\n  writeFileString: (path, data, options) => Effect.flatMap(Effect.try({\n    try: () => new TextEncoder().encode(data),\n    catch: cause => badArgument({\n      module: \"FileSystem\",\n      method: \"writeFileString\",\n      description: \"could not encode string\",\n      cause\n    })\n  }), _ => impl.writeFile(path, _, options))\n});\nconst notFound = (method, path) => systemError({\n  module: \"FileSystem\",\n  method,\n  _tag: \"NotFound\",\n  description: \"No such file or directory\",\n  pathOrDescriptor: path\n});\n/**\n * Creates a stub `FileSystem` implementation for tests.\n *\n * **Details**\n *\n * By default, `exists` returns `false`, `remove` succeeds, many file operations\n * fail with `PlatformError` `NotFound`, and temporary-directory/file operations\n * die as not implemented. Pass method overrides to provide the behavior needed\n * by a specific test without touching the real file system.\n *\n * **Example** (Creating a no-op FileSystem)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, PlatformError } from \"effect\"\n *\n * // Create a test filesystem that only allows reading specific files\n * const testFs = FileSystem.makeNoop({\n *   readFileString: (path) => {\n *     if (path === \"test-config.json\") {\n *       return Effect.succeed(\"{\\\"test\\\": true}\")\n *     }\n *     return Effect.fail(\n *       PlatformError.systemError({\n *         _tag: \"NotFound\",\n *         module: \"FileSystem\",\n *         method: \"readFileString\",\n *         description: \"File not found\",\n *         pathOrDescriptor: path\n *       })\n *     )\n *   },\n *   exists: (path) => Effect.succeed(path === \"test-config.json\")\n * })\n *\n * // Use in tests\n * const program = Effect.gen(function*() {\n *   const content = yield* testFs.readFileString(\"test-config.json\")\n *   return content\n * })\n *\n * // Test with the no-op filesystem\n * const testProgram = Effect.provideService(\n *   program,\n *   FileSystem.FileSystem,\n *   testFs\n * )\n * Effect.runSync(testProgram) // => \"{\\\"test\\\": true}\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeNoop = fileSystem => FileSystem.of({\n  [TypeId]: TypeId,\n  access(path) {\n    return Effect.fail(notFound(\"access\", path));\n  },\n  chmod(path) {\n    return Effect.fail(notFound(\"chmod\", path));\n  },\n  chown(path) {\n    return Effect.fail(notFound(\"chown\", path));\n  },\n  copy(path) {\n    return Effect.fail(notFound(\"copy\", path));\n  },\n  copyFile(path) {\n    return Effect.fail(notFound(\"copyFile\", path));\n  },\n  glob(pattern) {\n    return Effect.fail(notFound(\"glob\", pattern));\n  },\n  exists() {\n    return Effect.succeed(false);\n  },\n  link(path) {\n    return Effect.fail(notFound(\"link\", path));\n  },\n  makeDirectory() {\n    return Effect.die(\"not implemented\");\n  },\n  makeTempDirectory() {\n    return Effect.die(\"not implemented\");\n  },\n  makeTempDirectoryScoped() {\n    return Effect.die(\"not implemented\");\n  },\n  makeTempFile() {\n    return Effect.die(\"not implemented\");\n  },\n  makeTempFileScoped() {\n    return Effect.die(\"not implemented\");\n  },\n  open(path) {\n    return Effect.fail(notFound(\"open\", path));\n  },\n  readDirectory(path) {\n    return Effect.fail(notFound(\"readDirectory\", path));\n  },\n  readFile(path) {\n    return Effect.fail(notFound(\"readFile\", path));\n  },\n  readFileString(path) {\n    return Effect.fail(notFound(\"readFileString\", path));\n  },\n  readLink(path) {\n    return Effect.fail(notFound(\"readLink\", path));\n  },\n  realPath(path) {\n    return Effect.fail(notFound(\"realPath\", path));\n  },\n  remove() {\n    return Effect.void;\n  },\n  rename(oldPath) {\n    return Effect.fail(notFound(\"rename\", oldPath));\n  },\n  sink(path) {\n    return Sink.fail(notFound(\"sink\", path));\n  },\n  stat(path) {\n    return Effect.fail(notFound(\"stat\", path));\n  },\n  stream(path) {\n    return Stream.fail(notFound(\"stream\", path));\n  },\n  symlink(fromPath) {\n    return Effect.fail(notFound(\"symlink\", fromPath));\n  },\n  truncate(path) {\n    return Effect.fail(notFound(\"truncate\", path));\n  },\n  utimes(path) {\n    return Effect.fail(notFound(\"utimes\", path));\n  },\n  watch(path) {\n    return Stream.fail(notFound(\"watch\", path));\n  },\n  writeFile(path) {\n    return Effect.fail(notFound(\"writeFile\", path));\n  },\n  writeFileString(path) {\n    return Effect.fail(notFound(\"writeFileString\", path));\n  },\n  ...fileSystem\n});\n/**\n * Creates a Layer that provides a no-op FileSystem implementation for testing.\n *\n * **Details**\n *\n * This is a convenience function that wraps `makeNoop` in a Layer, making it easy\n * to provide the test filesystem to your Effect programs.\n *\n * **Example** (Providing a no-op FileSystem layer)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem } from \"effect\"\n *\n * // Create a test layer with specific behaviors\n * const testLayer = FileSystem.layerNoop({\n *   readFileString: (path) => Effect.succeed(\"mocked content\"),\n *   exists: () => Effect.succeed(true)\n * })\n *\n * const program = Effect.gen(function*() {\n *   const fs = yield* FileSystem.FileSystem\n *   const content = yield* fs.readFileString(\"any-file.txt\")\n *   return content\n * })\n *\n * // Provide the test layer\n * const testProgram = Effect.provide(program, testLayer)\n * Effect.runSync(testProgram) // => \"mocked content\"\n * ```\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerNoop = fileSystem => Layer.succeed(FileSystem)(makeNoop(fileSystem));\n/**\n * Runtime type identifier attached to `FileSystem.File` handles and used by\n * `isFile` to recognize them.\n *\n * **Details**\n *\n * This marker is part of the runtime representation of file handles. Prefer\n * `isFile` when narrowing unknown values.\n *\n * @see {@link File} for the open file handle shape that carries this marker\n * @see {@link isFile} for the public guard that checks this marker\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const FileTypeId = \"~effect/FileSystem/File\";\n/**\n * Returns `true` if a value is a `File` handle by checking for the\n * `FileTypeId` marker.\n *\n * **When to use**\n *\n * Use when accepting an unknown value and you need to narrow it to a `File`\n * before calling file-handle operations.\n *\n * **Details**\n *\n * This is a structural marker check. It does not validate the marker value or\n * the shape of the file handle.\n *\n * @see {@link File} for the file-handle interface narrowed by this guard\n * @see {@link FileTypeId} for the runtime marker checked by this guard\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isFile = u => hasProperty(u, FileTypeId);\n/**\n * Service key for file system watch backend implementations.\n *\n * **Details**\n *\n * This service provides the low-level file watching capabilities that can be\n * implemented differently on various platforms (e.g., inotify on Linux,\n * FSEvents on macOS, etc.).\n *\n * **Example** (Providing a custom watch backend)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Option, Stream } from \"effect\"\n *\n * // Custom watch backend implementation\n * const customWatchBackend = {\n *   register: (path: string, stat: FileSystem.File.Info) => {\n *     // Implementation would depend on platform\n *     return Option.some(Stream.empty) // Placeholder implementation\n *   }\n * }\n *\n * const program = Effect.gen(function*() {\n *   const backend = yield* FileSystem.WatchBackend\n *   return Option.isSome(\n *     backend.register(\"./directory\", { type: \"Directory\" } as FileSystem.File.Info)\n *   )\n * })\n *\n * const withCustomBackend = Effect.provideService(\n *   program,\n *   FileSystem.WatchBackend,\n *   customWatchBackend\n * )\n * Effect.runSync(withCustomBackend) // => true\n * ```\n *\n * @category services\n * @since 4.0.0\n */\nexport class WatchBackend extends /*#__PURE__*/Context.Service()(\"effect/FileSystem/WatchBackend\") {}\n//# sourceMappingURL=FileSystem.js.map","/**\n * Provides path operations through the Effect environment.\n *\n * The `Path` service works with file system paths without tying code to one\n * concrete platform module. It exposes common operations such as joining,\n * normalizing, parsing, formatting, resolving, and converting paths to or from\n * file URLs. This module includes the service interface, parsed path type,\n * service tag, runtime marker, and built-in POSIX path layer.\n *\n * @since 4.0.0\n */\nimport * as Context from \"./Context.js\";\nimport * as Effect from \"./Effect.js\";\nimport { identity } from \"./Function.js\";\nimport * as Layer from \"./Layer.js\";\nimport { BadArgument } from \"./PlatformError.js\";\n/**\n * Runtime type identifier used to mark implementations of the `Path` service.\n *\n * **Details**\n *\n * The marker is the exact string stored on `Path` service implementations.\n * Most code should depend on the `Path` service instead of inspecting this\n * value directly.\n *\n * @see {@link layer} for the built-in POSIX `Path` service layer\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const TypeId = \"~effect/Path\";\n/**\n * Service tag for accessing the current `Path` implementation.\n *\n * **When to use**\n *\n * Use when you need path operations supplied by an effect's environment.\n *\n * **Example** (Providing a custom Path service)\n *\n * ```ts import.meta.vitest\n * import { Effect, Layer, Path } from \"effect\"\n *\n * // Create a custom path implementation\n * const customPath: Path.Path = {\n *   [Path.TypeId]: Path.TypeId,\n *   sep: \"/\",\n *   basename: (path: string, suffix?: string) => {\n *     const base = path.split(\"/\").pop() || \"\"\n *     return suffix && base.endsWith(suffix)\n *       ? base.slice(0, -suffix.length)\n *       : base\n *   },\n *   dirname: (path: string) => path.split(\"/\").slice(0, -1).join(\"/\") || \"/\",\n *   extname: (path: string) => {\n *     const match = path.match(/\\.[^.]*$/)\n *     return match ? match[0] : \"\"\n *   },\n *   format: (pathObject) => {\n *     const dir = pathObject.dir || \"\"\n *     const name = pathObject.name || \"\"\n *     const ext = pathObject.ext || \"\"\n *     return dir ? `${dir}/${name}${ext}` : `${name}${ext}`\n *   },\n *   fromFileUrl: (url: URL) => Effect.succeed(url.pathname),\n *   isAbsolute: (path: string) => path.startsWith(\"/\"),\n *   join: (...paths: ReadonlyArray<string>) => paths.join(\"/\"),\n *   normalize: (path: string) => path.replace(/\\/+/g, \"/\"),\n *   parse: (path: string) => ({\n *     root: path.startsWith(\"/\") ? \"/\" : \"\",\n *     dir: path.split(\"/\").slice(0, -1).join(\"/\") || \"/\",\n *     base: path.split(\"/\").pop() || \"\",\n *     ext: path.match(/\\.[^.]*$/)?.[0] || \"\",\n *     name: path.split(\"/\").pop()?.replace(/\\.[^.]*$/, \"\") || \"\"\n *   }),\n *   relative: (from: string, to: string) => to.replace(from, \"\"),\n *   resolve: (...pathSegments: ReadonlyArray<string>) => pathSegments.join(\"/\"),\n *   toFileUrl: (path: string) => Effect.succeed(new URL(`file://${path}`)),\n *   toNamespacedPath: (path: string) => path\n * }\n *\n * // Provide the path service\n * const customPathLayer = Layer.succeed(Path.Path)(customPath)\n *\n * const program = Effect.gen(function*() {\n *   const path = yield* Path.Path\n *   return path.join(\"home\", \"user\", \"file.txt\")\n * })\n *\n * // Run with custom path implementation\n * Effect.runSync(Effect.provide(program, customPathLayer)) // => \"home/user/file.txt\"\n * ```\n *\n * @category services\n * @since 4.0.0\n */\nexport const Path = /*#__PURE__*/Context.Service(\"effect/Path\");\n/**\n * The following functions are adapted from the Node.js source code:\n * https://github.com/nodejs/node/blob/main/lib/internal/url.js\n *\n * The following license applies to these functions:\n * - MIT\n */\n// Resolves . and .. elements in a path with directory names\nfunction normalizeStringPosix(path, allowAboveRoot) {\n  let res = \"\";\n  let lastSegmentLength = 0;\n  let lastSlash = -1;\n  let dots = 0;\n  let code;\n  for (let i = 0; i <= path.length; ++i) {\n    if (i < path.length) {\n      code = path.charCodeAt(i);\n    } else if (code === 47 /*/*/) {\n      break;\n    } else {\n      code = 47; /*/*/\n    }\n    if (code === 47 /*/*/) {\n      if (lastSlash === i - 1 || dots === 1) {\n        // NOOP\n      } else if (lastSlash !== i - 1 && dots === 2) {\n        if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 /*.*/ || res.charCodeAt(res.length - 2) !== 46 /*.*/) {\n          if (res.length > 2) {\n            const lastSlashIndex = res.lastIndexOf(\"/\");\n            if (lastSlashIndex !== res.length - 1) {\n              if (lastSlashIndex === -1) {\n                res = \"\";\n                lastSegmentLength = 0;\n              } else {\n                res = res.slice(0, lastSlashIndex);\n                lastSegmentLength = res.length - 1 - res.lastIndexOf(\"/\");\n              }\n              lastSlash = i;\n              dots = 0;\n              continue;\n            }\n          } else if (res.length === 2 || res.length === 1) {\n            res = \"\";\n            lastSegmentLength = 0;\n            lastSlash = i;\n            dots = 0;\n            continue;\n          }\n        }\n        if (allowAboveRoot) {\n          if (res.length > 0) {\n            res += \"/..\";\n          } else {\n            res = \"..\";\n          }\n          lastSegmentLength = 2;\n        }\n      } else {\n        if (res.length > 0) {\n          res += \"/\" + path.slice(lastSlash + 1, i);\n        } else {\n          res = path.slice(lastSlash + 1, i);\n        }\n        lastSegmentLength = i - lastSlash - 1;\n      }\n      lastSlash = i;\n      dots = 0;\n    } else if (code === 46 /*.*/ && dots !== -1) {\n      ++dots;\n    } else {\n      dots = -1;\n    }\n  }\n  return res;\n}\nfunction _format(sep, pathObject) {\n  const dir = pathObject.dir || pathObject.root;\n  const base = pathObject.base || (pathObject.name || \"\") + (pathObject.ext || \"\");\n  if (!dir) {\n    return base;\n  }\n  if (dir === pathObject.root) {\n    return dir + base;\n  }\n  return dir + sep + base;\n}\nfunction fromFileUrl(url) {\n  if (url.protocol !== \"file:\") {\n    return Effect.fail(new BadArgument({\n      module: \"Path\",\n      method: \"fromFileUrl\",\n      description: \"URL must be of scheme file\"\n    }));\n  } else if (url.hostname !== \"\") {\n    return Effect.fail(new BadArgument({\n      module: \"Path\",\n      method: \"fromFileUrl\",\n      description: \"Invalid file URL host\"\n    }));\n  }\n  const pathname = url.pathname;\n  for (let n = 0; n < pathname.length; n++) {\n    if (pathname[n] === \"%\") {\n      const third = pathname.codePointAt(n + 2) | 0x20;\n      if (pathname[n + 1] === \"2\" && third === 102) {\n        return Effect.fail(new BadArgument({\n          module: \"Path\",\n          method: \"fromFileUrl\",\n          description: \"must not include encoded / characters\"\n        }));\n      }\n    }\n  }\n  return Effect.succeed(decodeURIComponent(pathname));\n}\nconst resolve = function resolve() {\n  let resolvedPath = \"\";\n  let resolvedAbsolute = false;\n  let cwd = undefined;\n  for (let i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n    let path;\n    if (i >= 0) {\n      path = arguments[i];\n    } else {\n      const process = globalThis.process;\n      if (cwd === undefined && \"process\" in globalThis && typeof process === \"object\" && process !== null && typeof process.cwd === \"function\") {\n        cwd = process.cwd();\n      }\n      path = cwd;\n    }\n    // Skip empty entries\n    if (path.length === 0) {\n      continue;\n    }\n    resolvedPath = path + \"/\" + resolvedPath;\n    resolvedAbsolute = path.charCodeAt(0) === 47; /*/*/\n  }\n  // At this point the path should be resolved to a full absolute path, but\n  // handle relative paths to be safe (might happen when process.cwd() fails)\n  // Normalize the path\n  resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute);\n  if (resolvedAbsolute) {\n    if (resolvedPath.length > 0) {\n      return \"/\" + resolvedPath;\n    } else {\n      return \"/\";\n    }\n  } else if (resolvedPath.length > 0) {\n    return resolvedPath;\n  } else {\n    return \".\";\n  }\n};\nconst CHAR_FORWARD_SLASH = 47;\nfunction toFileUrl(filepath) {\n  const outURL = new URL(\"file://\");\n  let resolved = resolve(filepath);\n  // path.resolve strips trailing slashes so we must add them back\n  const filePathLast = filepath.charCodeAt(filepath.length - 1);\n  if (filePathLast === CHAR_FORWARD_SLASH && resolved[resolved.length - 1] !== \"/\") {\n    resolved += \"/\";\n  }\n  outURL.pathname = encodePathChars(resolved);\n  return Effect.succeed(outURL);\n}\nconst percentRegExp = /%/g;\nconst backslashRegExp = /\\\\/g;\nconst newlineRegExp = /\\n/g;\nconst carriageReturnRegExp = /\\r/g;\nconst tabRegExp = /\\t/g;\nfunction encodePathChars(filepath) {\n  if (filepath.includes(\"%\")) {\n    filepath = filepath.replace(percentRegExp, \"%25\");\n  }\n  if (filepath.includes(\"\\\\\")) {\n    filepath = filepath.replace(backslashRegExp, \"%5C\");\n  }\n  if (filepath.includes(\"\\n\")) {\n    filepath = filepath.replace(newlineRegExp, \"%0A\");\n  }\n  if (filepath.includes(\"\\r\")) {\n    filepath = filepath.replace(carriageReturnRegExp, \"%0D\");\n  }\n  if (filepath.includes(\"\\t\")) {\n    filepath = filepath.replace(tabRegExp, \"%09\");\n  }\n  return filepath;\n}\nconst posixImpl = /*#__PURE__*/Path.of({\n  [TypeId]: TypeId,\n  resolve,\n  normalize(path) {\n    if (path.length === 0) return \".\";\n    const isAbsolute = path.charCodeAt(0) === 47; /*/*/\n    const trailingSeparator = path.charCodeAt(path.length - 1) === 47; /*/*/\n    // Normalize the path\n    path = normalizeStringPosix(path, !isAbsolute);\n    if (path.length === 0 && !isAbsolute) path = \".\";\n    if (path.length > 0 && trailingSeparator) path += \"/\";\n    if (isAbsolute) return \"/\" + path;\n    return path;\n  },\n  isAbsolute(path) {\n    return path.length > 0 && path.charCodeAt(0) === 47; /*/*/\n  },\n  join() {\n    if (arguments.length === 0) {\n      return \".\";\n    }\n    let joined;\n    for (let i = 0; i < arguments.length; ++i) {\n      const arg = arguments[i];\n      if (arg.length > 0) {\n        if (joined === undefined) {\n          joined = arg;\n        } else {\n          joined += \"/\" + arg;\n        }\n      }\n    }\n    if (joined === undefined) {\n      return \".\";\n    }\n    return posixImpl.normalize(joined);\n  },\n  relative(from, to) {\n    if (from === to) return \"\";\n    from = posixImpl.resolve(from);\n    to = posixImpl.resolve(to);\n    if (from === to) return \"\";\n    // Trim any leading backslashes\n    let fromStart = 1;\n    for (; fromStart < from.length; ++fromStart) {\n      if (from.charCodeAt(fromStart) !== 47 /*/*/) {\n        break;\n      }\n    }\n    const fromEnd = from.length;\n    const fromLen = fromEnd - fromStart;\n    // Trim any leading backslashes\n    let toStart = 1;\n    for (; toStart < to.length; ++toStart) {\n      if (to.charCodeAt(toStart) !== 47 /*/*/) {\n        break;\n      }\n    }\n    const toEnd = to.length;\n    const toLen = toEnd - toStart;\n    // Compare paths to find the longest common path from root\n    const length = fromLen < toLen ? fromLen : toLen;\n    let lastCommonSep = -1;\n    let i = 0;\n    for (; i <= length; ++i) {\n      if (i === length) {\n        if (toLen > length) {\n          if (to.charCodeAt(toStart + i) === 47 /*/*/) {\n            // We get here if `from` is the exact base path for `to`.\n            // For example: from='/foo/bar'; to='/foo/bar/baz'\n            return to.slice(toStart + i + 1);\n          } else if (i === 0) {\n            // We get here if `from` is the root\n            // For example: from='/'; to='/foo'\n            return to.slice(toStart + i);\n          }\n        } else if (fromLen > length) {\n          if (from.charCodeAt(fromStart + i) === 47 /*/*/) {\n            // We get here if `to` is the exact base path for `from`.\n            // For example: from='/foo/bar/baz'; to='/foo/bar'\n            lastCommonSep = i;\n          } else if (i === 0) {\n            // We get here if `to` is the root.\n            // For example: from='/foo'; to='/'\n            lastCommonSep = 0;\n          }\n        }\n        break;\n      }\n      const fromCode = from.charCodeAt(fromStart + i);\n      const toCode = to.charCodeAt(toStart + i);\n      if (fromCode !== toCode) {\n        break;\n      } else if (fromCode === 47 /*/*/) {\n        lastCommonSep = i;\n      }\n    }\n    let out = \"\";\n    // Generate the relative path based on the path difference between `to`\n    // and `from`\n    for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {\n      if (i === fromEnd || from.charCodeAt(i) === 47 /*/*/) {\n        if (out.length === 0) {\n          out += \"..\";\n        } else {\n          out += \"/..\";\n        }\n      }\n    }\n    // Lastly, append the rest of the destination (`to`) path that comes after\n    // the common path parts\n    if (out.length > 0) {\n      return out + to.slice(toStart + lastCommonSep);\n    } else {\n      toStart += lastCommonSep;\n      if (to.charCodeAt(toStart) === 47 /*/*/) {\n        ++toStart;\n      }\n      return to.slice(toStart);\n    }\n  },\n  dirname(path) {\n    if (path.length === 0) return \".\";\n    let code = path.charCodeAt(0);\n    const hasRoot = code === 47; /*/*/\n    let end = -1;\n    let matchedSlash = true;\n    for (let i = path.length - 1; i >= 1; --i) {\n      code = path.charCodeAt(i);\n      if (code === 47 /*/*/) {\n        if (!matchedSlash) {\n          end = i;\n          break;\n        }\n      } else {\n        // We saw the first non-path separator\n        matchedSlash = false;\n      }\n    }\n    if (end === -1) return hasRoot ? \"/\" : \".\";\n    if (hasRoot && end === 1) return \"//\";\n    return path.slice(0, end);\n  },\n  basename(path, ext) {\n    let start = 0;\n    let end = -1;\n    let matchedSlash = true;\n    let i;\n    if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {\n      if (ext.length === path.length && ext === path) return \"\";\n      let extIdx = ext.length - 1;\n      let firstNonSlashEnd = -1;\n      for (i = path.length - 1; i >= 0; --i) {\n        const code = path.charCodeAt(i);\n        if (code === 47 /*/*/) {\n          // If we reached a path separator that was not part of a set of path\n          // separators at the end of the string, stop now\n          if (!matchedSlash) {\n            start = i + 1;\n            break;\n          }\n        } else {\n          if (firstNonSlashEnd === -1) {\n            // We saw the first non-path separator, remember this index in case\n            // we need it if the extension ends up not matching\n            matchedSlash = false;\n            firstNonSlashEnd = i + 1;\n          }\n          if (extIdx >= 0) {\n            // Try to match the explicit extension\n            if (code === ext.charCodeAt(extIdx)) {\n              if (--extIdx === -1) {\n                // We matched the extension, so mark this as the end of our path\n                // component\n                end = i;\n              }\n            } else {\n              // Extension does not match, so our result is the entire path\n              // component\n              extIdx = -1;\n              end = firstNonSlashEnd;\n            }\n          }\n        }\n      }\n      if (start === end) end = firstNonSlashEnd;else if (end === -1) end = path.length;\n      return path.slice(start, end);\n    } else {\n      for (i = path.length - 1; i >= 0; --i) {\n        if (path.charCodeAt(i) === 47 /*/*/) {\n          // If we reached a path separator that was not part of a set of path\n          // separators at the end of the string, stop now\n          if (!matchedSlash) {\n            start = i + 1;\n            break;\n          }\n        } else if (end === -1) {\n          // We saw the first non-path separator, mark this as the end of our\n          // path component\n          matchedSlash = false;\n          end = i + 1;\n        }\n      }\n      if (end === -1) return \"\";\n      return path.slice(start, end);\n    }\n  },\n  extname(path) {\n    let startDot = -1;\n    let startPart = 0;\n    let end = -1;\n    let matchedSlash = true;\n    // Track the state of characters (if any) we see before our first dot and\n    // after any path separator we find\n    let preDotState = 0;\n    for (let i = path.length - 1; i >= 0; --i) {\n      const code = path.charCodeAt(i);\n      if (code === 47 /*/*/) {\n        // If we reached a path separator that was not part of a set of path\n        // separators at the end of the string, stop now\n        if (!matchedSlash) {\n          startPart = i + 1;\n          break;\n        }\n        continue;\n      }\n      if (end === -1) {\n        // We saw the first non-path separator, mark this as the end of our\n        // extension\n        matchedSlash = false;\n        end = i + 1;\n      }\n      if (code === 46 /*.*/) {\n        // If this is our first dot, mark it as the start of our extension\n        if (startDot === -1) {\n          startDot = i;\n        } else if (preDotState !== 1) {\n          preDotState = 1;\n        }\n      } else if (startDot !== -1) {\n        // We saw a non-dot and non-path separator before our dot, so we should\n        // have a good chance at having a non-empty extension\n        preDotState = -1;\n      }\n    }\n    if (startDot === -1 || end === -1 ||\n    // We saw a non-dot character immediately before the dot\n    preDotState === 0 ||\n    // The (right-most) trimmed path component is exactly '..'\n    preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {\n      return \"\";\n    }\n    return path.slice(startDot, end);\n  },\n  format: function format(pathObject) {\n    if (pathObject === null || typeof pathObject !== \"object\") {\n      throw new TypeError(\"The \\\"pathObject\\\" argument must be of type Object. Received type \" + typeof pathObject);\n    }\n    return _format(\"/\", pathObject);\n  },\n  parse(path) {\n    const ret = {\n      root: \"\",\n      dir: \"\",\n      base: \"\",\n      ext: \"\",\n      name: \"\"\n    };\n    if (path.length === 0) return ret;\n    let code = path.charCodeAt(0);\n    const isAbsolute = code === 47; /*/*/\n    let start;\n    if (isAbsolute) {\n      ret.root = \"/\";\n      start = 1;\n    } else {\n      start = 0;\n    }\n    let startDot = -1;\n    let startPart = 0;\n    let end = -1;\n    let matchedSlash = true;\n    let i = path.length - 1;\n    // Track the state of characters (if any) we see before our first dot and\n    // after any path separator we find\n    let preDotState = 0;\n    // Get non-dir info\n    for (; i >= start; --i) {\n      code = path.charCodeAt(i);\n      if (code === 47 /*/*/) {\n        // If we reached a path separator that was not part of a set of path\n        // separators at the end of the string, stop now\n        if (!matchedSlash) {\n          startPart = i + 1;\n          break;\n        }\n        continue;\n      }\n      if (end === -1) {\n        // We saw the first non-path separator, mark this as the end of our\n        // extension\n        matchedSlash = false;\n        end = i + 1;\n      }\n      if (code === 46 /*.*/) {\n        // If this is our first dot, mark it as the start of our extension\n        if (startDot === -1) startDot = i;else if (preDotState !== 1) preDotState = 1;\n      } else if (startDot !== -1) {\n        // We saw a non-dot and non-path separator before our dot, so we should\n        // have a good chance at having a non-empty extension\n        preDotState = -1;\n      }\n    }\n    if (startDot === -1 || end === -1 ||\n    // We saw a non-dot character immediately before the dot\n    preDotState === 0 ||\n    // The (right-most) trimmed path component is exactly '..'\n    preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {\n      if (end !== -1) {\n        if (startPart === 0 && isAbsolute) ret.base = ret.name = path.slice(1, end);else ret.base = ret.name = path.slice(startPart, end);\n      }\n    } else {\n      if (startPart === 0 && isAbsolute) {\n        ret.name = path.slice(1, startDot);\n        ret.base = path.slice(1, end);\n      } else {\n        ret.name = path.slice(startPart, startDot);\n        ret.base = path.slice(startPart, end);\n      }\n      ret.ext = path.slice(startDot, end);\n    }\n    if (startPart > 0) ret.dir = path.slice(0, startPart - 1);else if (isAbsolute) ret.dir = \"/\";\n    return ret;\n  },\n  sep: \"/\",\n  fromFileUrl,\n  toFileUrl,\n  toNamespacedPath: identity\n});\n/**\n * Layer that provides the built-in POSIX `Path` implementation.\n *\n * **When to use**\n *\n * Use when you need an effect that requires the `Path` service to run with the\n * built-in POSIX path implementation.\n *\n * **Details**\n *\n * The layer provides a static service whose separator is `/` and whose\n * operations use POSIX path semantics.\n *\n * @see {@link Path} for accessing the `Path` service from an effect\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.succeed(Path)(posixImpl);\n//# sourceMappingURL=Path.js.map","import { memoize } from \"../../Function.js\";\n/** @internal */\nexport function resolve(ast) {\n  return ast.checks ? ast.checks[ast.checks.length - 1].annotations : ast.annotations;\n}\n/** @internal */\nexport function resolveAt(key) {\n  return ast => resolve(ast)?.[key];\n}\n/** @internal */\nexport const STRUCTURAL_ANNOTATION_KEY = \"~structural\";\n/** @internal */\nexport const IDENTIFIER_FALLBACK_KEY = \"~identifier\";\n/** @internal */\nexport const SENTINELS_ANNOTATION_KEY = \"~sentinels\";\n/** @internal */\nexport const CONSTRUCTOR_ANNOTATION_KEY = \"~constructor\";\n/** @internal */\nexport const jsonSchemaAnnotationKeys = [\"title\", \"description\", \"default\", \"examples\", \"readOnly\", \"writeOnly\", \"format\", \"contentEncoding\", \"contentMediaType\", \"contentSchema\"];\n/** @internal */\nexport const resolveIdentifier = /*#__PURE__*/resolveAt(\"identifier\");\n/** @internal */\nexport const resolveIdentifierFallback = /*#__PURE__*/resolveAt(IDENTIFIER_FALLBACK_KEY);\n/** @internal */\nexport const resolveTitle = /*#__PURE__*/resolveAt(\"title\");\n/** @internal */\nexport const resolveDescription = /*#__PURE__*/resolveAt(\"description\");\n/** @internal */\nexport const resolveBrands = /*#__PURE__*/resolveAt(\"brands\");\n/** @internal */\nexport const getExpected = /*#__PURE__*/memoize(ast => {\n  const identifier = resolve(ast)?.identifier;\n  if (typeof identifier === \"string\") return identifier;\n  return ast.getExpected(getExpected);\n});\n/** @internal */\nexport function collectBrands(annotations) {\n  return annotations !== undefined && Array.isArray(annotations.brands) ? annotations.brands : [];\n}\n/** @internal */\nexport const annotationExcludedKeys = /*#__PURE__*/new Set([SENTINELS_ANNOTATION_KEY, STRUCTURAL_ANNOTATION_KEY, \"representation\", \"arbitraryConstraint\", \"brands\", \"toJsonSchema\", \"toCode\", \"toEquivalence\", \"toFormatter\", \"toCodec\", \"toCodecJson\", \"toCodecStringTree\", \"toCodecIso\", \"toCodecArbitrary\"]);\n//# sourceMappingURL=annotations.js.map","import * as Exit from \"../../Exit.js\";\nimport * as Option from \"../../Option.js\";\nimport { args } from \"../core.js\";\n/** @internal */\nexport const missing = /*#__PURE__*/Symbol();\n/** @internal */\nexport { args };\n/** @internal */\nexport const succeed = Exit.succeed;\n/** @internal */\nexport const missingExit = /*#__PURE__*/succeed(missing);\n// Shared success for a present input returned unchanged. It must be resolved\n// before crossing an asynchronous or transformation boundary.\n/** @internal */\nexport const sameExit = /*#__PURE__*/succeed(missing);\n/** @internal */\nexport const toOption = value => value === missing ? Option.none() : Option.some(value);\n/** @internal */\nexport const fromOptionExit = option => option._tag === \"None\" ? missingExit : succeed(option.value);\n//# sourceMappingURL=parser.js.map","/**\n * Describes problems found while decoding, encoding, or checking data with\n * schemas.\n *\n * An `Issue` records what failed and, for nested data, where the failure\n * happened. The Schema system uses these values for missing keys, unexpected\n * keys, invalid types, invalid values, failed filters, failed transformations,\n * and alternatives that did not match. This module also formats issues.\n *\n * @since 4.0.0\n */\nimport * as Arr from \"./Array.js\";\nimport { format, formatPath } from \"./Formatter.js\";\nimport * as InternalAnnotations from \"./internal/schema/annotations.js\";\nimport * as InternalParser from \"./internal/schema/parser.js\";\nimport { hasProperty } from \"./Predicate.js\";\nconst TypeId = \"~effect/SchemaIssue/Issue\";\n/**\n * Returns `true` if the given value is an {@link Issue}.\n *\n * **When to use**\n *\n * Use when you need to narrow an `unknown` value to `Issue` in error-handling\n * code, such as distinguishing an `Issue` from other error types in a catch-all\n * handler.\n *\n * **Details**\n *\n * - Checks for the internal `TypeId` brand on the value.\n *\n * **Example** (Type-guarding an unknown error)\n *\n * ```ts import.meta.vitest\n * import { SchemaIssue } from \"effect\"\n *\n * const issue = new SchemaIssue.MissingKey(undefined)\n * SchemaIssue.isIssue(issue) // => true\n * SchemaIssue.isIssue(\"not an issue\") // => false\n * ```\n *\n * @see {@link Issue}\n *\n * @category guards\n * @since 4.0.0\n */\nexport function isIssue(u) {\n  return hasProperty(u, TypeId) && u[TypeId] === TypeId;\n}\n/**\n * Returns `true` when an issue contains an input reported by the schema parser.\n *\n * **When to use**\n *\n * Use when reading `Issue.input`, especially when `undefined` is a valid input\n * value.\n *\n * **Details**\n *\n * Reported input is stored as an own property. This guard checks for that\n * property and narrows `input` from optional to required.\n *\n * **Example** (Reading a reported input)\n *\n * ```ts import.meta.vitest\n * import { Result, Schema, SchemaIssue } from \"effect\"\n *\n * const result = Schema.decodeUnknownResult(Schema.String)(1, { reportInput: true })\n * if (Result.isFailure(result) && SchemaIssue.hasInput(result.failure.issue)) {\n *   result.failure.issue.input // => 1\n * }\n * ```\n *\n * @see {@link Issue} for the complete issue model\n *\n * @category guards\n * @since 4.0.0\n */\nexport function hasInput(issue) {\n  return Object.hasOwn(issue, \"input\");\n}\nclass IssueNodeImpl {\n  [TypeId] = TypeId;\n  constructor(input, options) {\n    if (options?.reportInput === true && input !== InternalParser.missing) {\n      this.input = input;\n    }\n  }\n}\n/**\n * Constructs a schema issue for a failed refinement check.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Filter = class extends IssueNodeImpl {\n  _tag = \"Filter\";\n  /**\n   * The filter that failed.\n   */\n  filter;\n  /**\n   * The issue that occurred.\n   */\n  issue;\n  constructor(\n  /**\n   * The filter that failed.\n   */\n  filter,\n  /**\n   * The issue that occurred.\n   */\n  issue,\n  /**\n   * The present input associated with the issue. It is retained only when\n   * `options.reportInput` is `true`.\n   */\n  input,\n  /**\n   * The effective parse options controlling input retention.\n   */\n  options) {\n    super(input, options);\n    this.filter = filter;\n    this.issue = issue;\n  }\n};\n/**\n * Constructs a schema issue for a failed transformation.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Encoding = class extends IssueNodeImpl {\n  _tag = \"Encoding\";\n  /**\n   * The schema that caused the issue.\n   */\n  ast;\n  /**\n   * The issue that occurred.\n   */\n  issue;\n  constructor(\n  /**\n   * The schema that caused the issue.\n   */\n  ast,\n  /**\n   * The issue that occurred.\n   */\n  issue,\n  /**\n   * The present input associated with the issue. It is retained only when\n   * `options.reportInput` is `true`.\n   */\n  input,\n  /**\n   * The effective parse options controlling input retention.\n   */\n  options) {\n    super(input, options);\n    this.ast = ast;\n    this.issue = issue;\n  }\n};\n/**\n * Constructs a schema issue that points to a nested location.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Pointer = class extends IssueNodeImpl {\n  _tag = \"Pointer\";\n  /**\n   * The path to the location in the input that caused the issue.\n   */\n  path;\n  /**\n   * The issue that occurred.\n   */\n  issue;\n  constructor(\n  /**\n   * The path to the location in the input that caused the issue.\n   */\n  path,\n  /**\n   * The issue that occurred.\n   */\n  issue) {\n    super();\n    this.path = path;\n    this.issue = issue;\n  }\n};\n/**\n * Constructs a schema issue for a missing key or tuple index.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const MissingKey = class extends IssueNodeImpl {\n  _tag = \"MissingKey\";\n  /**\n   * The metadata for the issue.\n   */\n  annotations;\n  constructor(\n  /**\n   * The metadata for the issue.\n   */\n  annotations) {\n    super();\n    this.annotations = annotations;\n  }\n};\n/**\n * Constructs a schema issue for an unexpected key or tuple index.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const UnexpectedKey = class extends IssueNodeImpl {\n  _tag = \"UnexpectedKey\";\n  /**\n   * The schema that caused the issue.\n   */\n  ast;\n  constructor(\n  /**\n   * The schema that caused the issue.\n   */\n  ast,\n  /**\n   * The present input associated with the issue. It is retained only when\n   * `options.reportInput` is `true`.\n   */\n  input,\n  /**\n   * The effective parse options controlling input retention.\n   */\n  options) {\n    super(input, options);\n    this.ast = ast;\n  }\n};\n/**\n * Constructs a schema issue that groups multiple child issues.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Composite = class extends IssueNodeImpl {\n  _tag = \"Composite\";\n  /**\n   * The schema that caused the issue.\n   */\n  ast;\n  /**\n   * The issues that occurred.\n   */\n  issues;\n  constructor(\n  /**\n   * The schema that caused the issue.\n   */\n  ast,\n  /**\n   * The issues that occurred.\n   */\n  issues,\n  /**\n   * The present input associated with the issue. It is retained only when\n   * `options.reportInput` is `true`.\n   */\n  input,\n  /**\n   * The effective parse options controlling input retention.\n   */\n  options) {\n    super(input, options);\n    this.ast = ast;\n    this.issues = issues;\n  }\n};\n/**\n * Constructs a schema issue for an input with an invalid runtime type.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const InvalidType = class extends IssueNodeImpl {\n  _tag = \"InvalidType\";\n  /**\n   * The schema that caused the issue.\n   */\n  ast;\n  constructor(\n  /**\n   * The schema that caused the issue.\n   */\n  ast,\n  /**\n   * The present input associated with the issue. It is retained only when\n   * `options.reportInput` is `true`.\n   */\n  input,\n  /**\n   * The effective parse options controlling input retention.\n   */\n  options) {\n    super(input, options);\n    this.ast = ast;\n  }\n};\n/**\n * Constructs a schema issue for a value that violates a constraint.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const InvalidValue = class extends IssueNodeImpl {\n  _tag = \"InvalidValue\";\n  /**\n   * The metadata for the issue.\n   */\n  annotations;\n  constructor(\n  /**\n   * The metadata for the issue.\n   */\n  annotations,\n  /**\n   * The present input associated with the issue. It is retained only when\n   * `options.reportInput` is `true`.\n   */\n  input,\n  /**\n   * The effective parse options controlling input retention.\n   */\n  options) {\n    super(input, options);\n    this.annotations = annotations;\n  }\n};\n/** @internal */\nexport function makeCompositeAtKey(compositeAst, pointerKey, pointerIssue, compositeInput, parseOptions) {\n  return new Composite(compositeAst, [new Pointer([pointerKey], pointerIssue)], compositeInput, parseOptions);\n}\n/**\n * Constructs a schema issue for a forbidden parsing operation.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Forbidden = class extends IssueNodeImpl {\n  _tag = \"Forbidden\";\n  /**\n   * The metadata for the issue.\n   */\n  annotations;\n  constructor(\n  /**\n   * The metadata for the issue.\n   */\n  annotations,\n  /**\n   * The present input associated with the issue. It is retained only when\n   * `options.reportInput` is `true`.\n   */\n  input,\n  /**\n   * The effective parse options controlling input retention.\n   */\n  options) {\n    super(input, options);\n    this.annotations = annotations;\n  }\n};\n/**\n * Constructs a schema issue for a value that matches no union member.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const AnyOf = class extends IssueNodeImpl {\n  _tag = \"AnyOf\";\n  /**\n   * The schema that caused the issue.\n   */\n  ast;\n  /**\n   * The issues that occurred.\n   */\n  issues;\n  constructor(\n  /**\n   * The schema that caused the issue.\n   */\n  ast,\n  /**\n   * The issues that occurred.\n   */\n  issues,\n  /**\n   * The present input associated with the issue. It is retained only when\n   * `options.reportInput` is `true`.\n   */\n  input,\n  /**\n   * The effective parse options controlling input retention.\n   */\n  options) {\n    super(input, options);\n    this.ast = ast;\n    this.issues = issues;\n  }\n};\n/**\n * Constructs a schema issue for a value that matches multiple union members.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const OneOf = class extends IssueNodeImpl {\n  _tag = \"OneOf\";\n  /**\n   * The schema that caused the issue.\n   */\n  ast;\n  /**\n   * The schemas that were successful.\n   */\n  successes;\n  constructor(\n  /**\n   * The schema that caused the issue.\n   */\n  ast,\n  /**\n   * The schemas that were successful.\n   */\n  successes,\n  /**\n   * The present input associated with the issue. It is retained only when\n   * `options.reportInput` is `true`.\n   */\n  input,\n  /**\n   * The effective parse options controlling input retention.\n   */\n  options) {\n    super(input, options);\n    this.ast = ast;\n    this.successes = successes;\n  }\n};\nfunction makeFilterIssue(entry, input, options) {\n  if (isIssue(entry)) {\n    return entry;\n  }\n  if (typeof entry === \"string\") {\n    return new InvalidValue({\n      message: entry\n    }, input, options);\n  }\n  const inner = typeof entry.issue === \"string\" ? new InvalidValue({\n    message: entry.issue\n  }, input, options) : entry.issue;\n  return new Pointer(entry.path, inner);\n}\n/** @internal */\nexport function makeSingle(out, input, options) {\n  if (out === undefined) {\n    return undefined;\n  }\n  if (typeof out === \"boolean\") {\n    return out ? undefined : new InvalidValue(undefined, input, options);\n  }\n  return makeFilterIssue(out, input, options);\n}\n/** @internal */\nexport function normalizeFilterOutput(ast, out, input, options) {\n  if (Array.isArray(out)) {\n    if (!Arr.isReadonlyArrayNonEmpty(out)) {\n      return undefined;\n    }\n    return out.length === 1 ? makeFilterIssue(out[0], input, options) : new Composite(ast, Arr.map(out, entry => makeFilterIssue(entry, input, options)), input, options);\n  }\n  return makeSingle(out, input, options);\n}\n/**\n * Returns the built-in {@link LeafHook} used by default formatters.\n *\n * **When to use**\n *\n * Use as the default leaf renderer when customizing only the {@link CheckHook}.\n *\n * **Details**\n *\n * - Checks for a `message` annotation first; returns it if present.\n * - For `InvalidValue`, an `expected` annotation uses the standard expected\n *   value message and includes reported input when available.\n * - Otherwise generates a default message per `_tag`. When the issue reports\n *   input, the message includes its formatted value where applicable:\n *   - `InvalidType` → `\"Expected <type>\"` or `\"Expected <type>, got <input>\"`\n *   - `InvalidValue` → `\"Expected a valid value\"` or `\"Invalid data <input>\"`\n *   - `MissingKey` → `\"Missing key\"`\n *   - `UnexpectedKey` → `\"Expected no excess property\"` or\n *     `\"Unexpected key with value <input>\"`\n *   - `Forbidden` → `\"Forbidden operation\"`\n *   - `OneOf` → `\"Expected exactly one member to match\"` or\n *     `\"Expected exactly one member to match the input <input>\"`\n *\n * **Example** (Formatting Standard Schema issues with defaultLeafHook)\n *\n * ```ts import.meta.vitest\n * import { SchemaIssue } from \"effect\"\n *\n * const formatter = SchemaIssue.makeFormatterStandardSchemaV1({\n *   leafHook: SchemaIssue.defaultLeafHook\n * })\n * formatter(new SchemaIssue.MissingKey(undefined)) // => { issues: [{ path: [], message: \"Missing key\" }] }\n * ```\n *\n * @see {@link LeafHook}\n * @see {@link makeFormatterStandardSchemaV1}\n *\n * @category formatting\n * @since 4.0.0\n */\nexport const defaultLeafHook = issue => {\n  const message = findMessage(issue);\n  if (message !== undefined) return message;\n  switch (issue._tag) {\n    case \"InvalidType\":\n      return getExpectedMessage(InternalAnnotations.getExpected(issue.ast), issue);\n    case \"InvalidValue\":\n      {\n        const expected = findExpected(issue);\n        if (expected !== undefined) return getExpectedMessage(expected, issue);\n        const input = formatInput(issue);\n        return input === undefined ? \"Expected a valid value\" : `Invalid data ${input}`;\n      }\n    case \"MissingKey\":\n      return \"Missing key\";\n    case \"UnexpectedKey\":\n      {\n        const input = formatInput(issue);\n        return input === undefined ? \"Expected no excess property\" : `Unexpected key with value ${input}`;\n      }\n    case \"Forbidden\":\n      return \"Forbidden operation\";\n    case \"OneOf\":\n      {\n        const input = formatInput(issue);\n        return input === undefined ? \"Expected exactly one member to match\" : `Expected exactly one member to match the input ${input}`;\n      }\n  }\n};\n/**\n * Returns the built-in {@link CheckHook} used by default formatters.\n *\n * **When to use**\n *\n * Use as the default filter renderer when customizing only the {@link LeafHook}.\n *\n * **Details**\n *\n * - Looks for a `message` annotation on the inner issue first, then on the\n *   filter itself.\n * - Returns `undefined` when no annotation is found, causing the formatter to\n *   fall back to `\"Expected <filter>\"` or, when the filter reports input,\n *   `\"Expected <filter>, got <input>\"`.\n *\n * @see {@link CheckHook}\n * @see {@link makeFormatterStandardSchemaV1}\n *\n * @category formatting\n * @since 4.0.0\n */\nexport const defaultCheckHook = issue => findMessage(issue.issue) ?? findMessage(issue);\n/**\n * Creates a {@link Formatter} that produces a `StandardSchemaV1.FailureResult`.\n *\n * **When to use**\n *\n * Use when you need schema parse errors in\n * [Standard Schema V1](https://github.com/standard-schema/standard-schema)\n * format, optionally customizing leaf or check issue rendering.\n *\n * **Details**\n *\n * - Returns a `Formatter<StandardSchemaV1.FailureResult>`.\n * - Each leaf issue is flattened into `{ message, path }` entries.\n * - `Pointer` paths are accumulated to produce full property paths.\n * - Falls back to {@link defaultLeafHook} / {@link defaultCheckHook} when no\n *   hooks are provided.\n * - Default messages include reported input when the issue that produces the\n *   message has an `input` field. The returned Standard Schema issues do not\n *   receive an `input` field.\n *\n * **Gotchas**\n *\n * Reported input can appear inside the Standard Schema `message` string even\n * though it is not exposed as a separate property. Custom hooks control their\n * complete message and are not modified.\n *\n * **Example** (Creating a Standard Schema V1 formatter)\n *\n * ```ts import.meta.vitest\n * import { SchemaIssue } from \"effect\"\n *\n * const formatter = SchemaIssue.makeFormatterStandardSchemaV1()\n * formatter(new SchemaIssue.MissingKey(undefined)).issues[0].message // => \"Missing key\"\n * ```\n *\n * @see {@link makeFormatterDefault} — produces a plain string instead\n * @see {@link LeafHook}\n * @see {@link CheckHook}\n *\n * @category formatting\n * @since 4.0.0\n */\nexport function makeFormatterStandardSchemaV1(options) {\n  return issue => ({\n    issues: toDefaultIssues(issue, [], options?.leafHook ?? defaultLeafHook, options?.checkHook ?? defaultCheckHook)\n  });\n}\nfunction formatInput(issue) {\n  return hasInput(issue) ? format(issue.input) : undefined;\n}\nfunction findExpected(issue) {\n  const expected = issue.annotations?.expected;\n  return typeof expected === \"string\" ? expected : undefined;\n}\nfunction getExpectedMessage(expected, issue) {\n  const input = formatInput(issue);\n  return input === undefined ? `Expected ${expected}` : `Expected ${expected}, got ${input}`;\n}\nfunction toDefaultIssues(issue, path, leafHook, checkHook) {\n  switch (issue._tag) {\n    case \"Filter\":\n      {\n        const message = checkHook(issue);\n        if (message !== undefined) {\n          return [{\n            path,\n            message\n          }];\n        }\n        if (issue.issue._tag !== \"InvalidValue\") {\n          return toDefaultIssues(issue.issue, path, leafHook, checkHook);\n        }\n        const expected = findExpected(issue.issue);\n        return [{\n          path,\n          message: expected === undefined ? getExpectedMessage(formatCheck(issue.filter), issue) : getExpectedMessage(expected, issue.issue)\n        }];\n      }\n    case \"Encoding\":\n      return toDefaultIssues(issue.issue, path, leafHook, checkHook);\n    case \"Pointer\":\n      return toDefaultIssues(issue.issue, [...path, ...issue.path], leafHook, checkHook);\n    case \"Composite\":\n      return issue.issues.flatMap(issue => toDefaultIssues(issue, path, leafHook, checkHook));\n    case \"AnyOf\":\n      {\n        if (issue.issues.length === 0) {\n          return [{\n            path,\n            message: findMessage(issue) ?? getExpectedMessage(InternalAnnotations.getExpected(issue.ast), issue)\n          }];\n        }\n        return issue.issues.flatMap(issue => toDefaultIssues(issue, path, leafHook, checkHook));\n      }\n    default:\n      return [{\n        path,\n        message: leafHook(issue)\n      }];\n  }\n}\nfunction formatCheck(check) {\n  const expected = check.annotations?.expected;\n  if (typeof expected === \"string\") return expected;\n  switch (check._tag) {\n    case \"Filter\":\n      return \"<filter>\";\n    case \"FilterGroup\":\n      return check.checks.map(check => formatCheck(check)).join(\" & \");\n  }\n}\n/**\n * Creates a {@link Formatter} that converts an {@link Issue} into a\n * human-readable multi-line string.\n *\n * **When to use**\n *\n * Use when you need to format a `SchemaIssue.Issue` as error messages for\n * logging, CLI output, or developer-facing diagnostics.\n *\n * **Details**\n *\n * - Flattens the issue tree into `{ message, path }` entries using\n *   {@link defaultLeafHook} and {@link defaultCheckHook}.\n * - Includes reported input in default messages when the node producing the\n *   message has an `input` field.\n * - Each entry is rendered as `\"<message>\"` or `\"<message>\\n  at <path>\"`.\n * - Multiple entries are joined with newlines.\n *\n * **Gotchas**\n *\n * Formatting an issue can disclose input retained with `reportInput: true`.\n * Wrapper inputs are not inherited by child messages, and custom messages are\n * returned unchanged.\n *\n * **Example** (Formatting an issue as a string)\n *\n * ```ts import.meta.vitest\n * import { SchemaIssue } from \"effect\"\n *\n * const formatter = SchemaIssue.makeFormatterDefault()\n * formatter(new SchemaIssue.MissingKey(undefined)) // => \"Missing key\"\n * ```\n *\n * @see {@link makeFormatterStandardSchemaV1} — produces Standard Schema V1 format instead\n * @see {@link Formatter}\n *\n * @category formatting\n * @since 4.0.0\n */\nexport function makeFormatterDefault() {\n  return issue => formatIssue(issue, \"\");\n}\n/** @internal */\nexport const defaultFormatter = /*#__PURE__*/makeFormatterDefault();\nfunction formatIssue(issue, path) {\n  let message;\n  switch (issue._tag) {\n    case \"Filter\":\n      {\n        const annotated = defaultCheckHook(issue);\n        if (annotated !== undefined) {\n          message = annotated;\n        } else {\n          if (issue.issue._tag !== \"InvalidValue\") {\n            return formatIssue(issue.issue, path);\n          }\n          const expected = findExpected(issue.issue);\n          message = expected === undefined ? getExpectedMessage(formatCheck(issue.filter), issue) : getExpectedMessage(expected, issue.issue);\n        }\n        break;\n      }\n    case \"Encoding\":\n      return formatIssue(issue.issue, path);\n    case \"Pointer\":\n      return formatIssue(issue.issue, path + formatPath(issue.path));\n    case \"Composite\":\n    case \"AnyOf\":\n      {\n        if (issue._tag === \"Composite\" || issue.issues.length > 0) {\n          return issue.issues.map(issue => formatIssue(issue, path)).join(\"\\n\");\n        }\n        message = findMessage(issue) ?? getExpectedMessage(InternalAnnotations.getExpected(issue.ast), issue);\n        break;\n      }\n    default:\n      message = defaultLeafHook(issue);\n      break;\n  }\n  return path ? `${message}\\n  at ${path}` : message;\n}\nfunction findMessage(issue) {\n  if (issue._tag === \"Pointer\") return;\n  if (issue._tag === \"Encoding\") return findMessage(issue.issue);\n  const annotations = issue._tag === \"Filter\" ? issue.filter.annotations : \"annotations\" in issue ? issue.annotations : issue.ast.annotations;\n  const message = annotations?.[issue._tag === \"MissingKey\" ? \"messageMissingKey\" : issue._tag === \"UnexpectedKey\" ? \"messageUnexpectedKey\" : \"message\"];\n  if (typeof message === \"string\") return message;\n}\n//# sourceMappingURL=SchemaIssue.js.map","import * as Cause from \"../../Cause.js\";\nimport * as SchemaIssue from \"../../SchemaIssue.js\";\n/** @internal */\nexport function getSchemaIssue(cause) {\n  let issue;\n  for (const reason of cause.reasons) {\n    if (!Cause.isFailReason(reason) || !SchemaIssue.isIssue(reason.error)) {\n      return undefined;\n    }\n    issue ??= reason.error;\n  }\n  return issue;\n}\n/** @internal */\nexport function getSchemaIssueOrThrow(cause, message) {\n  const issue = getSchemaIssue(cause);\n  if (issue === undefined) {\n    throw new Error(message, {\n      cause\n    });\n  }\n  return issue;\n}\n//# sourceMappingURL=cause.js.map","import * as Context from \"./Context.js\";\nimport * as Effect from \"./Effect.js\";\nimport { dual, flow } from \"./Function.js\";\nimport * as Internal from \"./internal/dateTime.js\";\nimport { provideService } from \"./internal/effect.js\";\nimport * as Layer from \"./Layer.js\";\nconst TypeId = Internal.TypeId;\nconst TimeZoneTypeId = Internal.TimeZoneTypeId;\n// =============================================================================\n// guards\n// =============================================================================\n/**\n * Checks whether a value is a `DateTime`.\n *\n * **When to use**\n *\n * Use to narrow an unknown value before treating it as a `DateTime`.\n *\n * @see {@link isUtc} for narrowing a known `DateTime` to UTC\n * @see {@link isZoned} for narrowing a known `DateTime` to zoned\n *\n * @category guards\n * @since 3.6.0\n */\nexport const isDateTime = Internal.isDateTime;\n/**\n * Checks whether a value is a `TimeZone`.\n *\n * **When to use**\n *\n * Use to narrow unknown input to any `TimeZone` before passing it to APIs that\n * accept either fixed-offset or named time zones.\n *\n * @see {@link isTimeZoneOffset} for narrowing to fixed-offset time zones\n * @see {@link isTimeZoneNamed} for narrowing to named time zones\n *\n * @category guards\n * @since 3.6.0\n */\nexport const isTimeZone = Internal.isTimeZone;\n/**\n * Checks whether a value is an offset-based `TimeZone`.\n *\n * **When to use**\n *\n * Use when you need to narrow an unknown or union `TimeZone` value to the\n * fixed-offset variant before reading its offset in milliseconds.\n *\n * @see {@link isTimeZone} for checking either time zone variant\n * @see {@link isTimeZoneNamed} for narrowing to named time zones\n *\n * @category guards\n * @since 3.6.0\n */\nexport const isTimeZoneOffset = Internal.isTimeZoneOffset;\n/**\n * Checks whether a value is a named `TimeZone` (IANA time zone).\n *\n * **When to use**\n *\n * Use to narrow an unknown value to the `TimeZone.Named` variant before\n * reading named-zone fields such as `id`.\n *\n * @see {@link isTimeZone} for checking either time zone variant\n * @see {@link isTimeZoneOffset} for narrowing to fixed-offset time zones\n *\n * @category guards\n * @since 3.6.0\n */\nexport const isTimeZoneNamed = Internal.isTimeZoneNamed;\n/**\n * Checks whether a `DateTime` is a UTC `DateTime` (no time zone information).\n *\n * **When to use**\n *\n * Use to narrow a `DateTime` before passing it to code that requires a UTC\n * value without an associated time zone.\n *\n * @see {@link isZoned} for narrowing to zoned date-times\n * @see {@link match} for handling both UTC and zoned cases\n *\n * @category guards\n * @since 3.6.0\n */\nexport const isUtc = Internal.isUtc;\n/**\n * Checks whether a `DateTime` is a zoned `DateTime` (has time zone information).\n *\n * **When to use**\n *\n * Use to narrow a known `DateTime` before reading its zone or passing it to\n * APIs that require `DateTime.Zoned`.\n *\n * @see {@link isUtc} for narrowing to UTC date-times\n * @see {@link match} for handling both UTC and zoned cases\n *\n * @category guards\n * @since 3.6.0\n */\nexport const isZoned = Internal.isZoned;\n// =============================================================================\n// instances\n// =============================================================================\n/**\n * Provides an `Equivalence` for comparing two `DateTime` values for equality.\n *\n * **Details**\n *\n * Two `DateTime` values are considered equivalent if they represent the same\n * point in time, regardless of their time zone.\n *\n * **Example** (Comparing DateTime values for equivalence)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const utc = DateTime.makeUnsafe(\"2024-01-01T12:00:00Z\")\n * const zoned = DateTime.makeZonedUnsafe(\"2024-01-01T12:00:00Z\", {\n *   timeZone: \"Europe/London\"\n * })\n *\n * DateTime.Equivalence(utc, zoned) // => true\n * ```\n *\n * @category instances\n * @since 3.6.0\n */\nexport const Equivalence = Internal.Equivalence;\n/**\n * Provides an `Order` for comparing and sorting `DateTime` values.\n *\n * **Details**\n *\n * `DateTime` values are ordered by their epoch milliseconds, so earlier times\n * come before later times regardless of time zone.\n *\n * **Example** (Sorting DateTime values chronologically)\n *\n * ```ts import.meta.vitest\n * import { Array, DateTime } from \"effect\"\n *\n * const dates = [\n *   DateTime.makeUnsafe(\"2024-03-01\"),\n *   DateTime.makeUnsafe(\"2024-01-01\"),\n *   DateTime.makeUnsafe(\"2024-02-01\")\n * ]\n *\n * Array.sort(dates, DateTime.Order).map(DateTime.formatIsoDateUtc) // => [\"2024-01-01\", \"2024-02-01\", \"2024-03-01\"]\n * ```\n *\n * @category instances\n * @since 3.6.0\n */\nexport const Order = Internal.Order;\n/**\n * Returns a `DateTime` constrained between a minimum and maximum value.\n *\n * **Details**\n *\n * If the `DateTime` is before the minimum, the minimum is returned.\n * If the `DateTime` is after the maximum, the maximum is returned.\n * Otherwise, the original `DateTime` is returned.\n *\n * **Example** (Clamping DateTime values)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const min = DateTime.makeUnsafe(\"2024-01-01\")\n * const max = DateTime.makeUnsafe(\"2024-12-31\")\n * const date = DateTime.makeUnsafe(\"2025-06-15\")\n *\n * DateTime.clamp(date, { minimum: min, maximum: max }) // => DateTime.makeUnsafe(\"2024-12-31\")\n * ```\n *\n * @category ordering\n * @since 3.6.0\n */\nexport const clamp = Internal.clamp;\n// =============================================================================\n// constructors\n// =============================================================================\n/**\n * Create a `DateTime` from a `Date`.\n *\n * **Details**\n *\n * If the `Date` is invalid, an `IllegalArgumentError` will be thrown.\n *\n * **Example** (Creating DateTime values from Dates)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * DateTime.fromDateUnsafe(new Date(\"2024-01-01T12:00:00Z\")) // => DateTime.makeUnsafe(\"2024-01-01T12:00:00Z\")\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromDateUnsafe = Internal.fromDateUnsafe;\n/**\n * Create a `DateTime` from supported input values.\n *\n * **When to use**\n *\n * Use when creating a `DateTime` from trusted input and construction failures\n * should throw an `IllegalArgumentError` instead of returning `Option.none`.\n *\n * **Details**\n *\n * - A `DateTime`\n * - A `Date` instance (invalid dates will throw an `IllegalArgumentError`)\n * - The `number` of milliseconds since the Unix epoch\n * - An object with the parts of a date\n * - A `string` that can be parsed by `Date.parse`\n *\n * **Example** (Creating DateTime values unsafely)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * // from Date\n * DateTime.makeUnsafe(new Date(\"2024-01-01T12:00:00Z\")) // => DateTime.makeUnsafe(\"2024-01-01T12:00:00Z\")\n *\n * // from parts\n * DateTime.makeUnsafe({ year: 2024 }) // => DateTime.makeUnsafe(\"2024-01-01T00:00:00Z\")\n *\n * // from string\n * DateTime.makeUnsafe(\"2024-01-01\") // => DateTime.makeUnsafe(\"2024-01-01T00:00:00Z\")\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeUnsafe = Internal.makeUnsafe;\n/**\n * Creates a `DateTime.Utc` from the number of seconds since the Unix epoch.\n *\n * **Example** (Creating from epoch seconds)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * DateTime.fromEpochSeconds(1704067200).toJSON() // => \"2024-01-01T00:00:00.000Z\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromEpochSeconds = Internal.fromEpochSeconds;\n/**\n * Create a `DateTime.Zoned` using `DateTime.makeUnsafe` and a time zone.\n *\n * **When to use**\n *\n * Use when the date/time input and zone options are trusted and invalid or\n * rejected ambiguous times should throw instead of returning `Option.none`.\n *\n * **Details**\n *\n * The input is treated as UTC and then the time zone is attached, unless\n * `adjustForTimeZone` is set to `true`. In that case, the input is treated as\n * already in the time zone.\n *\n * When `adjustForTimeZone` is true and ambiguous times occur during DST transitions,\n * the `disambiguation` option controls how to resolve the ambiguity:\n * - `compatible` (default): Choose earlier time for repeated times, later for gaps\n * - `earlier`: Always choose the earlier of two possible times\n * - `later`: Always choose the later of two possible times\n * - `reject`: Throw an error when ambiguous times are encountered\n *\n * **Example** (Creating zoned DateTime values unsafely)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const zoned = DateTime.makeZonedUnsafe(\"2024-06-15T14:30:00Z\", {\n *   timeZone: \"Europe/London\"\n * })\n *\n * DateTime.formatIsoZoned(zoned) // => \"2024-06-15T15:30:00.000+01:00[Europe/London]\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeZonedUnsafe = Internal.makeZonedUnsafe;\n/**\n * Creates a `DateTime.Zoned` safely from an input and a time zone.\n *\n * **Details**\n *\n * By default, the input is interpreted as a UTC instant and the time zone is\n * attached without changing that instant. When `adjustForTimeZone` is `true`,\n * the input is interpreted as wall-clock time in the target zone.\n *\n * When `adjustForTimeZone` is `true`, `disambiguation` controls\n * daylight-saving gaps and repeated times:\n *\n * - `\"compatible\"` (default): chooses the earlier occurrence for repeated\n *   times and the later interpretation for gaps\n * - `\"earlier\"`: chooses the earlier possible instant\n * - `\"later\"`: chooses the later possible instant\n * - `\"reject\"`: rejects ambiguous or nonexistent wall-clock times\n *\n * Returns `Some` when construction succeeds, or `None` when the input, time\n * zone, or disambiguation cannot be resolved.\n *\n * **Example** (Creating optional zoned DateTime values)\n *\n * ```ts import.meta.vitest\n * import { DateTime, Option } from \"effect\"\n *\n * const result = DateTime.makeZoned(\"2024-06-15T14:30:00Z\", {\n *   timeZone: \"Europe/London\"\n * })\n *\n * result.pipe(Option.map(DateTime.formatIsoZoned)) // => Option.some(\"2024-06-15T15:30:00.000+01:00[Europe/London]\")\n * ```\n *\n * @category constructors\n * @since 3.6.0\n */\nexport const makeZoned = Internal.makeZoned;\n/**\n * Creates a `DateTime` safely from supported input values.\n *\n * **Details**\n *\n * - A `DateTime`\n * - A JavaScript `Date`\n * - The number of milliseconds since the Unix epoch\n * - An object with date and time parts\n * - A string that can be parsed as a date\n *\n * Returns `Some` with the constructed `DateTime` when the input is valid, or\n * `None` when construction would fail, including invalid `Date` instances or\n * unparseable strings.\n *\n * **Example** (Creating optional DateTime values)\n *\n * ```ts import.meta.vitest\n * import { DateTime, Option } from \"effect\"\n *\n * // from Date\n * DateTime.make(new Date(\"2024-01-01T12:00:00Z\")) // => Option.some(DateTime.makeUnsafe(\"2024-01-01T12:00:00Z\"))\n *\n * // from parts\n * DateTime.make({ year: 2024 }) // => Option.some(DateTime.makeUnsafe(\"2024-01-01T00:00:00Z\"))\n *\n * // from string\n * DateTime.make(\"2024-01-01\") // => Option.some(DateTime.makeUnsafe(\"2024-01-01T00:00:00Z\"))\n *\n * DateTime.make(\"not a date\") // => Option.none()\n * ```\n *\n * @category constructors\n * @since 3.6.0\n */\nexport const make = Internal.make;\n/**\n * Parses an ISO zoned date-time string into a `DateTime.Zoned` safely.\n *\n * **Details**\n *\n * Accepts named-zone strings such as\n * `YYYY-MM-DDTHH:mm:ss.sss+HH:MM[Time/Zone]` and offset-only strings such as\n * `YYYY-MM-DDTHH:mm:ss.sss+HH:MM`. Returns `None` when the input cannot be\n * parsed.\n *\n * **Example** (Parsing zoned DateTime strings)\n *\n * ```ts import.meta.vitest\n * import { DateTime, Option } from \"effect\"\n *\n * DateTime.makeZonedFromString(\n *   \"2024-01-01T12:00:00+02:00[Europe/Berlin]\"\n * ).pipe(Option.map(DateTime.formatIsoZoned)) // => Option.some(\"2024-01-01T11:00:00.000+01:00[Europe/Berlin]\")\n *\n * DateTime.makeZonedFromString(\"2024-01-01T12:00:00Z\") // => Option.none()\n * DateTime.makeZonedFromString(\"invalid\") // => Option.none()\n * ```\n *\n * @category constructors\n * @since 3.6.0\n */\nexport const makeZonedFromString = Internal.makeZonedFromString;\n/**\n * Gets the current time using the `Clock` service and converts it to a `DateTime`.\n *\n * **Example** (Getting the current DateTime)\n *\n * ```ts import.meta.vitest\n * import { DateTime, Effect } from \"effect\"\n * import { TestClock } from \"effect/testing\"\n *\n * await Effect.runPromise(Effect.map(DateTime.now, DateTime.isDateTime)) // => true\n * ```\n *\n * @category constructors\n * @since 3.6.0\n */\nexport const now = Internal.now;\n/**\n * Gets the current time from the `Clock` service and returns it as a\n * JavaScript `Date`.\n *\n * **Example** (Getting the current Date)\n *\n * ```ts import.meta.vitest\n * import { DateTime, Effect } from \"effect\"\n * import { TestClock } from \"effect/testing\"\n *\n * await Effect.runPromise(Effect.map(DateTime.nowAsDate, (now) => now instanceof Date)) // => true\n * ```\n *\n * @category constructors\n * @since 3.14.0\n */\nexport const nowAsDate = Internal.nowAsDate;\n/**\n * Gets the current time using `Date.now`.\n *\n * **When to use**\n *\n * Use when synchronous wall-clock access outside an Effect program is\n * acceptable and testability through the `Clock` service is not needed.\n *\n * **Details**\n *\n * This is a synchronous version of `now` that directly uses `Date.now()`\n * instead of the Effect `Clock` service.\n *\n * **Example** (Getting the current DateTime unsafely)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * Number.isFinite(DateTime.toEpochMillis(DateTime.nowUnsafe())) // => true\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const nowUnsafe = Internal.nowUnsafe;\n// =============================================================================\n// time zones\n// =============================================================================\n/**\n * Converts a `DateTime` to a UTC `DateTime`.\n *\n * **When to use**\n *\n * Use to represent the same instant in UTC instead of its current time zone.\n *\n * **Details**\n *\n * The returned value keeps the same epoch milliseconds and changes only the\n * `DateTime` representation to UTC.\n *\n * **Example** (Converting DateTime values to UTC)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const now = DateTime.makeZonedUnsafe({ year: 2024 }, {\n *   timeZone: \"Europe/London\"\n * })\n *\n * // set as UTC\n * const utc: DateTime.Utc = DateTime.toUtc(now)\n * utc // => DateTime.makeUnsafe(\"2024-01-01T00:00:00Z\")\n * ```\n *\n * @category converting\n * @since 3.13.0\n */\nexport const toUtc = Internal.toUtc;\n/**\n * Sets the time zone of a `DateTime`, returning a new `DateTime.Zoned`.\n *\n * **Example** (Setting time zones)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const zone = DateTime.zoneMakeNamedUnsafe(\"Europe/London\")\n * const zoned: DateTime.Zoned = DateTime.setZone(DateTime.makeUnsafe(\"2024-01-01\"), zone)\n *\n * DateTime.isZoned(zoned) // => true\n * ```\n *\n * @category transforming\n * @since 3.6.0\n */\nexport const setZone = Internal.setZone;\n/**\n * Adds a fixed offset time zone to a `DateTime`.\n *\n * **Details**\n *\n * The offset is in milliseconds.\n *\n * **Example** (Setting fixed-offset time zones)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const dateTime = DateTime.makeUnsafe(\"2024-01-01\")\n * const zoned: DateTime.Zoned = DateTime.setZoneOffset(dateTime, 3 * 60 * 60 * 1000)\n *\n * DateTime.zoneToString(zoned.zone) // => \"+03:00\"\n * ```\n *\n * @category transforming\n * @since 3.6.0\n */\nexport const setZoneOffset = Internal.setZoneOffset;\n/**\n * Attempts to create a named time zone from an IANA time zone identifier.\n *\n * **When to use**\n *\n * Use when the IANA zone id is trusted and invalid zones should throw instead\n * of returning `Option.none` or failing in `Effect`.\n *\n * **Details**\n *\n * If the time zone is invalid, an `IllegalArgumentError` will be thrown.\n *\n * **Example** (Creating named time zones unsafely)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * DateTime.zoneToString(DateTime.zoneMakeNamedUnsafe(\"Europe/London\")) // => \"Europe/London\"\n * DateTime.zoneToString(DateTime.zoneMakeNamedUnsafe(\"Asia/Tokyo\")) // => \"Asia/Tokyo\"\n *\n * // This would throw an IllegalArgumentError:\n * // DateTime.zoneMakeNamedUnsafe(\"Invalid/Zone\")\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const zoneMakeNamedUnsafe = Internal.zoneMakeNamedUnsafe;\n/**\n * Create a fixed offset time zone.\n *\n * **Details**\n *\n * The offset is specified in milliseconds from UTC. Positive values are\n * ahead of UTC, negative values are behind UTC.\n *\n * **Example** (Creating fixed-offset time zones)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * // Create a time zone with +3 hours offset\n * const zone = DateTime.zoneMakeOffset(3 * 60 * 60 * 1000)\n *\n * const dt = DateTime.makeZonedUnsafe(\"2024-01-01T12:00:00Z\", {\n *   timeZone: zone\n * })\n * DateTime.formatIsoZoned(dt) // => \"2024-01-01T15:00:00.000+03:00\"\n * ```\n *\n * @category constructors\n * @since 3.6.0\n */\nexport const zoneMakeOffset = Internal.zoneMakeOffset;\n/**\n * Creates a named time zone safely from an IANA time zone identifier.\n *\n * **Details**\n *\n * If the time zone is invalid, `None` will be returned.\n *\n * **Example** (Creating optional named time zones)\n *\n * ```ts import.meta.vitest\n * import { DateTime, Option } from \"effect\"\n *\n * DateTime.zoneMakeNamed(\"Europe/London\").pipe(Option.map(DateTime.zoneToString)) // => Option.some(\"Europe/London\")\n * DateTime.zoneMakeNamed(\"Invalid/Zone\") // => Option.none()\n * ```\n *\n * @category constructors\n * @since 3.6.0\n */\nexport const zoneMakeNamed = Internal.zoneMakeNamed;\n/**\n * Creates a named time zone effectfully from an IANA time zone identifier.\n *\n * **When to use**\n *\n * Use when invalid IANA zone ids should fail in the Effect error channel\n * instead of returning `Option.none` or throwing.\n *\n * **Example** (Creating named time zones effectfully)\n *\n * ```ts import.meta.vitest\n * import { DateTime, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const zone = yield* DateTime.zoneMakeNamedEffect(\"Europe/London\")\n *   const now = yield* DateTime.now\n *   return DateTime.setZone(now, zone)\n * })\n *\n * DateTime.zoneToString((await Effect.runPromise(program)).zone) // => \"Europe/London\"\n * ```\n *\n * @category constructors\n * @since 3.6.0\n */\nexport const zoneMakeNamedEffect = Internal.zoneMakeNamedEffect;\n/**\n * Create a named time zone from the system's local time zone.\n *\n * **Details**\n *\n * This uses the system's configured time zone, which may vary depending\n * on the runtime environment.\n *\n * **Example** (Creating local time zones)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * DateTime.isTimeZoneNamed(DateTime.zoneMakeLocal()) // => true\n * ```\n *\n * @category constructors\n * @since 3.6.0\n */\nexport const zoneMakeLocal = Internal.zoneMakeLocal;\n/**\n * Tries to parse a `TimeZone` from a string safely.\n *\n * **Details**\n *\n * Supports both IANA time zone identifiers and offset formats like \"+03:00\".\n *\n * **Example** (Parsing time zones)\n *\n * ```ts import.meta.vitest\n * import { DateTime, Option } from \"effect\"\n *\n * DateTime.zoneFromString(\"Europe/London\").pipe(Option.map(DateTime.zoneToString)) // => Option.some(\"Europe/London\")\n * DateTime.zoneFromString(\"+03:00\").pipe(Option.map(DateTime.zoneToString)) // => Option.some(\"+03:00\")\n * DateTime.zoneFromString(\"invalid\") // => Option.none()\n * ```\n *\n * @category decoding\n * @since 3.6.0\n */\nexport const zoneFromString = Internal.zoneFromString;\n/**\n * Formats a `TimeZone` as a string.\n *\n * **Example** (Formatting time zones)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * DateTime.zoneToString(DateTime.zoneMakeOffset(3 * 60 * 60 * 1000)) // => \"+03:00\"\n * DateTime.zoneToString(DateTime.zoneMakeNamedUnsafe(\"Europe/London\")) // => \"Europe/London\"\n * ```\n *\n * @category encoding\n * @since 3.6.0\n */\nexport const zoneToString = Internal.zoneToString;\n/**\n * Sets the time zone of a `DateTime` safely from an IANA time zone identifier. If the\n * time zone is invalid, `None` will be returned.\n *\n * **Example** (Setting named time zones safely)\n *\n * ```ts import.meta.vitest\n * import { DateTime, Option } from \"effect\"\n *\n * const dateTime = DateTime.makeUnsafe(\"2024-01-01\")\n * const result = DateTime.setZoneNamed(dateTime, \"Europe/London\").pipe(Option.map(DateTime.formatIsoZoned))\n *\n * result // => Option.some(\"2024-01-01T00:00:00.000+00:00[Europe/London]\")\n * ```\n *\n * @category transforming\n * @since 3.6.0\n */\nexport const setZoneNamed = Internal.setZoneNamed;\n/**\n * Sets the time zone of a `DateTime` from an IANA time zone identifier. If the\n * time zone is invalid, an `IllegalArgumentError` will be thrown.\n *\n * **Example** (Setting named time zones unsafely)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const dateTime = DateTime.makeUnsafe(\"2024-01-01\")\n * const zoned = DateTime.setZoneNamedUnsafe(dateTime, \"Europe/London\")\n *\n * DateTime.zoneToString(zoned.zone) // => \"Europe/London\"\n * ```\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const setZoneNamedUnsafe = Internal.setZoneNamedUnsafe;\n// =============================================================================\n// comparisons\n// =============================================================================\n/**\n * Computes the difference between two `DateTime` values, returning a\n * `Duration` representing the amount of time between them.\n *\n * **Details**\n *\n * If `other` is *after* `self`, the result will be a positive `Duration`. If\n * `other` is *before* `self`, the result will be a negative `Duration`. If they\n * are equal, the result will be a `Duration` of zero.\n *\n * **Example** (Measuring distance between DateTime values)\n *\n * ```ts import.meta.vitest\n * import { DateTime, Duration } from \"effect\"\n *\n * const start = DateTime.makeUnsafe(\"2024-01-01T00:00:00Z\")\n * const end = DateTime.add(start, { minutes: 1 })\n *\n * DateTime.distance(start, end) // => Duration.minutes(1)\n * ```\n *\n * @category comparisons\n * @since 3.6.0\n */\nexport const distance = Internal.distance;\n/**\n * Returns the earlier of two `DateTime` values.\n *\n * **Example** (Selecting the earlier DateTime)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const date1 = DateTime.makeUnsafe(\"2024-01-01\")\n * const date2 = DateTime.makeUnsafe(\"2024-02-01\")\n *\n * DateTime.min(date1, date2) // => DateTime.makeUnsafe(\"2024-01-01\")\n * ```\n *\n * @category comparisons\n * @since 3.6.0\n */\nexport const min = Internal.min;\n/**\n * Returns the later of two `DateTime` values.\n *\n * **Example** (Selecting the later DateTime)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const date1 = DateTime.makeUnsafe(\"2024-01-01\")\n * const date2 = DateTime.makeUnsafe(\"2024-02-01\")\n *\n * DateTime.max(date1, date2) // => DateTime.makeUnsafe(\"2024-02-01\")\n * ```\n *\n * @category comparisons\n * @since 3.6.0\n */\nexport const max = Internal.max;\n/**\n * Checks whether the first `DateTime` is after the second `DateTime`.\n *\n * **Example** (Checking whether a DateTime is later)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const date1 = DateTime.makeUnsafe(\"2024-02-01\")\n * const date2 = DateTime.makeUnsafe(\"2024-01-01\")\n *\n * DateTime.isGreaterThan(date1, date2) // => true\n * DateTime.isGreaterThan(date2, date1) // => false\n * ```\n *\n * @category comparisons\n * @since 4.0.0\n */\nexport const isGreaterThan = Internal.isGreaterThan;\n/**\n * Checks whether the first `DateTime` is after or equal to the second `DateTime`.\n *\n * **Example** (Checking whether a DateTime is later or equal)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const date1 = DateTime.makeUnsafe(\"2024-01-01\")\n * const date2 = DateTime.makeUnsafe(\"2024-01-01\")\n * const date3 = DateTime.makeUnsafe(\"2024-02-01\")\n *\n * DateTime.isGreaterThanOrEqualTo(date1, date2) // => true\n * DateTime.isGreaterThanOrEqualTo(date3, date1) // => true\n * DateTime.isGreaterThanOrEqualTo(date1, date3) // => false\n * ```\n *\n * @category comparisons\n * @since 4.0.0\n */\nexport const isGreaterThanOrEqualTo = Internal.isGreaterThanOrEqualTo;\n/**\n * Checks whether the first `DateTime` is before the second `DateTime`.\n *\n * **Example** (Checking whether a DateTime is earlier)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const date1 = DateTime.makeUnsafe(\"2024-01-01\")\n * const date2 = DateTime.makeUnsafe(\"2024-02-01\")\n *\n * DateTime.isLessThan(date1, date2) // => true\n * DateTime.isLessThan(date2, date1) // => false\n * ```\n *\n * @category comparisons\n * @since 4.0.0\n */\nexport const isLessThan = Internal.isLessThan;\n/**\n * Checks whether the first `DateTime` is before or equal to the second `DateTime`.\n *\n * **Example** (Checking whether a DateTime is earlier or equal)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const date1 = DateTime.makeUnsafe(\"2024-01-01\")\n * const date2 = DateTime.makeUnsafe(\"2024-01-01\")\n * const date3 = DateTime.makeUnsafe(\"2024-02-01\")\n *\n * DateTime.isLessThanOrEqualTo(date1, date2) // => true\n * DateTime.isLessThanOrEqualTo(date1, date3) // => true\n * DateTime.isLessThanOrEqualTo(date3, date1) // => false\n * ```\n *\n * @category comparisons\n * @since 4.0.0\n */\nexport const isLessThanOrEqualTo = Internal.isLessThanOrEqualTo;\n/**\n * Checks whether a `DateTime` is between two other `DateTime` values (inclusive).\n *\n * **Example** (Checking whether a DateTime is within bounds)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const min = DateTime.makeUnsafe(\"2024-01-01\")\n * const max = DateTime.makeUnsafe(\"2024-12-31\")\n * const date = DateTime.makeUnsafe(\"2024-06-15\")\n *\n * DateTime.between(date, { minimum: min, maximum: max }) // => true\n * ```\n *\n * @category comparisons\n * @since 3.6.0\n */\nexport const between = Internal.between;\n/**\n * Checks effectfully if a `DateTime` is in the future compared to the current time.\n *\n * **Details**\n *\n * This is an effectful operation that uses the current time from the `Clock` service.\n *\n * **Example** (Checking future DateTime values effectfully)\n *\n * ```ts import.meta.vitest\n * import { DateTime, Effect } from \"effect\"\n * import { TestClock } from \"effect/testing\"\n *\n * const futureDate = DateTime.makeUnsafe(1)\n * await Effect.runPromise(Effect.provide(DateTime.isFuture(futureDate), TestClock.layer())) // => true\n * ```\n *\n * @category comparisons\n * @since 3.6.0\n */\nexport const isFuture = Internal.isFuture;\n/**\n * Checks synchronously if a `DateTime` is in the future compared to the current time.\n *\n * **When to use**\n *\n * Use when checking whether a `DateTime` is in the future with a synchronous\n * live-clock read and `Clock`-based testability is not needed.\n *\n * **Details**\n *\n * This is a synchronous version that uses `Date.now()` directly.\n *\n * **Example** (Checking future DateTime values unsafely)\n *\n * ```ts\n * import { DateTime } from \"effect\"\n *\n * const oneHourFromNow = DateTime.add(DateTime.nowUnsafe(), { hours: 1 })\n * DateTime.isFutureUnsafe(oneHourFromNow)\n * ```\n *\n * @category comparisons\n * @since 4.0.0\n */\nexport const isFutureUnsafe = Internal.isFutureUnsafe;\n/**\n * Checks effectfully if a `DateTime` is in the past compared to the current time.\n *\n * **Details**\n *\n * This is an effectful operation that uses the current time from the `Clock` service.\n *\n * **Example** (Checking past DateTime values effectfully)\n *\n * ```ts import.meta.vitest\n * import { DateTime, Effect } from \"effect\"\n * import { TestClock } from \"effect/testing\"\n *\n * const pastDate = DateTime.makeUnsafe(-1)\n * await Effect.runPromise(Effect.provide(DateTime.isPast(pastDate), TestClock.layer())) // => true\n * ```\n *\n * @category comparisons\n * @since 3.6.0\n */\nexport const isPast = Internal.isPast;\n/**\n * Checks synchronously if a `DateTime` is in the past compared to the current time.\n *\n * **When to use**\n *\n * Use when checking whether a `DateTime` is in the past with a synchronous\n * live-clock read and `Clock`-based testability is not needed.\n *\n * **Details**\n *\n * This is a synchronous version that uses `Date.now()` directly.\n *\n * **Example** (Checking past DateTime values unsafely)\n *\n * ```ts\n * import { DateTime } from \"effect\"\n *\n * const oneHourAgo = DateTime.subtract(DateTime.nowUnsafe(), { hours: 1 })\n * DateTime.isPastUnsafe(oneHourAgo)\n * ```\n *\n * @category comparisons\n * @since 4.0.0\n */\nexport const isPastUnsafe = Internal.isPastUnsafe;\n// =============================================================================\n// conversions\n// =============================================================================\n/**\n * Gets the UTC `Date` of a `DateTime`.\n *\n * **Details**\n *\n * This always returns the UTC representation, ignoring any time zone information.\n *\n * **Example** (Converting DateTime values to UTC Dates)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const dt = DateTime.makeZonedUnsafe(\"2024-01-01T12:00:00Z\", {\n *   timeZone: \"Europe/London\"\n * })\n *\n * DateTime.toDateUtc(dt).toISOString() // => \"2024-01-01T12:00:00.000Z\"\n * ```\n *\n * @category converting\n * @since 3.6.0\n */\nexport const toDateUtc = Internal.toDateUtc;\n/**\n * Converts a `DateTime` to a `Date`, applying the time zone first.\n *\n * **Details**\n *\n * For `DateTime.Zoned`, this adjusts for the time zone before converting.\n * For `DateTime.Utc`, this is equivalent to `toDateUtc`.\n *\n * **Example** (Converting DateTime values to Dates)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const utc = DateTime.makeUnsafe(\"2024-01-01T12:00:00Z\")\n * const zoned = DateTime.makeZonedUnsafe(\"2024-01-01T12:00:00Z\", {\n *   timeZone: \"Europe/London\"\n * })\n *\n * DateTime.toDate(utc).toISOString() // => \"2024-01-01T12:00:00.000Z\"\n * DateTime.toDate(zoned).toISOString() // => \"2024-01-01T12:00:00.000Z\"\n * ```\n *\n * @category converting\n * @since 3.6.0\n */\nexport const toDate = Internal.toDate;\n/**\n * Computes the time zone offset of a `DateTime.Zoned` in milliseconds.\n *\n * **Details**\n *\n * Returns the offset from UTC in milliseconds. Positive values indicate\n * time zones ahead of UTC, negative values indicate time zones behind UTC.\n *\n * **Example** (Reading zoned offsets)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const zoned = DateTime.makeZonedUnsafe(\"2024-01-01T12:00:00Z\", {\n *   timeZone: \"Europe/London\"\n * })\n *\n * DateTime.zonedOffset(zoned) // => 0\n * ```\n *\n * @category converting\n * @since 3.6.0\n */\nexport const zonedOffset = Internal.zonedOffset;\n/**\n * Formats the time zone offset of a `DateTime.Zoned` as an ISO string.\n *\n * **Details**\n *\n * The offset is formatted as \"±HH:MM\".\n *\n * **Example** (Formatting zoned offsets)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const zoned = DateTime.makeZonedUnsafe(\"2024-01-01T12:00:00Z\", {\n *   timeZone: DateTime.zoneMakeOffset(3 * 60 * 60 * 1000) // +3 hours\n * })\n *\n * DateTime.zonedOffsetIso(zoned) // => \"+03:00\"\n * ```\n *\n * @category converting\n * @since 3.6.0\n */\nexport const zonedOffsetIso = Internal.zonedOffsetIso;\n/**\n * Gets the milliseconds since the Unix epoch of a `DateTime`.\n *\n * **Details**\n *\n * This returns the UTC timestamp regardless of any time zone information.\n *\n * **Example** (Reading epoch milliseconds)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const dt = DateTime.makeUnsafe(\"2024-01-01T00:00:00Z\")\n * DateTime.toEpochMillis(dt) // => 1704067200000\n * ```\n *\n * @category converting\n * @since 3.6.0\n */\nexport const toEpochMillis = Internal.toEpochMillis;\n/**\n * Converts a `DateTime` to the number of seconds since the Unix epoch.\n *\n * **Details**\n *\n * This returns the UTC timestamp regardless of any time zone information.\n * The result is floored to the nearest second.\n *\n * **Example** (Reading epoch seconds)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const dt = DateTime.makeUnsafe(\"2024-01-01T00:00:00Z\")\n * DateTime.toEpochSeconds(dt) // => 1704067200\n * ```\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toEpochSeconds = Internal.toEpochSeconds;\n/**\n * Removes the time aspect of a `DateTime`, first adjusting for the time\n * zone. It will return a `DateTime.Utc` only containing the date.\n *\n * **Example** (Removing time components)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * // returns \"2024-01-01T00:00:00Z\"\n * DateTime.makeZonedUnsafe(\"2024-01-01T05:00:00Z\", {\n *   timeZone: \"Pacific/Auckland\",\n *   adjustForTimeZone: true\n * }).pipe(\n *   DateTime.removeTime,\n *   DateTime.formatIso\n * ) // => \"2024-01-01T00:00:00.000Z\"\n * ```\n *\n * @category converting\n * @since 3.6.0\n */\nexport const removeTime = Internal.removeTime;\n// =============================================================================\n// parts\n// =============================================================================\n/**\n * Gets the time-zone-adjusted parts of a `DateTime` as an object.\n *\n * **Details**\n *\n * The parts will be time zone adjusted if the `DateTime` is zoned.\n *\n * **Example** (Reading DateTime parts)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const dt = DateTime.makeUnsafe(\"2024-01-01T12:30:45.123Z\")\n * const parts = DateTime.toParts(dt)\n *\n * const selectedParts = [parts.year, parts.month, parts.day, parts.hour] // => [2024, 1, 1, 12]\n * ```\n *\n * @category getters\n * @since 3.6.0\n */\nexport const toParts = Internal.toParts;\n/**\n * Gets the UTC parts of a `DateTime` as an object.\n *\n * **Details**\n *\n * The parts will always be in UTC, ignoring any time zone information.\n *\n * **Example** (Reading UTC DateTime parts)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const zoned = DateTime.makeZonedUnsafe(\"2024-01-01T12:30:45.123Z\", {\n *   timeZone: \"Europe/London\"\n * })\n * const parts = DateTime.toPartsUtc(zoned)\n *\n * const selectedParts = [parts.year, parts.month, parts.day, parts.hour] // => [2024, 1, 1, 12]\n * ```\n *\n * @category getters\n * @since 3.6.0\n */\nexport const toPartsUtc = Internal.toPartsUtc;\n/**\n * Gets one UTC part of a `DateTime` as a number.\n *\n * **Details**\n *\n * The part will be in the UTC time zone.\n *\n * **Example** (Reading UTC DateTime parts by key)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const dateTime = DateTime.makeUnsafe({ year: 2024 })\n * DateTime.getPartUtc(dateTime, \"year\") // => 2024\n * ```\n *\n * @category getters\n * @since 3.6.0\n */\nexport const getPartUtc = Internal.getPartUtc;\n/**\n * Gets one time-zone-adjusted part of a `DateTime` as a number.\n *\n * **Details**\n *\n * The part will be time zone adjusted.\n *\n * **Example** (Reading DateTime parts by key)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const dateTime = DateTime.makeZonedUnsafe({ year: 2024 }, {\n *   timeZone: \"Europe/London\"\n * })\n * DateTime.getPart(dateTime, \"year\") // => 2024\n * ```\n *\n * @category getters\n * @since 3.6.0\n */\nexport const getPart = Internal.getPart;\n/**\n * Sets time-zone-adjusted parts on a `DateTime`.\n *\n * **Details**\n *\n * The date will be time zone adjusted for `DateTime.Zoned`.\n *\n * **Example** (Updating DateTime parts)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const dt = DateTime.makeZonedUnsafe(\"2024-01-01T12:00:00Z\", { timeZone: \"UTC\" })\n * const updated = DateTime.setParts(dt, {\n *   year: 2025,\n *   month: 6,\n *   day: 15\n * })\n *\n * updated // => DateTime.makeZonedUnsafe(\"2025-06-15T12:00:00Z\", { timeZone: \"UTC\" })\n * ```\n *\n * @category transforming\n * @since 3.6.0\n */\nexport const setParts = Internal.setParts;\n/**\n * Sets UTC parts on a `DateTime`.\n *\n * **Details**\n *\n * The parts are always interpreted as UTC, ignoring any time zone information.\n *\n * **Example** (Updating UTC DateTime parts)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const dt = DateTime.makeUnsafe(\"2024-01-01T12:00:00Z\")\n * const updated = DateTime.setPartsUtc(dt, {\n *   year: 2025,\n *   hour: 18\n * })\n *\n * updated // => DateTime.makeUnsafe(\"2025-01-01T18:00:00Z\")\n * ```\n *\n * @category transforming\n * @since 3.6.0\n */\nexport const setPartsUtc = Internal.setPartsUtc;\n// =============================================================================\n// current time zone\n// =============================================================================\n/**\n * Context service that supplies the ambient `TimeZone` for APIs that work in\n * the current zone, such as `DateTime.setZoneCurrent` and\n * `DateTime.nowInCurrentZone`.\n *\n * **Details**\n *\n * Provide it with `DateTime.withCurrentZone`, one of the `withCurrentZone*`\n * helpers, or one of the `layerCurrentZone*` layers.\n *\n * **Example** (Accessing the current time zone service)\n *\n * ```ts import.meta.vitest\n * import { DateTime, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   return DateTime.zoneToString(yield* DateTime.CurrentTimeZone)\n * })\n *\n * // Provide a time zone\n * const layer = DateTime.layerCurrentZoneNamed(\"Europe/London\")\n * await Effect.runPromise(Effect.provide(program, layer)) // => \"Europe/London\"\n * ```\n *\n * @category services\n * @since 3.11.0\n */\nexport class CurrentTimeZone extends /*#__PURE__*/Context.Service()(\"effect/DateTime/CurrentTimeZone\") {}\n/**\n * Sets the time zone of a `DateTime` to the current time zone, which is\n * determined by the `CurrentTimeZone` service.\n *\n * **Example** (Setting the current time zone)\n *\n * ```ts import.meta.vitest\n * import { DateTime, Effect } from \"effect\"\n *\n * await Effect.runPromise(Effect.gen(function*() {\n *   const zoned = yield* DateTime.setZoneCurrent(DateTime.makeUnsafe(\"2024-01-01\"))\n *   return DateTime.zoneToString(zoned.zone)\n * }).pipe(DateTime.withCurrentZoneNamed(\"Europe/London\"))) // => \"Europe/London\"\n * ```\n *\n * @category accessors\n * @since 3.6.0\n */\nexport const setZoneCurrent = self => Effect.map(CurrentTimeZone, zone => setZone(self, zone));\n/**\n * Provides the `CurrentTimeZone` to an effect.\n *\n * **Example** (Providing the current time zone)\n *\n * ```ts import.meta.vitest\n * import { DateTime, Effect } from \"effect\"\n *\n * const zone = DateTime.zoneMakeNamedUnsafe(\"Europe/London\")\n *\n * await Effect.runPromise(Effect.gen(function*() {\n *   const zoned = yield* DateTime.setZoneCurrent(DateTime.makeUnsafe(\"2024-01-01\"))\n *   return DateTime.zoneToString(zoned.zone)\n * }).pipe(DateTime.withCurrentZone(zone))) // => \"Europe/London\"\n * ```\n *\n * @category providing services\n * @since 3.6.0\n */\nexport const withCurrentZone = /*#__PURE__*/provideService(CurrentTimeZone);\n/**\n * Provides the `CurrentTimeZone` to an effect, using the system's local time\n * zone.\n *\n * **Example** (Providing the local time zone)\n *\n * ```ts import.meta.vitest\n * import { DateTime, Effect } from \"effect\"\n *\n * await Effect.runPromise(Effect.gen(function*() {\n *   return DateTime.isZoned(yield* DateTime.nowInCurrentZone)\n * }).pipe(DateTime.withCurrentZoneLocal)) // => true\n * ```\n *\n * @category providing services\n * @since 3.6.0\n */\nexport const withCurrentZoneLocal = effect => Effect.provideServiceEffect(effect, CurrentTimeZone, Effect.sync(zoneMakeLocal));\n/**\n * Provides the `CurrentTimeZone` to an effect, using an offset.\n *\n * **Example** (Providing a fixed-offset time zone)\n *\n * ```ts import.meta.vitest\n * import { DateTime, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   return DateTime.zoneToString(yield* DateTime.CurrentTimeZone)\n * }).pipe(DateTime.withCurrentZoneOffset(3 * 60 * 60 * 1000))\n *\n * await Effect.runPromise(program) // => \"+03:00\"\n * ```\n *\n * @category providing services\n * @since 3.6.0\n */\nexport const withCurrentZoneOffset = /*#__PURE__*/dual(2, (effect, offset) => Effect.provideService(effect, CurrentTimeZone, zoneMakeOffset(offset)));\n/**\n * Provides the `CurrentTimeZone` to an effect using an IANA time zone\n * identifier.\n *\n * **Details**\n *\n * If the time zone is invalid, it will fail with an `IllegalArgumentError`.\n *\n * **Example** (Providing a named time zone)\n *\n * ```ts import.meta.vitest\n * import { DateTime, Effect } from \"effect\"\n *\n * await Effect.runPromise(Effect.gen(function*() {\n *   const zoned = yield* DateTime.setZoneCurrent(DateTime.makeUnsafe(\"2024-01-01\"))\n *   return DateTime.zoneToString(zoned.zone)\n * }).pipe(DateTime.withCurrentZoneNamed(\"Europe/London\"))) // => \"Europe/London\"\n * ```\n *\n * @category providing services\n * @since 3.6.0\n */\nexport const withCurrentZoneNamed = /*#__PURE__*/dual(2, (effect, zone) => Effect.provideServiceEffect(effect, CurrentTimeZone, zoneMakeNamedEffect(zone)));\n/**\n * Gets the current time as a `DateTime.Zoned`, using the `CurrentTimeZone`.\n *\n * **Example** (Getting the current time in the current zone)\n *\n * ```ts import.meta.vitest\n * import { DateTime, Effect } from \"effect\"\n *\n * await Effect.runPromise(Effect.gen(function*() {\n *   return DateTime.zoneToString((yield* DateTime.nowInCurrentZone).zone)\n * }).pipe(DateTime.withCurrentZoneNamed(\"Europe/London\"))) // => \"Europe/London\"\n * ```\n *\n * @category accessors\n * @since 3.6.0\n */\nexport const nowInCurrentZone = /*#__PURE__*/Effect.flatMap(now, setZoneCurrent);\n// =============================================================================\n// mapping\n// =============================================================================\n/**\n * Modifies a `DateTime` with a mutable local `Date` copy.\n *\n * **When to use**\n *\n * Use to adjust calendar fields in the `DateTime`'s own time zone with an\n * existing `Date` mutation API.\n *\n * **Details**\n *\n * The `Date` will first have the time zone applied if possible, and then be\n * converted back to a `DateTime` within the same time zone.\n *\n * Supports `disambiguation` when the new wall clock time is ambiguous.\n *\n * **Example** (Mutating DateTime values with Dates)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const dt = DateTime.makeUnsafe(\"2024-01-01T12:00:00Z\")\n *\n * DateTime.mutate(dt, (date) => {\n *   date.setHours(15) // Set to 3 PM\n *   date.setMinutes(30) // Set to 30 minutes\n * })\n * ```\n *\n * @category mapping\n * @since 3.6.0\n */\nexport const mutate = Internal.mutate;\n/**\n * Modifies a `DateTime` with a mutable UTC `Date` copy.\n *\n * **When to use**\n *\n * Use to adjust the instant with an existing `Date` mutation API that works on\n * UTC calendar fields.\n *\n * **Example** (Mutating DateTime values with UTC Dates)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const dt = DateTime.makeZonedUnsafe(\"2024-01-01T12:00:00Z\", {\n *   timeZone: \"Europe/London\"\n * })\n *\n * const modified = DateTime.mutateUtc(dt, (date) => {\n *   date.setUTCHours(18) // Set UTC time to 6 PM\n * })\n *\n * modified // => DateTime.makeZonedUnsafe(\"2024-01-01T18:00:00Z\", { timeZone: \"Europe/London\" })\n * ```\n *\n * @category mapping\n * @since 3.6.0\n */\nexport const mutateUtc = Internal.mutateUtc;\n/**\n * Transforms a `DateTime` by applying a function to the number of milliseconds\n * since the Unix epoch.\n *\n * **Example** (Mapping epoch milliseconds)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * // add 10 milliseconds\n * const result = DateTime.makeUnsafe(0).pipe(\n *   DateTime.mapEpochMillis((millis) => millis + 10)\n * )\n * result // => DateTime.makeUnsafe(10)\n * ```\n *\n * @category mapping\n * @since 3.6.0\n */\nexport const mapEpochMillis = Internal.mapEpochMillis;\n/**\n * Applies a function to a JavaScript `Date` representing the `DateTime` and\n * returns the function's result.\n *\n * **Details**\n *\n * The callback receives the time-zone-adjusted wall-clock date for\n * `DateTime.Zoned` values. Use `DateTime.withDateUtc` when the callback should\n * receive the UTC instant.\n *\n * **Example** (Applying time zone adjusted Dates)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * // get the time zone adjusted date in milliseconds\n * DateTime.makeZonedUnsafe(0, { timeZone: \"Europe/London\" }).pipe(\n *   DateTime.withDate((date) => date.getTime())\n * ) // => 3600000\n * ```\n *\n * @category mapping\n * @since 3.6.0\n */\nexport const withDate = Internal.withDate;\n/**\n * Applies a function to a JavaScript `Date` representing the `DateTime`'s UTC\n * instant and returns the function's result.\n *\n * **Details**\n *\n * This ignores any associated time zone. Use `DateTime.withDate` when the\n * callback should receive the time-zone-adjusted wall-clock date.\n *\n * **Example** (Applying UTC Dates)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * // get the date in milliseconds\n * DateTime.makeUnsafe(0).pipe(\n *   DateTime.withDateUtc((date) => date.getTime())\n * ) // => 0\n * ```\n *\n * @category mapping\n * @since 3.6.0\n */\nexport const withDateUtc = Internal.withDateUtc;\n/**\n * Pattern match on a `DateTime` to handle `Utc` and `Zoned` cases differently.\n *\n * **Example** (Pattern matching DateTime variants)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const dt1 = DateTime.makeUnsafe(\"2024-01-01T12:00:00Z\") // Utc\n * const dt2 = DateTime.makeZonedUnsafe(\"2024-06-15T14:30:00Z\", {\n *   timeZone: \"Europe/London\"\n * }) // Zoned\n *\n * const result1 = DateTime.match(dt1, {\n *   onUtc: (utc) => `UTC: ${DateTime.formatIso(utc)}`,\n *   onZoned: (zoned) => `Zoned: ${DateTime.formatIsoZoned(zoned)}`\n * })\n *\n * const result2 = DateTime.match(dt2, {\n *   onUtc: (utc) => `UTC: ${DateTime.formatIso(utc)}`,\n *   onZoned: (zoned) => `Zoned: ${DateTime.formatIsoZoned(zoned)}`\n * })\n *\n * result1 // => \"UTC: 2024-01-01T12:00:00.000Z\"\n * result2 // => \"Zoned: 2024-06-15T15:30:00.000+01:00[Europe/London]\"\n * ```\n *\n * @category mapping\n * @since 3.6.0\n */\nexport const match = Internal.match;\n// =============================================================================\n// math\n// =============================================================================\n/**\n * Adds the given `Duration` to a `DateTime`.\n *\n * **When to use**\n *\n * Use to move a `DateTime` by an elapsed duration such as minutes, seconds, or\n * milliseconds.\n *\n * **Details**\n *\n * The duration is converted to milliseconds and added to the epoch\n * milliseconds. Zoned values keep their original time zone.\n *\n * **Gotchas**\n *\n * This is elapsed-time arithmetic, not calendar-aware local date arithmetic.\n * Use `add` when adding days, weeks, months, or years should account for the\n * date/time zone rules.\n *\n * **Example** (Adding durations)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * // add 5 minutes\n * DateTime.makeUnsafe(0).pipe(\n *   DateTime.addDuration(\"5 minutes\")\n * ) // => DateTime.makeUnsafe(300000)\n * ```\n *\n * @see {@link add} for calendar-aware date/time part arithmetic\n * @see {@link subtractDuration} for subtracting an elapsed duration\n *\n * @category math\n * @since 3.6.0\n */\nexport const addDuration = Internal.addDuration;\n/**\n * Subtracts the given `Duration` from a `DateTime`.\n *\n * **Example** (Subtracting durations)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * // subtract 5 minutes\n * DateTime.makeUnsafe(0).pipe(\n *   DateTime.subtractDuration(\"5 minutes\")\n * ) // => DateTime.makeUnsafe(-300000)\n * ```\n *\n * @category math\n * @since 3.6.0\n */\nexport const subtractDuration = Internal.subtractDuration;\n/**\n * Adds the given `amount` of `unit` to a `DateTime`.\n *\n * **Details**\n *\n * The time zone is taken into account when adding days, weeks, months, and\n * years.\n *\n * **Example** (Adding date and time parts)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * // add 5 minutes\n * DateTime.makeUnsafe(0).pipe(\n *   DateTime.add({ minutes: 5 })\n * ) // => DateTime.makeUnsafe(300000)\n * ```\n *\n * @category math\n * @since 3.6.0\n */\nexport const add = Internal.add;\n/**\n * Subtracts the given `amount` of `unit` from a `DateTime`.\n *\n * **Example** (Subtracting date and time parts)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * // subtract 5 minutes\n * DateTime.makeUnsafe(0).pipe(\n *   DateTime.subtract({ minutes: 5 })\n * ) // => DateTime.makeUnsafe(-300000)\n * ```\n *\n * @category math\n * @since 3.6.0\n */\nexport const subtract = Internal.subtract;\n/**\n * Converts a `DateTime` to the start of the given `part`.\n *\n * **Details**\n *\n * If the part is `week`, the `weekStartsOn` option can be used to specify the\n * day of the week that the week starts on. The default is 0 (Sunday).\n *\n * **Example** (Rounding down DateTime values)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * // returns \"2024-01-01T00:00:00Z\"\n * DateTime.makeUnsafe(\"2024-01-01T12:00:00Z\").pipe(\n *   DateTime.startOf(\"day\"),\n * ) // => DateTime.makeUnsafe(\"2024-01-01T00:00:00Z\")\n * ```\n *\n * @category math\n * @since 3.6.0\n */\nexport const startOf = Internal.startOf;\n/**\n * Converts a `DateTime` to the end of the given `part`.\n *\n * **Details**\n *\n * If the part is `week`, the `weekStartsOn` option can be used to specify the\n * day of the week that the week starts on. The default is 0 (Sunday).\n *\n * **Example** (Rounding up DateTime values)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * // returns \"2024-01-01T23:59:59.999Z\"\n * DateTime.makeUnsafe(\"2024-01-01T12:00:00Z\").pipe(\n *   DateTime.endOf(\"day\"),\n * ) // => DateTime.makeUnsafe(\"2024-01-01T23:59:59.999Z\")\n * ```\n *\n * @category math\n * @since 3.6.0\n */\nexport const endOf = Internal.endOf;\n/**\n * Converts a `DateTime` to the nearest given `part`.\n *\n * **Details**\n *\n * If the part is `week`, the `weekStartsOn` option can be used to specify the\n * day of the week that the week starts on. The default is 0 (Sunday).\n *\n * **Example** (Rounding DateTime values to nearest units)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * // returns \"2024-01-02T00:00:00Z\"\n * DateTime.makeUnsafe(\"2024-01-01T12:01:00Z\").pipe(\n *   DateTime.nearest(\"day\"),\n * ) // => DateTime.makeUnsafe(\"2024-01-02T00:00:00Z\")\n * ```\n *\n * @category math\n * @since 3.6.0\n */\nexport const nearest = Internal.nearest;\n// =============================================================================\n// formatting\n// =============================================================================\n/**\n * Formats a `DateTime` with `Intl.DateTimeFormat`.\n *\n * **Details**\n *\n * Unless a `timeZone` option is supplied, UTC values are formatted in UTC and\n * zoned values are formatted in their named zone or fixed-offset zone.\n *\n * Fixed-offset zones depend on runtime support for offset `timeZone`\n * identifiers. When unsupported, formatting falls back to UTC with the\n * `DateTime` adjusted to the offset.\n *\n * **Example** (Formatting DateTime values with Intl options)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const dt = DateTime.makeZonedUnsafe(\"2024-06-15T14:30:00Z\", {\n *   timeZone: \"Europe/London\"\n * })\n *\n * DateTime.format(dt, {\n *   dateStyle: \"full\",\n *   timeStyle: \"short\",\n *   locale: \"en-US\"\n * }) // => \"Saturday, June 15, 2024 at 3:30 PM\"\n * ```\n *\n * @category formatting\n * @since 3.6.0\n */\nexport const format = Internal.format;\n/**\n * Formats a `DateTime` with `Intl.DateTimeFormat` using the system local time\n * zone and locale.\n *\n * **Example** (Formatting DateTime values locally)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const dt = DateTime.makeUnsafe(\"2024-06-15T14:30:00Z\")\n *\n * // Uses system local time zone and locale\n * DateTime.formatLocal(dt, {\n *   year: \"numeric\",\n *   month: \"long\",\n *   day: \"numeric\",\n *   hour: \"2-digit\",\n *   minute: \"2-digit\"\n * })\n * ```\n *\n * @category formatting\n * @since 3.6.0\n */\nexport const formatLocal = Internal.formatLocal;\n/**\n * Formats a `DateTime` with `Intl.DateTimeFormat` using the UTC time zone.\n *\n * **Details**\n *\n * This forces the time zone to be UTC.\n *\n * **Example** (Formatting DateTime values in UTC)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const dt = DateTime.makeZonedUnsafe(\"2024-06-15T14:30:00Z\", {\n *   timeZone: \"Europe/London\"\n * })\n *\n * // Force UTC formatting regardless of time zone\n * DateTime.formatUtc(dt, {\n *   year: \"numeric\",\n *   month: \"2-digit\",\n *   day: \"2-digit\",\n *   hour: \"2-digit\",\n *   minute: \"2-digit\",\n *   timeZoneName: \"short\"\n * })\n * ```\n *\n * @category formatting\n * @since 3.6.0\n */\nexport const formatUtc = Internal.formatUtc;\n/**\n * Formats a `DateTime` as a string using the `Intl.DateTimeFormat` API.\n *\n * **When to use**\n *\n * Use when you already have an `Intl.DateTimeFormat` and want it to control the\n * locale, time zone, and formatting options.\n *\n * **Details**\n *\n * The formatter receives the `DateTime` epoch milliseconds. Any time zone\n * conversion comes from the supplied formatter.\n *\n * **Example** (Formatting DateTime values with custom formatters)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const dt = DateTime.makeUnsafe(\"2024-06-15T14:30:00Z\")\n *\n * // Create a custom formatter\n * const formatter = new Intl.DateTimeFormat(\"de-DE\", {\n *   year: \"numeric\",\n *   month: \"long\",\n *   day: \"numeric\",\n *   hour: \"2-digit\",\n *   minute: \"2-digit\",\n *   timeZone: \"Europe/Berlin\"\n * })\n *\n * DateTime.formatIntl(dt, formatter).length > 0 // => true\n * ```\n *\n * @see {@link formatUtc} for formatting with options forced to UTC\n * @see {@link formatIso} for stable ISO formatting\n *\n * @category formatting\n * @since 3.6.0\n */\nexport const formatIntl = Internal.formatIntl;\n/**\n * Formats a `DateTime` as a UTC ISO string.\n *\n * **Details**\n *\n * Always returns the UTC representation in ISO 8601 format, ignoring any time zone.\n *\n * **Example** (Formatting DateTime values as ISO strings)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * DateTime.formatIso(DateTime.makeUnsafe(\"2024-01-01T12:30:45.123Z\")) // => \"2024-01-01T12:30:45.123Z\"\n *\n * const zoned = DateTime.makeZonedUnsafe(\"2024-01-01T12:30:45.123Z\", {\n *   timeZone: \"Europe/London\"\n * })\n * DateTime.formatIso(zoned) // => \"2024-01-01T12:30:45.123Z\"\n * ```\n *\n * @category formatting\n * @since 3.6.0\n */\nexport const formatIso = Internal.formatIso;\n/**\n * Formats a `DateTime` as a time zone adjusted ISO date string.\n *\n * **Details**\n *\n * Returns only the date part (YYYY-MM-DD) after applying time zone adjustments.\n *\n * **Example** (Formatting DateTime values as ISO dates)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const dt = DateTime.makeUnsafe(\"2024-01-01T23:30:00Z\")\n * DateTime.formatIsoDate(dt) // => \"2024-01-01\"\n *\n * const zoned = DateTime.makeZonedUnsafe(\"2024-01-01T23:30:00Z\", {\n *   timeZone: \"Pacific/Auckland\" // UTC+12/13\n * })\n * DateTime.formatIsoDate(zoned) // => \"2024-01-02\"\n * ```\n *\n * @category formatting\n * @since 3.6.0\n */\nexport const formatIsoDate = Internal.formatIsoDate;\n/**\n * Formats a `DateTime` as a UTC ISO date string.\n *\n * **Details**\n *\n * Returns only the date part (YYYY-MM-DD) in UTC, ignoring any time zone.\n *\n * **Example** (Formatting DateTime values as UTC ISO dates)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const dt = DateTime.makeUnsafe(\"2024-01-01T23:30:00Z\")\n * DateTime.formatIsoDateUtc(dt) // => \"2024-01-01\"\n *\n * const zoned = DateTime.makeZonedUnsafe(\"2024-01-01T23:30:00Z\", {\n *   timeZone: \"Pacific/Auckland\"\n * })\n * DateTime.formatIsoDateUtc(zoned) // => \"2024-01-01\"\n * ```\n *\n * @category formatting\n * @since 3.6.0\n */\nexport const formatIsoDateUtc = Internal.formatIsoDateUtc;\n/**\n * Formats a `DateTime.Zoned` as an ISO string with an offset.\n *\n * **Details**\n *\n * For `DateTime.Utc`, returns the same as `formatIso`. For `DateTime.Zoned`,\n * includes the time zone offset in the format.\n *\n * **Example** (Formatting DateTime values with offsets)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const utc = DateTime.makeUnsafe(\"2024-01-01T12:00:00Z\")\n * DateTime.formatIsoOffset(utc) // => \"2024-01-01T12:00:00.000Z\"\n *\n * const zoned = DateTime.makeZonedUnsafe(\"2024-01-01T12:00:00Z\", {\n *   timeZone: DateTime.zoneMakeOffset(3 * 60 * 60 * 1000)\n * })\n * DateTime.formatIsoOffset(zoned) // => \"2024-01-01T15:00:00.000+03:00\"\n * ```\n *\n * @category formatting\n * @since 3.6.0\n */\nexport const formatIsoOffset = Internal.formatIsoOffset;\n/**\n * Formats a `DateTime.Zoned` as a string.\n *\n * **Details**\n *\n * It uses the format: `YYYY-MM-DDTHH:mm:ss.sss+HH:MM[Time/Zone]`.\n *\n * **Example** (Formatting zoned DateTime values)\n *\n * ```ts import.meta.vitest\n * import { DateTime } from \"effect\"\n *\n * const zoned = DateTime.makeZonedUnsafe(\"2024-06-15T14:30:45.123Z\", {\n *   timeZone: \"Europe/London\"\n * })\n *\n * DateTime.formatIsoZoned(zoned) // => \"2024-06-15T15:30:45.123+01:00[Europe/London]\"\n *\n * const offsetZone = DateTime.makeZonedUnsafe(\"2024-06-15T14:30:45.123Z\", {\n *   timeZone: DateTime.zoneMakeOffset(3 * 60 * 60 * 1000)\n * })\n *\n * DateTime.formatIsoZoned(offsetZone) // => \"2024-06-15T17:30:45.123+03:00\"\n * ```\n *\n * @category formatting\n * @since 3.6.0\n */\nexport const formatIsoZoned = Internal.formatIsoZoned;\n/**\n * Create a Layer from the given time zone.\n *\n * **Details**\n *\n * This layer provides the `CurrentTimeZone` service with the specified time zone.\n *\n * **Example** (Providing current time zone layers)\n *\n * ```ts import.meta.vitest\n * import { DateTime, Effect } from \"effect\"\n *\n * const zone = DateTime.zoneMakeNamedUnsafe(\"Europe/London\")\n * const layer = DateTime.layerCurrentZone(zone)\n *\n * const program = Effect.gen(function*() {\n *   const now = yield* DateTime.nowInCurrentZone\n *   return DateTime.zoneToString(now.zone)\n * })\n *\n * // Use the layer to provide the time zone\n * await Effect.runPromise(Effect.provide(program, layer)) // => \"Europe/London\"\n * ```\n *\n * @category layers\n * @since 3.6.0\n */\nexport const layerCurrentZone = /*#__PURE__*/Layer.succeed(CurrentTimeZone);\n/**\n * Create a Layer from the given time zone offset.\n *\n * **Details**\n *\n * This layer provides the `CurrentTimeZone` service with a fixed offset time zone.\n *\n * **Example** (Providing fixed-offset time zone layers)\n *\n * ```ts import.meta.vitest\n * import { DateTime, Effect } from \"effect\"\n *\n * // Create a layer for UTC+3\n * const layer = DateTime.layerCurrentZoneOffset(3 * 60 * 60 * 1000)\n *\n * const program = Effect.gen(function*() {\n *   const now = yield* DateTime.nowInCurrentZone\n *   return DateTime.zoneToString(now.zone)\n * })\n *\n * await Effect.runPromise(Effect.provide(program, layer)) // => \"+03:00\"\n * ```\n *\n * @category layers\n * @since 3.6.0\n */\nexport const layerCurrentZoneOffset = offset => Layer.succeed(CurrentTimeZone)(Internal.zoneMakeOffset(offset));\n/**\n * Create a Layer from the given IANA time zone identifier.\n *\n * **Details**\n *\n * This layer provides the `CurrentTimeZone` service with a named time zone.\n * If the time zone identifier is invalid, the layer will fail.\n *\n * **Example** (Providing named time zone layers)\n *\n * ```ts import.meta.vitest\n * import { DateTime, Effect } from \"effect\"\n *\n * const layer = DateTime.layerCurrentZoneNamed(\"Europe/London\")\n *\n * const program = Effect.gen(function*() {\n *   const now = yield* DateTime.nowInCurrentZone\n *   return DateTime.zoneToString(now.zone)\n * })\n *\n * await Effect.runPromise(Effect.provide(program, layer)) // => \"Europe/London\"\n * ```\n *\n * @category layers\n * @since 3.6.0\n */\nexport const layerCurrentZoneNamed = /*#__PURE__*/flow(Internal.zoneMakeNamedEffect, /*#__PURE__*/Layer.effect(CurrentTimeZone));\n/**\n * Create a Layer from the system's local time zone.\n *\n * **Details**\n *\n * This layer provides the `CurrentTimeZone` service using the system's\n * configured local time zone.\n *\n * **Example** (Providing local time zone layers)\n *\n * ```ts import.meta.vitest\n * import { DateTime, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const now = yield* DateTime.nowInCurrentZone\n *   return DateTime.isZoned(now)\n * })\n *\n * // Use the system's local time zone\n * await Effect.runPromise(Effect.provide(program, DateTime.layerCurrentZoneLocal)) // => true\n * ```\n *\n * @category layers\n * @since 3.6.0\n */\nexport const layerCurrentZoneLocal = /*#__PURE__*/Layer.sync(CurrentTimeZone)(zoneMakeLocal);\n//# sourceMappingURL=DateTime.js.map","/**\n * Builds one-way conversions used by schemas.\n *\n * A `Getter<T, E, R>` receives an optional encoded value and returns an\n * optional decoded value. It can also report a schema issue or require Effect\n * services. Schema transformations use getters to describe one direction of a\n * conversion, for example decoding a field from input data. This module\n * includes basic getters, validation helpers, pure and effectful conversions,\n * and ready-made conversions for common string, number, binary, date, form, and\n * URL-related values.\n *\n * @since 4.0.0\n */\nimport * as Arr from \"./Array.js\";\nimport * as DateTime from \"./DateTime.js\";\nimport * as Effect from \"./Effect.js\";\nimport * as Encoding from \"./Encoding.js\";\nimport * as InternalRecord from \"./internal/record.js\";\nimport * as Option from \"./Option.js\";\nimport * as Pipeable from \"./Pipeable.js\";\nimport * as Predicate from \"./Predicate.js\";\nimport * as Result from \"./Result.js\";\nimport * as SchemaIssue from \"./SchemaIssue.js\";\nimport * as Str from \"./String.js\";\n/**\n * Constructs a composable schema getter.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Getter = class extends Pipeable.Class {\n  run;\n  constructor(run) {\n    super();\n    this.run = run;\n  }\n  map(f) {\n    return new Getter((oe, options) => this.run(oe, options).pipe(Effect.mapEager(Option.map(f))));\n  }\n  compose(other) {\n    if (isPassthrough(this)) {\n      return other;\n    }\n    if (isPassthrough(other)) {\n      return this;\n    }\n    return new Getter((oe, options) => this.run(oe, options).pipe(Effect.flatMapEager(ot => other.run(ot, options))));\n  }\n};\n/**\n * Creates a getter that always produces the given constant value, ignoring the input.\n *\n * **When to use**\n *\n * Use when you need a schema getter that always decodes a field to a fixed\n * value.\n *\n * **Details**\n *\n * The getter is pure and always returns `Option.some(t)` regardless of whether\n * the input is `Some` or `None`.\n *\n * **Example** (Returning a constant getter)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const alwaysZero = SchemaGetter.succeed(0)\n * await Effect.runPromise(alwaysZero.run(Option.none(), {})) // => Option.some(0)\n * ```\n *\n * @see {@link transform} when you need to use the input value\n * @see {@link passthrough} when you want to keep the input as-is\n *\n * @category constructors\n * @since 4.0.0\n */\nexport function succeed(t) {\n  return new Getter(() => Effect.succeedSome(t));\n}\n/**\n * Creates a getter that always fails with the given issue.\n *\n * **When to use**\n *\n * Use when you need a schema getter that unconditionally rejects input.\n * - Building custom validation getters that produce specific error types.\n *\n * **Details**\n *\n * - Always fails with the `Issue` returned by `f`.\n * - The failure function receives the original `Option<E>` input and the\n *   effective `ParseOptions` for error context.\n *\n * **Example** (Defining an always-failing getter)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter, SchemaIssue } from \"effect\"\n *\n * const rejectAll = SchemaGetter.fail<string, string>(\n *   () => new SchemaIssue.InvalidValue({ message: \"not allowed\" })\n * )\n * const issue = await Effect.runPromise(Effect.flip(rejectAll.run(Option.some(\"x\"), {})))\n * issue._tag // => \"InvalidValue\"\n * ```\n *\n * @see {@link forbidden} for a convenience helper for `Forbidden` issues\n * @see {@link checkEffect} to fail conditionally based on input value\n *\n * @category constructors\n * @since 4.0.0\n */\nexport function fail(f) {\n  return new Getter((oe, options) => Effect.fail(f(oe, options)));\n}\n/**\n * Creates a getter that always fails with a `Forbidden` issue.\n *\n * **When to use**\n *\n * Use when you need a schema getter to disallow a field or direction\n * (encode/decode) entirely.\n * - You want a clear \"forbidden\" error message in schema validation output.\n *\n * **Details**\n *\n * - Always fails with `SchemaIssue.Forbidden`.\n * - The message function receives the `Option<E>` input for context.\n *\n * **Example** (Forbidding a decode direction)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const noEncode = SchemaGetter.forbidden<string, number>(\n *   () => \"encoding is not supported\"\n * )\n * const issue = await Effect.runPromise(Effect.flip(noEncode.run(Option.some(1), {})))\n * issue._tag // => \"Forbidden\"\n * ```\n *\n * @see {@link fail} to fail with a custom issue type\n *\n * @category constructors\n * @since 4.0.0\n */\nexport function forbidden(message) {\n  return fail((oe, options) => {\n    const annotations = {\n      message: message(oe)\n    };\n    return Option.isSome(oe) ? new SchemaIssue.Forbidden(annotations, oe.value, options) : new SchemaIssue.Forbidden(annotations);\n  });\n}\n/**\n * Getter that always fails with a `Forbidden` issue indicating that encoding is unsupported.\n *\n * **When to use**\n *\n * Use as the encode side of a decode-only Schema transformation.\n *\n * **Details**\n *\n * Its `Getter<never, unknown>` type is assignable to every encoding getter because it accepts any input and never\n * produces an output value.\n *\n * **Example** (Rejecting encoding)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const issue = await Effect.runPromise(\n *   Effect.flip(SchemaGetter.forbiddenEncoding.run(Option.some(\"value\"), {}))\n * )\n * issue._tag // => \"Forbidden\"\n * ```\n *\n * @see {@link forbidden} for a forbidden getter with a custom message\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const forbiddenEncoding = /*#__PURE__*/forbidden(() => \"Encoding is not supported\");\nconst passthrough_ = /*#__PURE__*/new Getter(Effect.succeed);\nfunction isPassthrough(getter) {\n  return getter.run === passthrough_.run;\n}\nexport function passthrough() {\n  return passthrough_;\n}\nexport function passthroughSupertype() {\n  return passthrough_;\n}\nexport function passthroughSubtype() {\n  return passthrough_;\n}\n/**\n * Creates a getter that handles the case when the input is absent (`Option.None`).\n *\n * **When to use**\n *\n * Use when you need a schema getter to provide a fallback or computed value for\n * missing struct keys.\n * - Building custom \"default value\" logic more complex than {@link withDefault}.\n *\n * **Details**\n *\n * - When input is `None`, calls `f` to produce the result.\n * - When input is `Some`, passes it through unchanged.\n * - `f` receives the parse options and may return `None` to keep the value absent.\n *\n * **Example** (Providing a default timestamp for a missing field)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const withTimestamp = SchemaGetter.onNone<number>(() =>\n *   Effect.succeed(Option.some(0))\n * )\n * await Effect.runPromise(withTimestamp.run(Option.none(), {})) // => Option.some(0)\n * ```\n *\n * @see {@link required} when absent input should fail\n * @see {@link withDefault} for a simpler default value for undefined inputs\n * @see {@link onSome} to handle only present values\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function onNone(f) {\n  return new Getter((ot, options) => Option.isNone(ot) ? f(options) : Effect.succeed(ot));\n}\n/**\n * Creates a getter that fails with `MissingKey` if the input is absent (`Option.None`).\n *\n * **When to use**\n *\n * Use when you need a schema getter to require a struct field in the encoded\n * input and report a missing key error when it is absent.\n *\n * **Details**\n *\n * - When input is `None`, fails with `SchemaIssue.MissingKey`.\n * - When input is `Some`, passes it through unchanged.\n * - Optional `annotations` customize the error message for the missing key.\n *\n * **Example** (Defining a required struct field)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const mustExist = SchemaGetter.required<string>()\n * const issue = await Effect.runPromise(Effect.flip(mustExist.run(Option.none(), {})))\n * issue._tag // => \"MissingKey\"\n * ```\n *\n * @see {@link onNone} to provide a fallback instead of failing\n * @see {@link withDefault} to substitute a default for undefined values\n *\n * @category validation\n * @since 4.0.0\n */\nexport function required(annotations) {\n  return onNone(() => Effect.fail(new SchemaIssue.MissingKey(annotations)));\n}\n/**\n * Creates a getter that handles present values (`Option.Some`), passing `None` through.\n *\n * **When to use**\n *\n * Use when you need a schema getter to transform or validate only when a field\n * value is present.\n * - Missing keys should remain absent in the output.\n *\n * **Details**\n *\n * - When input is `None`, returns `None` (no-op).\n * - When input is `Some(e)`, calls `f(e, options)` to produce the result.\n * - `f` may return `None` to omit the value, or fail with an `Issue`.\n *\n * **Example** (Transforming only present values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const parseIfPresent = SchemaGetter.onSome<number, string>(\n *   (s) => Effect.succeed(Option.some(Number(s)))\n * )\n * await Effect.runPromise(parseIfPresent.run(Option.some(\"42\"), {})) // => Option.some(42)\n * ```\n *\n * @see {@link onNone} to handle only absent values\n * @see {@link transform} for a simpler pure transformation of present values\n * @see {@link transformEffect} for effectful transformation of present values\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function onSome(f) {\n  return new Getter((oe, options) => Option.isNone(oe) ? Effect.succeedNone : f(oe.value, options));\n}\n/**\n * Creates a getter that validates a value using an effectful check function.\n *\n * **When to use**\n *\n * Use when you need a schema getter to validate a decoded value (e.g. check a\n * constraint or call an external service).\n * - The validation may be asynchronous or require Effect services.\n *\n * **Details**\n *\n * - Only runs when input is `Some` — `None` passes through.\n * - The check function returns a validation result:\n *   - `undefined` or `true` — value is valid, passes through.\n *   - `false` or a `string` — value is invalid, fails with an `Issue`.\n *   - An `Issue` object — fails with that issue directly.\n *   - `{ path, issue }` — fails with a nested path issue (`issue` may be a\n *     message string or a full {@link SchemaIssue.Issue}).\n * - Does not transform the value — input and output types are the same.\n *\n * **Example** (Validating effectfully)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const nonNegative = SchemaGetter.checkEffect<number>((n) =>\n *   Effect.succeed(n >= 0 ? undefined : \"must be non-negative\")\n * )\n * await Effect.runPromise(nonNegative.run(Option.some(1), {})) // => Option.some(1)\n * ```\n *\n * @see {@link transform} when you need to change the value, not just validate\n * @see {@link fail} for unconditional failure\n *\n * @category validation\n * @since 4.0.0\n */\nexport function checkEffect(f) {\n  return onSome((t, options) => {\n    return f(t, options).pipe(Effect.flatMapEager(out => {\n      const issue = SchemaIssue.makeSingle(out, t, options);\n      return issue ? Effect.fail(issue) : Effect.succeed(Option.some(t));\n    }));\n  });\n}\n/**\n * Creates a getter that applies a pure function to present values.\n *\n * **When to use**\n *\n * Use when you need a schema getter for a pure, infallible transformation\n * between types.\n * - Building encode/decode pairs for `Schema.decodeTo`.\n *\n * **Details**\n *\n * - This is the most commonly used constructor.\n * - Transforms `Some(e)` to `Some(f(e))` and leaves `None` unchanged.\n * - Skips `None` inputs — only called when a value is present.\n * - Never fails.\n *\n * **Example** (Transforming strings to numbers)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaGetter } from \"effect\"\n *\n * const NumberFromString = Schema.String.pipe(\n *   Schema.decodeTo(Schema.Number, {\n *     decode: SchemaGetter.transform((s) => Number(s)),\n *     encode: SchemaGetter.transform((n) => String(n))\n *   })\n * )\n * Schema.decodeSync(NumberFromString)(\"42\") // => 42\n * ```\n *\n * @see {@link transformEffect} when the transformation returns an `Effect`\n * @see {@link transformOptional} when you need to handle `None` inputs\n * @see {@link passthrough} when no transformation is needed\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function transform(f) {\n  return transformOptional(Option.map(f));\n}\n/**\n * Creates a getter that applies an effectful transformation to present values.\n *\n * **When to use**\n *\n * Use when you need a schema getter for a transformation that may fail, require\n * Effect services, or run asynchronously.\n *\n * **Details**\n *\n * - Skips `None` inputs — only called when a value is present.\n * - On success, wraps the result in `Some`.\n * - On failure, propagates the `Issue`.\n *\n * **Example** (Parsing with failure)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter, SchemaIssue } from \"effect\"\n *\n * const safeParseInt = SchemaGetter.transformEffect<number, string>(\n *   (s, options) => {\n *     const n = parseInt(s, 10)\n *     return isNaN(n)\n *       ? Effect.fail(new SchemaIssue.InvalidValue({ message: \"not an integer\" }, s, options))\n *       : Effect.succeed(n)\n *   }\n * )\n * await Effect.runPromise(safeParseInt.run(Option.some(\"42\"), {})) // => Option.some(42)\n * ```\n *\n * @see {@link transform} when transformation cannot fail\n * @see {@link onSome} when you need full `Option` control over the output\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function transformEffect(f) {\n  return onSome((e, options) => f(e, options).pipe(Effect.mapEager(Option.some)));\n}\n/**\n * Creates a getter that transforms the full `Option` — both present and absent values.\n *\n * **When to use**\n *\n * Use when you need a schema getter to handle both `Some` and `None` cases.\n *\n * **Details**\n *\n * The getter is pure and never fails. It receives the full `Option<E>` and\n * must return `Option<T>`, so it can turn a present value into absent or an\n * absent value into present.\n *\n * **Example** (Filtering out empty strings)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const skipEmpty = SchemaGetter.transformOptional<string, string>((o) =>\n *   Option.filter(o, (s) => s.length > 0)\n * )\n * await Effect.runPromise(skipEmpty.run(Option.some(\"\"), {})) // => Option.none()\n * ```\n *\n * @see {@link transform} when you only need to transform present values\n * @see {@link omit} when you always want `None`\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function transformOptional(f) {\n  return new Getter(oe => Effect.succeed(f(oe)));\n}\n/**\n * Creates a getter that always returns `None`, effectively omitting the value from output.\n *\n * **When to use**\n *\n * Use when you need a schema getter to exclude a field during decoding or\n * encoding.\n *\n * **Details**\n *\n * - Always returns `Option.None` regardless of input.\n * - Never fails.\n *\n * **Example** (Omitting a field during encoding)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const omitField = SchemaGetter.omit<string>()\n * await Effect.runPromise(omitField.run(Option.some(\"hidden\"), {})) // => Option.none()\n * ```\n *\n * @see {@link transformOptional} when you want conditional omission\n * @see {@link forbidden} when you want to fail instead of silently omit\n *\n * @category filtering\n * @since 4.0.0\n */\nexport function omit() {\n  return new Getter(() => Effect.succeedNone);\n}\n/**\n * Creates a getter that replaces `undefined` values with a default.\n *\n * **When to use**\n *\n * Use when you need a schema getter to provide a fallback for a field that may\n * be `undefined` in the encoded input.\n *\n * **Details**\n *\n * - If the input is `Some(undefined)` or `None`, produces `Some(T)`.\n * - If the input is `Some(value)` where value is not `undefined`, passes it through.\n * - `defaultValue` is an `Effect` that will be executed each time a default is needed.\n *\n * **Example** (Providing a default value for an optional field)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const withZero = SchemaGetter.withDefault(Effect.succeed(0))\n * await Effect.runPromise(withZero.run(Option.some(undefined), {})) // => Option.some(0)\n * ```\n *\n * @see {@link onNone} to handle only absent keys (not `undefined` values)\n * @see {@link required} when absent input should fail instead of using a default\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function withDefault(defaultValue) {\n  return new Getter(o => {\n    const filtered = Option.filter(o, Predicate.isNotUndefined);\n    return Option.isSome(filtered) ? Effect.succeed(filtered) : Effect.mapEager(defaultValue, Option.some);\n  });\n}\n/**\n * Coerces any value to a `string` using the global `String()` constructor.\n *\n * **When to use**\n *\n * Use when you need a schema getter to coerce a present encoded value to a\n * string with `String()`.\n *\n * **Details**\n *\n * The getter is pure, never fails, and delegates to `globalThis.String`.\n *\n * **Example** (Coercing to a string)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const toString = SchemaGetter.String<number>()\n * await Effect.runPromise(toString.run(Option.some(42), {})) // => Option.some(\"42\")\n * ```\n *\n * @see {@link transform} for custom string conversions\n *\n * @category converting\n * @since 4.0.0\n */\nexport function String() {\n  return transform(globalThis.String);\n}\n/**\n * Coerces any value to a `number` using the global `Number()` constructor.\n *\n * **When to use**\n *\n * Use when you need a schema getter to coerce a present encoded value to a\n * number with `Number()`.\n *\n * **Details**\n *\n * The getter is pure, never fails, and delegates to `globalThis.Number`. It may\n * produce `NaN` for non-numeric inputs.\n *\n * **Example** (Coercing to a number)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const toNumber = SchemaGetter.Number<string>()\n * await Effect.runPromise(toNumber.run(Option.some(\"42\"), {})) // => Option.some(42)\n * ```\n *\n * @see {@link transformEffect} for effectful or validated number parsing\n *\n * @category converting\n * @since 4.0.0\n */\nexport function Number() {\n  return transform(globalThis.Number);\n}\n/**\n * Coerces any value to a `boolean` using the global `Boolean()` constructor.\n *\n * **When to use**\n *\n * Use when you need a schema getter to coerce a present encoded value to a\n * boolean with `Boolean()`.\n *\n * **Details**\n *\n * The getter is pure, never fails, and delegates to `globalThis.Boolean`.\n *\n * **Example** (Coercing to a boolean)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const toBool = SchemaGetter.Boolean<string>()\n * await Effect.runPromise(toBool.run(Option.some(\"true\"), {})) // => Option.some(true)\n * ```\n *\n * @category converting\n * @since 4.0.0\n */\nexport function Boolean() {\n  return transform(globalThis.Boolean);\n}\n/**\n * Coerces a value to `bigint` using the global `BigInt()` constructor.\n *\n * **When to use**\n *\n * Use when you need a schema getter to convert a present string, number, or\n * boolean value to `bigint`.\n *\n * **Details**\n *\n * - Delegates to `globalThis.BigInt`.\n * - Throws at runtime if the input cannot be converted (e.g. non-numeric string).\n *\n * **Example** (Coercing to a bigint)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const toBigInt = SchemaGetter.BigInt<string>()\n * await Effect.runPromise(toBigInt.run(Option.some(\"42\"), {})) // => Option.some(42n)\n * ```\n *\n * @category converting\n * @since 4.0.0\n */\nexport function BigInt() {\n  return transform(globalThis.BigInt);\n}\n/**\n * Coerces a value to a `Date` using `new Date(input)`.\n *\n * **When to use**\n *\n * Use when you need a schema getter to coerce a present string, number, or\n * existing date object into a new date object.\n *\n * **Details**\n *\n * - Delegates to `new globalThis.Date(input)`.\n * - Does not validate the result — may produce an invalid Date.\n *\n * **Example** (Coercing to a Date)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const toDate = SchemaGetter.Date<string>()\n * const result = await Effect.runPromise(toDate.run(Option.some(\"1970-01-01\"), {}))\n * Option.map(result, (date) => date.toISOString()) // => Option.some(\"1970-01-01T00:00:00.000Z\")\n * ```\n *\n * @see {@link dateTimeUtcFromInput} for validated DateTime parsing\n *\n * @category converting\n * @since 4.0.0\n */\nexport function Date() {\n  return transform(u => new globalThis.Date(u));\n}\n/**\n * Strips whitespace from both ends of a string.\n *\n * **Details**\n *\n * - Pure, delegates to `String.trim`.\n *\n * **Example** (Trimming whitespace)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const trimmed = SchemaGetter.trim<string>()\n * await Effect.runPromise(trimmed.run(Option.some(\"  hello  \"), {})) // => Option.some(\"hello\")\n * ```\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function trim() {\n  return transform(Str.trim);\n}\n/**\n * Capitalizes the first character of a string.\n *\n * **Details**\n *\n * - Pure, delegates to `String.capitalize`.\n *\n * **Example** (Capitalizing a string)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const cap = SchemaGetter.capitalize<string>()\n * await Effect.runPromise(cap.run(Option.some(\"hello\"), {})) // => Option.some(\"Hello\")\n * ```\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function capitalize() {\n  return transform(Str.capitalize);\n}\n/**\n * Uncapitalizes the first character of a string.\n *\n * **Details**\n *\n * - Pure, delegates to `String.uncapitalize`.\n *\n * **Example** (Uncapitalizing a string)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const uncap = SchemaGetter.uncapitalize<string>()\n * await Effect.runPromise(uncap.run(Option.some(\"Hello\"), {})) // => Option.some(\"hello\")\n * ```\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function uncapitalize() {\n  return transform(Str.uncapitalize);\n}\n/**\n * Converts a `snake_case` string to `camelCase`.\n *\n * **Details**\n *\n * - Pure, delegates to `String.snakeToCamel`.\n *\n * **Example** (Converting snake case to camel case)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const toCamel = SchemaGetter.snakeToCamel<string>()\n * await Effect.runPromise(toCamel.run(Option.some(\"user_name\"), {})) // => Option.some(\"userName\")\n * ```\n *\n * @see {@link camelToSnake} for the inverse operation\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function snakeToCamel() {\n  return transform(Str.snakeToCamel);\n}\n/**\n * Converts a `camelCase` string to `snake_case`.\n *\n * **Details**\n *\n * - Pure, delegates to `String.camelToSnake`.\n *\n * **Example** (Converting camel case to snake case)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const toSnake = SchemaGetter.camelToSnake<string>()\n * await Effect.runPromise(toSnake.run(Option.some(\"userName\"), {})) // => Option.some(\"user_name\")\n * ```\n *\n * @see {@link snakeToCamel} for the inverse operation\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function camelToSnake() {\n  return transform(Str.camelToSnake);\n}\n/**\n * Converts a string to lowercase.\n *\n * **Details**\n *\n * - Pure, delegates to `String.toLowerCase`.\n *\n * **Example** (Converting to lowercase)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const lower = SchemaGetter.toLowerCase<string>()\n * await Effect.runPromise(lower.run(Option.some(\"HELLO\"), {})) // => Option.some(\"hello\")\n * ```\n *\n * @see {@link toUpperCase} for the inverse operation\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function toLowerCase() {\n  return transform(Str.toLowerCase);\n}\n/**\n * Converts a string to uppercase.\n *\n * **Details**\n *\n * - Pure, delegates to `String.toUpperCase`.\n *\n * **Example** (Converting to uppercase)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const upper = SchemaGetter.toUpperCase<string>()\n * await Effect.runPromise(upper.run(Option.some(\"hello\"), {})) // => Option.some(\"HELLO\")\n * ```\n *\n * @see {@link toLowerCase} for the inverse operation\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function toUpperCase() {\n  return transform(Str.toUpperCase);\n}\nexport function parseJson(options) {\n  return onSome((input, parseOptions) => Effect.try({\n    try: () => Option.some(JSON.parse(input, options?.reviver)),\n    catch: () => new SchemaIssue.InvalidValue({\n      expected: \"a valid JSON string\"\n    }, input, parseOptions)\n  }));\n}\n/**\n * Stringifies a present value using `JSON.stringify`.\n *\n * **When to use**\n *\n * Use when you need a schema getter to serialize a present decoded value to\n * JSON text during encoding.\n *\n * **Details**\n *\n * - Skips `None` inputs.\n * - If `JSON.stringify` throws or returns `undefined`, fails with\n *   `SchemaIssue.InvalidValue`.\n * - Supports optional `replacer` and `space` options, matching\n *   `JSON.stringify`.\n *\n * **Example** (Stringifying JSON)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const stringify = SchemaGetter.stringifyJson()\n * await Effect.runPromise(stringify.run(Option.some({ a: 1 }), {})) // => Option.some(\"{\\\"a\\\":1}\")\n * ```\n *\n * @see {@link parseJson} for the inverse operation\n *\n * @category encoding\n * @since 4.0.0\n */\nexport function stringifyJson(options) {\n  return onSome((input, parseOptions) => Effect.try({\n    try: () => {\n      const output = JSON.stringify(input, options?.replacer, options?.space);\n      if (output === undefined) {\n        throw new TypeError(\"Value cannot be represented as JSON\");\n      }\n      return Option.some(output);\n    },\n    catch: () => new SchemaIssue.InvalidValue({\n      expected: \"a JSON-serializable value\"\n    }, input, parseOptions)\n  }));\n}\n/**\n * Parses a string into a record of key-value pairs.\n *\n * **When to use**\n *\n * Use when you need a schema getter to parse a present encoded string that\n * contains delimited key-value pairs (e.g. `\"a=1,b=2\"`).\n *\n * **Details**\n *\n * The getter is pure and never fails. It splits the string by `separator`\n * (default `,`) and then each pair by `keyValueSeparator` (default `=`). Pairs\n * missing a key or value are silently skipped.\n *\n * **Example** (Parsing a key-value string)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const parse = SchemaGetter.splitKeyValue<string>()\n * await Effect.runPromise(parse.run(Option.some(\"a=1,b=2\"), {})) // => Option.some({ a: \"1\", b: \"2\" })\n * ```\n *\n * @see {@link joinKeyValue} for the inverse operation\n * @see {@link split} to split into an array of strings\n *\n * @category splitting\n * @since 4.0.0\n */\nexport function splitKeyValue(options) {\n  const separator = options?.separator ?? \",\";\n  const keyValueSeparator = options?.keyValueSeparator ?? \"=\";\n  return transform(input => input.split(separator).reduce((acc, pair) => {\n    const [key, value] = pair.split(keyValueSeparator);\n    if (key && value) {\n      InternalRecord.assignProperty(acc, key, value);\n    }\n    return acc;\n  }, {}));\n}\n/**\n * Joins a record of key-value pairs into a delimited string.\n *\n * **When to use**\n *\n * Use when you need a schema getter to serialize a present decoded record as a\n * delimited key-value string.\n *\n * **Details**\n *\n * The getter is pure and never fails. It joins entries with `separator`\n * (default `,`) and joins each key and value with `keyValueSeparator` (default\n * `=`).\n *\n * **Example** (Joining key-value records)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const join = SchemaGetter.joinKeyValue()\n * await Effect.runPromise(join.run(Option.some({ a: \"1\", b: \"2\" }), {})) // => Option.some(\"a=1,b=2\")\n * ```\n *\n * @see {@link splitKeyValue} for the inverse operation\n *\n * @category combining\n * @since 4.0.0\n */\nexport function joinKeyValue(options) {\n  const separator = options?.separator ?? \",\";\n  const keyValueSeparator = options?.keyValueSeparator ?? \"=\";\n  return transform(input => Object.entries(input).map(([key, value]) => `${key}${keyValueSeparator}${value}`).join(separator));\n}\n/**\n * Splits a string into an array of strings by a separator.\n *\n * **When to use**\n *\n * Use when you need a schema getter to split a present encoded string\n * containing a delimited list, such as CSV values.\n *\n * **Details**\n *\n * The getter is pure and never fails. It splits by `separator` (default `,`).\n * An empty string produces an empty array, not `[\"\"]`.\n *\n * **Example** (Splitting a comma-separated string)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const splitComma = SchemaGetter.split<string>()\n * await Effect.runPromise(splitComma.run(Option.some(\"a,b,c\"), {})) // => Option.some([\"a\", \"b\", \"c\"])\n * ```\n *\n * @see {@link splitKeyValue} when values are key-value pairs\n *\n * @category splitting\n * @since 4.0.0\n */\nexport function split(options) {\n  const separator = options?.separator ?? \",\";\n  return transform(input => input === \"\" ? [] : input.split(separator));\n}\n/**\n * Encodes a `Uint8Array` or string to a Base64 string.\n *\n * **Details**\n *\n * The getter is pure and never fails.\n *\n * **Example** (Encoding to Base64)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const encode = SchemaGetter.encodeBase64<Uint8Array>()\n * await Effect.runPromise(encode.run(Option.some(new Uint8Array([1, 2, 3])), {})) // => Option.some(\"AQID\")\n * ```\n *\n * @see {@link decodeBase64} for the inverse operation to `Uint8Array`\n * @see {@link decodeBase64String} for the inverse operation to `string`\n * @see {@link encodeBase64Url} for the URL-safe variant\n *\n * @category encoding\n * @since 4.0.0\n */\nexport function encodeBase64() {\n  return transform(Encoding.encodeBase64);\n}\n/**\n * Encodes a `Uint8Array` or string to a URL-safe Base64 string.\n *\n * **Details**\n *\n * The getter is pure and never fails.\n *\n * **Example** (Encoding to Base64Url)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const encode = SchemaGetter.encodeBase64Url<Uint8Array>()\n * await Effect.runPromise(encode.run(Option.some(new Uint8Array([251, 255])), {})) // => Option.some(\"-_8\")\n * ```\n *\n * @see {@link decodeBase64Url} for the inverse operation to `Uint8Array`\n * @see {@link decodeBase64UrlString} for the inverse operation to `string`\n * @see {@link encodeBase64} for the standard Base64 variant\n *\n * @category encoding\n * @since 4.0.0\n */\nexport function encodeBase64Url() {\n  return transform(Encoding.encodeBase64Url);\n}\n/**\n * Encodes a `Uint8Array` or string to a hexadecimal string.\n *\n * **Details**\n *\n * The getter is pure and never fails.\n *\n * **Example** (Encoding to hex)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const encode = SchemaGetter.encodeHex<Uint8Array>()\n * await Effect.runPromise(encode.run(Option.some(new Uint8Array([1, 2, 3])), {})) // => Option.some(\"010203\")\n * ```\n *\n * @see {@link decodeHex} for the inverse operation to `Uint8Array`\n * @see {@link decodeHexString} for the inverse operation to `string`\n *\n * @category encoding\n * @since 4.0.0\n */\nexport function encodeHex() {\n  return transform(Encoding.encodeHex);\n}\n/**\n * Decodes a Base64 string to a `Uint8Array`.\n *\n * **Details**\n *\n * - Fails with `SchemaIssue.InvalidValue` if the input is not valid Base64.\n *\n * **Example** (Decoding Base64 to bytes)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const decode = SchemaGetter.decodeBase64<string>()\n * const result = await Effect.runPromise(decode.run(Option.some(\"AQID\"), {}))\n * Option.map(result, Array.from) // => Option.some([1, 2, 3])\n * ```\n *\n * @see {@link decodeBase64String} to decode to `string` instead\n * @see {@link encodeBase64} for the inverse operation\n *\n * @category decoding\n * @since 4.0.0\n */\nexport function decodeBase64() {\n  return transformEffect((input, options) => Effect.mapErrorEager(Effect.fromResult(Encoding.decodeBase64(input)), () => new SchemaIssue.InvalidValue({\n    expected: \"a valid Base64 string\"\n  }, input, options)));\n}\n/**\n * Decodes a Base64 string to a UTF-8 `string`.\n *\n * **Details**\n *\n * - Fails with `SchemaIssue.InvalidValue` if the input is not valid Base64.\n *\n * **Example** (Decoding Base64 to string)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const decode = SchemaGetter.decodeBase64String<string>()\n * await Effect.runPromise(decode.run(Option.some(\"aGVsbG8=\"), {})) // => Option.some(\"hello\")\n * ```\n *\n * @see {@link decodeBase64} to decode to `Uint8Array` instead\n * @see {@link encodeBase64} for the inverse operation\n *\n * @category decoding\n * @since 4.0.0\n */\nexport function decodeBase64String() {\n  return transformEffect((input, options) => Result.match(Encoding.decodeBase64String(input), {\n    onFailure: () => Effect.fail(new SchemaIssue.InvalidValue({\n      expected: \"a valid Base64 string\"\n    }, input, options)),\n    onSuccess: Effect.succeed\n  }));\n}\n/**\n * Decodes a URL-safe Base64 string to a `Uint8Array`.\n *\n * **Details**\n *\n * - Fails with `SchemaIssue.InvalidValue` if the input is not valid Base64Url.\n *\n * **Example** (Decoding Base64Url to bytes)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const decode = SchemaGetter.decodeBase64Url<string>()\n * const result = await Effect.runPromise(decode.run(Option.some(\"-_8=\"), {}))\n * Option.map(result, Array.from) // => Option.some([251, 255])\n * ```\n *\n * @see {@link decodeBase64UrlString} to decode to `string` instead\n * @see {@link encodeBase64Url} for the inverse operation\n *\n * @category decoding\n * @since 4.0.0\n */\nexport function decodeBase64Url() {\n  return transformEffect((input, options) => Result.match(Encoding.decodeBase64Url(input), {\n    onFailure: () => Effect.fail(new SchemaIssue.InvalidValue({\n      expected: \"a valid Base64Url string\"\n    }, input, options)),\n    onSuccess: Effect.succeed\n  }));\n}\n/**\n * Decodes a URL-safe Base64 string to a UTF-8 `string`.\n *\n * **Details**\n *\n * - Fails with `SchemaIssue.InvalidValue` if the input is not valid Base64Url.\n *\n * **Example** (Decoding Base64Url to string)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const decode = SchemaGetter.decodeBase64UrlString<string>()\n * await Effect.runPromise(decode.run(Option.some(\"aGVsbG8\"), {})) // => Option.some(\"hello\")\n * ```\n *\n * @see {@link decodeBase64Url} to decode to `Uint8Array` instead\n * @see {@link encodeBase64Url} for the inverse operation\n *\n * @category decoding\n * @since 4.0.0\n */\nexport function decodeBase64UrlString() {\n  return transformEffect((input, options) => Result.match(Encoding.decodeBase64UrlString(input), {\n    onFailure: () => Effect.fail(new SchemaIssue.InvalidValue({\n      expected: \"a valid Base64Url string\"\n    }, input, options)),\n    onSuccess: Effect.succeed\n  }));\n}\n/**\n * Decodes a hexadecimal string to a `Uint8Array`.\n *\n * **Details**\n *\n * - Fails with `SchemaIssue.InvalidValue` if the input is not valid hex.\n *\n * **Example** (Decoding hex to bytes)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const decode = SchemaGetter.decodeHex<string>()\n * const result = await Effect.runPromise(decode.run(Option.some(\"010203\"), {}))\n * Option.map(result, Array.from) // => Option.some([1, 2, 3])\n * ```\n *\n * @see {@link decodeHexString} to decode to `string` instead\n * @see {@link encodeHex} for the inverse operation\n *\n * @category decoding\n * @since 4.0.0\n */\nexport function decodeHex() {\n  return transformEffect((input, options) => Result.match(Encoding.decodeHex(input), {\n    onFailure: () => Effect.fail(new SchemaIssue.InvalidValue({\n      expected: \"a valid hexadecimal string\"\n    }, input, options)),\n    onSuccess: Effect.succeed\n  }));\n}\n/**\n * Decodes a hexadecimal string to a UTF-8 `string`.\n *\n * **Details**\n *\n * - Fails with `SchemaIssue.InvalidValue` if the input is not valid hex.\n *\n * **Example** (Decoding hex to string)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const decode = SchemaGetter.decodeHexString<string>()\n * await Effect.runPromise(decode.run(Option.some(\"68656c6c6f\"), {})) // => Option.some(\"hello\")\n * ```\n *\n * @see {@link decodeHex} to decode to `Uint8Array` instead\n * @see {@link encodeHex} for the inverse operation\n *\n * @category decoding\n * @since 4.0.0\n */\nexport function decodeHexString() {\n  return transformEffect((input, options) => Result.match(Encoding.decodeHexString(input), {\n    onFailure: () => Effect.fail(new SchemaIssue.InvalidValue({\n      expected: \"a valid hexadecimal string\"\n    }, input, options)),\n    onSuccess: Effect.succeed\n  }));\n}\n/**\n * Encodes a present string using `encodeURIComponent`.\n *\n * **Details**\n *\n * - Skips `None` inputs.\n * - May throw a `URIError` for malformed surrogate pairs; this exception is not\n *   converted into an `Issue`.\n *\n * **Example** (Encoding a URI component)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const encode = SchemaGetter.encodeUriComponent<string>()\n * await Effect.runPromise(encode.run(Option.some(\"hello world\"), {})) // => Option.some(\"hello%20world\")\n * ```\n *\n * @see {@link decodeUriComponent} for the inverse operation\n *\n * @category encoding\n * @since 4.0.0\n */\nexport function encodeUriComponent() {\n  return transform(encodeURIComponent);\n}\n/**\n * Decodes a URI component encoded string using `decodeURIComponent`.\n *\n * **Details**\n *\n * - Fails with `SchemaIssue.InvalidValue` if the input contains malformed percent-encoding sequences.\n *\n * **Example** (Decoding a URI component)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const decode = SchemaGetter.decodeUriComponent<string>()\n * await Effect.runPromise(decode.run(Option.some(\"hello%20world\"), {})) // => Option.some(\"hello world\")\n * ```\n *\n * @see {@link encodeUriComponent} for the inverse operation\n *\n * @category decoding\n * @since 4.0.0\n */\nexport function decodeUriComponent() {\n  return transformEffect((input, options) => {\n    try {\n      return Effect.succeed(globalThis.decodeURIComponent(input));\n    } catch {\n      return Effect.fail(new SchemaIssue.InvalidValue({\n        expected: \"a valid URI component\"\n      }, input, options));\n    }\n  });\n}\n/**\n * Parses a `DateTime.Input` value into a `DateTime.Utc`.\n *\n * **When to use**\n *\n * Use when you need a schema getter to decode a present encoded date/time value\n * to a `DateTime.Utc`.\n *\n * **Details**\n *\n * - Accepted input includes existing `DateTime` values, partial date/time parts,\n *   instant objects, zoned instant objects, JavaScript `Date` instances, epoch\n *   milliseconds, and date strings.\n * - Converts successfully parsed values to UTC.\n * - Fails with `SchemaIssue.InvalidValue` if the input cannot be parsed as a valid\n *   `DateTime`.\n *\n * **Example** (Parsing DateTime)\n *\n * ```ts import.meta.vitest\n * import { DateTime, Effect, Option, SchemaGetter } from \"effect\"\n *\n * const parseDate = SchemaGetter.dateTimeUtcFromInput<string>()\n * const result = await Effect.runPromise(parseDate.run(Option.some(\"2024-01-01T00:00:00Z\"), {}))\n * Option.map(result, DateTime.toEpochMillis) // => Option.some(1704067200000)\n * ```\n *\n * @see {@link Date} for a simpler coercion to `Date` (no validation)\n *\n * @category converting\n * @since 4.0.0\n */\nexport function dateTimeUtcFromInput() {\n  return transformEffect((input, options) => {\n    return Option.match(DateTime.make(input), {\n      onNone: () => Effect.fail(new SchemaIssue.InvalidValue({\n        message: \"Invalid DateTime input\"\n      }, input, options)),\n      onSome: dt => Effect.succeed(DateTime.toUtc(dt))\n    });\n  });\n}\n/**\n * Decodes a `FormData` object into a nested tree structure using bracket-path notation.\n *\n * **When to use**\n *\n * Use when you need a schema getter to parse `FormData` from HTTP requests into\n * structured objects.\n *\n * **Details**\n *\n * The getter is pure and never fails. It interprets bracket-path keys such as\n * `user[name]` and `items[0]` to build nested objects or arrays, and each leaf\n * value is a `string` or `Blob`.\n *\n * **Example** (Decoding FormData)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const decode = SchemaGetter.decodeFormData()\n * const formData = new FormData()\n * formData.append(\"user[name]\", \"Alice\")\n * await Effect.runPromise(decode.run(Option.some(formData), {})) // => Option.some({ user: { name: \"Alice\" } })\n * ```\n *\n * @see {@link encodeFormData} for the corresponding encoder\n * @see {@link makeTreeRecord} for the underlying bracket-path parser\n * @see {@link decodeURLSearchParams} for the URLSearchParams variant\n *\n * @category decoding\n * @since 4.0.0\n */\nexport function decodeFormData() {\n  return transform(input => makeTreeRecord(Array.from(input.entries())));\n}\nconst collectFormDataEntries = /*#__PURE__*/collectBracketPathEntries(value => typeof value === \"string\" || typeof Blob !== \"undefined\" && value instanceof Blob);\n/**\n * Encodes a nested object into a `FormData` instance using bracket-path notation.\n *\n * **When to use**\n *\n * Use when you need a schema getter to serialize structured data to `FormData`\n * for HTTP requests.\n *\n * **Details**\n *\n * The getter is pure and never fails. It flattens nested objects or arrays into\n * bracket-path keys such as `user[name]` and `items[0]`. Non-object inputs\n * produce an empty `FormData`.\n *\n * **Example** (Encoding to FormData)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const encode = SchemaGetter.encodeFormData()\n * const result = await Effect.runPromise(encode.run(Option.some({ name: \"Alice\" }), {}))\n * Option.map(result, (formData) => formData.get(\"name\")) // => Option.some(\"Alice\")\n * ```\n *\n * @see {@link decodeFormData} for the corresponding decoder\n * @see {@link collectBracketPathEntries} for the underlying flattener\n * @see {@link encodeURLSearchParams} for the URLSearchParams variant\n *\n * @category encoding\n * @since 4.0.0\n */\nexport function encodeFormData() {\n  return transform(input => {\n    const out = new FormData();\n    if (typeof input === \"object\" && input !== null) {\n      const entries = collectFormDataEntries(input);\n      entries.forEach(([key, value]) => {\n        out.append(key, value);\n      });\n    }\n    return out;\n  });\n}\n/**\n * Decodes a `URLSearchParams` object into a nested tree structure using bracket-path notation.\n *\n * **When to use**\n *\n * Use when you need a schema getter to parse query parameters from URLs into\n * structured objects.\n *\n * **Details**\n *\n * The getter is pure and never fails. It interprets bracket-path keys such as\n * `user[name]` and `items[0]` to build nested objects or arrays, and each leaf\n * value is a `string`.\n *\n * **Example** (Decoding URLSearchParams)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const decode = SchemaGetter.decodeURLSearchParams()\n * const params = new URLSearchParams(\"user[name]=Alice\")\n * await Effect.runPromise(decode.run(Option.some(params), {})) // => Option.some({ user: { name: \"Alice\" } })\n * ```\n *\n * @see {@link encodeURLSearchParams} for the corresponding encoder\n * @see {@link makeTreeRecord} for the underlying bracket-path parser\n * @see {@link decodeFormData} for the FormData variant\n *\n * @category decoding\n * @since 4.0.0\n */\nexport function decodeURLSearchParams() {\n  return transform(input => makeTreeRecord(Array.from(input.entries())));\n}\nconst collectURLSearchParamsEntries = /*#__PURE__*/collectBracketPathEntries(Predicate.isString);\n/**\n * Encodes a nested object into a `URLSearchParams` instance using bracket-path notation.\n *\n * **When to use**\n *\n * Use when you need a schema getter to serialize structured data to query\n * parameters for URLs.\n *\n * **Details**\n *\n * The getter is pure and never fails. It flattens nested objects or arrays into\n * bracket-path keys. Non-object inputs produce an empty `URLSearchParams`.\n *\n * **Example** (Encoding to URLSearchParams)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, SchemaGetter } from \"effect\"\n *\n * const encode = SchemaGetter.encodeURLSearchParams()\n * const result = await Effect.runPromise(encode.run(Option.some({ name: \"Alice\" }), {}))\n * Option.map(result, (params) => params.toString()) // => Option.some(\"name=Alice\")\n * ```\n *\n * @see {@link decodeURLSearchParams} for the corresponding decoder\n * @see {@link collectBracketPathEntries} for the underlying flattener\n * @see {@link encodeFormData} for the FormData variant\n *\n * @category encoding\n * @since 4.0.0\n */\nexport function encodeURLSearchParams() {\n  return transform(input => {\n    if (typeof input === \"object\" && input !== null) {\n      return new URLSearchParams(collectURLSearchParamsEntries(input));\n    }\n    return new URLSearchParams();\n  });\n}\nfunction bracketPathToTokens(bracketPath) {\n  // real empty path (from append(\"\", value))\n  if (bracketPath === \"\") {\n    return [\"\"];\n  }\n  const replaced = bracketPath.replace(/\\[(.*?)\\]/g, \".$1\");\n  const parts = replaced.split(\".\");\n  // if bracket path started with \"[...]\" we get \".foo\" => [\"\", \"foo\"]; drop the synthetic first \"\"\n  const start = replaced.startsWith(\".\") ? 1 : 0;\n  return parts.slice(start).map(part => Arr.isCanonicalArrayIndex(part) ? globalThis.Number(part) : part);\n}\n/**\n * Builds a nested tree object from a list of bracket-path entries.\n *\n * **When to use**\n *\n * Use when you need a schema getter to parse FormData or URLSearchParams\n * entries into structured objects.\n * - You have flat key-value pairs with bracket-path keys that need nesting.\n *\n * **Details**\n *\n * - A bracket path is a string like `\"user[address][city]\"` that describes nested\n *   object/array structure.\n * - Interprets bracket paths and constructs the corresponding nested object.\n * - Builds and returns a nested object from the input entries.\n * - Supported syntax:\n *   - `\"foo\"` → object key `\"foo\"`\n *   - `\"foo[bar]\"` → nested `{ foo: { bar: ... } }`\n *   - `\"foo[0]\"` → array index `{ foo: [value] }`\n *   - `\"foo[]\"` → append to array `foo`\n *   - `\"\"` → real empty key\n * - Numeric bracket segments become array indices only when they are valid\n *   JavaScript array-index strings; otherwise they remain object keys.\n * - Duplicate keys for the same path are merged into arrays.\n * - If a structural path conflicts with a previous leaf or a different container\n *   type, the later structural path replaces the conflicting value.\n * - The notation has no escaping for `.`, `[` or `]`, so keys containing these\n *   delimiters cannot be round-tripped without changing their structure.\n *\n * **Example** (Building a tree from bracket paths)\n *\n * ```ts import.meta.vitest\n * import { SchemaGetter } from \"effect\"\n *\n * SchemaGetter.makeTreeRecord([\n *   [\"user[name]\", \"Alice\"],\n *   [\"user[tags][]\", \"admin\"],\n *   [\"user[tags][]\", \"editor\"]\n * ]) // => { user: { name: \"Alice\", tags: [\"admin\", \"editor\"] } }\n * ```\n *\n * @see {@link collectBracketPathEntries} for flattening trees into bracket-path entries\n * @see {@link decodeFormData} for a higher-level FormData decoder\n * @see {@link decodeURLSearchParams} for a higher-level URLSearchParams decoder\n *\n * @category constructors\n * @since 4.0.0\n */\nexport function makeTreeRecord(bracketPathEntries) {\n  const out = {};\n  const containers = new WeakSet();\n  const duplicates = new WeakSet();\n  function getOrCreateContainer(self, key, shouldBeArray) {\n    const current = Object.hasOwn(self, key) ? self[key] : undefined;\n    if (containers.has(current) && Array.isArray(current) === shouldBeArray) {\n      return current;\n    }\n    const container = shouldBeArray ? [] : {};\n    containers.add(container);\n    InternalRecord.assignProperty(self, key, container);\n    return container;\n  }\n  bracketPathEntries.forEach(([key, value]) => {\n    const tokens = bracketPathToTokens(key);\n    let cur = out;\n    tokens.forEach((token, i) => {\n      const isLast = i === tokens.length - 1;\n      // We are inside an array and see \"[]\" (empty token) => append\n      if (Array.isArray(cur) && token === \"\") {\n        if (isLast) {\n          cur.push(value);\n        } else {\n          // bracket path: \"foo[][bar]\" => push a new element and descend into it\n          const next = tokens[i + 1];\n          const shouldBeArray = typeof next === \"number\" || next === \"\";\n          const index = cur.length;\n          cur = getOrCreateContainer(cur, index, shouldBeArray);\n        }\n      } else if (isLast) {\n        // If we're setting a value at a path that already exists\n        // convert it to an array to support multiple values for the same key\n        const hasOwn = Object.hasOwn(cur, token);\n        if (hasOwn && Array.isArray(cur[token]) && (containers.has(cur[token]) || duplicates.has(cur[token]))) {\n          cur[token].push(value);\n        } else if (hasOwn) {\n          const values = [cur[token], value];\n          duplicates.add(values);\n          InternalRecord.assignProperty(cur, token, values);\n        } else {\n          InternalRecord.assignProperty(cur, token, value);\n        }\n      } else {\n        const next = tokens[i + 1];\n        // if next is a number OR \"\" (from []), we are building an array\n        const shouldBeArray = typeof next === \"number\" || next === \"\";\n        cur = getOrCreateContainer(cur, token, shouldBeArray);\n      }\n    });\n  });\n  return out;\n}\n/**\n * Flattens a nested object into bracket-path entries, filtering leaf values by a type guard.\n *\n * **When to use**\n *\n * Use when you need a schema getter to serialize structured objects to flat\n * key-value entries.\n * - Building custom `FormData` or `URLSearchParams` encoders.\n *\n * **Details**\n *\n * - Takes a nested object and produces flat `[bracketPath, value]` pairs suitable for\n *   `FormData` or `URLSearchParams`.\n * - Returns a curried function: first call provides the leaf type guard, second call provides the object.\n * - Recursively traverses objects and arrays.\n * - If all elements of an array are leaves, encodes them as multiple entries with the same key\n *   (e.g. `tags=a&tags=b`). Otherwise uses indexed bracket paths (e.g. `items[0]`, `items[1]`).\n * - Non-leaf values that aren't objects or arrays are silently skipped.\n * - Empty arrays and objects produce no entries, and path delimiters in property\n *   names are not escaped. The resulting format is therefore lossy.\n *\n * **Example** (Flattening an object to bracket paths)\n *\n * ```ts import.meta.vitest\n * import { Predicate, SchemaGetter } from \"effect\"\n *\n * const collectStrings = SchemaGetter.collectBracketPathEntries(Predicate.isString)\n * const entries = collectStrings({ user: { name: \"Alice\", tags: [\"admin\", \"editor\"] } })\n *\n * entries // => [[\"user[name]\", \"Alice\"], [\"user[tags]\", \"admin\"], [\"user[tags]\", \"editor\"]]\n * ```\n *\n * @see {@link makeTreeRecord} for building trees from bracket-path entries\n * @see {@link encodeFormData} for a higher-level FormData encoder\n * @see {@link encodeURLSearchParams} for a higher-level URLSearchParams encoder\n *\n * @category converting\n * @since 4.0.0\n */\nexport function collectBracketPathEntries(isLeaf) {\n  return input => {\n    const bracketPathEntries = [];\n    function append(key, value) {\n      if (isLeaf(value)) {\n        bracketPathEntries.push([key, value]);\n      } else if (Array.isArray(value)) {\n        // If all values are leaves, encode as multiple entries with the same key\n        const allLeaves = value.every(isLeaf);\n        if (allLeaves) {\n          value.forEach(v => {\n            bracketPathEntries.push([key, v]);\n          });\n        } else {\n          value.forEach((v, i) => {\n            append(`${key}[${i}]`, v);\n          });\n        }\n      } else if (typeof value === \"object\" && value !== null) {\n        for (const [k, v] of Object.entries(value)) {\n          append(`${key}[${k}]`, v);\n        }\n      }\n    }\n    for (const [key, value] of Object.entries(input)) {\n      append(key, value);\n    }\n    return bracketPathEntries;\n  };\n}\n//# sourceMappingURL=SchemaGetter.js.map","/**\n * Decimal numbers and arithmetic for cases where JavaScript `number` rounding\n * is not precise enough. A `BigDecimal` stores digits as a `bigint` plus a\n * decimal scale, which lets the module parse, compare, add, subtract, multiply,\n * divide, round, and format decimal values such as money, quantities, and\n * measurements.\n *\n * @since 2.0.0\n */\nimport * as Equal from \"./Equal.js\";\nimport * as Equ from \"./Equivalence.js\";\nimport { dual } 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 } from \"./Predicate.js\";\nconst DEFAULT_PRECISION = 100;\nconst FINITE_INT_REGEXP = /^[+-]?\\d+$/;\nconst TypeId = \"~effect/BigDecimal\";\nconst BigDecimalProto = {\n  [TypeId]: TypeId,\n  [Hash.symbol]() {\n    const normalized = normalize(this);\n    return Hash.combine(Hash.hash(normalized.value), Hash.number(normalized.scale));\n  },\n  [Equal.symbol](that) {\n    return isBigDecimal(that) && equals(this, that);\n  },\n  toString() {\n    return `BigDecimal(${format(this)})`;\n  },\n  toJSON() {\n    return {\n      _id: \"BigDecimal\",\n      value: String(this.value),\n      scale: this.scale\n    };\n  },\n  [NodeInspectSymbol]() {\n    return this.toJSON();\n  },\n  pipe() {\n    return pipeArguments(this, arguments);\n  }\n};\n/**\n * Checks whether a given value is a `BigDecimal`.\n *\n * **When to use**\n *\n * Use to validate unknown input and narrow it to `BigDecimal`.\n *\n * **Example** (Checking BigDecimal values)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * const decimal = BigDecimal.fromNumber(123.45)\n * BigDecimal.isBigDecimal(decimal) // => false\n * BigDecimal.isBigDecimal(BigDecimal.fromStringUnsafe(\"123.45\")) // => true\n * BigDecimal.isBigDecimal(123.45) // => false\n * BigDecimal.isBigDecimal(\"123.45\") // => false\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isBigDecimal = u => hasProperty(u, TypeId);\n/**\n * Creates a `BigDecimal` from a `bigint` value and a safe integer scale.\n *\n * **When to use**\n *\n * Use to construct a decimal directly from its unscaled integer value and\n * decimal scale.\n *\n * **Gotchas**\n *\n * Throws a `RangeError` if `scale` is not a safe integer.\n *\n * **Example** (Creating decimals from bigint and scale)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * // Create 123.45 (12345 with scale 2)\n * const decimal = BigDecimal.make(12345n, 2)\n * decimal // => BigDecimal.fromStringUnsafe(\"123.45\")\n *\n * // Create 42 (42 with scale 0)\n * const integer = BigDecimal.make(42n, 0)\n * integer // => BigDecimal.fromBigInt(42n)\n * ```\n *\n * @see {@link fromBigInt} for constructing an integer decimal from a `bigint`\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const make = (value, scale) => {\n  if (!Number.isSafeInteger(scale)) {\n    throw new RangeError(`Scale must be a safe integer, got ${scale}`);\n  }\n  const o = Object.create(BigDecimalProto);\n  o.value = value;\n  o.scale = scale;\n  return o;\n};\n/**\n * Internal function used to create pre-normalized `BigDecimal`s.\n *\n * @internal\n */\nexport const makeNormalizedUnsafe = (value, scale) => {\n  if (value !== bigint0 && value % bigint10 === bigint0) {\n    throw new RangeError(\"Value must be normalized\");\n  }\n  const o = make(value, scale);\n  o.normalized = o;\n  return o;\n};\nconst bigint0 = /*#__PURE__*/BigInt(0);\nconst bigint1 = /*#__PURE__*/BigInt(1);\nconst bigint_1 = /*#__PURE__*/BigInt(-1);\nconst bigint2 = /*#__PURE__*/BigInt(2);\nconst bigint5 = /*#__PURE__*/BigInt(5);\nconst bigint_5 = /*#__PURE__*/BigInt(-5);\nconst bigint10 = /*#__PURE__*/BigInt(10);\nconst zero = /*#__PURE__*/makeNormalizedUnsafe(bigint0, 0);\nconst one = /*#__PURE__*/makeNormalizedUnsafe(bigint1, 0);\n/**\n * Normalizes a given `BigDecimal` by removing trailing zeros.\n *\n * **When to use**\n *\n * Use to canonicalize decimals that have equivalent values but different\n * internal scales.\n *\n * **Example** (Normalizing trailing zeros)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * const decimal = BigDecimal.normalize(BigDecimal.fromStringUnsafe(\"123.00000\"))\n * const decimalStorage = [decimal.value, decimal.scale] // => [123n, 0]\n *\n * const largeDecimal = BigDecimal.normalize(BigDecimal.fromStringUnsafe(\"12300000\"))\n * const largeDecimalStorage = [largeDecimal.value, largeDecimal.scale] // => [123n, -5]\n * ```\n *\n * @see {@link format} for rendering normalized decimals as strings\n *\n * @category scaling\n * @since 2.0.0\n */\nexport const normalize = self => {\n  if (self.normalized === undefined) {\n    if (self.value === bigint0) {\n      self.normalized = zero;\n    } else {\n      const digits = `${self.value}`;\n      let trail = 0;\n      for (let i = digits.length - 1; i >= 0; i--) {\n        if (digits[i] === \"0\") {\n          trail++;\n        } else {\n          break;\n        }\n      }\n      if (trail === 0) {\n        self.normalized = self;\n      }\n      const value = BigInt(digits.substring(0, digits.length - trail));\n      const scale = self.scale - trail;\n      self.normalized = makeNormalizedUnsafe(value, scale);\n    }\n  }\n  return self.normalized;\n};\n/**\n * Changes a `BigDecimal` to the specified scale.\n *\n * **When to use**\n *\n * Use to change how many decimal places are represented by a `BigDecimal`.\n *\n * **Details**\n *\n * Increasing the scale appends decimal zeros. Decreasing the scale discards\n * digits beyond the target scale by `bigint` division, which truncates toward\n * zero.\n *\n * **Example** (Scaling decimal precision)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * const decimal = BigDecimal.fromNumberUnsafe(123.45)\n *\n * // Increase scale (add more precision)\n * const scaled = BigDecimal.scale(decimal, 4)\n * const scaledStorage = [scaled.value, scaled.scale] // => [1234500n, 4]\n *\n * // Decrease scale (reduce precision, truncating toward zero)\n * const reduced = BigDecimal.scale(decimal, 1)\n * reduced // => BigDecimal.fromStringUnsafe(\"123.4\")\n * ```\n *\n * @see {@link round} for changing scale with configurable rounding\n *\n * @category scaling\n * @since 2.0.0\n */\nexport const scale = /*#__PURE__*/dual(2, (self, scale) => {\n  if (scale > self.scale) {\n    return make(self.value * bigint10 ** BigInt(scale - self.scale), scale);\n  }\n  if (scale < self.scale) {\n    return make(self.value / bigint10 ** BigInt(self.scale - scale), scale);\n  }\n  return self;\n});\n/**\n * Provides an addition operation on `BigDecimal`s.\n *\n * **When to use**\n *\n * Use when you need a decimal addition function for piping or higher-order APIs\n * while preserving decimal precision.\n *\n * **Example** (Adding decimals)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * const result = BigDecimal.sum(\n *   BigDecimal.fromStringUnsafe(\"2\"),\n *   BigDecimal.fromStringUnsafe(\"3\")\n * ) // => BigDecimal.fromBigInt(5n)\n * ```\n *\n * @see {@link sumAll} for summing an iterable of `BigDecimal` values\n *\n * @category math\n * @since 2.0.0\n */\nexport const sum = /*#__PURE__*/dual(2, (self, that) => {\n  if (that.value === bigint0) {\n    return self;\n  }\n  if (self.value === bigint0) {\n    return that;\n  }\n  if (self.scale > that.scale) {\n    return make(scale(that, self.scale).value + self.value, self.scale);\n  }\n  if (self.scale < that.scale) {\n    return make(scale(self, that.scale).value + that.value, that.scale);\n  }\n  return make(self.value + that.value, self.scale);\n});\n/**\n * Takes an `Iterable` of `BigDecimal`s and returns their sum as a single `BigDecimal`.\n *\n * **When to use**\n *\n * Use when you need to aggregate decimal quantities with decimal precision\n * instead of converting through JavaScript numbers.\n *\n * **Example** (Adding multiple decimals)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * const result = BigDecimal.sumAll([\n *   BigDecimal.fromStringUnsafe(\"2\"),\n *   BigDecimal.fromStringUnsafe(\"3\"),\n *   BigDecimal.fromStringUnsafe(\"4\")\n * ]) // => BigDecimal.fromBigInt(9n)\n * ```\n *\n * @see {@link sum} for adding two `BigDecimal` values\n *\n * @category math\n * @since 3.16.0\n */\nexport const sumAll = collection => {\n  let out = zero;\n  for (const n of collection) {\n    out = sum(out, n);\n  }\n  return out;\n};\n/**\n * Provides a multiplication operation on `BigDecimal`s.\n *\n * **When to use**\n *\n * Use to multiply two `BigDecimal` values.\n *\n * **Example** (Multiplying decimals)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * const result = BigDecimal.multiply(\n *   BigDecimal.fromStringUnsafe(\"2\"),\n *   BigDecimal.fromStringUnsafe(\"3\")\n * ) // => BigDecimal.fromBigInt(6n)\n * ```\n *\n * @see {@link multiplyAll} for multiplying an iterable of `BigDecimal` values\n *\n * @category math\n * @since 2.0.0\n */\nexport const multiply = /*#__PURE__*/dual(2, (self, that) => {\n  if (that.value === bigint0 || self.value === bigint0) {\n    return zero;\n  }\n  return make(self.value * that.value, self.scale + that.scale);\n});\n/**\n * Takes an `Iterable` of `BigDecimal`s and returns their multiplication as a single `BigDecimal`.\n *\n * **When to use**\n *\n * Use to multiply all `BigDecimal` values in an iterable.\n *\n * **Example** (Multiplying multiple decimals)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * const result = BigDecimal.multiplyAll([\n *   BigDecimal.fromStringUnsafe(\"2\"),\n *   BigDecimal.fromStringUnsafe(\"3\"),\n *   BigDecimal.fromStringUnsafe(\"4\")\n * ]) // => BigDecimal.fromBigInt(24n)\n * ```\n *\n * @see {@link multiply} for multiplying two `BigDecimal` values\n *\n * @category math\n * @since 4.0.0\n */\nexport const multiplyAll = collection => {\n  let out = one;\n  for (const n of collection) {\n    if (n.value === bigint0) {\n      return zero;\n    }\n    out = multiply(out, n);\n  }\n  return out;\n};\n/**\n * Provides a subtraction operation on `BigDecimal`s.\n *\n * **When to use**\n *\n * Use to subtract one `BigDecimal` value from another.\n *\n * **Example** (Subtracting decimals)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * const result = BigDecimal.subtract(\n *   BigDecimal.fromStringUnsafe(\"2\"),\n *   BigDecimal.fromStringUnsafe(\"3\")\n * ) // => BigDecimal.fromBigInt(-1n)\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const subtract = /*#__PURE__*/dual(2, (self, that) => {\n  if (that.value === bigint0) {\n    return self;\n  }\n  if (self.value === bigint0) {\n    return make(-that.value, that.scale);\n  }\n  if (self.scale > that.scale) {\n    return make(self.value - scale(that, self.scale).value, self.scale);\n  }\n  if (self.scale < that.scale) {\n    return make(scale(self, that.scale).value - that.value, that.scale);\n  }\n  return make(self.value - that.value, self.scale);\n});\n/**\n * Internal function used for arbitrary precision division.\n */\nconst divideWithPrecision = (num, den, scale, precision) => {\n  const numNegative = num < bigint0;\n  const denNegative = den < bigint0;\n  const negateResult = numNegative !== denNegative;\n  num = numNegative ? -num : num;\n  den = denNegative ? -den : den;\n  // Shift digits until numerator is larger than denominator (set scale appropriately).\n  while (num < den) {\n    num *= bigint10;\n    scale++;\n  }\n  // First division.\n  let quotient = num / den;\n  let remainder = num % den;\n  if (remainder === bigint0) {\n    // No remainder, return immediately.\n    return make(negateResult ? -quotient : quotient, scale);\n  }\n  // The quotient is guaranteed to be non-negative at this point. No need to consider sign.\n  let count = `${quotient}`.length;\n  // Shift the remainder by 1 decimal; The quotient will be 1 digit upon next division.\n  remainder *= bigint10;\n  while (remainder !== bigint0 && count < precision) {\n    const q = remainder / den;\n    const r = remainder % den;\n    quotient = quotient * bigint10 + q;\n    remainder = r * bigint10;\n    count++;\n    scale++;\n  }\n  if (remainder !== bigint0) {\n    // Round final number with remainder.\n    quotient += roundTerminal(remainder / den);\n  }\n  return make(negateResult ? -quotient : quotient, scale);\n};\n/**\n * Internal function used for rounding.\n *\n * Returns 1 if the most significant digit is >= 5, otherwise 0.\n *\n * This is used after dividing a number by a power of ten and rounding the last digit.\n *\n * @internal\n */\nexport const roundTerminal = n => {\n  const pos = n >= bigint0 ? 0 : 1;\n  return Number(`${n}`[pos]) < 5 ? bigint0 : bigint1;\n};\n/**\n * Divides `BigDecimal`s safely.\n *\n * **When to use**\n *\n * Use to divide `BigDecimal` values while representing division by zero as\n * `Option.none`.\n *\n * **Details**\n *\n * If the dividend is not a multiple of the divisor, the result will be a `BigDecimal` value\n * with up to the default division precision. If the divisor is `0`, the result\n * will be `Option.none()`.\n *\n * **Example** (Dividing decimals safely)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal, Option } from \"effect\"\n *\n * const six = BigDecimal.fromBigInt(6n)\n *\n * BigDecimal.divide(six, BigDecimal.fromBigInt(3n)) // => Option.some(BigDecimal.fromBigInt(2n))\n * BigDecimal.divide(six, BigDecimal.fromBigInt(4n)) // => Option.some(BigDecimal.fromStringUnsafe(\"1.5\"))\n * BigDecimal.divide(six, BigDecimal.fromBigInt(0n)) // => Option.none()\n * ```\n *\n * @see {@link divideUnsafe} for division that throws when the divisor is zero\n * @see {@link remainder} for the decimal remainder operation\n *\n * @category math\n * @since 2.0.0\n */\nexport const divide = /*#__PURE__*/dual(2, (self, that) => {\n  if (that.value === bigint0) {\n    return Option.none();\n  }\n  if (self.value === bigint0) {\n    return Option.some(zero);\n  }\n  const scale = self.scale - that.scale;\n  if (self.value === that.value) {\n    return Option.some(make(bigint1, scale));\n  }\n  return Option.some(divideWithPrecision(self.value, that.value, scale, DEFAULT_PRECISION));\n});\n/**\n * Provides an unsafe division operation on `BigDecimal`s.\n *\n * **When to use**\n *\n * Use when you need to divide `BigDecimal` values where the divisor is known\n * to be non-zero, so division by zero should be a thrown exception.\n *\n * **Details**\n *\n * If the dividend is not a multiple of the divisor, the result will be a `BigDecimal` value\n * with up to the default division precision.\n *\n * **Gotchas**\n *\n * Throws a `RangeError` if the divisor is `0`.\n *\n * **Example** (Dividing decimals unsafely)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * BigDecimal.divideUnsafe(BigDecimal.fromStringUnsafe(\"6\"), BigDecimal.fromStringUnsafe(\"3\")) // => BigDecimal.fromBigInt(2n)\n * BigDecimal.divideUnsafe(BigDecimal.fromStringUnsafe(\"6\"), BigDecimal.fromStringUnsafe(\"4\")) // => BigDecimal.fromStringUnsafe(\"1.5\")\n * ```\n *\n * @see {@link divide} for division that returns `Option.none` when the divisor is zero\n *\n * @category math\n * @since 4.0.0\n */\nexport const divideUnsafe = /*#__PURE__*/dual(2, (self, that) => {\n  if (that.value === bigint0) {\n    throw new RangeError(\"Division by zero\");\n  }\n  if (self.value === bigint0) {\n    return zero;\n  }\n  const scale = self.scale - that.scale;\n  if (self.value === that.value) {\n    return make(bigint1, scale);\n  }\n  return divideWithPrecision(self.value, that.value, scale, DEFAULT_PRECISION);\n});\nconst MAX_COMPARISON_SCALE_ALIGNMENT = 100;\nconst comparisonPowersOfTen = [bigint1];\nconst compareBigInt = (self, that) => self === that ? 0 : self < that ? -1 : 1;\nconst compareMagnitude = (self, that) => {\n  const selfDigits = `${self.value < bigint0 ? -self.value : self.value}`;\n  const thatDigits = `${that.value < bigint0 ? -that.value : that.value}`;\n  const exponentDifference = BigInt(selfDigits.length - thatDigits.length) - BigInt(self.scale) + BigInt(that.scale);\n  if (exponentDifference !== bigint0) return exponentDifference < bigint0 ? -1 : 1;\n  const length = Math.max(selfDigits.length, thatDigits.length);\n  for (let i = 0; i < length; i++) {\n    const selfDigit = i < selfDigits.length ? selfDigits.charCodeAt(i) : 48;\n    const thatDigit = i < thatDigits.length ? thatDigits.charCodeAt(i) : 48;\n    if (selfDigit !== thatDigit) return selfDigit < thatDigit ? -1 : 1;\n  }\n  return 0;\n};\nconst compare = (self, that) => {\n  if (self.scale === that.scale) return compareBigInt(self.value, that.value);\n  const selfSign = sign(self);\n  const thatSign = sign(that);\n  if (selfSign !== thatSign) return selfSign < thatSign ? -1 : 1;\n  if (selfSign === 0) return 0;\n  const scaleDifference = self.scale - that.scale;\n  const absoluteScaleDifference = Math.abs(scaleDifference);\n  if (absoluteScaleDifference > MAX_COMPARISON_SCALE_ALIGNMENT) {\n    return selfSign === -1 ? compareMagnitude(that, self) : compareMagnitude(self, that);\n  }\n  const powerOfTen = comparisonPowersOfTen[absoluteScaleDifference] ??= bigint10 ** BigInt(absoluteScaleDifference);\n  return scaleDifference > 0 ? compareBigInt(self.value, that.value * powerOfTen) : compareBigInt(self.value * powerOfTen, that.value);\n};\n/**\n * Provides an `Order` instance for `BigDecimal` that allows comparing and sorting BigDecimal values.\n *\n * **When to use**\n *\n * Use when you need to sort or compare decimal values through APIs that accept\n * an ordering instance.\n *\n * **Example** (Comparing decimals)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * const a = BigDecimal.fromNumberUnsafe(1.5)\n * const b = BigDecimal.fromNumberUnsafe(2.3)\n * const c = BigDecimal.fromNumberUnsafe(1.5)\n *\n * BigDecimal.Order(a, b) // => -1\n * BigDecimal.Order(b, a) // => 1\n * BigDecimal.Order(a, c) // => 0\n * ```\n *\n * @category instances\n * @since 2.0.0\n */\nexport const Order = /*#__PURE__*/order.make(compare);\n/**\n * Returns `true` if the first argument is less than the second, otherwise `false`.\n *\n * **When to use**\n *\n * Use to test whether one `BigDecimal` is strictly less than another.\n *\n * **Example** (Checking less-than comparisons)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * const two = BigDecimal.fromStringUnsafe(\"2\")\n * const three = BigDecimal.fromStringUnsafe(\"3\")\n * const four = BigDecimal.fromStringUnsafe(\"4\")\n *\n * BigDecimal.isLessThan(two, three) // => true\n * BigDecimal.isLessThan(three, three) // => false\n * BigDecimal.isLessThan(four, three) // => false\n * ```\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isLessThan = /*#__PURE__*/order.isLessThan(Order);\n/**\n * Checks whether a given `BigDecimal` is less than or equal to the provided one.\n *\n * **When to use**\n *\n * Use to test whether one `BigDecimal` is less than or equal to another.\n *\n * **Example** (Checking less-than-or-equal comparisons)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * const two = BigDecimal.fromStringUnsafe(\"2\")\n * const three = BigDecimal.fromStringUnsafe(\"3\")\n * const four = BigDecimal.fromStringUnsafe(\"4\")\n *\n * BigDecimal.isLessThanOrEqualTo(two, three) // => true\n * BigDecimal.isLessThanOrEqualTo(three, three) // => true\n * BigDecimal.isLessThanOrEqualTo(four, three) // => false\n * ```\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isLessThanOrEqualTo = /*#__PURE__*/order.isLessThanOrEqualTo(Order);\n/**\n * Returns `true` if the first argument is greater than the second, otherwise `false`.\n *\n * **When to use**\n *\n * Use to test whether one `BigDecimal` is strictly greater than another.\n *\n * **Example** (Checking greater-than comparisons)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * const two = BigDecimal.fromStringUnsafe(\"2\")\n * const three = BigDecimal.fromStringUnsafe(\"3\")\n * const four = BigDecimal.fromStringUnsafe(\"4\")\n *\n * BigDecimal.isGreaterThan(two, three) // => false\n * BigDecimal.isGreaterThan(three, three) // => false\n * BigDecimal.isGreaterThan(four, three) // => true\n * ```\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isGreaterThan = /*#__PURE__*/order.isGreaterThan(Order);\n/**\n * Checks whether a given `BigDecimal` is greater than or equal to the provided one.\n *\n * **When to use**\n *\n * Use to test whether one `BigDecimal` is greater than or equal to another.\n *\n * **Example** (Checking greater-than-or-equal comparisons)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * const two = BigDecimal.fromStringUnsafe(\"2\")\n * const three = BigDecimal.fromStringUnsafe(\"3\")\n * const four = BigDecimal.fromStringUnsafe(\"4\")\n *\n * BigDecimal.isGreaterThanOrEqualTo(two, three) // => false\n * BigDecimal.isGreaterThanOrEqualTo(three, three) // => true\n * BigDecimal.isGreaterThanOrEqualTo(four, three) // => true\n * ```\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isGreaterThanOrEqualTo = /*#__PURE__*/order.isGreaterThanOrEqualTo(Order);\n/**\n * Checks whether a `BigDecimal` is between a `minimum` and `maximum` value (inclusive).\n *\n * **When to use**\n *\n * Use to test whether a `BigDecimal` falls inside an inclusive range.\n *\n * **Example** (Checking decimal ranges)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * const between = BigDecimal.between({\n *   minimum: BigDecimal.fromStringUnsafe(\"1\"),\n *   maximum: BigDecimal.fromStringUnsafe(\"5\")\n * })\n *\n * between(BigDecimal.fromStringUnsafe(\"3\")) // => true\n * between(BigDecimal.fromStringUnsafe(\"0\")) // => false\n * between(BigDecimal.fromStringUnsafe(\"6\")) // => false\n * ```\n *\n * @see {@link clamp} for forcing a `BigDecimal` into an inclusive range\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const between = /*#__PURE__*/order.isBetween(Order);\n/**\n * Restricts the given `BigDecimal` to be within the range specified by the `minimum` and `maximum` values.\n *\n * **When to use**\n *\n * Use to force a `BigDecimal` into an inclusive range.\n *\n * **Details**\n *\n * If the `BigDecimal` is less than the `minimum` value, the function returns\n * the `minimum` value. If it is greater than the `maximum` value, the function\n * returns the `maximum` value. Otherwise, it returns the original `BigDecimal`.\n *\n * **Example** (Clamping decimals to a range)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * const clamp = BigDecimal.clamp({\n *   minimum: BigDecimal.fromStringUnsafe(\"1\"),\n *   maximum: BigDecimal.fromStringUnsafe(\"5\")\n * })\n *\n * clamp(BigDecimal.fromStringUnsafe(\"3\")) // => BigDecimal.fromBigInt(3n)\n * clamp(BigDecimal.fromStringUnsafe(\"0\")) // => BigDecimal.fromBigInt(1n)\n * clamp(BigDecimal.fromStringUnsafe(\"6\")) // => BigDecimal.fromBigInt(5n)\n * ```\n *\n * @see {@link between} for checking whether a `BigDecimal` is already inside a range\n *\n * @category math\n * @since 2.0.0\n */\nexport const clamp = /*#__PURE__*/order.clamp(Order);\n/**\n * Returns the minimum between two `BigDecimal`s.\n *\n * **When to use**\n *\n * Use to select the smaller of two `BigDecimal` values.\n *\n * **Example** (Selecting the smaller decimal)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * const result = BigDecimal.min(\n *   BigDecimal.fromStringUnsafe(\"2\"),\n *   BigDecimal.fromStringUnsafe(\"3\")\n * ) // => BigDecimal.fromBigInt(2n)\n * ```\n *\n * @see {@link max} for selecting the larger value\n *\n * @category math\n * @since 2.0.0\n */\nexport const min = /*#__PURE__*/order.min(Order);\n/**\n * Returns the maximum between two `BigDecimal`s.\n *\n * **When to use**\n *\n * Use to select the larger of two `BigDecimal` values.\n *\n * **Example** (Selecting the larger decimal)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * const result = BigDecimal.max(\n *   BigDecimal.fromStringUnsafe(\"2\"),\n *   BigDecimal.fromStringUnsafe(\"3\")\n * ) // => BigDecimal.fromBigInt(3n)\n * ```\n *\n * @see {@link min} for selecting the smaller value\n *\n * @category math\n * @since 2.0.0\n */\nexport const max = /*#__PURE__*/order.max(Order);\n/**\n * Determines the sign of a given `BigDecimal`.\n *\n * **When to use**\n *\n * Use to classify a `BigDecimal` as negative, zero, or positive.\n *\n * **Example** (Reading decimal signs)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * BigDecimal.sign(BigDecimal.fromStringUnsafe(\"-5\")) // => -1\n * BigDecimal.sign(BigDecimal.fromStringUnsafe(\"0\")) // => 0\n * BigDecimal.sign(BigDecimal.fromStringUnsafe(\"5\")) // => 1\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const sign = n => n.value === bigint0 ? 0 : n.value < bigint0 ? -1 : 1;\n/**\n * Determines the absolute value of a given `BigDecimal`.\n *\n * **When to use**\n *\n * Use to remove the sign from a `BigDecimal` while preserving its magnitude.\n *\n * **Example** (Calculating absolute values)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * BigDecimal.abs(BigDecimal.fromStringUnsafe(\"-5\")) // => BigDecimal.fromBigInt(5n)\n * BigDecimal.abs(BigDecimal.fromStringUnsafe(\"0\")) // => BigDecimal.fromBigInt(0n)\n * BigDecimal.abs(BigDecimal.fromStringUnsafe(\"5\")) // => BigDecimal.fromBigInt(5n)\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const abs = n => n.value < bigint0 ? make(-n.value, n.scale) : n;\n/**\n * Provides a negate operation on `BigDecimal`s.\n *\n * **When to use**\n *\n * Use to flip the sign of a `BigDecimal`.\n *\n * **Example** (Negating decimals)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * BigDecimal.negate(BigDecimal.fromStringUnsafe(\"3\")) // => BigDecimal.fromBigInt(-3n)\n * BigDecimal.negate(BigDecimal.fromStringUnsafe(\"-6\")) // => BigDecimal.fromBigInt(6n)\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const negate = n => make(-n.value, n.scale);\n/**\n * Computes the decimal remainder safely when one operand is divided by a second\n * operand.\n *\n * **When to use**\n *\n * Use to compute a decimal remainder while representing division by zero as\n * `Option.none`.\n *\n * **Details**\n *\n * If the divisor is `0`, the result will be `Option.none()`.\n *\n * **Example** (Computing remainders safely)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal, Option } from \"effect\"\n *\n * const two = BigDecimal.fromStringUnsafe(\"2\")\n * const three = BigDecimal.fromStringUnsafe(\"3\")\n * const zero = BigDecimal.fromStringUnsafe(\"0\")\n *\n * BigDecimal.remainder(three, two) // => Option.some(BigDecimal.fromBigInt(1n))\n * BigDecimal.remainder(two, zero) // => Option.none()\n * ```\n *\n * @see {@link remainderUnsafe} for remainder calculation that throws when the divisor is zero\n * @see {@link divide} for decimal quotient calculation\n *\n * @category math\n * @since 2.0.0\n */\nexport const remainder = /*#__PURE__*/dual(2, (self, divisor) => {\n  if (divisor.value === bigint0) {\n    return Option.none();\n  }\n  const max = Math.max(self.scale, divisor.scale);\n  return Option.some(make(scale(self, max).value % scale(divisor, max).value, max));\n});\n/**\n * Returns the decimal remainder left over when one operand is divided by a\n * non-zero second operand.\n *\n * **When to use**\n *\n * Use when you need to compute a `BigDecimal` remainder with a divisor known to\n * be non-zero and want a plain `BigDecimal` result instead of an `Option`.\n *\n * **Gotchas**\n *\n * Throws a `RangeError` if the divisor is `0`.\n *\n * **Example** (Computing remainders unsafely)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * BigDecimal.remainderUnsafe(\n *   BigDecimal.fromStringUnsafe(\"3\"),\n *   BigDecimal.fromStringUnsafe(\"2\")\n * ) // => BigDecimal.fromBigInt(1n)\n * ```\n *\n * @see {@link remainder} for returning `Option.none` when the divisor is zero\n *\n * @category math\n * @since 4.0.0\n */\nexport const remainderUnsafe = /*#__PURE__*/dual(2, (self, divisor) => {\n  if (divisor.value === bigint0) {\n    throw new RangeError(\"Division by zero\");\n  }\n  const max = Math.max(self.scale, divisor.scale);\n  return make(scale(self, max).value % scale(divisor, max).value, max);\n});\n/**\n * Provides an `Equivalence` instance for `BigDecimal` that determines equality between BigDecimal values.\n *\n * **When to use**\n *\n * Use when comparing decimal values through APIs that accept an equivalence\n * relation.\n *\n * **Example** (Checking decimal equivalence)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * const a = BigDecimal.fromStringUnsafe(\"1.50\")\n * const b = BigDecimal.fromStringUnsafe(\"1.5\")\n * const c = BigDecimal.fromStringUnsafe(\"2.0\")\n *\n * BigDecimal.Equivalence(a, b) // => true\n * BigDecimal.Equivalence(a, c) // => false\n * ```\n *\n * @category instances\n * @since 2.0.0\n */\nexport const Equivalence = /*#__PURE__*/Equ.make((self, that) => compare(self, that) === 0);\n/**\n * Checks whether two `BigDecimal`s are equal.\n *\n * **When to use**\n *\n * Use to compare two `BigDecimal` values for numeric equality.\n *\n * **Example** (Checking decimal equality)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * const a = BigDecimal.fromStringUnsafe(\"1.5\")\n * const b = BigDecimal.fromStringUnsafe(\"1.50\")\n * const c = BigDecimal.fromStringUnsafe(\"2.0\")\n *\n * BigDecimal.equals(a, b) // => true\n * BigDecimal.equals(a, c) // => false\n * ```\n *\n * @see {@link Equivalence} for passing decimal equality to APIs that require an `Equivalence`\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const equals = /*#__PURE__*/dual(2, (self, that) => Equivalence(self, that));\n/**\n * Creates a `BigDecimal` from a `bigint` value.\n *\n * **When to use**\n *\n * Use to construct an integer `BigDecimal` from a `bigint`.\n *\n * **Example** (Creating decimals from bigint)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * const decimal = BigDecimal.fromBigInt(123n)\n * decimal // => BigDecimal.fromStringUnsafe(\"123\")\n *\n * const largeBigInt = BigDecimal.fromBigInt(9007199254740991n)\n * largeBigInt // => BigDecimal.fromStringUnsafe(\"9007199254740991\")\n * ```\n *\n * @see {@link make} for constructing a decimal with an explicit scale\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromBigInt = n => make(n, 0);\n/**\n * Creates a `BigDecimal` from a finite `number`.\n *\n * **When to use**\n *\n * Use when you need to convert a trusted finite JavaScript number to a\n * `BigDecimal` and want a plain result instead of an `Option`.\n *\n * **Gotchas**\n *\n * It is not recommended to convert a floating point number to a decimal\n * directly, as the floating point representation may be unexpected. Throws a\n * `RangeError` if the number is not finite (`NaN`, `+Infinity` or `-Infinity`).\n *\n * **Example** (Creating decimals from finite numbers)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * BigDecimal.fromNumberUnsafe(123) // => BigDecimal.fromBigInt(123n)\n * BigDecimal.fromNumberUnsafe(123.456) // => BigDecimal.fromStringUnsafe(\"123.456\")\n * ```\n *\n * @see {@link fromNumber} for returning `Option.none` when the number is not finite\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromNumberUnsafe = n => {\n  return Option.getOrThrowWith(fromNumber(n), () => new RangeError(`Number must be finite, got ${n}`));\n};\n/**\n * Creates a `BigDecimal` safely from a finite `number`.\n *\n * **When to use**\n *\n * Use to convert a finite JavaScript number to a `BigDecimal` without throwing\n * on invalid input.\n *\n * **Details**\n *\n * Returns `Option.none()` for `NaN`, `+Infinity` or `-Infinity`.\n *\n * **Gotchas**\n *\n * It is not recommended to convert a floating point number to a decimal\n * directly, as the floating point representation may be unexpected.\n *\n * **Example** (Creating decimals from numbers safely)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal, Option } from \"effect\"\n *\n * BigDecimal.fromNumber(123.456) // => Option.some(BigDecimal.fromStringUnsafe(\"123.456\"))\n * BigDecimal.fromNumber(Infinity) // => Option.none()\n * ```\n *\n * @see {@link fromNumberUnsafe} for throwing when the number is not finite\n * @see {@link fromString} for parsing decimal strings directly\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromNumber = n => {\n  if (!Number.isFinite(n)) {\n    return Option.none();\n  }\n  const string = `${n}`;\n  if (string.includes(\"e\")) {\n    return fromString(string);\n  }\n  const [lead, trail = \"\"] = string.split(\".\");\n  return Option.some(make(BigInt(`${lead}${trail}`), trail.length));\n};\n/**\n * Parses a decimal string into a `BigDecimal` safely.\n *\n * **When to use**\n *\n * Use to parse external decimal text without throwing on invalid input.\n *\n * **Details**\n *\n * Returns `Option.some` for valid decimal or exponent notation and\n * `Option.none` when the string cannot be parsed or would produce an unsafe\n * scale. The empty string parses as zero.\n *\n * **Example** (Parsing decimal strings safely)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal, Option } from \"effect\"\n *\n * BigDecimal.fromString(\"123.456\") // => Option.some(BigDecimal.make(123456n, 3))\n * BigDecimal.fromString(\"123.abc\") // => Option.none()\n * ```\n *\n * @see {@link fromStringUnsafe} for parsing that throws on invalid input\n * @see {@link fromNumber} for converting finite JavaScript numbers\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromString = s => {\n  if (s === \"\") {\n    return Option.some(zero);\n  }\n  let base;\n  let exp;\n  const seperator = s.search(/[eE]/);\n  if (seperator !== -1) {\n    const trail = s.slice(seperator + 1);\n    base = s.slice(0, seperator);\n    exp = Number(trail);\n    if (base === \"\" || !Number.isSafeInteger(exp) || !FINITE_INT_REGEXP.test(trail)) {\n      return Option.none();\n    }\n  } else {\n    base = s;\n    exp = 0;\n  }\n  let digits;\n  let offset;\n  const dot = base.search(/\\./);\n  if (dot !== -1) {\n    const lead = base.slice(0, dot);\n    const trail = base.slice(dot + 1);\n    digits = `${lead}${trail}`;\n    offset = trail.length;\n  } else {\n    digits = base;\n    offset = 0;\n  }\n  if (!FINITE_INT_REGEXP.test(digits)) {\n    return Option.none();\n  }\n  const scale = offset - exp;\n  if (!Number.isSafeInteger(scale)) {\n    return Option.none();\n  }\n  return Option.some(make(BigInt(digits), scale));\n};\n/**\n * Parses a decimal string into a `BigDecimal`, throwing if the string is\n * invalid.\n *\n * **When to use**\n *\n * Use when you expect decimal text to be valid and want parse errors to throw.\n *\n * **Details**\n *\n * Accepts the same syntax as `fromString`. Use `fromString` when invalid input\n * should be represented as `Option.none` instead of throwing.\n *\n * **Example** (Parsing decimal strings unsafely)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * BigDecimal.fromStringUnsafe(\"123\") // => BigDecimal.fromBigInt(123n)\n * BigDecimal.fromStringUnsafe(\"123.456\") // => BigDecimal.make(123456n, 3)\n * ```\n *\n * @see {@link fromString} for returning `Option.none` on invalid input\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromStringUnsafe = s => {\n  return Option.getOrThrowWith(fromString(s), () => new Error(`Invalid numerical string: ${s}`));\n};\n/**\n * Formats a `BigDecimal` as a string.\n *\n * **When to use**\n *\n * Use to render a `BigDecimal` as plain decimal text when possible.\n *\n * **Details**\n *\n * The value is normalized before formatting. Scientific notation is used when\n * the absolute value of the normalized scale is at least `16`; otherwise plain\n * decimal notation is used.\n *\n * **Example** (Formatting decimals)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * BigDecimal.format(BigDecimal.fromStringUnsafe(\"-5\")) // => \"-5\"\n * BigDecimal.format(BigDecimal.fromStringUnsafe(\"123.456\")) // => \"123.456\"\n * BigDecimal.format(BigDecimal.fromStringUnsafe(\"-0.00000123\")) // => \"-0.00000123\"\n * ```\n *\n * @see {@link toExponential} for always rendering scientific notation\n *\n * @category converting\n * @since 2.0.0\n */\nexport const format = n => {\n  const normalized = normalize(n);\n  if (Math.abs(normalized.scale) >= 16) {\n    return toExponential(normalized);\n  }\n  const negative = normalized.value < bigint0;\n  const absolute = negative ? `${normalized.value}`.substring(1) : `${normalized.value}`;\n  let before;\n  let after;\n  if (normalized.scale >= absolute.length) {\n    before = \"0\";\n    after = \"0\".repeat(normalized.scale - absolute.length) + absolute;\n  } else {\n    const location = absolute.length - normalized.scale;\n    if (location > absolute.length) {\n      const zeros = location - absolute.length;\n      before = `${absolute}${\"0\".repeat(zeros)}`;\n      after = \"\";\n    } else {\n      after = absolute.slice(location);\n      before = absolute.slice(0, location);\n    }\n  }\n  const complete = after === \"\" ? before : `${before}.${after}`;\n  return negative ? `-${complete}` : complete;\n};\n/**\n * Formats a given `BigDecimal` as a `string` in scientific notation.\n *\n * **When to use**\n *\n * Use to render a `BigDecimal` in scientific notation.\n *\n * **Example** (Formatting decimals exponentially)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * BigDecimal.toExponential(BigDecimal.make(123456n, -5)) // => \"1.23456e+10\"\n * ```\n *\n * @see {@link format} for plain decimal formatting when possible\n *\n * @category converting\n * @since 3.11.0\n */\nexport const toExponential = n => {\n  if (isZero(n)) {\n    return \"0e+0\";\n  }\n  const normalized = normalize(n);\n  const digits = `${abs(normalized).value}`;\n  const head = digits.slice(0, 1);\n  const tail = digits.slice(1);\n  let output = `${isNegative(normalized) ? \"-\" : \"\"}${head}`;\n  if (tail !== \"\") {\n    output += `.${tail}`;\n  }\n  const exp = tail.length - normalized.scale;\n  return `${output}e${exp >= 0 ? \"+\" : \"\"}${exp}`;\n};\n/**\n * Converts a `BigDecimal` to a JavaScript `number`.\n *\n * **When to use**\n *\n * Use when you need a JavaScript number at an interop boundary where precision\n * loss is acceptable.\n *\n * **Gotchas**\n *\n * This conversion is unsafe because the result can lose integer or fractional\n * precision, round to a nearby representable value, or become `Infinity` when\n * the decimal cannot be represented as a finite JavaScript `number`.\n *\n * **Example** (Converting decimals to numbers)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * BigDecimal.toNumberUnsafe(BigDecimal.fromStringUnsafe(\"123.456\")) // => 123.456\n * ```\n *\n * @see {@link format} for preserving decimal precision as text\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toNumberUnsafe = n => Number(format(n));\n/**\n * Checks whether a given `BigDecimal` is an integer.\n *\n * **When to use**\n *\n * Use to test whether a `BigDecimal` has no fractional decimal part.\n *\n * **Example** (Checking integer decimals)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * BigDecimal.isInteger(BigDecimal.fromStringUnsafe(\"0\")) // => true\n * BigDecimal.isInteger(BigDecimal.fromStringUnsafe(\"1\")) // => true\n * BigDecimal.isInteger(BigDecimal.fromStringUnsafe(\"1.1\")) // => false\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const isInteger = n => normalize(n).scale <= 0;\n/**\n * Checks whether a given `BigDecimal` is `0`.\n *\n * **When to use**\n *\n * Use to test whether a `BigDecimal` is exactly zero.\n *\n * **Example** (Checking zero decimals)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * BigDecimal.isZero(BigDecimal.fromStringUnsafe(\"0\")) // => true\n * BigDecimal.isZero(BigDecimal.fromStringUnsafe(\"1\")) // => false\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const isZero = n => n.value === bigint0;\n/**\n * Checks whether a given `BigDecimal` is negative.\n *\n * **When to use**\n *\n * Use to test whether a `BigDecimal` is less than zero.\n *\n * **Example** (Checking negative decimals)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * BigDecimal.isNegative(BigDecimal.fromStringUnsafe(\"-1\")) // => true\n * BigDecimal.isNegative(BigDecimal.fromStringUnsafe(\"0\")) // => false\n * BigDecimal.isNegative(BigDecimal.fromStringUnsafe(\"1\")) // => false\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const isNegative = n => n.value < bigint0;\n/**\n * Checks whether a given `BigDecimal` is positive.\n *\n * **When to use**\n *\n * Use to test whether a `BigDecimal` is greater than zero.\n *\n * **Example** (Checking positive decimals)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * BigDecimal.isPositive(BigDecimal.fromStringUnsafe(\"-1\")) // => false\n * BigDecimal.isPositive(BigDecimal.fromStringUnsafe(\"0\")) // => false\n * BigDecimal.isPositive(BigDecimal.fromStringUnsafe(\"1\")) // => true\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const isPositive = n => n.value > bigint0;\nconst isBigDecimalArgs = args => isBigDecimal(args[0]);\n/**\n * Computes a rounded `BigDecimal` at the given scale with the specified rounding mode.\n *\n * **When to use**\n *\n * Use to round a decimal at a requested scale with an explicit rounding mode.\n *\n * **Example** (Rounding decimals)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * const positive = BigDecimal.round(BigDecimal.fromStringUnsafe(\"145\"), { mode: \"from-zero\", scale: -1 })\n * positive // => BigDecimal.fromBigInt(150n)\n *\n * const negative = BigDecimal.round(BigDecimal.fromStringUnsafe(\"-14.5\"))\n * negative // => BigDecimal.fromBigInt(-15n)\n * ```\n *\n * @see {@link ceil} for fixed rounding toward positive infinity\n * @see {@link floor} for fixed rounding toward negative infinity\n * @see {@link truncate} for fixed rounding toward zero\n *\n * @category math\n * @since 3.16.0\n */\nexport const round = /*#__PURE__*/dual(isBigDecimalArgs, (self, options) => {\n  const mode = options?.mode ?? \"half-from-zero\";\n  const scale = options?.scale ?? 0;\n  switch (mode) {\n    case \"ceil\":\n      return ceil(self, scale);\n    case \"floor\":\n      return floor(self, scale);\n    case \"to-zero\":\n      return truncate(self, scale);\n    case \"from-zero\":\n      return isPositive(self) ? ceil(self, scale) : floor(self, scale);\n    case \"half-ceil\":\n      return floor(sum(self, make(bigint5, scale + 1)), scale);\n    case \"half-floor\":\n      return ceil(sum(self, make(bigint_5, scale + 1)), scale);\n    case \"half-to-zero\":\n      return isNegative(self) ? floor(sum(self, make(bigint5, scale + 1)), scale) : ceil(sum(self, make(bigint_5, scale + 1)), scale);\n    case \"half-from-zero\":\n      return isNegative(self) ? ceil(sum(self, make(bigint_5, scale + 1)), scale) : floor(sum(self, make(bigint5, scale + 1)), scale);\n  }\n  const halfCeil = floor(sum(self, make(bigint5, scale + 1)), scale);\n  const halfFloor = ceil(sum(self, make(bigint_5, scale + 1)), scale);\n  const digit = digitAt(halfCeil, scale);\n  switch (mode) {\n    case \"half-even\":\n      return equals(halfCeil, halfFloor) ? halfCeil : digit % bigint2 === bigint0 ? halfCeil : halfFloor;\n    case \"half-odd\":\n      return equals(halfCeil, halfFloor) ? halfCeil : digit % bigint2 === bigint0 ? halfFloor : halfCeil;\n  }\n});\n/**\n * Computes a truncated `BigDecimal` at the given scale. This removes fractional digits beyond the scale,\n * rounding toward zero.\n *\n * **When to use**\n *\n * Use when you need to discard fractional digits beyond a scale rather than\n * round half up, half down, or toward an infinity.\n *\n * **Example** (Truncating decimals)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * BigDecimal.truncate(BigDecimal.fromStringUnsafe(\"145\"), -1) // => BigDecimal.fromBigInt(140n)\n * BigDecimal.truncate(BigDecimal.fromStringUnsafe(\"-14.5\")) // => BigDecimal.fromBigInt(-14n)\n * ```\n *\n * @see {@link round} for configurable rounding modes\n * @see {@link ceil} for rounding toward positive infinity\n * @see {@link floor} for rounding toward negative infinity\n *\n * @category math\n * @since 3.16.0\n */\nexport const truncate = /*#__PURE__*/dual(isBigDecimalArgs, (self, scale = 0) => {\n  if (self.scale <= scale) {\n    return self;\n  }\n  // BigInt division truncates towards zero\n  return make(self.value / bigint10 ** BigInt(self.scale - scale), scale);\n});\n/**\n * Computes the ceiling of a `BigDecimal` at the given scale.\n *\n * **When to use**\n *\n * Use to round a decimal toward positive infinity at a requested scale.\n *\n * **Details**\n *\n * The default scale is `0`. Positive scales keep digits to the right of the\n * decimal point, and negative scales round positions to the left of the decimal\n * point.\n *\n * @see {@link floor} for rounding toward negative infinity\n * @see {@link truncate} for rounding toward zero\n * @see {@link round} for configurable rounding modes\n *\n * **Example** (Rounding decimals up)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * BigDecimal.ceil(BigDecimal.fromStringUnsafe(\"145\"), -1) // => BigDecimal.fromBigInt(150n)\n * BigDecimal.ceil(BigDecimal.fromStringUnsafe(\"-14.5\")) // => BigDecimal.fromBigInt(-14n)\n * ```\n *\n * @category math\n * @since 3.16.0\n */\nexport const ceil = /*#__PURE__*/dual(isBigDecimalArgs, (self, scale = 0) => {\n  const truncated = truncate(self, scale);\n  if (isPositive(self) && isLessThan(truncated, self)) {\n    return sum(truncated, make(bigint1, scale));\n  }\n  return truncated;\n});\n/**\n * Internal function used by `round` for `half-even` and `half-odd` rounding modes.\n *\n * Returns the digit at the position of the given `scale` within the `BigDecimal`.\n *\n * @internal\n */\nexport const digitAt = /*#__PURE__*/dual(2, (self, scale) => {\n  if (self.scale < scale) {\n    return bigint0;\n  }\n  const scaled = self.value / bigint10 ** BigInt(self.scale - scale);\n  return scaled % bigint10;\n});\n/**\n * Computes the floor of a `BigDecimal` at the given scale.\n *\n * **When to use**\n *\n * Use to round a decimal toward negative infinity at a requested scale.\n *\n * **Example** (Rounding decimals down)\n *\n * ```ts import.meta.vitest\n * import { BigDecimal } from \"effect\"\n *\n * BigDecimal.floor(BigDecimal.fromStringUnsafe(\"145\"), -1) // => BigDecimal.fromBigInt(140n)\n * BigDecimal.floor(BigDecimal.fromStringUnsafe(\"-14.5\")) // => BigDecimal.fromBigInt(-15n)\n * ```\n *\n * @see {@link ceil} for rounding toward positive infinity\n * @see {@link truncate} for rounding toward zero\n * @see {@link round} for configurable rounding modes\n *\n * @category math\n * @since 3.16.0\n */\nexport const floor = /*#__PURE__*/dual(isBigDecimalArgs, (self, scale = 0) => {\n  const truncated = truncate(self, scale);\n  if (isNegative(self) && isGreaterThan(truncated, self)) {\n    return sum(truncated, make(bigint_1, scale));\n  }\n  return truncated;\n});\n//# sourceMappingURL=BigDecimal.js.map","/**\n * Builds two-way conversions used by schemas.\n *\n * A `Transformation<T, E>` describes how to decode an encoded value into a\n * decoded value and how to encode it back again. Schema APIs use\n * transformations to connect two representations, such as a string and a\n * number, a JSON value and a richer TypeScript value, or a form field and an\n * application value. This module includes transformation and middleware types,\n * constructors for pure or effectful conversions, and common conversions used\n * by the Schema module.\n *\n * @since 4.0.0\n */\nimport * as BigDecimal from \"./BigDecimal.js\";\nimport * as ByteSize from \"./ByteSize.js\";\nimport * as DateTime from \"./DateTime.js\";\nimport * as Duration from \"./Duration.js\";\nimport * as Effect from \"./Effect.js\";\nimport { format, formatDate, formatJson } from \"./Formatter.js\";\nimport * as Option from \"./Option.js\";\nimport * as Predicate from \"./Predicate.js\";\nimport * as SchemaGetter from \"./SchemaGetter.js\";\nimport * as SchemaIssue from \"./SchemaIssue.js\";\n/**\n * Constructs schema middleware from its decode and encode functions.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Middleware = class {\n  _tag = \"Middleware\";\n  decode;\n  encode;\n  constructor(decode, encode) {\n    this.decode = decode;\n    this.encode = encode;\n  }\n  flip() {\n    return new Middleware(this.encode, this.decode);\n  }\n};\nconst TypeId = \"~effect/SchemaTransformation/Transformation\";\n/**\n * Constructs a bidirectional schema transformation from its decode and encode getters.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Transformation = class {\n  [TypeId] = TypeId;\n  _tag = \"Transformation\";\n  decode;\n  encode;\n  constructor(decode, encode) {\n    this.decode = decode;\n    this.encode = encode;\n  }\n  flip() {\n    return new Transformation(this.encode, this.decode);\n  }\n  compose(other) {\n    return new Transformation(this.decode.compose(other.decode), other.encode.compose(this.encode));\n  }\n};\n/**\n * Returns `true` if `u` is a `Transformation` instance.\n *\n * **When to use**\n *\n * Use to check whether a value is already a schema transformation before\n * wrapping it.\n *\n * **Details**\n *\n * - Pure predicate, no side effects.\n * - Acts as a TypeScript type guard.\n *\n * **Example** (Checking a value)\n *\n * ```ts import.meta.vitest\n * import { SchemaTransformation } from \"effect\"\n *\n * SchemaTransformation.isTransformation(SchemaTransformation.trim()) // => true\n * SchemaTransformation.isTransformation({ decode: null, encode: null }) // => false\n * ```\n *\n * @see {@link Transformation}\n * @see {@link make}\n *\n * @category guards\n * @since 4.0.0\n */\nexport function isTransformation(u) {\n  return Predicate.hasProperty(u, TypeId) && u[TypeId] === TypeId;\n}\n/**\n * Constructs a `Transformation` from an object with `decode` and `encode`\n * `Getter`s. If the input is already a `Transformation`, returns it as-is.\n *\n * **When to use**\n *\n * Use when you already have schema getter instances and want to pair them into\n * a schema transformation.\n * - You want idempotent wrapping (won't double-wrap).\n *\n * **Details**\n *\n * - Returns the input unchanged if it is already a `Transformation`.\n *\n * **Example** (Wrapping existing getters)\n *\n * ```ts import.meta.vitest\n * import { SchemaGetter, SchemaTransformation } from \"effect\"\n *\n * const t = SchemaTransformation.make({\n *   decode: SchemaGetter.transform<number, string>((s) => Number(s)),\n *   encode: SchemaGetter.transform<string, number>((n) => String(n))\n * })\n * t._tag // => \"Transformation\"\n * ```\n *\n * @see {@link transform} — simpler constructor from pure functions\n * @see {@link transformEffect} — constructor from effectful functions\n * @see {@link Transformation}\n *\n * @category constructors\n * @since 3.10.0\n */\nexport const make = options => {\n  if (isTransformation(options)) {\n    return options;\n  }\n  return new Transformation(options.decode, options.encode);\n};\n/**\n * Creates a `Transformation` from effectful decode and encode functions.\n *\n * **When to use**\n *\n * Use when you need a schema transformation that may fail or require Effect\n * services.\n *\n * **Details**\n *\n * - Each function receives the input value and `ParseOptions`.\n * - Must return an `Effect` that succeeds with the output or fails with `Issue`.\n * - Skips `None` inputs (missing keys) — functions are only called on present values.\n *\n * **Example** (Parsing a date string that can fail)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, Schema, SchemaIssue, SchemaTransformation } from \"effect\"\n *\n * const DateFromString = Schema.String.pipe(\n *   Schema.decodeTo(\n *     Schema.Date,\n *     SchemaTransformation.transformEffect({\n *       decode: (s, options) => {\n *         const d = new Date(s)\n *         return isNaN(d.getTime())\n *           ? Effect.fail(new SchemaIssue.InvalidValue({ message: \"Invalid date\" }, s, options))\n *           : Effect.succeed(d)\n *       },\n *       encode: (d) => Effect.succeed(d.toISOString())\n *     })\n *   )\n * )\n * Schema.decodeSync(DateFromString)(\"2024-01-01\").toISOString() // => \"2024-01-01T00:00:00.000Z\"\n * ```\n *\n * @see {@link transform} — for infallible, pure transformations\n * @see {@link transformOptional} — for transformations that handle missing keys\n * @see {@link make} — for transformations from existing Getters\n *\n * @category transforming\n * @since 3.10.0\n */\nexport function transformEffect(options) {\n  return new Transformation(SchemaGetter.transformEffect(options.decode), SchemaGetter.transformEffect(options.encode));\n}\n/**\n * Creates a `Transformation` from pure (sync, infallible) decode and encode\n * functions.\n *\n * **When to use**\n *\n * Use when you need an infallible schema transformation that does not require\n * Effect services.\n *\n * **Details**\n *\n * - Each function receives the input and returns the output directly.\n * - Skips `None` inputs (missing keys) — functions are only called on present values.\n * - Does not allocate Effects internally; uses optimized sync path.\n *\n * **Example** (Converting between cents and dollars)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaTransformation } from \"effect\"\n *\n * const CentsFromDollars = Schema.Number.pipe(\n *   Schema.decodeTo(\n *     Schema.Number,\n *     SchemaTransformation.transform({\n *       decode: (dollars) => dollars * 100,\n *       encode: (cents) => cents / 100\n *     })\n *   )\n * )\n * Schema.decodeSync(CentsFromDollars)(2.5) // => 250\n * ```\n *\n * @see {@link transformEffect} — for fallible or effectful transformations\n * @see {@link transformOptional} — for transformations that handle missing keys\n * @see {@link passthrough} — when no conversion is needed\n *\n * @category transforming\n * @since 3.10.0\n */\nexport function transform(options) {\n  return new Transformation(SchemaGetter.transform(options.decode), SchemaGetter.transform(options.encode));\n}\n/**\n * Creates a `Transformation` where decode and encode operate on `Option`\n * values, giving full control over missing-key handling.\n *\n * **When to use**\n *\n * Use when you need a schema transformation to produce or consume `Option.None`\n * for absent keys.\n * - You are working with optional struct fields.\n *\n * **Details**\n *\n * - Each function receives `Option<input>` and returns `Option<output>`.\n * - `Option.None` input means the key is absent; returning `Option.None`\n *   omits the key from the output.\n * - Pure and synchronous.\n *\n * **Example** (Converting an optional key to Option)\n *\n * ```ts import.meta.vitest\n * import { Option, Schema, SchemaTransformation } from \"effect\"\n *\n * const schema = Schema.Struct({\n *   a: Schema.optionalKey(Schema.Number).pipe(\n *     Schema.decodeTo(\n *       Schema.Option(Schema.Number),\n *       SchemaTransformation.transformOptional({\n *         decode: Option.some,\n *         encode: Option.flatten\n *       })\n *     )\n *   )\n * })\n * Schema.decodeSync(schema)({}).a // => Option.none()\n * ```\n *\n * @see {@link transform} — when you don't need Option-level control\n * @see {@link optionFromOptionalKey} — built-in for the common optional-key-to-Option pattern\n * @see {@link optionFromOptional} — built-in for optional (undefined) to Option\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function transformOptional(options) {\n  return new Transformation(SchemaGetter.transformOptional(options.decode), SchemaGetter.transformOptional(options.encode));\n}\n/**\n * Transforms strings by trimming whitespace on decode.\n * Encode is passthrough (no change).\n *\n * **When to use**\n *\n * Use when you need a schema transformation to normalize user input by\n * stripping leading/trailing whitespace.\n *\n * **Details**\n *\n * Decoding applies `String.prototype.trim()`. Encoding is passthrough and\n * returns the string unchanged. This is not round-trippable if the original had\n * whitespace.\n *\n * **Example** (Trimming on decode)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaTransformation } from \"effect\"\n *\n * const Trimmed = Schema.String.pipe(\n *   Schema.decode(SchemaTransformation.trim())\n * )\n * Schema.decodeSync(Trimmed)(\"  hello  \") // => \"hello\"\n * ```\n *\n * @see {@link toLowerCase}\n * @see {@link toUpperCase}\n * @see {@link snakeToCamel}\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function trim() {\n  return new Transformation(SchemaGetter.trim(), SchemaGetter.passthrough());\n}\n/**\n * Transforms strings by converting snake_case to camelCase\n * on decode and camelCase to snake_case on encode.\n *\n * **When to use**\n *\n * Use when you need a schema transformation to convert API field names between\n * snake_case and camelCase conventions.\n *\n * **Details**\n *\n * Decoding converts values such as `\"my_field_name\"` to `\"myFieldName\"`.\n * Encoding converts values such as `\"myFieldName\"` back to `\"my_field_name\"`.\n * The transformation is round-trippable for standard snake_case and camelCase.\n *\n * **Example** (Converting snake case to camel case)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaTransformation } from \"effect\"\n *\n * const SnakeToCamel = Schema.String.pipe(\n *   Schema.decode(SchemaTransformation.snakeToCamel())\n * )\n * Schema.decodeSync(SnakeToCamel)(\"user_name\") // => \"userName\"\n * ```\n *\n * @see {@link trim}\n * @see {@link toLowerCase}\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function snakeToCamel() {\n  return new Transformation(SchemaGetter.snakeToCamel(), SchemaGetter.camelToSnake());\n}\n/**\n * Transforms strings by lowercasing on decode.\n * Encode is passthrough.\n *\n * **When to use**\n *\n * Use when you need a schema transformation to normalize strings to lowercase\n * (e.g. email addresses).\n *\n * **Details**\n *\n * Decoding applies `String.prototype.toLowerCase()`. Encoding is passthrough.\n * This is not round-trippable if the original had uppercase characters.\n *\n * **Example** (Lowercasing on decode)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaTransformation } from \"effect\"\n *\n * const Lowered = Schema.String.pipe(\n *   Schema.decode(SchemaTransformation.toLowerCase())\n * )\n * Schema.decodeSync(Lowered)(\"HELLO\") // => \"hello\"\n * ```\n *\n * @see {@link toUpperCase}\n * @see {@link trim}\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function toLowerCase() {\n  return new Transformation(SchemaGetter.toLowerCase(), SchemaGetter.passthrough());\n}\n/**\n * Transforms strings by uppercasing on decode.\n * Encode is passthrough.\n *\n * **When to use**\n *\n * Use when you need a schema transformation to normalize strings to uppercase\n * (e.g. country codes).\n *\n * **Details**\n *\n * Decoding applies `String.prototype.toUpperCase()`. Encoding is passthrough.\n * This is not round-trippable if the original had lowercase characters.\n *\n * **Example** (Uppercasing on decode)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaTransformation } from \"effect\"\n *\n * const Uppered = Schema.String.pipe(\n *   Schema.decode(SchemaTransformation.toUpperCase())\n * )\n * Schema.decodeSync(Uppered)(\"hello\") // => \"HELLO\"\n * ```\n *\n * @see {@link toLowerCase}\n * @see {@link trim}\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function toUpperCase() {\n  return new Transformation(SchemaGetter.toUpperCase(), SchemaGetter.passthrough());\n}\n/**\n * Transforms strings by capitalizing the first character on\n * decode. Encode is passthrough.\n *\n * **When to use**\n *\n * Use when you need a schema transformation to normalize display names or\n * titles.\n *\n * **Details**\n *\n * Decoding uppercases the first character and leaves the rest unchanged.\n * Encoding is passthrough.\n *\n * **Example** (Capitalizing on decode)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaTransformation } from \"effect\"\n *\n * const Capitalized = Schema.String.pipe(\n *   Schema.decode(SchemaTransformation.capitalize())\n * )\n * Schema.decodeSync(Capitalized)(\"hello\") // => \"Hello\"\n * ```\n *\n * @see {@link uncapitalize}\n * @see {@link toUpperCase}\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function capitalize() {\n  return new Transformation(SchemaGetter.capitalize(), SchemaGetter.passthrough());\n}\n/**\n * Transforms strings by lowercasing the first character on\n * decode. Encode is passthrough.\n *\n * **When to use**\n *\n * Use when you need a schema transformation to normalize identifiers or field\n * names.\n *\n * **Details**\n *\n * Decoding lowercases the first character and leaves the rest unchanged.\n * Encoding is passthrough.\n *\n * **Example** (Uncapitalizing on decode)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaTransformation } from \"effect\"\n *\n * const Uncapitalized = Schema.String.pipe(\n *   Schema.decode(SchemaTransformation.uncapitalize())\n * )\n * Schema.decodeSync(Uncapitalized)(\"Hello\") // => \"hello\"\n * ```\n *\n * @see {@link capitalize}\n * @see {@link toLowerCase}\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function uncapitalize() {\n  return new Transformation(SchemaGetter.uncapitalize(), SchemaGetter.passthrough());\n}\n/**\n * Transforms a string into a record of key-value pairs and\n * encodes a record of key-value pairs into a string.\n *\n * **When to use**\n *\n * Use when you need a schema transformation to parse query-string-like or\n * config-file-like strings into records.\n *\n * **Details**\n *\n * Decoding splits the string by `separator` (default `\",\"`) into pairs, then\n * splits each pair by `keyValueSeparator` (default `\"=\"`). Encoding joins the\n * record back into a string using the same separators. The transformation is\n * round-trippable when keys and values do not contain the separators.\n *\n * **Example** (Parsing key-value pairs)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaTransformation } from \"effect\"\n *\n * const Config = Schema.String.pipe(\n *   Schema.decodeTo(\n *     Schema.Record(Schema.String, Schema.String),\n *     SchemaTransformation.splitKeyValue({ separator: \";\", keyValueSeparator: \":\" })\n *   )\n * )\n * Schema.decodeSync(Config)(\"host:localhost;port:3000\") // => { host: \"localhost\", port: \"3000\" }\n * ```\n *\n * @see {@link trim}\n * @see {@link snakeToCamel}\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function splitKeyValue(options) {\n  return new Transformation(SchemaGetter.splitKeyValue(options), SchemaGetter.joinKeyValue(options));\n}\nconst passthrough_ = /*#__PURE__*/new Transformation(/*#__PURE__*/SchemaGetter.passthrough(), /*#__PURE__*/SchemaGetter.passthrough());\nexport function passthrough() {\n  return passthrough_;\n}\nexport function passthroughSupertype() {\n  return passthrough_;\n}\nexport function passthroughSubtype() {\n  return passthrough_;\n}\n/**\n * Decodes a `string` into a `number` and encodes a `number` back to a\n * `string`.\n *\n * **When to use**\n *\n * Use when you need a schema transformation to parse numeric strings from APIs,\n * form data, or URL parameters.\n *\n * **Details**\n *\n * Decoding coerces the string to a number like `Number(s)`. Encoding coerces\n * the number to a string like `String(n)`. This does not validate that the\n * result is finite; combine with `Schema.Finite` or `Schema.Int` for stricter\n * checks.\n *\n * **Example** (Converting a string to a number)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaTransformation } from \"effect\"\n *\n * const schema = Schema.String.pipe(\n *   Schema.decodeTo(Schema.Number, SchemaTransformation.numberFromString)\n * )\n * Schema.decodeSync(schema)(\"42\") // => 42\n * ```\n *\n * @see {@link bigintFromString}\n * @see {@link transform}\n *\n * @category converting\n * @since 4.0.0\n */\nexport const numberFromString = /*#__PURE__*/new Transformation(/*#__PURE__*/SchemaGetter.Number(), /*#__PURE__*/SchemaGetter.String());\n/**\n * Decodes a `string` into a `bigint` and encodes a `bigint` back to a\n * `string`.\n *\n * **When to use**\n *\n * Use when you need a schema transformation to parse large integer strings\n * (e.g. database IDs, blockchain values).\n *\n * **Details**\n *\n * Decoding coerces the string to a bigint like `BigInt(s)`. Encoding coerces\n * the bigint to a string like `String(n)`. Decoding fails if the string is not\n * a valid bigint representation.\n *\n * **Example** (Converting a string to a BigInt)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaTransformation } from \"effect\"\n *\n * const schema = Schema.String.pipe(\n *   Schema.decodeTo(Schema.BigInt, SchemaTransformation.bigintFromString)\n * )\n * Schema.decodeSync(schema)(\"42\") // => 42n\n * ```\n *\n * @see {@link numberFromString}\n * @see {@link transform}\n *\n * @category converting\n * @since 4.0.0\n */\nexport const bigintFromString = /*#__PURE__*/new Transformation(/*#__PURE__*/SchemaGetter.BigInt(), /*#__PURE__*/SchemaGetter.String());\n/**\n * Decodes a `string` into a `Date` and encodes a `Date` back to a `string`.\n *\n * **When to use**\n *\n * Use when you need a schema transformation to parse date strings from APIs or\n * user input.\n *\n * **Details**\n *\n * Decoding creates a `Date` from the string like `new Date(s)`. Encoding\n * converts the `Date` to an ISO string like `date.toISOString()`, returning\n * `\"Invalid Date\"` for invalid dates.\n *\n * **Example** (Converting a string to a Date)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaTransformation } from \"effect\"\n *\n * const schema = Schema.String.pipe(\n *   Schema.decodeTo(Schema.Date, SchemaTransformation.dateFromString)\n * )\n * Schema.decodeSync(schema)(\"2024-01-01\").toISOString() // => \"2024-01-01T00:00:00.000Z\"\n * ```\n *\n * @see {@link dateFromMillis}\n * @see {@link dateTimeUtcFromString}\n *\n * @category converting\n * @since 4.0.0\n */\nexport const dateFromString = /*#__PURE__*/new Transformation(/*#__PURE__*/SchemaGetter.Date(), /*#__PURE__*/SchemaGetter.transform(formatDate));\n/**\n * Decodes epoch milliseconds into a `Date` and encodes a `Date` back to epoch\n * milliseconds.\n *\n * **When to use**\n *\n * Use when you need a schema transformation for numeric timestamps represented\n * as milliseconds since the Unix epoch.\n *\n * **Details**\n *\n * Decoding creates a `Date` from the number like `new Date(ms)`. Encoding\n * returns the `Date` timestamp like `date.getTime()`.\n *\n * **Gotchas**\n *\n * This transformation does not validate date validity. `NaN`, `Infinity`, and\n * `-Infinity` decode to invalid `Date` instances.\n *\n * **Example** (Converting milliseconds to a Date)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaTransformation } from \"effect\"\n *\n * const schema = Schema.Number.pipe(\n *   Schema.decodeTo(Schema.Date, SchemaTransformation.dateFromMillis)\n * )\n * Schema.decodeSync(schema)(0).toISOString() // => \"1970-01-01T00:00:00.000Z\"\n * ```\n *\n * @see {@link dateFromString}\n * @see {@link SchemaGetter.dateTimeUtcFromInput}\n *\n * @category converting\n * @since 4.0.0\n */\nexport const dateFromMillis = /*#__PURE__*/new Transformation(/*#__PURE__*/SchemaGetter.Date(), /*#__PURE__*/SchemaGetter.transform(date => date.getTime()));\n/**\n * Decodes a `string` into a `Duration` and encodes a `Duration` back to a\n * parseable `string`.\n *\n * **When to use**\n *\n * Use when you need a schema transformation to parse human-readable duration\n * strings from APIs, config, or user input.\n *\n * **Details**\n *\n * Decoding accepts any string that `Duration.fromInput` can parse, including\n * `\"Infinity\"` and `\"-Infinity\"`. Encoding returns `String(duration)`,\n * producing strings such as `\"2000 millis\"` or `\"10 nanos\"` that round-trip\n * through the parser.\n *\n * **Example** (Converting a string to a Duration)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaTransformation } from \"effect\"\n *\n * const schema = Schema.String.pipe(\n *   Schema.decodeTo(Schema.Duration, SchemaTransformation.durationFromString)\n * )\n * String(Schema.decodeSync(schema)(\"5 seconds\")) // => \"5000 millis\"\n * ```\n *\n * @see {@link durationFromNanos}\n * @see {@link durationFromMillis}\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const durationFromString = /*#__PURE__*/transformEffect({\n  decode: (s, options) => Option.match(Duration.fromInput(s), {\n    onNone: () => Effect.fail(new SchemaIssue.InvalidValue({\n      expected: \"a valid Duration string\"\n    }, s, options)),\n    onSome: Effect.succeed\n  }),\n  encode: duration => Effect.succeed(String(duration))\n});\n/**\n * Decodes a `bigint` (nanoseconds) into a `Duration` and encodes a\n * `Duration` back to `bigint` nanoseconds.\n *\n * **When to use**\n *\n * Use when you need a schema transformation for nanosecond-precision timestamps\n * or intervals.\n *\n * **Details**\n *\n * Decoding always succeeds and creates a `Duration` from nanoseconds. Encoding\n * fails with `InvalidValue` if the `Duration` cannot be represented as a\n * `bigint`, such as `Duration.infinity`.\n *\n * **Example** (Converting nanoseconds to a Duration)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaTransformation } from \"effect\"\n *\n * const schema = Schema.BigInt.pipe(\n *   Schema.decodeTo(Schema.Duration, SchemaTransformation.durationFromNanos)\n * )\n * String(Schema.decodeSync(schema)(5n)) // => \"5 nanos\"\n * ```\n *\n * @see {@link durationFromMillis}\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const durationFromNanos = /*#__PURE__*/transformEffect({\n  decode: i => Effect.succeed(Duration.nanos(i)),\n  encode: (a, options) => Option.match(Duration.toNanos(a), {\n    onNone: () => Effect.fail(new SchemaIssue.InvalidValue({\n      expected: \"a Duration representable as a bigint\"\n    }, a, options)),\n    onSome: nanos => Effect.succeed(nanos)\n  })\n});\n/**\n * Decodes a `number` of milliseconds into a `Duration` and encodes a `Duration`\n * back to milliseconds.\n *\n * **When to use**\n *\n * Use when you need a schema transformation to decode timeouts, delays, elapsed\n * intervals, or other duration values stored as millisecond counts.\n *\n * **Details**\n *\n * Decode creates a duration from the number, and encode returns the duration\n * length in milliseconds.\n *\n * **Example** (Converting milliseconds to a Duration)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaTransformation } from \"effect\"\n *\n * const schema = Schema.Number.pipe(\n *   Schema.decodeTo(Schema.Duration, SchemaTransformation.durationFromMillis)\n * )\n * String(Schema.decodeSync(schema)(5000)) // => \"5000 millis\"\n * ```\n *\n * @see {@link durationFromNanos}\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const durationFromMillis = /*#__PURE__*/transform({\n  decode: i => Duration.millis(i),\n  encode: a => Duration.toMillis(a)\n});\n/**\n * Decodes a string into a `ByteSize` and encodes it as an exact string.\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const byteSizeFromString = /*#__PURE__*/transformEffect({\n  decode: (input, options) => Option.match(ByteSize.fromInput(input), {\n    onNone: () => Effect.fail(new SchemaIssue.InvalidValue({\n      expected: \"a valid ByteSize string\"\n    }, input, options)),\n    onSome: Effect.succeed\n  }),\n  encode: byteSize => Effect.succeed(`${byteSize} ${byteSize === BigInt(1) ? \"byte\" : \"bytes\"}`)\n});\n/**\n * Decodes a non-negative bigint byte count into a `ByteSize`.\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const byteSizeFromBigInt = /*#__PURE__*/transformEffect({\n  decode: (input, options) => Option.match(ByteSize.fromInput(input), {\n    onNone: () => Effect.fail(new SchemaIssue.InvalidValue({\n      expected: \"a non-negative bigint byte count\"\n    }, input, options)),\n    onSome: Effect.succeed\n  }),\n  encode: byteSize => Effect.succeed(ByteSize.toBigInt(byteSize))\n});\n/**\n * Decodes a non-negative safe-integer byte count into a `ByteSize`.\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const byteSizeFromNumber = /*#__PURE__*/transformEffect({\n  decode: (input, options) => Option.match(ByteSize.fromInput(input), {\n    onNone: () => Effect.fail(new SchemaIssue.InvalidValue({\n      expected: \"a non-negative safe-integer byte count\"\n    }, input, options)),\n    onSome: Effect.succeed\n  }),\n  encode: (byteSize, options) => Option.match(ByteSize.toNumber(byteSize), {\n    onNone: () => Effect.fail(new SchemaIssue.InvalidValue({\n      expected: \"a ByteSize representable as a safe integer\"\n    }, byteSize, options)),\n    onSome: Effect.succeed\n  })\n});\nconst isJsonError = input => Predicate.isObject(input) && typeof input[\"message\"] === \"string\";\nconst decodeJsonError = input => {\n  const hasCause = Object.hasOwn(input, \"cause\");\n  const err = hasCause ? new Error(input.message, {\n    cause: decodeDefect(input.cause)\n  }) : new Error(input.message);\n  if (typeof input.name === \"string\" && input.name !== \"Error\") err.name = input.name;\n  if (typeof input.stack === \"string\") err.stack = input.stack;\n  return err;\n};\nconst encodeUnknownAsJson = input => {\n  try {\n    const json = formatJson(input);\n    return json === undefined ? format(input) : JSON.parse(json);\n  } catch {\n    return format(input);\n  }\n};\nconst encodeJsonError = (input, options, encodeDefect) => {\n  const encoded = {\n    name: input.name,\n    message: typeof input.message === \"string\" ? input.message : \"\"\n  };\n  if (options?.includeStack && typeof input.stack === \"string\") {\n    encoded.stack = input.stack;\n  }\n  if (!options?.excludeCause && input.cause !== undefined) {\n    encoded.cause = encodeDefect(input.cause);\n  }\n  return encoded;\n};\nconst makeEncodeDefect = options => {\n  const seen = new WeakSet();\n  const encode = input => {\n    if (Predicate.isError(input)) {\n      if (seen.has(input)) {\n        return \"[Circular]\";\n      }\n      seen.add(input);\n      const encoded = encodeJsonError(input, options, encode);\n      seen.delete(input);\n      return encoded;\n    }\n    return encodeUnknownAsJson(input);\n  };\n  return encode;\n};\nconst decodeDefect = input => isJsonError(input) ? decodeJsonError(input) : input;\n/** @internal */\nexport const errorFromJsonError = options => transform({\n  decode: decodeJsonError,\n  encode: input => makeEncodeDefect(options)(input)\n});\n/** @internal */\nexport const defectFromJson = options => transform({\n  decode: decodeDefect,\n  encode: makeEncodeDefect(options)\n});\n/**\n * Decodes `T | null` into `Option<T>` and encodes `Option<T>` back to\n * `T | null`.\n *\n * **When to use**\n *\n * Use when you need a schema transformation to convert nullable API fields to\n * `Option`.\n *\n * **Details**\n *\n * Decoding maps `null` to `Option.none()` and non-null values to\n * `Option.some(value)`. Encoding maps `Option.none()` to `null` and\n * `Option.some(value)` to `value`. The transformation is pure and synchronous.\n *\n * **Example** (Converting nullable values to an Option)\n *\n * ```ts import.meta.vitest\n * import { Option, Schema, SchemaTransformation } from \"effect\"\n *\n * const schema = Schema.NullOr(Schema.String).pipe(\n *   Schema.decodeTo(\n *     Schema.Option(Schema.String),\n *     SchemaTransformation.optionFromNullOr()\n *   )\n * )\n * Schema.decodeSync(schema)(null) // => Option.none()\n * ```\n *\n * @see {@link optionFromNullishOr}\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function optionFromNullOr() {\n  return transform({\n    decode: Option.fromNullOr,\n    encode: Option.getOrNull\n  });\n}\n/**\n * Decodes `T | undefined` into `Option<T>` and encodes `Option.none()` back to\n * `undefined`.\n *\n * **When to use**\n *\n * Use when you need a schema transformation to convert API fields that use\n * `undefined` for absence to `Option`.\n *\n * **Details**\n *\n * Decoding maps `undefined` to `Option.none()` and non-undefined values to\n * `Option.some(value)`. Encoding maps `Option.none()` to `undefined` and\n * `Option.some(value)` to `value`. The transformation is pure and synchronous.\n *\n * **Example** (Converting undefined-or values to an Option)\n *\n * ```ts import.meta.vitest\n * import { Option, Schema, SchemaTransformation } from \"effect\"\n *\n * const schema = Schema.UndefinedOr(Schema.String).pipe(\n *   Schema.decodeTo(\n *     Schema.Option(Schema.String),\n *     SchemaTransformation.optionFromUndefinedOr()\n *   )\n * )\n * Schema.decodeSync(schema)(undefined) // => Option.none()\n * ```\n *\n * @see {@link optionFromOptionalKey}\n * @see {@link optionFromOptional}\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function optionFromUndefinedOr() {\n  return transform({\n    decode: Option.fromUndefinedOr,\n    encode: Option.getOrUndefined\n  });\n}\n/**\n * Decodes `T | null | undefined` into `Option<T>` and encodes `Option<T>`\n * back to `T | null` or `T | undefined` depending on the provided\n * `options.onNoneEncoding` (defaults to `undefined`).\n *\n * **When to use**\n *\n * Use when you need a schema transformation to convert nullish API fields to\n * `Option` when both `null` and `undefined` represent absence.\n *\n * **Details**\n *\n * Decoding maps `null` and `undefined` to `Option.none()` and all other values\n * to `Option.some(value)`. Encoding maps `Option.none()` to `null` or\n * `undefined` according to `options.onNoneEncoding`, and maps\n * `Option.some(value)` to `value`. The transformation is pure and synchronous.\n *\n * **Example** (Converting nullish values to an Option and encoding None as null)\n *\n * ```ts import.meta.vitest\n * import { Option, Schema, SchemaTransformation } from \"effect\"\n *\n * const schema = Schema.NullishOr(Schema.String).pipe(\n *   Schema.decodeTo(\n *     Schema.Option(Schema.String),\n *     SchemaTransformation.optionFromNullishOr({ onNoneEncoding: null })\n *   )\n * )\n * Schema.encodeSync(schema)(Option.none()) // => null\n * ```\n *\n * @see {@link optionFromNullOr}\n * @see {@link optionFromUndefinedOr}\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function optionFromNullishOr(options) {\n  return transform({\n    decode: Option.fromNullishOr,\n    encode: options?.onNoneEncoding === null ? Option.getOrNull : Option.getOrUndefined\n  });\n}\n/**\n * Decodes an optional struct key into `Option<T>` and encodes `Option<T>`\n * back to an optional key.\n *\n * **When to use**\n *\n * Use when you need a schema transformation to convert optional struct keys\n * (declared with `Schema.optionalKey`) to `Option` values.\n *\n * **Details**\n *\n * Decoding maps an absent key (`None`) to `Some(None)` and a present key\n * (`Some(v)`) to `Some(Some(v))`. Encoding maps `Some(None)` to `None` to omit\n * the key, and maps `Some(Some(v))` to `Some(v)`. This uses\n * `transformOptional` under the hood.\n *\n * **Example** (Converting an optional key to an Option)\n *\n * ```ts import.meta.vitest\n * import { Option, Schema, SchemaTransformation } from \"effect\"\n *\n * const schema = Schema.Struct({\n *   name: Schema.optionalKey(Schema.String).pipe(\n *     Schema.decodeTo(\n *       Schema.Option(Schema.String),\n *       SchemaTransformation.optionFromOptionalKey()\n *     )\n *   )\n * })\n * Schema.decodeSync(schema)({}).name // => Option.none()\n * ```\n *\n * @see {@link optionFromOptional}\n * @see {@link optionFromUndefinedOr}\n * @see {@link transformOptional}\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function optionFromOptionalKey() {\n  return transformOptional({\n    decode: Option.some,\n    encode: Option.flatten\n  });\n}\n/**\n * Decodes optional values into `Option<T>` and encodes `Option.none()` back to\n * an omitted optional value.\n *\n * **When to use**\n *\n * Use when you need a schema transformation to convert optional (possibly\n * `undefined`) values to `Option`.\n *\n * **Details**\n *\n * Decoding maps an absent or `undefined` value to `Some(None)` and a present\n * value to `Some(Some(v))`. Encoding maps `Some(None)` to `None` to omit the\n * value, and maps `Some(Some(v))` to `Some(v)`. This uses\n * `transformOptional` under the hood and filters out `undefined` on decode.\n *\n * **Example** (Converting an optional value to an Option)\n *\n * ```ts import.meta.vitest\n * import { Option, Schema, SchemaTransformation } from \"effect\"\n *\n * const schema = Schema.Struct({\n *   age: Schema.optional(Schema.Number).pipe(\n *     Schema.decodeTo(\n *       Schema.Option(Schema.Number),\n *       SchemaTransformation.optionFromOptional()\n *     )\n *   )\n * })\n * Schema.decodeSync(schema)({ age: undefined }).age // => Option.none()\n * ```\n *\n * @see {@link optionFromOptionalKey}\n * @see {@link optionFromUndefinedOr}\n * @see {@link transformOptional}\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function optionFromOptional() {\n  return transformOptional({\n    decode: ot => ot.pipe(Option.filter(Predicate.isNotUndefined), Option.some),\n    encode: Option.flatten\n  });\n}\n/**\n * Decodes a `string` into a `URL` and encodes a `URL` back to its `href`\n * string.\n *\n * **When to use**\n *\n * Use when you need a schema transformation to parse URL strings from user\n * input or API responses.\n *\n * **Details**\n *\n * Decoding checks `URL.canParse(s)` and fails with `InvalidValue` if the string\n * is not a valid URL. Encoding returns `url.href`.\n *\n * **Example** (Converting a string to a URL)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaTransformation } from \"effect\"\n *\n * const schema = Schema.String.pipe(\n *   Schema.decodeTo(Schema.URL, SchemaTransformation.urlFromString)\n * )\n * Schema.decodeSync(schema)(\"https://example.com/path\").href // => \"https://example.com/path\"\n * ```\n *\n * @see {@link numberFromString}\n * @see {@link transformEffect}\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const urlFromString = /*#__PURE__*/transformEffect({\n  decode: (s, options) => URL.canParse(s) ? Effect.succeed(new URL(s)) : Effect.fail(new SchemaIssue.InvalidValue({\n    expected: \"a valid URL string\"\n  }, s, options)),\n  encode: url => Effect.succeed(url.href)\n});\n/**\n * Decodes a `string` into a `BigDecimal` and encodes a `BigDecimal` back to\n * its string representation.\n *\n * **When to use**\n *\n * Use when you need a schema transformation to parse decimal number strings\n * from APIs or user input.\n *\n * **Details**\n *\n * Decoding calls `BigDecimal.fromString(s)` and fails with `InvalidValue` if\n * the string is not a valid `BigDecimal` representation. Encoding returns\n * `BigDecimal.format(bd)`.\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const bigDecimalFromString = /*#__PURE__*/transformEffect({\n  decode: (s, options) => {\n    const result = BigDecimal.fromString(s);\n    return Option.isNone(result) ? Effect.fail(new SchemaIssue.InvalidValue({\n      expected: \"a valid BigDecimal string\"\n    }, s, options)) : Effect.succeed(result.value);\n  },\n  encode: bd => Effect.succeed(BigDecimal.format(bd))\n});\n/**\n * Decodes a Base64-encoded `string` into a `Uint8Array` and encodes a\n * `Uint8Array` back to a Base64 string.\n *\n * **When to use**\n *\n * Use when you need a schema transformation for binary data transmitted as\n * Base64 strings (e.g. file uploads, API payloads).\n *\n * **Details**\n *\n * Decoding parses the Base64 string into bytes. Encoding writes the byte array\n * as a Base64 string.\n *\n * **Example** (Converting Base64 to a Uint8Array)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaTransformation } from \"effect\"\n *\n * const schema = Schema.String.pipe(\n *   Schema.decodeTo(Schema.Uint8Array, SchemaTransformation.uint8ArrayFromBase64String)\n * )\n * Array.from(Schema.decodeSync(schema)(\"AQID\")) // => [1, 2, 3]\n * ```\n *\n * @see {@link fromJsonString}\n * @see `Schema.Uint8ArrayFromBase64` - a ready-made schema wrapping this transformation.\n *\n * @category encoding\n * @since 4.0.0\n */\nexport const uint8ArrayFromBase64String = /*#__PURE__*/new Transformation(/*#__PURE__*/SchemaGetter.decodeBase64(), /*#__PURE__*/SchemaGetter.encodeBase64());\n/**\n * Decodes a Base64-encoded `string` into a UTF-8 `string` and encodes a\n * UTF-8 `string` back to a Base64 string.\n *\n * **When to use**\n *\n * Use when you need a schema transformation for text data transmitted as Base64\n * strings.\n *\n * **Details**\n *\n * Decoding parses the Base64 string into a UTF-8 string. Encoding writes the\n * string as a Base64 string.\n *\n * **Example** (Converting Base64 to a string)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaTransformation } from \"effect\"\n *\n * const schema = Schema.String.pipe(\n *   Schema.decodeTo(Schema.String, SchemaTransformation.stringFromBase64String)\n * )\n * Schema.decodeSync(schema)(\"aGVsbG8=\") // => \"hello\"\n * ```\n *\n * @see {@link uint8ArrayFromBase64String}\n * @see `Schema.StringFromBase64` - a ready-made schema wrapping this transformation.\n *\n * @category encoding\n * @since 4.0.0\n */\nexport const stringFromBase64String = /*#__PURE__*/new Transformation(/*#__PURE__*/SchemaGetter.decodeBase64String(), /*#__PURE__*/SchemaGetter.encodeBase64());\n/**\n * Decodes a base64 (URL) encoded `string` into a UTF-8 `string` and encodes it back.\n *\n * **When to use**\n *\n * Use when you need a schema transformation for text data transmitted as Base64\n * URL-safe strings.\n *\n * **Details**\n *\n * Decoding parses the Base64 URL string into a UTF-8 string. Encoding writes\n * the string as a Base64 URL string.\n *\n * **Example** (Converting Base64Url to a string)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaTransformation } from \"effect\"\n *\n * const schema = Schema.String.pipe(\n *   Schema.decodeTo(Schema.String, SchemaTransformation.stringFromBase64UrlString)\n * )\n * Schema.decodeSync(schema)(\"aGVsbG8\") // => \"hello\"\n * ```\n *\n * @see {@link stringFromBase64String}\n * @see `Schema.StringFromBase64Url` - a ready-made schema wrapping this transformation.\n *\n * @category encoding\n * @since 4.0.0\n */\nexport const stringFromBase64UrlString = /*#__PURE__*/new Transformation(/*#__PURE__*/SchemaGetter.decodeBase64UrlString(), /*#__PURE__*/SchemaGetter.encodeBase64Url());\n/**\n * Decodes a hex encoded `string` into a UTF-8 `string` and encodes it back.\n *\n * **When to use**\n *\n * Use when you need a schema transformation for text data transmitted as\n * hexadecimal strings.\n *\n * **Details**\n *\n * Decoding parses the hex string into a UTF-8 string. Encoding writes the\n * string as a hex string.\n *\n * **Example** (Converting hex to a string)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaTransformation } from \"effect\"\n *\n * const schema = Schema.String.pipe(\n *   Schema.decodeTo(Schema.String, SchemaTransformation.stringFromHexString)\n * )\n * Schema.decodeSync(schema)(\"68656c6c6f\") // => \"hello\"\n * ```\n *\n * @see {@link stringFromBase64String}\n * @see `Schema.StringFromHex` - a ready-made schema wrapping this transformation.\n *\n * @category encoding\n * @since 4.0.0\n */\nexport const stringFromHexString = /*#__PURE__*/new Transformation(/*#__PURE__*/SchemaGetter.decodeHexString(), /*#__PURE__*/SchemaGetter.encodeHex());\n/**\n * Decodes a URI component encoded string into a UTF-8 string and encodes a\n * UTF-8 string into a URI component encoded string.\n *\n * **When to use**\n *\n * Use when you need a schema transformation to store structured data in URL\n * query parameters or fragments, such as composing with `Schema.parseJson` to\n * round-trip JSON through a URL.\n *\n * **Details**\n *\n * Decoding calls `decodeURIComponent` and fails if the input contains malformed\n * percent-encoding sequences. Encoding calls `encodeURIComponent`.\n *\n * **Example** (Defining a URI component schema)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaTransformation } from \"effect\"\n *\n * const schema = Schema.String.pipe(\n *   Schema.decodeTo(Schema.String, SchemaTransformation.stringFromUriComponent)\n * )\n * Schema.decodeSync(schema)(\"hello%20world\") // => \"hello world\"\n * ```\n *\n * @see {@link stringFromBase64String}\n * @see `Schema.StringFromUriComponent` - a ready-made schema wrapping this transformation.\n *\n * @category encoding\n * @since 4.0.0\n */\nexport const stringFromUriComponent = /*#__PURE__*/new Transformation(/*#__PURE__*/SchemaGetter.decodeUriComponent(), /*#__PURE__*/SchemaGetter.encodeUriComponent());\n/**\n * Decodes a JSON string with `JSON.parse` and encodes a value with\n * `JSON.stringify`.\n *\n * **When to use**\n *\n * Use when you need a schema transformation to decode JSON stored or\n * transmitted as a string, usually before composing with another schema that\n * validates the parsed structure.\n *\n * **Details**\n *\n * The `reviver` option is passed to `JSON.parse` during decoding. The\n * `replacer` and `space` options are passed to `JSON.stringify` during\n * encoding. Decode fails with `InvalidValue` for invalid JSON, and encode can\n * fail with `InvalidValue` when `JSON.stringify` cannot serialize the value.\n *\n * **Example** (Parsing JSON)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaTransformation } from \"effect\"\n *\n * const schema = Schema.String.pipe(\n *   Schema.decodeTo(Schema.Unknown, SchemaTransformation.fromJsonString())\n * )\n * Schema.decodeSync(schema)(\"{\\\"ok\\\":true}\") // => { ok: true }\n * ```\n *\n * @see {@link uint8ArrayFromBase64String}\n * @see {@link fromFormData}\n *\n * @category decoding\n * @since 4.0.0\n */\nexport function fromJsonString(options) {\n  return new Transformation(SchemaGetter.parseJson(options ?? {}), SchemaGetter.stringifyJson(options));\n}\n/**\n * Decodes a `FormData` instance into a nested record using bracket-path keys and\n * encodes object-like values back into `FormData`.\n *\n * **When to use**\n *\n * Use when you need a schema transformation for form or multipart payloads\n * whose keys, such as `user[name]` or `items[0]`, should become nested data.\n *\n * **Details**\n *\n * Decode preserves string and `Blob` leaves. Encode flattens nested objects and\n * arrays into bracket-path entries and returns an empty `FormData` for\n * non-object inputs.\n *\n * **Example** (Decoding FormData)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaTransformation } from \"effect\"\n *\n * const schema = Schema.instanceOf(FormData).pipe(\n *   Schema.decodeTo(Schema.Unknown, SchemaTransformation.fromFormData)\n * )\n * const formData = new FormData()\n * formData.append(\"user[name]\", \"Alice\")\n * Schema.decodeSync(schema)(formData) // => { user: { name: \"Alice\" } }\n * ```\n *\n * @see {@link fromURLSearchParams}\n * @see {@link fromJsonString}\n *\n * @category decoding\n * @since 4.0.0\n */\nexport const fromFormData = /*#__PURE__*/new Transformation(/*#__PURE__*/SchemaGetter.decodeFormData(), /*#__PURE__*/SchemaGetter.encodeFormData());\n/**\n * Decodes `URLSearchParams` into a nested record using bracket-path keys and\n * encodes object-like values back into `URLSearchParams`.\n *\n * **When to use**\n *\n * Use when you need a schema transformation for query strings whose keys, such\n * as `filter[name]` or `items[0]`, should become nested data.\n *\n * **Details**\n *\n * Decode produces string leaves. Encode flattens nested objects and arrays into\n * bracket-path entries and returns empty `URLSearchParams` for non-object\n * inputs.\n *\n * **Example** (Decoding URLSearchParams)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaTransformation } from \"effect\"\n *\n * const schema = Schema.instanceOf(URLSearchParams).pipe(\n *   Schema.decodeTo(Schema.Unknown, SchemaTransformation.fromURLSearchParams)\n * )\n * Schema.decodeSync(schema)(new URLSearchParams(\"user[name]=Alice\")) // => { user: { name: \"Alice\" } }\n * ```\n *\n * @see {@link fromFormData}\n * @see {@link fromJsonString}\n *\n * @category decoding\n * @since 4.0.0\n */\nexport const fromURLSearchParams = /*#__PURE__*/new Transformation(/*#__PURE__*/SchemaGetter.decodeURLSearchParams(), /*#__PURE__*/SchemaGetter.encodeURLSearchParams());\n/**\n * Decodes a numeric time-zone offset in milliseconds into a\n * `DateTime.TimeZone.Offset` and encodes it back to the offset number.\n *\n * **When to use**\n *\n * Use when you need a schema transformation to represent fixed-offset time\n * zones with numeric millisecond offsets.\n *\n * **Details**\n *\n * Decode uses `DateTime.zoneMakeOffset`; encode returns the offset's `offset`\n * field.\n *\n * @see {@link timeZoneFromString} for IANA or offset string encodings\n * @see {@link timeZoneNamedFromString} for IANA named-zone strings\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const timeZoneOffsetFromNumber = /*#__PURE__*/transform({\n  decode: n => DateTime.zoneMakeOffset(n),\n  encode: tz => tz.offset\n});\n/**\n * Decodes an IANA time-zone identifier string into a\n * `DateTime.TimeZone.Named` and encodes a named time zone back to its `id`.\n *\n * **When to use**\n *\n * Use when you need a schema transformation to accept only IANA time-zone\n * identifier strings and produce `DateTime.TimeZone.Named` values.\n *\n * **Details**\n *\n * Decode fails with `InvalidValue` when the string is not a valid IANA time-zone\n * identifier.\n *\n * @see {@link timeZoneFromString} for time-zone strings that may be either IANA identifiers or offset strings\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const timeZoneNamedFromString = /*#__PURE__*/transformEffect({\n  decode: (s, options) => {\n    return Option.match(DateTime.zoneMakeNamed(s), {\n      onNone: () => Effect.fail(new SchemaIssue.InvalidValue({\n        expected: \"a valid IANA time zone\"\n      }, s, options)),\n      onSome: Effect.succeed\n    });\n  },\n  encode: tz => Effect.succeed(tz.id)\n});\n/**\n * Decodes a string into a `DateTime.TimeZone` and encodes a time zone back to\n * its string representation.\n *\n * **When to use**\n *\n * Use when you need a schema transformation to accept either an IANA time-zone\n * identifier or an offset string and produce a general `DateTime.TimeZone`.\n *\n * **Details**\n *\n * Accepted decode inputs include valid IANA identifiers and offset strings such\n * as `\"+03:00\"`. Decode fails with `InvalidValue` when the string cannot be\n * parsed as a time zone.\n *\n * @see {@link timeZoneNamedFromString} for IANA named-zone strings only\n * @see {@link timeZoneOffsetFromNumber} for fixed-offset zones encoded as numbers\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const timeZoneFromString = /*#__PURE__*/transformEffect({\n  decode: (s, options) => {\n    return Option.match(DateTime.zoneFromString(s), {\n      onNone: () => Effect.fail(new SchemaIssue.InvalidValue({\n        expected: \"a valid time zone\"\n      }, s, options)),\n      onSome: Effect.succeed\n    });\n  },\n  encode: tz => Effect.succeed(DateTime.zoneToString(tz))\n});\n/**\n * Decodes a date-time string into a `DateTime.Utc` and encodes it back to an ISO\n * string.\n *\n * **When to use**\n *\n * Use when you need a schema transformation to decode date-time strings to a\n * normalized `DateTime.Utc` and encode back as a UTC ISO string.\n *\n * **Details**\n *\n * Decode accepts strings supported by `DateTime.make`, converts the result to\n * UTC, and fails with `InvalidValue` when parsing fails. Encode uses\n * `DateTime.formatIso`.\n *\n * @see {@link dateFromString} for decoding into JavaScript `Date`\n * @see {@link dateTimeZonedFromString} for ISO strings that should preserve zoned date-time information\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const dateTimeUtcFromString = /*#__PURE__*/transformEffect({\n  decode: (s, options) => {\n    return Option.match(DateTime.make(s), {\n      onNone: () => Effect.fail(new SchemaIssue.InvalidValue({\n        expected: \"a valid UTC DateTime string\"\n      }, s, options)),\n      onSome: result => Effect.succeed(DateTime.toUtc(result))\n    });\n  },\n  encode: utc => Effect.succeed(DateTime.formatIso(utc))\n});\n/**\n * Decodes a zoned date-time string into a `DateTime.Zoned` and encodes it back\n * to an ISO zoned string.\n *\n * **When to use**\n *\n * Use when you need a schema transformation for ISO zoned date-time strings\n * that decode to `DateTime.Zoned` and encode with `DateTime.formatIsoZoned`.\n *\n * **Details**\n *\n * Decode uses `DateTime.makeZonedFromString` and fails with `InvalidValue` when\n * the input is not a valid zoned date-time. Encode uses\n * `DateTime.formatIsoZoned`.\n *\n * @see {@link dateTimeUtcFromString} for date-time strings that should decode to `DateTime.Utc` and encode as UTC ISO strings\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const dateTimeZonedFromString = /*#__PURE__*/transformEffect({\n  decode: (s, options) => {\n    return Option.match(DateTime.makeZonedFromString(s), {\n      onNone: () => Effect.fail(new SchemaIssue.InvalidValue({\n        expected: \"a valid Zoned DateTime string\"\n      }, s, options)),\n      onSome: Effect.succeed\n    });\n  },\n  encode: zoned => Effect.succeed(DateTime.formatIsoZoned(zoned))\n});\n//# sourceMappingURL=SchemaTransformation.js.map","/**\n * Represents Effect schemas as runtime trees.\n *\n * Every `Schema` has an AST made from nodes for declarations, primitives,\n * literals, arrays, objects, unions, suspended schemas, checks, annotations,\n * encoding links, and parsing context. Most users work with the higher-level\n * `Schema` module. Use `SchemaAST` when you need to inspect schema nodes, build\n * ASTs programmatically, change encoded or decoded views, collect issues, or\n * run low-level schema checks.\n *\n * @since 4.0.0\n */\nimport * as Arr from \"./Array.js\";\nimport * as Cause from \"./Cause.js\";\nimport * as Effect from \"./Effect.js\";\nimport * as Exit from \"./Exit.js\";\nimport { format, formatPropertyKey } from \"./Formatter.js\";\nimport { identity, memoize, memoizeIdempotent } from \"./Function.js\";\nimport { effectIsExit, iterateConcurrent, iterateEager, resolveConcurrency } from \"./internal/effect.js\";\nimport * as InternalRecord from \"./internal/record.js\";\nimport * as InternalAnnotations from \"./internal/schema/annotations.js\";\nimport * as InternalSchemaCause from \"./internal/schema/cause.js\";\nimport * as InternalParser from \"./internal/schema/parser.js\";\nimport * as Pipeable from \"./Pipeable.js\";\nimport * as Predicate from \"./Predicate.js\";\nimport * as Result from \"./Result.js\";\nimport * as SchemaGetter from \"./SchemaGetter.js\";\nimport * as SchemaIssue from \"./SchemaIssue.js\";\nimport * as SchemaTransformation from \"./SchemaTransformation.js\";\nfunction makeGuard(tag) {\n  return ast => ast._tag === tag;\n}\n/**\n * Returns `true` if the value is an {@link AST} node (any variant).\n *\n * **Details**\n *\n * Uses the internal `TypeId` brand to distinguish AST nodes from arbitrary\n * objects.\n *\n * @see {@link AST}\n * @category guards\n * @since 4.0.0\n */\nexport function isAST(u) {\n  return Predicate.hasProperty(u, TypeId) && u[TypeId] === TypeId;\n}\n/**\n * Narrows an {@link AST} to {@link Declaration}.\n *\n * **When to use**\n *\n * Use to recognize declaration AST nodes before running declaration-specific\n * handling.\n *\n * @see {@link Declaration} for the AST node type narrowed by this guard\n *\n * @category guards\n * @since 3.10.0\n */\nexport const isDeclaration = /*#__PURE__*/makeGuard(\"Declaration\");\n/**\n * Narrows an {@link AST} to {@link Null}.\n *\n * **When to use**\n *\n * Use to recognize an AST node that represents exactly the `null` literal when\n * inspecting, traversing, or transforming schema ASTs.\n *\n * @see {@link Null} for the AST node type narrowed by this guard\n * @see {@link null_ null} for the singleton `Null` AST instance\n * @see {@link isLiteral} for exact primitive literal AST nodes\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isNull = /*#__PURE__*/makeGuard(\"Null\");\n/**\n * Narrows an {@link AST} to {@link Undefined}.\n *\n * **When to use**\n *\n * Use to identify AST nodes that represent exactly the JavaScript `undefined`\n * value.\n *\n * @see {@link isVoid} for narrowing AST nodes that represent TypeScript `void` instead of exact `undefined`\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isUndefined = /*#__PURE__*/makeGuard(\"Undefined\");\n/**\n * Narrows an {@link AST} to {@link Void}.\n *\n * **When to use**\n *\n * Use to identify AST nodes that represent the TypeScript `void` type before\n * handling `Void`-specific schema behavior.\n *\n * @see {@link isUndefined} for narrowing AST nodes that represent the literal `undefined` value instead of TypeScript `void`\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isVoid = /*#__PURE__*/makeGuard(\"Void\");\n/**\n * Narrows an {@link AST} to {@link Never}.\n *\n * **When to use**\n *\n * Use to detect the AST node for a schema that can never match before handling\n * other schema variants.\n *\n * @see {@link Never} for the AST node type narrowed by this guard\n * @see {@link never} for the singleton `Never` AST instance\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isNever = /*#__PURE__*/makeGuard(\"Never\");\n/**\n * Narrows an {@link AST} to {@link Unknown}.\n *\n * **When to use**\n *\n * Use when you need to inspect a schema AST and handle the `Unknown` node\n * variant specifically.\n *\n * @see {@link isAny} for the guard for the `Any` node, whose parsed result is typed as `any` rather than `unknown`\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isUnknown = /*#__PURE__*/makeGuard(\"Unknown\");\n/**\n * Narrows an {@link AST} to {@link Any}.\n *\n * **When to use**\n *\n * Use when you need to inspect a schema AST and handle the `Any` node\n * variant specifically.\n *\n * @see {@link isUnknown} for the guard for the `Unknown` node, whose parsed result is typed as `unknown` rather than `any`\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isAny = /*#__PURE__*/makeGuard(\"Any\");\n/**\n * Narrows an {@link AST} to {@link String}.\n *\n * **When to use**\n *\n * Use to detect schema AST nodes that match any string value while inspecting\n * or transforming a Schema AST.\n *\n * @see {@link String} for the AST node class narrowed by this guard\n * @see {@link string} for the singleton `String` AST instance\n * @see {@link isLiteral} for exact primitive literal AST nodes, including exact string literals\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isString = /*#__PURE__*/makeGuard(\"String\");\n/**\n * Narrows an {@link AST} to {@link Number}.\n *\n * **When to use**\n *\n * Use to detect `Number` AST nodes while inspecting, traversing, or transforming\n * schema ASTs.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isNumber = /*#__PURE__*/makeGuard(\"Number\");\n/**\n * Narrows an {@link AST} to {@link Boolean}.\n *\n * **When to use**\n *\n * Use to identify the `Boolean` AST variant while inspecting, traversing, or\n * transforming schema definitions.\n *\n * @see {@link Boolean} for the AST node type matched by this guard\n * @see {@link boolean} for the singleton instance to use when constructing a boolean AST directly\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isBoolean = /*#__PURE__*/makeGuard(\"Boolean\");\n/**\n * Narrows an {@link AST} to {@link BigInt}.\n *\n * **When to use**\n *\n * Use to identify bigint AST nodes while inspecting or transforming schema ASTs.\n *\n * @see {@link BigInt} for the AST node matched by this guard\n * @see {@link bigInt} for the singleton instance; use `isBigInt` when narrowing an existing `AST` value\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isBigInt = /*#__PURE__*/makeGuard(\"BigInt\");\n/**\n * Narrows an {@link AST} to {@link Symbol}.\n *\n * **When to use**\n *\n * Use to narrow an `AST` node before handling the `Symbol` variant for schemas\n * that accept any JavaScript symbol value.\n *\n * @see {@link isUniqueSymbol} for the sibling guard that narrows the `UniqueSymbol` variant for one exact symbol value\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isSymbol = /*#__PURE__*/makeGuard(\"Symbol\");\n/**\n * Narrows an {@link AST} to {@link Literal}.\n *\n * **When to use**\n *\n * Use to recognize exact string, number, boolean, or bigint literal AST nodes.\n *\n * @see {@link Literal} for the AST node type narrowed by this guard\n * @see {@link LiteralValue} for the values stored by literal nodes\n *\n * @category guards\n * @since 3.10.0\n */\nexport const isLiteral = /*#__PURE__*/makeGuard(\"Literal\");\n/**\n * Narrows an {@link AST} to {@link UniqueSymbol}.\n *\n * @category guards\n * @since 3.10.0\n */\nexport const isUniqueSymbol = /*#__PURE__*/makeGuard(\"UniqueSymbol\");\n/**\n * Narrows an {@link AST} to {@link ObjectKeyword}.\n *\n * **When to use**\n *\n * Use to identify the AST node for the TypeScript `object` keyword when\n * inspecting or transforming a Schema AST.\n *\n * @see {@link ObjectKeyword} for the AST node matched by this guard\n * @see {@link objectKeyword} for the singleton `ObjectKeyword` AST instance\n * @see {@link isObjects} for struct and record AST nodes\n *\n * @category guards\n * @since 3.10.0\n */\nexport const isObjectKeyword = /*#__PURE__*/makeGuard(\"ObjectKeyword\");\n/**\n * Narrows an {@link AST} to {@link Enum}.\n *\n * **When to use**\n *\n * Use to recognize enum AST nodes before reading enum cases or running\n * enum-specific handling.\n *\n * @see {@link Enum} for the AST node type narrowed by this guard\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isEnum = /*#__PURE__*/makeGuard(\"Enum\");\n/**\n * Narrows an {@link AST} to {@link TemplateLiteral}.\n *\n * @category guards\n * @since 3.10.0\n */\nexport const isTemplateLiteral = /*#__PURE__*/makeGuard(\"TemplateLiteral\");\n/**\n * Narrows an {@link AST} to {@link Arrays}.\n *\n * **When to use**\n *\n * Use to recognize array-like AST nodes before reading their element, rest, or\n * mutability metadata.\n *\n * @see {@link Arrays} for the AST node type narrowed by this guard\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isArrays = /*#__PURE__*/makeGuard(\"Arrays\");\n/**\n * Narrows an {@link AST} to {@link Objects}.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isObjects = /*#__PURE__*/makeGuard(\"Objects\");\n/**\n * Narrows an {@link AST} to {@link Union}.\n *\n * @category guards\n * @since 3.10.0\n */\nexport const isUnion = /*#__PURE__*/makeGuard(\"Union\");\n/**\n * Narrows an {@link AST} to {@link Suspend}.\n *\n * @category guards\n * @since 3.10.0\n */\nexport const isSuspend = /*#__PURE__*/makeGuard(\"Suspend\");\n/**\n * Constructs a {@link Link}.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Link = class {\n  to;\n  transformation;\n  constructor(to, transformation) {\n    this.to = to;\n    this.transformation = transformation;\n  }\n};\n/** @internal */\nexport const defaultParseOptions = {};\n/**\n * Constructs a {@link Context}.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Context = class {\n  isOptional;\n  isMutable;\n  /** Used for constructor default values (e.g. `withConstructorDefault` API) */\n  constructorDefault;\n  annotations;\n  constructor(isOptional, isMutable, /** Used for constructor default values (e.g. `withConstructorDefault` API) */\n  constructorDefault = undefined, annotations = undefined) {\n    this.isOptional = isOptional;\n    this.isMutable = isMutable;\n    this.constructorDefault = constructorDefault;\n    this.annotations = annotations;\n  }\n};\nconst TypeId = \"~effect/Schema\";\nclass ASTNodeImpl {\n  [TypeId] = TypeId;\n  annotations;\n  checks;\n  encoding;\n  context;\n  constructor(annotations = undefined, checks = undefined, encoding = undefined, context = undefined) {\n    this.annotations = annotations;\n    this.checks = checks;\n    this.encoding = encoding;\n    this.context = context;\n  }\n  toString() {\n    return `<${this._tag}>`;\n  }\n}\n/**\n * Constructs a {@link Declaration}.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Declaration = class extends ASTNodeImpl {\n  _tag = \"Declaration\";\n  typeParameters;\n  run;\n  encodingChecks;\n  /**\n   * Parser factory {@link flip} swaps in, so a declaration can behave\n   * differently when encoding. `undefined` reuses `run`.\n   */\n  encodingRun;\n  constructor(typeParameters, run, annotations, checks, encoding, context, encodingChecks, encodingRun) {\n    super(annotations, checks, encoding, context);\n    this.typeParameters = typeParameters;\n    this.run = run;\n    this.encodingChecks = encodingChecks;\n    this.encodingRun = encodingRun;\n  }\n  /** @internal */\n  getParser() {\n    let run;\n    return (input, options) => {\n      if (input === InternalParser.missing) return InternalParser.missingExit;\n      return (run ??= this.run(this.typeParameters))(input, this, options);\n    };\n  }\n  _rebuild(recur, checks, encodingChecks, run, encodingRun) {\n    const tps = mapOrSame(this.typeParameters, recur);\n    return tps === this.typeParameters && checks === this.checks && encodingChecks === this.encodingChecks && run === this.run && encodingRun === this.encodingRun ? this : new Declaration(tps, run, this.annotations, checks, undefined, this.context, encodingChecks, encodingRun);\n  }\n  /** @internal */\n  recur(recur) {\n    return this._rebuild(recur, this.checks, this.encodingChecks, this.run, this.encodingRun);\n  }\n  /** @internal */\n  flip(recur) {\n    return this._rebuild(recur, this.encodingChecks, this.checks, this.encodingRun ?? this.run, this.run);\n  }\n  /** @internal */\n  getExpected() {\n    const expected = this.annotations?.expected;\n    if (typeof expected === \"string\") return expected;\n    return \"<Declaration>\";\n  }\n};\n/**\n * Constructs a {@link Null}.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Null = class extends ASTNodeImpl {\n  _tag = \"Null\";\n  /** @internal */\n  getParser() {\n    return fromConst(this, null);\n  }\n  /** @internal */\n  getExpected() {\n    return \"null\";\n  }\n};\nconst null_ = /*#__PURE__*/new Null();\nexport {\n/**\n * Provides the singleton {@link Null} AST instance.\n *\n * **When to use**\n *\n * Use when you need the shared AST node for exact null values while inspecting\n * or constructing schema ASTs.\n *\n * @category constants\n * @since 4.0.0\n */\nnull_ as null };\n/**\n * Constructs a {@link Undefined}.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Undefined = class extends ASTNodeImpl {\n  _tag = \"Undefined\";\n  /** @internal */\n  getParser() {\n    return fromConst(this, undefined);\n  }\n  /** @internal */\n  toCodecJson() {\n    return replaceEncoding(this, [undefinedToNull]);\n  }\n  /** @internal */\n  getExpected() {\n    return \"undefined\";\n  }\n};\nconst undefinedToNull = /*#__PURE__*/new Link(null_, /*#__PURE__*/new SchemaTransformation.Transformation(/*#__PURE__*/SchemaGetter.transform(() => undefined), /*#__PURE__*/SchemaGetter.transform(() => null)));\nconst undefined_ = /*#__PURE__*/new Undefined();\nexport {\n/**\n * Provides the singleton {@link Undefined} AST instance.\n *\n * **When to use**\n *\n * Use when you need the shared AST node for exact undefined values while\n * inspecting or constructing schema ASTs.\n *\n * @category constants\n * @since 4.0.0\n */\nundefined_ as undefined };\n/**\n * Constructs a {@link Void}.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Void = class extends ASTNodeImpl {\n  _tag = \"Void\";\n  /** @internal */\n  getParser() {\n    const succeed = InternalParser.succeed(undefined);\n    return input => input === InternalParser.missing ? InternalParser.missingExit : succeed;\n  }\n  /** @internal */\n  toCodecJson() {\n    return replaceEncoding(this, [undefinedToNull]);\n  }\n  /** @internal */\n  getExpected() {\n    return \"void\";\n  }\n};\nconst void_ = /*#__PURE__*/new Void();\nexport {\n/**\n * Provides the singleton {@link Void} AST instance.\n *\n * **When to use**\n *\n * Use when constructing or comparing AST nodes for TypeScript `void` return\n * values whose result is intentionally ignored.\n *\n * **Details**\n *\n * The node parses any present runtime value as `undefined`; schemas may still\n * expose `void` on their typed decoded and encoded sides.\n *\n * @see {@link Void} for the AST node class\n * @see {@link undefined} for the sibling AST singleton that matches exactly `undefined`\n * @see {@link isVoid} for narrowing an AST to a `Void` node\n *\n * @category constructors\n * @since 4.0.0\n */\nvoid_ as void };\n/**\n * Constructs a {@link Never}.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Never = class extends ASTNodeImpl {\n  _tag = \"Never\";\n  /** @internal */\n  getParser() {\n    return fromRefinement(this, Predicate.isNever);\n  }\n  /** @internal */\n  getExpected() {\n    return \"never\";\n  }\n};\n/**\n * Provides the singleton {@link Never} AST instance.\n *\n * **When to use**\n *\n * Use to reuse the canonical bottom-type AST node when constructing,\n * comparing, or returning ASTs.\n *\n * @see {@link Never} for the AST node class\n * @see {@link isNever} for narrowing an AST to a `Never` node\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const never = /*#__PURE__*/new Never();\n/**\n * Constructs a {@link Any}.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Any = class extends ASTNodeImpl {\n  _tag = \"Any\";\n  /** @internal */\n  getParser() {\n    return fromRefinement(this, Predicate.isUnknown);\n  }\n  /** @internal */\n  getExpected() {\n    return \"any\";\n  }\n};\n/**\n * Provides the singleton {@link Any} AST instance.\n *\n * **When to use**\n *\n * Use when you need the singleton AST node for the TypeScript `any` type and\n * intentionally want parsing to accept every input value.\n *\n * @see {@link unknown} for the sibling AST singleton that also accepts every value while preserving the safer `unknown` type\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const any = /*#__PURE__*/new Any();\n/**\n * Constructs a {@link Unknown}.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Unknown = class extends ASTNodeImpl {\n  _tag = \"Unknown\";\n  /** @internal */\n  getParser() {\n    return fromRefinement(this, Predicate.isUnknown);\n  }\n  /** @internal */\n  getExpected() {\n    return \"unknown\";\n  }\n};\n/**\n * Provides the singleton {@link Unknown} AST instance.\n *\n * **When to use**\n *\n * Use when you need the reusable AST singleton for a schema node that accepts\n * every value while keeping parsed values opaque.\n *\n * @see {@link any} for the singleton that accepts every value as `any`\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const unknown = /*#__PURE__*/new Unknown();\n/**\n * Constructs a {@link ObjectKeyword}.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const ObjectKeyword = class extends ASTNodeImpl {\n  _tag = \"ObjectKeyword\";\n  /** @internal */\n  getParser() {\n    return fromRefinement(this, Predicate.isObjectKeyword);\n  }\n  /** @internal */\n  getExpected() {\n    return \"object | array | function\";\n  }\n};\n/**\n * Provides the singleton {@link ObjectKeyword} AST instance.\n *\n * **When to use**\n *\n * Use to reuse the canonical AST node for the TypeScript `object` keyword when\n * building or comparing `SchemaAST` values directly.\n *\n * @see {@link ObjectKeyword} for the AST node class\n * @see {@link isObjectKeyword} for narrowing an AST to an `ObjectKeyword` node\n *\n * @category constructors\n * @since 3.10.0\n */\nexport const objectKeyword = /*#__PURE__*/new ObjectKeyword();\n/**\n * Constructs a {@link Enum}. Numeric values must be finite.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Enum = class extends ASTNodeImpl {\n  _tag = \"Enum\";\n  enums;\n  constructor(enums, annotations, checks, encoding, context) {\n    super(annotations, checks, encoding, context);\n    for (const [, value] of enums) {\n      if (typeof value === \"number\" && !globalThis.Number.isFinite(value)) {\n        throw new Error(`A numeric enum value must be finite, got ${format(value)}`);\n      }\n    }\n    this.enums = enums;\n  }\n  /** @internal */\n  getParser() {\n    const values = new Set(this.enums.map(([, v]) => v));\n    return fromRefinement(this, input => values.has(input));\n  }\n  /** @internal */\n  toCodecStringTree() {\n    if (this.enums.some(([_, v]) => typeof v === \"number\")) {\n      const coercions = Object.fromEntries(this.enums.map(([_, v]) => [globalThis.String(v), v]));\n      return replaceEncoding(this, [new Link(new Union(Object.keys(coercions).map(k => new Literal(k))), new SchemaTransformation.Transformation(SchemaGetter.transform(s => coercions[s]), SchemaGetter.String()))]);\n    }\n    return this;\n  }\n  /** @internal */\n  getExpected() {\n    return this.enums.map(([_, value]) => JSON.stringify(value)).join(\" | \");\n  }\n};\nfunction formatTemplateLiteralPath(path) {\n  return typeof path === \"number\" ? `parts[${path}]` : path;\n}\nfunction isTemplateLiteralPart(ast, path, validated) {\n  if (validated.has(ast)) return true;\n  if (ast.encoding) {\n    throw new Error(`TemplateLiteral parts cannot have an encoding at ${formatTemplateLiteralPath(path)}`);\n  }\n  let valid;\n  switch (ast._tag) {\n    case \"String\":\n    case \"Number\":\n    case \"BigInt\":\n      valid = true;\n      break;\n    case \"Literal\":\n      valid = !ast.checks;\n      break;\n    case \"TemplateLiteral\":\n      {\n        const currentPath = formatTemplateLiteralPath(path);\n        valid = !ast.checks && ast.parts.every((part, index) => isTemplateLiteralPart(part, `${currentPath}.parts[${index}]`, validated));\n        break;\n      }\n    case \"Union\":\n      {\n        const currentPath = formatTemplateLiteralPath(path);\n        valid = !ast.checks && ast.types.every((part, index) => isTemplateLiteralPart(part, `${currentPath}.types[${index}]`, validated));\n        break;\n      }\n    default:\n      return false;\n  }\n  if (valid) validated.add(ast);\n  return valid;\n}\n/**\n * Constructs a {@link TemplateLiteral}.\n *\n * **Gotchas**\n *\n * Throws if a part contains an encoding, including inside unions or nested\n * template literals. Parts must describe their values without transformations.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const TemplateLiteral = class extends ASTNodeImpl {\n  _tag = \"TemplateLiteral\";\n  parts;\n  /** @internal */\n  encodedParts;\n  /** @internal */\n  literals;\n  /** @internal */\n  suffixLengths;\n  constructor(parts, annotations, checks, encoding, context) {\n    super(annotations, checks, encoding, context);\n    const encodedParts = [];\n    const literals = [];\n    const validated = new Set();\n    for (let index = 0; index < parts.length; index++) {\n      const part = parts[index];\n      if (!isTemplateLiteralPart(part, index, validated)) {\n        throw new Error(`Invalid TemplateLiteral part ${part._tag}`);\n      }\n      encodedParts.push(part);\n      literals.push(part._tag === \"Literal\" ? globalThis.String(part.literal) : undefined);\n    }\n    const suffixLengths = new Array(encodedParts.length + 1);\n    suffixLengths[encodedParts.length] = 0;\n    for (let i = encodedParts.length - 1; i >= 0; i--) {\n      suffixLengths[i] = suffixLengths[i + 1] + (literals[i]?.length ?? 0);\n    }\n    this.parts = parts;\n    this.encodedParts = encodedParts;\n    this.literals = literals;\n    this.suffixLengths = suffixLengths;\n  }\n  /** @internal */\n  getParser(compile) {\n    const tuple = new Arrays(false, this.parts.map(partFromString), []);\n    const parser = compile(decodeTo(string, tuple, templateLiteralTransformation(this)));\n    return (input, options) => {\n      if (input === InternalParser.missing) return InternalParser.missingExit;\n      const result = parser(input, options);\n      if (result._tag === \"Success\") {\n        return InternalParser.sameExit;\n      }\n      return Effect.mapBothEager(result, {\n        onSuccess: () => input,\n        onFailure: issue => new SchemaIssue.Composite(this, [issue], input, options)\n      });\n    };\n  }\n  /** @internal */\n  getExpected() {\n    return \"string\";\n  }\n  /** @internal */\n  matchPart(s, options) {\n    return segmentTemplateLiteralParts(this, s, options) === undefined ? undefined : s;\n  }\n};\n/** @internal */\nexport function templateLiteralParser(parts) {\n  // Encoded members can overlap even when decoding selects exactly one member.\n  // Match their spellings here; the original tuple enforces the union's mode.\n  const normalize = memoize(encoded => {\n    if (encoded._tag !== \"Union\") return encoded;\n    const types = mapOrSame(encoded.types, normalize);\n    return (encoded.options?.mode ?? \"anyOf\") === \"anyOf\" && types === encoded.types ? encoded : new Union(types, encoded.options === undefined ? undefined : {\n      ...encoded.options,\n      mode: \"anyOf\"\n    }, encoded.annotations, encoded.checks, undefined, encoded.context);\n  });\n  const template = new TemplateLiteral(parts.map(part => normalize(toEncoded(part))));\n  const tuple = new Arrays(false, parts.map(partFromString), []);\n  return decodeTo(template, tuple, templateLiteralTransformation(template));\n}\nfunction templateLiteralTransformation(template) {\n  return new SchemaTransformation.Transformation(SchemaGetter.transformEffect((s, options) => {\n    const segments = segmentTemplateLiteralParts(template, s, options);\n    if (segments) return Effect.succeed(segments);\n    return Effect.fail(new SchemaIssue.InvalidValue({\n      expected: \"a string matching template literal parts\"\n    }, s, options));\n  }), SchemaGetter.transform(parts => parts.join(\"\")));\n}\n/**\n * Constructs a {@link UniqueSymbol}.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const UniqueSymbol = class extends ASTNodeImpl {\n  _tag = \"UniqueSymbol\";\n  symbol;\n  constructor(symbol, annotations, checks, encoding, context) {\n    super(annotations, checks, encoding, context);\n    this.symbol = symbol;\n  }\n  /** @internal */\n  getParser() {\n    return fromConst(this, this.symbol);\n  }\n  /** @internal */\n  toCodecStringTree() {\n    const key = globalThis.Symbol.keyFor(this.symbol);\n    return replaceEncoding(this, [new Link(key === undefined ? never : new Literal(globalThis.String(this.symbol)), symbolToString.transformation)]);\n  }\n  /** @internal */\n  getExpected() {\n    return globalThis.String(this.symbol);\n  }\n};\n/**\n * Constructs a {@link Literal}.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Literal = class extends ASTNodeImpl {\n  _tag = \"Literal\";\n  literal;\n  constructor(literal, annotations, checks, encoding, context) {\n    super(annotations, checks, encoding, context);\n    if (typeof literal === \"number\" && !globalThis.Number.isFinite(literal)) {\n      throw new Error(`A numeric literal must be finite, got ${format(literal)}`);\n    }\n    this.literal = literal;\n  }\n  /** @internal */\n  getParser() {\n    return fromConst(this, this.literal);\n  }\n  /** @internal */\n  matchPart(s, _options) {\n    return s === globalThis.String(this.literal) ? this.literal : undefined;\n  }\n  /** @internal */\n  toCodecJson() {\n    return typeof this.literal === \"bigint\" ? literalToString(this) : this;\n  }\n  /** @internal */\n  toCodecStringTree() {\n    return typeof this.literal === \"string\" ? this : literalToString(this);\n  }\n  /** @internal */\n  getExpected() {\n    return typeof this.literal === \"string\" ? JSON.stringify(this.literal) : globalThis.String(this.literal);\n  }\n};\nfunction literalToString(ast) {\n  const literalAsString = globalThis.String(ast.literal);\n  return replaceEncoding(ast, [new Link(new Literal(literalAsString), new SchemaTransformation.Transformation(SchemaGetter.transform(() => ast.literal), SchemaGetter.transform(() => literalAsString)))]);\n}\n/**\n * Constructs a {@link String}.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const String = class extends ASTNodeImpl {\n  _tag = \"String\";\n  /** @internal */\n  getParser() {\n    return fromRefinement(this, Predicate.isString);\n  }\n  /** @internal */\n  matchPart(s, options) {\n    const checks = this.checks;\n    return checks && !options.disableChecks && collectIssues(checks, s, undefined, this, options) ? undefined : s;\n  }\n  /** @internal */\n  getExpected() {\n    return \"string\";\n  }\n};\n/**\n * Provides the singleton {@link String} AST instance.\n *\n * **When to use**\n *\n * Use as the shared `SchemaAST` node for unconstrained JavaScript strings.\n *\n * @see {@link String} for the AST node class\n * @see {@link isString} for narrowing an AST to a string node\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const string = /*#__PURE__*/new String();\n/**\n * Constructs a {@link Number}.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Number = class extends ASTNodeImpl {\n  _tag = \"Number\";\n  /** @internal */\n  getParser() {\n    return fromRefinement(this, Predicate.isNumber);\n  }\n  /** @internal */\n  matchKey(s, options) {\n    return this._match(isStringNumberRegExp, s, options);\n  }\n  /** @internal */\n  matchPart(s, options) {\n    return this._match(isStringFiniteRegExp, s, options);\n  }\n  _match(regexp, s, options) {\n    if (!regexp.test(s)) return undefined;\n    const value = globalThis.Number(s);\n    if (options.disableChecks || !this.checks) return value;\n    return collectIssues(this.checks, value, undefined, this, options) ? undefined : value;\n  }\n  /** @internal */\n  toCodecJson() {\n    if (this.checks && (hasCheck(this.checks, \"effect/schema/isFinite\") || hasCheck(this.checks, \"effect/schema/isInt\"))) {\n      return this;\n    }\n    return replaceEncoding(this, [numberToJson]);\n  }\n  /** @internal */\n  toCodecStringTree() {\n    if (this.toCodecJson() === this) {\n      return replaceEncoding(this, [finiteToString]);\n    }\n    return replaceEncoding(this, [numberToString]);\n  }\n  /** @internal */\n  getExpected() {\n    return \"number\";\n  }\n};\nfunction hasCheck(checks, id) {\n  return checks.some(check => check.annotations?.representation?.id === id || check._tag === \"FilterGroup\" && hasCheck(check.checks, id));\n}\n/**\n * Provides the singleton {@link Number} AST instance.\n *\n * **When to use**\n *\n * Use when you need the canonical `SchemaAST` node for schemas that accept any\n * JavaScript number value.\n *\n * @see {@link Number} for the AST node class and serialization behavior\n * @see {@link Literal} for exact finite numeric literal AST nodes\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const number = /*#__PURE__*/new Number();\n/**\n * Constructs a {@link Boolean}.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Boolean = class extends ASTNodeImpl {\n  _tag = \"Boolean\";\n  /** @internal */\n  getParser() {\n    return fromRefinement(this, Predicate.isBoolean);\n  }\n  /** @internal */\n  getExpected() {\n    return \"boolean\";\n  }\n};\n/**\n * Provides the singleton {@link Boolean} AST instance.\n *\n * **When to use**\n *\n * Use to reuse the standard AST node that accepts either `true` or `false` when\n * constructing schema ASTs directly.\n *\n * @see {@link Boolean} for the AST node class\n * @see {@link Literal} for exact boolean literal AST nodes\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const boolean = /*#__PURE__*/new Boolean();\n/**\n * Constructs a {@link Symbol}.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Symbol = class extends ASTNodeImpl {\n  _tag = \"Symbol\";\n  /** @internal */\n  getParser() {\n    return fromRefinement(this, Predicate.isSymbol);\n  }\n  /** @internal */\n  matchKey(s, options) {\n    if (options.disableChecks || !this.checks) return s;\n    return collectIssues(this.checks, s, undefined, this, options) ? undefined : s;\n  }\n  /** @internal */\n  toCodecStringTree() {\n    return replaceEncoding(this, [symbolToString]);\n  }\n  /** @internal */\n  getExpected() {\n    return \"symbol\";\n  }\n};\n/**\n * Provides the singleton {@link Symbol} AST instance.\n *\n * **When to use**\n *\n * Use to reuse the singleton AST node for schemas that match any JavaScript\n * symbol value.\n *\n * **Gotchas**\n *\n * String-based codecs can encode only symbols registered with `Symbol.for`,\n * because the implementation uses `Symbol.keyFor`.\n *\n * @see {@link UniqueSymbol} for an AST node that matches one specific symbol\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const symbol = /*#__PURE__*/new Symbol();\n/**\n * Constructs a {@link BigInt}.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const BigInt = class extends ASTNodeImpl {\n  _tag = \"BigInt\";\n  /** @internal */\n  getParser() {\n    return fromRefinement(this, Predicate.isBigInt);\n  }\n  /** @internal */\n  matchPart(s, options) {\n    if (!isStringBigIntRegExp.test(s)) return undefined;\n    const value = globalThis.BigInt(s);\n    if (options.disableChecks || !this.checks) return value;\n    return collectIssues(this.checks, value, undefined, this, options) ? undefined : value;\n  }\n  /** @internal */\n  toCodecStringTree() {\n    return replaceEncoding(this, [bigIntToString]);\n  }\n  /** @internal */\n  getExpected() {\n    return \"bigint\";\n  }\n};\n/**\n * Provides the singleton {@link BigInt} AST instance.\n *\n * **When to use**\n *\n * Use to reuse the canonical `BigInt` AST node when constructing, inspecting,\n * or transforming schemas at the AST level.\n *\n * @see {@link BigInt} for the AST node class and string-codec behavior\n * @see {@link isBigInt} for narrowing an AST to a `BigInt` node\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const bigInt = /*#__PURE__*/new BigInt();\n/**\n * Constructs a {@link Arrays}.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Arrays = class extends ASTNodeImpl {\n  _tag = \"Arrays\";\n  isMutable;\n  elements;\n  rest;\n  encodingChecks;\n  constructor(isMutable, elements, rest, annotations, checks, encoding, context, encodingChecks) {\n    super(annotations, checks, encoding, context);\n    this.isMutable = isMutable;\n    this.elements = elements;\n    this.rest = rest;\n    this.encodingChecks = encodingChecks;\n    let hasOptional = false;\n    for (let i = 0; i < elements.length; i++) {\n      if (isOptional(elements[i])) {\n        hasOptional = true;\n      } else if (hasOptional) {\n        throw new Error(\"A required element cannot follow an optional element. ts(1257)\");\n      }\n    }\n    if (hasOptional && rest.length > 1) {\n      throw new Error(\"A required element cannot follow an optional element. ts(1257)\");\n    }\n    // An optional element cannot follow a rest element.ts(1266)\n    for (let i = 1; i < rest.length; i++) {\n      if (isOptional(rest[i])) {\n        throw new Error(\"An optional element cannot follow a rest element. ts(1266)\");\n      }\n    }\n  }\n  /** @internal */\n  getParser(compile, compileConstructorDefault = compile) {\n    // oxlint-disable-next-line @typescript-eslint/no-this-alias\n    const ast = this;\n    let elements;\n    let rest;\n    const elementLen = ast.elements.length;\n    const tailLen = Math.max(0, ast.rest.length - 1);\n    function getParser(tailThreshold, index) {\n      if (index < elementLen) {\n        return elements[index];\n      } else if (index >= tailThreshold) {\n        return rest[index - tailThreshold + 1];\n      }\n      return rest[0];\n    }\n    return Effect.fnUntracedEager(function* (input, options) {\n      if (input === InternalParser.missing) {\n        return InternalParser.missing;\n      }\n      // If the input is not an array, return early with an error\n      if (!Array.isArray(input)) {\n        return yield* Effect.fail(new SchemaIssue.InvalidType(ast, input, options));\n      }\n      if (!elements) {\n        elements = ast.elements.map(ast => ({\n          ast,\n          parser: compileConstructorDefault(ast)\n        }));\n        rest = ast.rest.map(ast => ({\n          ast,\n          parser: compileConstructorDefault(ast)\n        }));\n      }\n      const len = input.length;\n      const state = {\n        ast,\n        getParser,\n        input,\n        len,\n        tailThreshold: Math.max(elementLen, len - tailLen),\n        output: new globalThis.Array(len),\n        issues: undefined,\n        options\n      };\n      const end = ast.rest.length === 0 ? elementLen : Math.max(len, elementLen + tailLen);\n      const concurrency = options.concurrency === undefined ? 1 : resolveConcurrency(options.concurrency);\n      const eff = concurrency === 1 ? parseArray(state, input, 0, end) : parseArrayConcurrent(state, input, {\n        concurrency,\n        end\n      });\n      if (eff) yield* eff;\n      // ---------------------------------------------\n      // handle excess indexes\n      // ---------------------------------------------\n      if (ast.rest.length === 0 && len > elementLen) {\n        for (let i = elementLen; i <= len - 1; i++) {\n          const unexpected = new SchemaIssue.UnexpectedKey(ast, input[i], options);\n          const issue = new SchemaIssue.Pointer([i], unexpected);\n          if (options.errors === \"all\") {\n            if (state.issues) state.issues.push(issue);else state.issues = [issue];\n          } else {\n            return yield* Effect.fail(new SchemaIssue.Composite(ast, [issue], input, options));\n          }\n        }\n      }\n      if (state.issues) {\n        return yield* Effect.fail(new SchemaIssue.Composite(ast, state.issues, input, options));\n      }\n      return state.output;\n    });\n  }\n  _rebuild(recur, checks, encodingChecks) {\n    const elements = mapOrSame(this.elements, recur);\n    const rest = mapOrSame(this.rest, recur);\n    return elements === this.elements && rest === this.rest && checks === this.checks && encodingChecks === this.encodingChecks ? this : new Arrays(this.isMutable, elements, rest, this.annotations, checks, undefined, this.context, encodingChecks);\n  }\n  /** @internal */\n  recur(recur) {\n    return this._rebuild(recur, this.checks, this.encodingChecks);\n  }\n  /** @internal */\n  flip(recur) {\n    return this._rebuild(recur, this.encodingChecks, this.checks);\n  }\n  /** @internal */\n  getExpected() {\n    return \"array\";\n  }\n};\nconst parseArrayOptions = {\n  onItem(s, item, i) {\n    const value = i < s.len ? item : InternalParser.missing;\n    return s.getParser(s.tailThreshold, i).parser(value, s.options);\n  },\n  step(s, item, exit, i) {\n    if (exit._tag === \"Failure\") {\n      return wrapPropertyKeyIssue(s, s.ast, i, exit);\n    }\n    const value = exit === InternalParser.sameExit ? item : exit[InternalParser.args];\n    if (value !== InternalParser.missing) {\n      s.output[i] = value;\n    } else {\n      const p = s.getParser(s.tailThreshold, i);\n      if (isOptional(p.ast)) return;\n      const issue = new SchemaIssue.Pointer([i], new SchemaIssue.MissingKey(p.ast.context?.annotations));\n      if (s.options.errors === \"all\") {\n        if (s.issues) s.issues.push(issue);else s.issues = [issue];\n      } else {\n        return Exit.fail(new SchemaIssue.Composite(s.ast, [issue], s.input, s.options));\n      }\n    }\n  }\n};\nconst parseArray = /*#__PURE__*/iterateEager()(parseArrayOptions);\nconst parseArrayConcurrent = /*#__PURE__*/iterateConcurrent()(parseArrayOptions);\nconst wrapPropertyKeyIssue = (s, ast, key, exit) => {\n  if (exit.cause.reasons.length === 0) {\n    return exit;\n  }\n  const issue = InternalSchemaCause.getSchemaIssue(exit.cause);\n  if (issue === undefined) {\n    return Exit.failCause(Cause.map(exit.cause, issue => new SchemaIssue.Composite(ast, [new SchemaIssue.Pointer([key], issue)], s.input, s.options)));\n  }\n  const pointer = new SchemaIssue.Pointer([key], issue);\n  if (s.options.errors === \"all\") {\n    if (s.issues) s.issues.push(pointer);else s.issues = [pointer];\n  } else {\n    return Exit.fail(new SchemaIssue.Composite(ast, [pointer], s.input, s.options));\n  }\n};\n/**\n * floating point or integer, with optional exponent\n * @internal\n */\nexport const FINITE_PATTERN = \"[+-]?\\\\d*\\\\.?\\\\d+(?:[Ee][+-]?\\\\d+)?\";\n/**\n * Returns the object keys that match the index signature parameter schema.\n * @internal\n */\nexport function getIndexSignatureKeys(input, parameter, options = defaultParseOptions) {\n  let stringKeys;\n  let symbolKeys;\n  function go(parameter) {\n    switch (parameter._tag) {\n      case \"String\":\n      case \"TemplateLiteral\":\n        return (stringKeys ??= Object.keys(input)).filter(k => parameter.matchPart(k, options) !== undefined);\n      case \"Number\":\n        return (stringKeys ??= Object.keys(input)).filter(k => parameter.matchKey(k, options) !== undefined);\n      case \"Symbol\":\n        return (symbolKeys ??= Object.getOwnPropertySymbols(input)).filter(k => parameter.matchKey(k, options) !== undefined);\n      case \"Union\":\n        return [...new Set(parameter.types.flatMap(go))];\n      default:\n        return [];\n    }\n  }\n  return go(parameterFromPropertyKey(toEncoded(parameter)));\n}\n/**\n * Constructs a {@link PropertySignature}.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const PropertySignature = class {\n  name;\n  type;\n  constructor(name, type) {\n    this.name = name;\n    this.type = type;\n  }\n};\nfunction isIndexSignatureParameterSide(ast) {\n  switch (ast._tag) {\n    case \"String\":\n    case \"Number\":\n    case \"Symbol\":\n    case \"TemplateLiteral\":\n      return true;\n    case \"Union\":\n      return ast.types.every(isIndexSignatureParameterSide);\n    default:\n      return false;\n  }\n}\nfunction isIndexSignatureParameterEncodedSide(ast) {\n  const encoded = getLastEncoding(ast);\n  switch (encoded._tag) {\n    case \"String\":\n    case \"Number\":\n    case \"Symbol\":\n    case \"TemplateLiteral\":\n      return true;\n    case \"Union\":\n      return encoded.types.every(isIndexSignatureParameterEncodedSide);\n    default:\n      return false;\n  }\n}\nfunction isIndexSignatureParameter(ast) {\n  return isIndexSignatureParameterSide(ast) && isIndexSignatureParameterEncodedSide(ast);\n}\n/**\n * Constructs a {@link IndexSignature}.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const IndexSignature = class {\n  parameter;\n  type;\n  constructor(parameter, type) {\n    if (!isIndexSignatureParameter(parameter)) {\n      throw new Error(`Invalid index signature parameter ${parameter._tag}`);\n    }\n    this.parameter = parameter;\n    this.type = type;\n    if (isOptional(type) && !containsUndefined(type)) {\n      throw new Error(\"Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.\");\n    }\n  }\n};\n/**\n * Constructs a {@link Objects}.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Objects = class extends ASTNodeImpl {\n  _tag = \"Objects\";\n  propertySignatures;\n  indexSignatures;\n  encodingChecks;\n  constructor(propertySignatures, indexSignatures, annotations, checks, encoding, context, encodingChecks) {\n    super(annotations, checks, encoding, context);\n    this.propertySignatures = propertySignatures;\n    this.indexSignatures = indexSignatures;\n    this.encodingChecks = encodingChecks;\n    // Duplicate property signatures\n    const seen = new Set();\n    const duplicates = [];\n    for (const propertySignature of propertySignatures) {\n      const name = propertySignature.name;\n      if (seen.has(name)) {\n        duplicates.push(name);\n      } else {\n        seen.add(name);\n      }\n    }\n    if (duplicates.length > 0) {\n      throw new Error(`Duplicate identifiers: ${JSON.stringify(duplicates)}. ts(2300)`);\n    }\n  }\n  /** @internal */\n  getParser(compile, compileConstructorDefault = compile) {\n    // oxlint-disable-next-line @typescript-eslint/no-this-alias\n    const ast = this;\n    const expectedKeys = [];\n    for (const ps of ast.propertySignatures) {\n      expectedKeys.push(typeof ps.name === \"number\" ? globalThis.String(ps.name) : ps.name);\n    }\n    const hasProperties = expectedKeys.length;\n    const indexCount = ast.indexSignatures.length;\n    let expectedKeysSet = hasProperties && indexCount ? new Set(expectedKeys) : undefined;\n    // ---------------------------------------------\n    // handle empty struct\n    // ---------------------------------------------\n    if (!hasProperties && !indexCount) {\n      return fromRefinement(ast, Predicate.isNotNullish);\n    }\n    let properties;\n    let indexes;\n    const finishIndex = (s, key, k2, inputValue, exitValue) => {\n      if (exitValue._tag === \"Failure\") {\n        return wrapPropertyKeyIssue(s, ast, key, exitValue) ?? Exit.void;\n      }\n      const value = exitValue === InternalParser.sameExit ? inputValue : exitValue[InternalParser.args];\n      if (k2 !== InternalParser.missing && value !== InternalParser.missing) {\n        if (hasProperties && (expectedKeysSet.has(key) || expectedKeysSet.has(typeof k2 === \"number\" ? globalThis.String(k2) : k2))) return Exit.void;\n        InternalRecord.assignProperty(s.out, k2, value);\n      }\n      return Exit.void;\n    };\n    const parseIndex = (s, key, index, exitKey) => {\n      if (!exitKey) {\n        const eff = index.parserKey(key, s.options);\n        if (!effectIsExit(eff)) {\n          return Effect.flatMap(Effect.exit(eff), exit => parseIndex(s, key, index, exit));\n        }\n        exitKey = eff;\n      }\n      if (exitKey._tag === \"Failure\") {\n        return wrapPropertyKeyIssue(s, ast, key, exitKey) ?? Exit.void;\n      }\n      const k2 = exitKey === InternalParser.sameExit ? key : exitKey[InternalParser.args];\n      const inputValue = s.input[key];\n      const result = index.parserValue(inputValue, s.options);\n      return effectIsExit(result) ? finishIndex(s, key, k2, inputValue, result) : Effect.flatMap(Effect.exit(result), exit => finishIndex(s, key, k2, inputValue, exit));\n    };\n    const parseStringIndex = (s, key, index) => {\n      const inputValue = s.input[key];\n      const result = index.parserValue(inputValue, s.options);\n      return effectIsExit(result) ? finishIndex(s, key, key, inputValue, result) : Effect.flatMap(Effect.exit(result), exit => finishIndex(s, key, key, inputValue, exit));\n    };\n    const parseIndexes = indexCount ? iterateConcurrent()({\n      onItem: (s, [key, index]) => index.is.parameter === string ? parseStringIndex(s, key, index) : parseIndex(s, key, index),\n      step: (_s, _item, exit) => exit._tag === \"Failure\" ? exit : undefined\n    }) : undefined;\n    const compileMembers = () => {\n      if (!properties) {\n        properties = ast.propertySignatures.map(ps => ({\n          parser: compileConstructorDefault(ps.type),\n          name: ps.name,\n          type: ps.type\n        }));\n        indexes = indexCount ? ast.indexSignatures.map(is => ({\n          is,\n          parserKey: compile(parameterFromPropertyKey(is.parameter)),\n          parserValue: compileConstructorDefault(is.type)\n        })) : undefined;\n      }\n      return properties;\n    };\n    const fallback = Effect.fnUntracedEager(function* (input, options) {\n      if (input === InternalParser.missing) {\n        return InternalParser.missing;\n      }\n      // If the input is not a record, return early with an error\n      if (!(typeof input === \"object\" && input !== null && !Array.isArray(input))) {\n        return yield* Effect.fail(new SchemaIssue.InvalidType(ast, input, options));\n      }\n      compileMembers();\n      const record = input;\n      const out = {};\n      const state = {\n        ast,\n        input: record,\n        out,\n        issues: undefined,\n        options\n      };\n      const errorsAllOption = options.errors === \"all\";\n      const onExcessPropertyError = options.onExcessProperty === \"error\";\n      const concurrency = options.concurrency === undefined ? 1 : resolveConcurrency(options.concurrency);\n      // ---------------------------------------------\n      // handle excess properties\n      // ---------------------------------------------\n      const indexKeys = indexCount && onExcessPropertyError ? ast.indexSignatures.map(index => getIndexSignatureKeys(record, index.parameter, options)) : undefined;\n      if (onExcessPropertyError) {\n        expectedKeysSet ??= new Set(expectedKeys);\n        const coveredKeys = indexKeys ? new Set(expectedKeysSet) : expectedKeysSet;\n        if (indexKeys) {\n          for (const keys of indexKeys) {\n            for (const key of keys) coveredKeys.add(key);\n          }\n        }\n        const inputKeys = Reflect.ownKeys(record);\n        for (let i = 0; i < inputKeys.length; i++) {\n          const key = inputKeys[i];\n          if (!coveredKeys.has(key)) {\n            // key is unexpected\n            const unexpected = new SchemaIssue.UnexpectedKey(ast, record[key], options);\n            const issue = new SchemaIssue.Pointer([key], unexpected);\n            if (errorsAllOption) {\n              if (state.issues) {\n                state.issues.push(issue);\n              } else {\n                state.issues = [issue];\n              }\n              continue;\n            } else {\n              return yield* Effect.fail(new SchemaIssue.Composite(ast, [issue], input, options));\n            }\n          }\n        }\n      }\n      // ---------------------------------------------\n      // handle property signatures\n      // ---------------------------------------------\n      if (hasProperties) {\n        const eff = concurrency === 1 ? parseProperties(state, properties) : parsePropertiesConcurrent(state, properties, {\n          concurrency\n        });\n        if (eff) yield* eff;\n      }\n      // ---------------------------------------------\n      // handle index signatures\n      // ---------------------------------------------\n      if (indexCount && concurrency === 1) {\n        for (let i = 0; i < indexCount; i++) {\n          const index = indexes[i];\n          const parse = index.is.parameter === string ? parseStringIndex : parseIndex;\n          const keys = indexKeys?.[i] ?? (index.is.parameter === string ? Object.keys(record) : getIndexSignatureKeys(record, index.is.parameter, options));\n          for (let j = 0; j < keys.length; j++) {\n            const eff = parse(state, keys[j], index);\n            if (!effectIsExit(eff)) yield* eff;else if (eff._tag === \"Failure\") return yield* eff;\n          }\n        }\n      } else if (parseIndexes) {\n        const keyPairs = Arr.empty();\n        for (let i = 0; i < indexCount; i++) {\n          const index = indexes[i];\n          const keys = indexKeys?.[i] ?? (index.is.parameter === string ? Object.keys(record) : getIndexSignatureKeys(record, index.is.parameter, options));\n          for (let j = 0; j < keys.length; j++) {\n            keyPairs.push([keys[j], index]);\n          }\n        }\n        const eff = parseIndexes(state, keyPairs, {\n          concurrency\n        });\n        if (eff) yield* eff;\n      }\n      if (state.issues) {\n        return yield* Effect.fail(new SchemaIssue.Composite(ast, state.issues, input, options));\n      }\n      return out;\n    });\n    if (indexCount) return fallback;\n    // Resumes at the property whose parser suspended, without replaying the\n    // properties already parsed.\n    const resume = (state, index, pending) => {\n      const property = properties[index];\n      return Effect.flatMap(Effect.exit(pending), exit => {\n        const terminal = stepProperty(state, property, exit);\n        if (terminal) return terminal;\n        const done = () => InternalParser.succeed(state.out);\n        const eff = parseProperties(state, properties.slice(index + 1));\n        return eff ? Effect.flatMapEager(eff, done) : done();\n      });\n    };\n    // Fast path: a struct without index signatures, under the default parse\n    // options, needs none of the generator the fallback runs per value.\n    return (input, options) => {\n      if (input === InternalParser.missing) return InternalParser.missingExit;\n      if (options.errors === \"all\" || options.onExcessProperty !== undefined || options.concurrency !== undefined && resolveConcurrency(options.concurrency) !== 1) {\n        return fallback(input, options);\n      }\n      if (!(typeof input === \"object\" && input !== null && !Array.isArray(input))) {\n        return Effect.fail(new SchemaIssue.InvalidType(ast, input, options));\n      }\n      const props = compileMembers();\n      const record = input;\n      const out = {};\n      const state = {\n        ast,\n        input: record,\n        out,\n        issues: undefined,\n        options\n      };\n      try {\n        for (let index = 0; index < props.length; index++) {\n          const property = props[index];\n          const name = property.name;\n          const hasKey = hasPropertySignature(record, name);\n          const value = hasKey ? record[name] : InternalParser.missing;\n          const exit = property.parser(value, options);\n          if (!effectIsExit(exit)) {\n            return resume(state, index, exit);\n          }\n          if (exit === InternalParser.sameExit) {\n            if (hasKey) InternalRecord.assignProperty(out, name, value);\n            continue;\n          }\n          const terminal = stepProperty(state, property, exit);\n          if (terminal) return terminal;\n        }\n      } catch (error) {\n        // `Effect.fnUntracedEager` turns a synchronous throw into a defect\n        return Effect.die(error);\n      }\n      return InternalParser.succeed(out);\n    };\n  }\n  _rebuild(recur, recurParameter, checks, encodingChecks) {\n    const props = mapOrSame(this.propertySignatures, ps => {\n      const t = recur(ps.type);\n      return t === ps.type ? ps : new PropertySignature(ps.name, t);\n    });\n    const indexes = mapOrSame(this.indexSignatures, is => {\n      const p = recurParameter(is.parameter);\n      const t = recur(is.type);\n      return p === is.parameter && t === is.type ? is : new IndexSignature(p, t);\n    });\n    return props === this.propertySignatures && indexes === this.indexSignatures && checks === this.checks && encodingChecks === this.encodingChecks ? this : new Objects(props, indexes, this.annotations, checks, undefined, this.context, encodingChecks);\n  }\n  /** @internal */\n  flip(recur) {\n    return this._rebuild(recur, recur, this.encodingChecks, this.checks);\n  }\n  /** @internal */\n  recur(recur, recurParameter = recur) {\n    return this._rebuild(recur, recurParameter, this.checks, this.encodingChecks);\n  }\n  /** @internal */\n  getExpected() {\n    if (this.propertySignatures.length === 0 && this.indexSignatures.length === 0) return \"object | array\";\n    return \"object\";\n  }\n};\nfunction stepProperty(s, p, exit) {\n  if (exit._tag === \"Failure\") {\n    return wrapPropertyKeyIssue(s, s.ast, p.name, exit);\n  }\n  if (exit === InternalParser.sameExit) return;\n  const value = exit[InternalParser.args];\n  if (value !== InternalParser.missing) {\n    InternalRecord.assignProperty(s.out, p.name, value);\n    return;\n  }\n  delete s.out[p.name];\n  if (!isOptional(p.type)) {\n    const issue = new SchemaIssue.Pointer([p.name], new SchemaIssue.MissingKey(p.type.context?.annotations));\n    if (s.options.errors === \"all\") {\n      if (s.issues) s.issues.push(issue);else s.issues = [issue];\n      return;\n    } else {\n      return Exit.fail(new SchemaIssue.Composite(s.ast, [issue], s.input, s.options));\n    }\n  }\n}\nconst parsePropertiesOptions = {\n  onItem(s, p) {\n    if (!hasPropertySignature(s.input, p.name)) {\n      return p.parser(InternalParser.missing, s.options);\n    }\n    const value = s.input[p.name];\n    InternalRecord.assignProperty(s.out, p.name, value);\n    return p.parser(value, s.options);\n  },\n  step: stepProperty\n};\nconst parseProperties = /*#__PURE__*/iterateEager()(parsePropertiesOptions);\nconst parsePropertiesConcurrent = /*#__PURE__*/iterateConcurrent()(parsePropertiesOptions);\nfunction combineChecks(a, b) {\n  if (!a) return b;\n  if (!b) return a;\n  return [...a, ...b];\n}\n/** @internal */\nexport function struct(fields, checks, annotations) {\n  return new Objects(Reflect.ownKeys(fields).map(key => {\n    return new PropertySignature(key, fields[key].ast);\n  }), [], annotations, checks);\n}\n/** @internal */\nexport function getAST(self) {\n  return self.ast;\n}\n/** @internal */\nexport function tuple(elements, checks = undefined) {\n  return new Arrays(false, elements.map(e => e.ast), [], undefined, checks);\n}\n/** @internal */\nexport function union(members, options, checks) {\n  return new Union(members.map(getAST), options, undefined, checks);\n}\n/** @internal */\nexport function structWithRest(ast, records) {\n  if (ast.encoding || records.some(r => r.encoding)) {\n    throw new Error(\"StructWithRest does not support encodings\");\n  }\n  let propertySignatures = ast.propertySignatures;\n  let indexSignatures = ast.indexSignatures;\n  let checks = ast.checks;\n  for (const record of records) {\n    propertySignatures = propertySignatures.concat(record.propertySignatures);\n    indexSignatures = indexSignatures.concat(record.indexSignatures);\n    checks = combineChecks(checks, record.checks);\n  }\n  return new Objects(propertySignatures, indexSignatures, undefined, checks);\n}\n/** @internal */\nexport function tupleWithRest(ast, rest) {\n  if (ast.encoding) {\n    throw new Error(\"TupleWithRest does not support encodings\");\n  }\n  return new Arrays(ast.isMutable, ast.elements, rest, undefined, ast.checks);\n}\n/** @internal */\nexport function mutable(ast) {\n  if (ast.encoding) {\n    throw new Error(\"mutable does not support encodings\");\n  }\n  return new Arrays(true, ast.elements, ast.rest, ast.annotations, ast.checks, undefined, ast.context, ast.encodingChecks);\n}\nconst toCandidate = /*#__PURE__*/memoizeIdempotent(ast => {\n  while (true) {\n    if (isSuspend(ast)) return unknown;\n    const encoding = ast.encoding;\n    if (!encoding) {\n      // Index signature parameters do not participate in union selection.\n      return ast.recur?.(toCandidate, identity) ?? ast;\n    }\n    if (encoding.some(link => link.transformation._tag === \"Middleware\" && link.transformation.decode !== identity)) return unknown;\n    ast = encoding[encoding.length - 1].to;\n  }\n});\nfunction getCandidateTypes(ast) {\n  switch (ast._tag) {\n    case \"Null\":\n      return [\"null\"];\n    case \"Undefined\":\n      return [\"undefined\"];\n    case \"String\":\n    case \"TemplateLiteral\":\n      return [\"string\"];\n    case \"Number\":\n      return [\"number\"];\n    case \"Boolean\":\n      return [\"boolean\"];\n    case \"Symbol\":\n    case \"UniqueSymbol\":\n      return [\"symbol\"];\n    case \"BigInt\":\n      return [\"bigint\"];\n    case \"Arrays\":\n      return [\"array\"];\n    case \"ObjectKeyword\":\n      return [\"object\", \"array\", \"function\"];\n    case \"Objects\":\n      return ast.propertySignatures.length || ast.indexSignatures.length ? [\"object\"] : [\"string\", \"number\", \"boolean\", \"symbol\", \"bigint\", \"object\", \"array\", \"function\"];\n    case \"Enum\":\n      return Array.from(new Set(ast.enums.map(([, v]) => typeof v)));\n    case \"Literal\":\n      return [typeof ast.literal];\n    case \"Union\":\n      return Array.from(new Set(ast.types.flatMap(getCandidateTypes)));\n    default:\n      return [\"null\", \"undefined\", \"string\", \"number\", \"boolean\", \"symbol\", \"bigint\", \"object\", \"array\", \"function\"];\n  }\n}\n/** @internal */\nexport function collectSentinels(ast) {\n  switch (ast._tag) {\n    default:\n      return [];\n    case \"Declaration\":\n      {\n        const s = ast.annotations?.[InternalAnnotations.SENTINELS_ANNOTATION_KEY];\n        return Array.isArray(s) ? s : [];\n      }\n    case \"Objects\":\n      return ast.propertySignatures.flatMap(ps => {\n        const type = ps.type;\n        if (!isOptional(type)) {\n          if (isLiteral(type)) {\n            return [{\n              key: ps.name,\n              literal: type.literal\n            }];\n          }\n          if (isUniqueSymbol(type)) {\n            return [{\n              key: ps.name,\n              literal: type.symbol\n            }];\n          }\n        }\n        return [];\n      });\n    case \"Arrays\":\n      return ast.elements.flatMap((e, i) => {\n        if (!isOptional(e)) {\n          if (isLiteral(e)) {\n            return [{\n              key: i,\n              literal: e.literal\n            }];\n          }\n          if (isUniqueSymbol(e)) {\n            return [{\n              key: i,\n              literal: e.symbol\n            }];\n          }\n        }\n        return [];\n      });\n    case \"Union\":\n      {\n        if (ast.types.length === 0) return [];\n        const members = ast.types.map(type => collectSentinels(toCandidate(type)));\n        return members[0].filter(s => members.every(sentinels => sentinels.some(o => o.key === s.key && o.literal === s.literal)));\n      }\n    case \"Suspend\":\n      return collectSentinels(ast.thunk());\n  }\n}\nconst candidateIndexCache = /*#__PURE__*/new WeakMap();\nconst emptyCandidates = /*#__PURE__*/Object.freeze([]);\nconst hasPropertySignature = (input, key) => key === \"__proto__\" ? Object.hasOwn(input, key) : key in input;\nfunction getIndex(types) {\n  let index = candidateIndexCache.get(types);\n  if (index) return index;\n  let bySentinel;\n  let sentinelCandidateCount = 0;\n  let otherwise;\n  let literalCandidates;\n  let onlyLiterals = true;\n  for (let i = 0; i < types.length; i++) {\n    const a = types[i];\n    const encoded = toCandidate(a);\n    if (isNever(encoded)) continue;\n    if (onlyLiterals) {\n      if (isLiteral(encoded) || isUniqueSymbol(encoded)) {\n        literalCandidates ??= new Map();\n        const literal = isLiteral(encoded) ? encoded.literal : encoded.symbol;\n        let arr = literalCandidates.get(literal);\n        if (!arr) literalCandidates.set(literal, arr = []);\n        arr.push(a);\n      } else {\n        onlyLiterals = false;\n      }\n    }\n    const sentinels = collectSentinels(encoded);\n    if (sentinels.length) {\n      // discriminated variants\n      bySentinel ??= new Map();\n      sentinelCandidateCount++;\n      for (const {\n        key,\n        literal\n      } of sentinels) {\n        let entry = bySentinel.get(key);\n        if (!entry) bySentinel.set(key, entry = [new Map(), new Set()]);\n        entry[1].add(i);\n        let indexes = entry[0].get(literal);\n        if (!indexes) entry[0].set(literal, indexes = new Set());\n        indexes.add(i);\n      }\n    } else {\n      // non-discriminated\n      otherwise ??= {};\n      const candidateTypes = getCandidateTypes(encoded);\n      for (const t of candidateTypes) (otherwise[t] ??= []).push(i);\n    }\n  }\n  if (onlyLiterals && literalCandidates) {\n    literalCandidates.forEach(Object.freeze);\n    index = input => literalCandidates.get(input) ?? emptyCandidates;\n  } else if (bySentinel?.size === 1 && !otherwise) {\n    const [key, [byValue]] = bySentinel.entries().next().value;\n    const candidates = byValue;\n    for (const [literal, indexes] of byValue) {\n      candidates.set(literal, Object.freeze(Array.from(indexes, index => types[index])));\n    }\n    index = (input, isConstructor) => {\n      if (Predicate.isObjectKeyword(input)) {\n        const value = hasPropertySignature(input, key) ? input[key] : undefined;\n        if (value !== undefined) return candidates.get(value) ?? emptyCandidates;\n        if (isConstructor) return types;\n      }\n      return emptyCandidates;\n    };\n  } else if (bySentinel) {\n    // A key owned by every discriminated candidate is safe to use as the initial selector: no candidate can\n    // be excluded merely because it uses a different sentinel key. Prefer the key with the most distinct values\n    // to minimize the matching bucket.\n    let commonSentinel;\n    for (const entry of bySentinel) {\n      if ((!commonSentinel || entry[1][0].size > commonSentinel[1][0].size) && entry[1][1].size === sentinelCandidateCount) {\n        commonSentinel = entry;\n      }\n    }\n    index = (input, isConstructor) => {\n      const runtimeType = input === null ? \"null\" : Array.isArray(input) ? \"array\" : typeof input;\n      const base = otherwise?.[runtimeType] ?? emptyCandidates;\n      if (!Predicate.isObjectKeyword(input)) return base.map(i => types[i]);\n      // Non-discriminated candidates are runtime-type fallbacks and are never removed by sentinel checks.\n      const selected = new Set(base);\n      let directKey;\n      // An observed common key can seed the selection directly; an unknown value rules out every\n      // discriminated candidate.\n      if (commonSentinel) {\n        const [key, [byValue]] = commonSentinel;\n        const hasKey = hasPropertySignature(input, key);\n        const value = hasKey ? input[key] : undefined;\n        if (hasKey && (!isConstructor || value !== undefined)) {\n          const match = byValue.get(value);\n          if (!match) return base.map(i => types[i]);\n          for (const i of match) selected.add(i);\n          directKey = key;\n        }\n      }\n      // Without an observed common key, collect positive matches from every sentinel. Constructor mode treats\n      // absent and undefined keys as unconstrained and therefore selects every candidate that owns the key.\n      if (directKey === undefined) {\n        for (const [key, [byValue, all]] of bySentinel) {\n          const hasKey = hasPropertySignature(input, key);\n          const value = hasKey ? input[key] : undefined;\n          if (hasKey && (!isConstructor || value !== undefined)) {\n            const match = byValue.get(value);\n            if (match) {\n              for (const i of match) selected.add(i);\n            }\n          } else if (isConstructor) {\n            for (const i of all) selected.add(i);\n          }\n        }\n      }\n      // Missing keys are neutral. An observed key rejects only selected candidates that own it and do not match.\n      for (const [key, [byValue, all]] of bySentinel) {\n        if (key === directKey) continue;\n        const hasKey = hasPropertySignature(input, key);\n        const value = hasKey ? input[key] : undefined;\n        if (hasKey && (!isConstructor || value !== undefined)) {\n          const match = byValue.get(value);\n          for (const i of selected) {\n            if (all.has(i) && !match?.has(i)) selected.delete(i);\n          }\n        }\n      }\n      return Array.from(selected).sort((a, b) => a - b).map(i => types[i]);\n    };\n  } else {\n    index = input => {\n      const runtimeType = input === null ? \"null\" : Array.isArray(input) ? \"array\" : typeof input;\n      return (otherwise?.[runtimeType] ?? emptyCandidates).map(i => types[i]).filter(filterLiterals(input));\n    };\n  }\n  candidateIndexCache.set(types, index);\n  return index;\n}\nfunction filterLiterals(input) {\n  return ast => {\n    const encoded = toCandidate(ast);\n    return encoded._tag === \"Literal\" ? encoded.literal === input : encoded._tag === \"UniqueSymbol\" ? encoded.symbol === input : true;\n  };\n}\n/**\n * The goal is to reduce the number of a union members that will be checked.\n * This is useful to reduce the number of issues that will be returned.\n *\n * @internal\n */\nexport function getCandidates(input, types, isConstructor = false) {\n  return getIndex(types)(input, isConstructor);\n}\n/**\n * Constructs a {@link Union}.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Union = class extends ASTNodeImpl {\n  _tag = \"Union\";\n  types;\n  options;\n  encodingChecks;\n  constructor(types, options, annotations, checks, encoding, context, encodingChecks) {\n    super(annotations, checks, encoding, context);\n    this.types = types;\n    this.options = options;\n    this.encodingChecks = encodingChecks;\n  }\n  /** @internal */\n  getParser(compile, compileConstructorDefault) {\n    // oxlint-disable-next-line @typescript-eslint/no-this-alias\n    const ast = this;\n    return (input, options) => {\n      if (input === InternalParser.missing) {\n        return InternalParser.missingExit;\n      }\n      const candidates = getCandidates(input, ast.types, compileConstructorDefault !== undefined);\n      if (candidates.length === 0) {\n        return Effect.fail(new SchemaIssue.AnyOf(ast, [], input, options));\n      }\n      if (candidates.length === 1) {\n        const result = compile(candidates[0])(input, options);\n        if (result._tag === \"Success\") return result;\n        return effectIsExit(result) ? failSingleUnionCandidate(ast, result.cause, input, options) : Effect.catchCause(result, cause => failSingleUnionCandidate(ast, cause, input, options));\n      }\n      const state = {\n        ast,\n        compile,\n        input,\n        out: undefined,\n        successes: ast.options?.mode === \"oneOf\" ? [] : undefined,\n        issues: undefined,\n        options\n      };\n      const eff = parseUnion(state, candidates);\n      if (!eff) {\n        if (state.out) return state.out;\n        return Effect.fail(new SchemaIssue.AnyOf(ast, state.issues ?? [], input, options));\n      }\n      return Effect.flatMapEager(eff, _ => {\n        if (state.out === InternalParser.sameExit) return Effect.succeed(input);\n        if (state.out) return state.out;\n        return Effect.fail(new SchemaIssue.AnyOf(ast, state.issues ?? [], input, options));\n      });\n    };\n  }\n  _rebuild(recur, checks, encodingChecks) {\n    const types = mapOrSame(this.types, recur);\n    return types === this.types && checks === this.checks && encodingChecks === this.encodingChecks ? this : new Union(types, this.options, this.annotations, checks, undefined, this.context, encodingChecks);\n  }\n  /** @internal */\n  recur(recur) {\n    return this._rebuild(recur, this.checks, this.encodingChecks);\n  }\n  /** @internal */\n  flip(recur) {\n    return this._rebuild(recur, this.encodingChecks, this.checks);\n  }\n  /** @internal */\n  matchPart(s, options) {\n    for (const type of this.types) {\n      const out = type.matchPart(s, options);\n      if (out !== undefined) return out;\n    }\n    return undefined;\n  }\n  /** @internal */\n  getExpected(getExpected) {\n    const expected = this.annotations?.expected;\n    if (typeof expected === \"string\") return expected;\n    if (this.types.length === 0) return \"never\";\n    const types = this.types.map(type => {\n      const encoded = toEncoded(type);\n      switch (encoded._tag) {\n        case \"Arrays\":\n          {\n            const literals = encoded.elements.filter(isLiteral);\n            if (literals.length > 0) {\n              return `${formatIsMutable(encoded.isMutable)}[ ${literals.map(e => getExpected(e) + formatIsOptional(e.context?.isOptional)).join(\", \")}, ... ]`;\n            }\n            break;\n          }\n        case \"Objects\":\n          {\n            const literals = encoded.propertySignatures.filter(ps => isLiteral(ps.type));\n            if (literals.length > 0) {\n              return `{ ${literals.map(ps => `${formatIsMutable(ps.type.context?.isMutable)}${formatPropertyKey(ps.name)}${formatIsOptional(ps.type.context?.isOptional)}: ${getExpected(ps.type)}`).join(\", \")}, ... }`;\n            }\n            break;\n          }\n      }\n      return getExpected(encoded);\n    });\n    return Array.from(new Set(types)).join(\" | \");\n  }\n};\nfunction failSingleUnionCandidate(ast, cause, input, options) {\n  const issue = InternalSchemaCause.getSchemaIssue(cause);\n  if (!issue) return Exit.failCause(cause);\n  return Exit.fail(new SchemaIssue.AnyOf(ast, [issue], input, options));\n}\nconst parseUnion = /*#__PURE__*/iterateEager()({\n  onItem(s, ast) {\n    const parser = s.compile(ast);\n    return parser(s.input, s.options);\n  },\n  step(s, candidate, exit) {\n    if (exit._tag === \"Failure\") {\n      const issue = InternalSchemaCause.getSchemaIssue(exit.cause);\n      if (issue === undefined) {\n        return exit;\n      }\n      if (s.issues) s.issues.push(issue);else s.issues = [issue];\n    } else {\n      if (s.out && s.successes) {\n        s.successes.push(candidate);\n        return Exit.fail(new SchemaIssue.OneOf(s.ast, s.successes, s.input, s.options));\n      }\n      s.out = exit;\n      if (s.successes) {\n        s.successes.push(candidate);\n      } else {\n        return Exit.void;\n      }\n    }\n  }\n});\nconst nonFiniteLiterals = /*#__PURE__*/new Union([/*#__PURE__*/new Literal(\"Infinity\"), /*#__PURE__*/new Literal(\"-Infinity\"), /*#__PURE__*/new Literal(\"NaN\")]);\nfunction formatIsMutable(isMutable) {\n  return isMutable ? \"\" : \"readonly \";\n}\nfunction formatIsOptional(isOptional) {\n  return isOptional ? \"?\" : \"\";\n}\n/**\n * Constructs a {@link Suspend}.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Suspend = class extends ASTNodeImpl {\n  _tag = \"Suspend\";\n  thunk;\n  constructor(thunk, annotations, checks, encoding, context) {\n    if (checks) {\n      throw new Error(\"Cannot add checks to Suspend\");\n    }\n    super(annotations, undefined, encoding, context);\n    let ast;\n    this.thunk = () => ast ??= thunk();\n  }\n  /** @internal */\n  getParser(compile) {\n    let parser;\n    return (input, options) => (parser ??= compile(this.thunk()))(input, options);\n  }\n  /** @internal */\n  recur(recur) {\n    return new Suspend(() => recur(this.thunk()), this.annotations, undefined, undefined, this.context);\n  }\n  /** @internal */\n  getExpected(getExpected) {\n    return getExpected(this.thunk());\n  }\n};\n/**\n * Constructs a {@link Filter}.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Filter = class extends Pipeable.Class {\n  _tag = \"Filter\";\n  run;\n  annotations;\n  /**\n   * Whether the parsing process should be aborted after this check has failed.\n   */\n  aborted;\n  constructor(run, annotations = undefined,\n  /**\n   * Whether the parsing process should be aborted after this check has failed.\n   */\n  aborted = false) {\n    super();\n    this.run = run;\n    this.annotations = annotations;\n    this.aborted = aborted;\n  }\n  annotate(annotations) {\n    return new Filter(this.run, {\n      ...this.annotations,\n      ...annotations\n    }, this.aborted);\n  }\n  abort() {\n    return new Filter(this.run, this.annotations, true);\n  }\n  and(other, annotations) {\n    return new FilterGroup([this, other], annotations);\n  }\n};\n/**\n * Constructs a {@link FilterGroup}.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const FilterGroup = class extends Pipeable.Class {\n  _tag = \"FilterGroup\";\n  checks;\n  annotations;\n  constructor(checks, annotations = undefined) {\n    super();\n    this.checks = checks;\n    this.annotations = annotations;\n  }\n  annotate(annotations) {\n    return new FilterGroup(this.checks, {\n      ...this.annotations,\n      ...annotations\n    });\n  }\n  and(other, annotations) {\n    return new FilterGroup([this, other], annotations);\n  }\n};\n/** @internal */\nexport function makeFilter(filter, annotations, aborted = false) {\n  return new Filter((input, ast, options) => SchemaIssue.normalizeFilterOutput(ast, filter(input, ast, options), input, options), annotations, aborted);\n}\n/** @internal */\nexport function makeFilterByGuard(is, annotations) {\n  return new Filter((input, _ast, options) => is(input) ? undefined : new SchemaIssue.InvalidValue(undefined, input, options), annotations, true // after a guard, we always want to abort\n  );\n}\n/** @internal */\nexport function isFinite(annotations) {\n  return makeFilter(n => globalThis.Number.isFinite(n), {\n    expected: \"a finite number\",\n    representation: {\n      id: \"effect/schema/isFinite\",\n      payload: null\n    },\n    toJsonSchema: () => ({\n      type: \"number\"\n    }),\n    toCode: () => ({\n      runtime: \"Schema.isFinite()\"\n    }),\n    arbitraryConstraint: {\n      number: \"finite\"\n    },\n    ...annotations\n  });\n}\n/** @internal */\nexport const finite = /*#__PURE__*/appendChecks(number, [/*#__PURE__*/isFinite()]);\nconst numberToJson = /*#__PURE__*/new Link(/*#__PURE__*/new Union([finite, nonFiniteLiterals]), /*#__PURE__*/new SchemaTransformation.Transformation(/*#__PURE__*/SchemaGetter.Number(), /*#__PURE__*/SchemaGetter.transform(n => globalThis.Number.isFinite(n) ? n : globalThis.String(n))));\n/**\n * Creates a {@link Filter} that validates strings by running `RegExp.test`.\n *\n * **When to use**\n *\n * Use when string validation should be represented as a schema `Filter` backed\n * by a regular expression.\n *\n * **Details**\n *\n * The filter can be used with `Schema.filter` or attached directly to a\n * `String` AST node through checks. The regular expression is cloned and its\n * `lastIndex` is reset before each test, so global and sticky expressions are\n * deterministic and the provided regular expression is not mutated. The\n * regular expression source is stored in annotations for serialization and\n * arbitrary generation.\n *\n * **Gotchas**\n *\n * Arbitrary metadata preserves both `regExp.source` and `regExp.flags`.\n * Implementations that cannot consume all flags may still use the source as a\n * generation hint because the Schema filter validates every generated value.\n * JSON Schema has no way to carry JavaScript regular-expression flags. The\n * generated `pattern` contains the source only, so validation can differ when\n * the RegExp uses flags or relies on JavaScript's non-Unicode behavior.\n *\n * **Example** (Validating an email pattern)\n *\n * ```ts import.meta.vitest\n * import { SchemaAST } from \"effect\"\n *\n * const emailFilter = SchemaAST.isPattern(/^[^@]+@[^@]+$/)\n * emailFilter.run(\"alice@example.com\", SchemaAST.string, {}) // => undefined\n * emailFilter.run(\"invalid\", SchemaAST.string, {})?._tag // => \"InvalidValue\"\n * ```\n *\n * @see {@link Filter}\n * @category constructors\n * @since 4.0.0\n */\nexport function isPattern(regExp, annotations) {\n  const source = regExp.source;\n  const pattern = new globalThis.RegExp(source, regExp.flags);\n  return makeFilter(s => {\n    pattern.lastIndex = 0;\n    return pattern.test(s);\n  }, {\n    expected: `a string matching the RegExp ${source}`,\n    representation: {\n      id: \"effect/schema/isPattern\",\n      payload: {\n        source,\n        flags: regExp.flags\n      }\n    },\n    toJsonSchema: () => ({\n      pattern: source\n    }),\n    arbitraryConstraint: {\n      patterns: [{\n        source: regExp.source,\n        flags: regExp.flags\n      }]\n    },\n    ...annotations\n  });\n}\nfunction modifyOwnPropertyDescriptors(ast, f) {\n  const d = Object.getOwnPropertyDescriptors(ast);\n  f(d);\n  return Object.create(Object.getPrototypeOf(ast), d);\n}\nconst contextOwners = /*#__PURE__*/new WeakMap();\n/** @internal */\nexport function getContextOwner(ast) {\n  return contextOwners.get(ast) ?? ast;\n}\n/** @internal */\nexport function replaceEncoding(ast, encoding) {\n  if (ast.encoding === encoding) {\n    return ast;\n  }\n  return modifyOwnPropertyDescriptors(ast, d => {\n    d.encoding.value = encoding;\n  });\n}\n/** @internal */\nexport function replaceContext(ast, context) {\n  if (ast.context === context) {\n    return ast;\n  }\n  const owner = getContextOwner(ast);\n  if (owner.context === context) {\n    return owner;\n  }\n  const out = modifyOwnPropertyDescriptors(ast, d => {\n    d.context.value = context;\n  });\n  contextOwners.set(out, owner);\n  return out;\n}\n/** @internal */\nexport function getLastEncoding(ast) {\n  return ast.encoding ? getLastEncoding(ast.encoding[ast.encoding.length - 1].to) : ast;\n}\n/** @internal */\nexport function annotate(ast, annotations) {\n  if (ast.checks) {\n    const last = ast.checks[ast.checks.length - 1];\n    return replaceChecks(ast, Arr.append(ast.checks.slice(0, -1), last.annotate(annotations)));\n  }\n  return modifyOwnPropertyDescriptors(ast, d => {\n    d.annotations.value = {\n      ...d.annotations.value,\n      ...annotations\n    };\n  });\n}\n/** @internal */\nexport function replaceChecks(ast, checks) {\n  if (ast._tag === \"Suspend\" && checks) {\n    throw new Error(\"Cannot add checks to Suspend\");\n  }\n  if (ast.checks === checks) {\n    return ast;\n  }\n  return modifyOwnPropertyDescriptors(ast, d => {\n    d.checks.value = checks;\n  });\n}\n/** @internal */\nexport function appendChecks(ast, checks) {\n  return replaceChecks(ast, combineChecks(ast.checks, checks));\n}\n/** @internal */\nexport function mapLink(link, f) {\n  const to = f(link.to);\n  return to === link.to ? link : new Link(to, link.transformation);\n}\nfunction updateLastLink(encoding, f) {\n  const links = encoding;\n  const last = links[links.length - 1];\n  const out = mapLink(last, f);\n  return out === last ? encoding : Arr.append(encoding.slice(0, encoding.length - 1), out);\n}\n/** @internal */\nexport function applyToLastLink(f) {\n  return ast => ast.encoding ? replaceEncoding(ast, updateLastLink(ast.encoding, f)) : ast;\n}\n/** @internal */\nexport function replaceContextLastLink(ast, context) {\n  return applyToLastLink(ast => replaceContext(ast, context))(ast);\n}\n/** @internal */\nexport function applyToSelfOrLastLinkEncoding(f) {\n  function out(ast) {\n    return ast.encoding ? replaceEncoding(ast, updateLastLink(ast.encoding, out)) : f(ast);\n  }\n  return memoize(out);\n}\n/** @internal */\nexport function applyToSelfOrLastLinkEncodingIdempotent(f, options) {\n  function out(ast) {\n    if (ast.encoding) {\n      const last = ast.encoding[ast.encoding.length - 1];\n      return options?.stopAt?.(last) ? ast : replaceEncoding(ast, updateLastLink(ast.encoding, out));\n    }\n    return f(ast);\n  }\n  return memoizeIdempotent(out);\n}\n/** @internal */\nexport function middlewareDecoding(ast, middleware) {\n  return appendTransformation(ast, middleware, toType(ast));\n}\n/** @internal */\nexport function middlewareEncoding(ast, middleware) {\n  return appendTransformation(toEncoded(ast), middleware, ast);\n}\nfunction appendTransformation(from, transformation, to) {\n  const link = new Link(from, transformation);\n  return replaceEncoding(to, to.encoding ? [...to.encoding, link] : [link]);\n}\n/** @internal */\nexport function brand(ast, brand) {\n  const existing = InternalAnnotations.resolveBrands(ast);\n  const brands = existing ? [...existing, brand] : [brand];\n  return annotate(ast, {\n    brands\n  });\n}\nexport function mapOrSame(as, f) {\n  let changed = false;\n  const out = new Array(as.length);\n  for (let i = 0; i < as.length; i++) {\n    const a = as[i];\n    const fa = f(a);\n    if (fa !== a) {\n      changed = true;\n    }\n    out[i] = fa;\n  }\n  return changed ? out : as;\n}\n/** @internal */\nexport function annotateKey(ast, annotations) {\n  const context = ast.context ? new Context(ast.context.isOptional, ast.context.isMutable, ast.context.constructorDefault, {\n    ...ast.context.annotations,\n    ...annotations\n  }) : new Context(false, false, undefined, annotations);\n  return replaceContext(ast, context);\n}\n/** @internal */\nexport const optionalKey = /*#__PURE__*/memoizeIdempotent(ast => {\n  const context = ast.context ? ast.context.isOptional === false ? new Context(true, ast.context.isMutable, ast.context.constructorDefault, ast.context.annotations) : ast.context : new Context(true, false);\n  return optionalKeyLastLink(replaceContext(ast, context));\n});\nconst optionalKeyLastLink = /*#__PURE__*/applyToLastLink(optionalKey);\n/** @internal */\nexport const optional = /*#__PURE__*/memoize(ast => optionalKey(new Union([ast, undefined_])));\n/** @internal */\nexport const mutableKey = /*#__PURE__*/memoizeIdempotent(ast => {\n  const context = ast.context ? ast.context.isMutable === false ? new Context(ast.context.isOptional, true, ast.context.constructorDefault, ast.context.annotations) : ast.context : new Context(false, true);\n  return mutableKeyLastLink(replaceContext(ast, context));\n});\nconst mutableKeyLastLink = /*#__PURE__*/applyToLastLink(mutableKey);\n/** @internal */\nexport function withConstructorDefault(ast, defaultValue) {\n  const transformation = new SchemaTransformation.Transformation(SchemaGetter.withDefault(defaultValue), SchemaGetter.passthrough());\n  const constructorDefault = new Link(unknown, transformation);\n  const context = ast.context ? new Context(ast.context.isOptional, ast.context.isMutable, constructorDefault, ast.context.annotations) : new Context(false, false, constructorDefault);\n  return replaceContext(ast, context);\n}\n/**\n * Attaches a `Transformation` to the `to` AST, making it decode from the\n * `from` AST and encode back to it.\n *\n * **Details**\n *\n * This is the low-level primitive behind `Schema.decodeTo`. It appends a\n * {@link Link} to the `to` node's encoding chain.\n *\n * - Returns a new AST with the same type as `to`.\n *\n * @see {@link Link}\n * @see {@link Encoding}\n * @see {@link flip}\n * @category transforming\n * @since 4.0.0\n */\nexport function decodeTo(from, to, transformation) {\n  return appendTransformation(from, transformation, to);\n}\nfunction parseParameter(ast) {\n  const literals = [];\n  const parameters = [];\n  function go(ast) {\n    switch (ast._tag) {\n      case \"Literal\":\n        if (Predicate.isPropertyKey(ast.literal)) {\n          literals.push(ast.literal);\n        }\n        return;\n      case \"UniqueSymbol\":\n        literals.push(ast.symbol);\n        return;\n      case \"Never\":\n        return;\n      case \"Union\":\n        for (let i = 0; i < ast.types.length; i++) {\n          go(ast.types[i]);\n        }\n        return;\n      default:\n        parameters.push(ast);\n    }\n  }\n  go(ast);\n  return {\n    literals,\n    parameters\n  };\n}\n/** @internal */\nexport function record(key, value) {\n  const {\n    literals,\n    parameters: indexSignatures\n  } = parseParameter(key);\n  return new Objects(literals.map(literal => new PropertySignature(literal, value)), indexSignatures.map(parameter => new IndexSignature(parameter, value)));\n}\n// -------------------------------------------------------------------------------------\n// Public APIs\n// -------------------------------------------------------------------------------------\n/**\n * Returns `true` if the AST node represents an optional property.\n *\n * **Details**\n *\n * Checks `ast.context?.isOptional`. Defaults to `false` when no\n * {@link Context} is set.\n *\n * @see `Schema.optionalKey`\n * @see {@link Context}\n * @category predicates\n * @since 4.0.0\n */\nexport function isOptional(ast) {\n  return ast.context?.isOptional ?? false;\n}\n/** @internal */\nexport function isMutable(ast) {\n  return ast.context?.isMutable ?? false;\n}\nfunction isStructuralCheck(check) {\n  return check.annotations?.[InternalAnnotations.STRUCTURAL_ANNOTATION_KEY] === true || check._tag === \"FilterGroup\" && check.checks.every(isStructuralCheck);\n}\nfunction extractStructuralChecks(checks) {\n  function extract(check) {\n    if (isStructuralCheck(check)) return [check];\n    return check._tag === \"FilterGroup\" ? check.checks.flatMap(extract) : [];\n  }\n  const out = checks.flatMap(extract);\n  return Arr.isArrayNonEmpty(out) ? out : undefined;\n}\n/**\n * Strips all encoding transformations from an AST, returning the decoded\n * (type-level) representation.\n *\n * **Details**\n *\n * - Memoized: same input reference → same output reference.\n * - Recursively walks into composite nodes ({@link Arrays}, {@link Objects},\n *   {@link Union}, {@link Suspend}).\n *\n * **Example** (Getting the type AST)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaAST } from \"effect\"\n *\n * const schema = Schema.NumberFromString\n * const typeAst = SchemaAST.toType(schema.ast)\n * typeAst._tag // => \"Number\"\n * ```\n *\n * @see {@link toEncoded}\n * @see {@link flip}\n * @category transforming\n * @since 4.0.0\n */\nexport const toType = /*#__PURE__*/memoizeIdempotent(ast => {\n  if (ast.encoding) {\n    return toType(replaceEncoding(ast, undefined));\n  }\n  const out = ast;\n  const type = out.recur?.(toType) ?? out;\n  const encodingChecks = type.encodingChecks;\n  if (encodingChecks) {\n    const checks = type === ast ? encodingChecks : isArrays(type) || isObjects(type) || isDeclaration(type) && type.typeParameters.length > 0 ? extractStructuralChecks(encodingChecks) : undefined;\n    return modifyOwnPropertyDescriptors(type, d => {\n      d.encodingChecks.value = undefined;\n      d.checks.value = combineChecks(type.checks, checks);\n    });\n  }\n  return type;\n});\n/**\n * Returns the encoded (wire-format) AST by flipping and then stripping\n * encodings.\n *\n * **Details**\n *\n * Equivalent to `toType(flip(ast))`. This gives you the AST that describes\n * the shape of the serialized/encoded data.\n *\n * - Memoized: same input reference → same output reference.\n *\n * **Example** (Getting the encoded AST)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaAST } from \"effect\"\n *\n * const schema = Schema.NumberFromString\n * const encodedAst = SchemaAST.toEncoded(schema.ast)\n * encodedAst._tag // => \"String\"\n * ```\n *\n * @see {@link toType}\n * @see {@link flip}\n * @category transforming\n * @since 4.0.0\n */\nexport const toEncoded = /*#__PURE__*/memoizeIdempotent(ast => {\n  return toType(flip(ast));\n});\nfunction flipEncoding(ast, encoding) {\n  const links = encoding;\n  const len = links.length;\n  const last = links[len - 1];\n  const ls = [new Link(flip(replaceEncoding(ast, undefined)), links[0].transformation.flip())];\n  for (let i = 1; i < len; i++) {\n    ls.unshift(new Link(flip(links[i - 1].to), links[i].transformation.flip()));\n  }\n  const to = flip(last.to);\n  if (to.encoding) {\n    return replaceEncoding(to, [...to.encoding, ...ls]);\n  } else {\n    return replaceEncoding(to, ls);\n  }\n}\n/**\n * Swaps the decode and encode directions of an AST's {@link Encoding} chain.\n *\n * **Details**\n *\n * After flipping, what was decoding becomes encoding and vice versa. This is\n * the core operation behind `Schema.encode` — encoding a value is decoding\n * with a flipped SchemaAST.\n *\n * - Memoized: same input reference → same output reference.\n * - Recursively walks composite nodes.\n *\n * @see {@link toType}\n * @see {@link toEncoded}\n * @category transforming\n * @since 4.0.0\n */\nexport const flip = /*#__PURE__*/memoize(ast => {\n  if (ast.encoding) {\n    return flipEncoding(ast, ast.encoding);\n  }\n  const out = ast;\n  return out.flip?.(flip) ?? out.recur?.(flip) ?? out;\n});\n/** @internal */\nexport function containsUndefined(ast) {\n  switch (ast._tag) {\n    case \"Undefined\":\n      return true;\n    case \"Union\":\n      return ast.types.some(containsUndefined);\n    default:\n      return false;\n  }\n}\nfunction fromConst(ast, value) {\n  const succeed = value === 0 ? InternalParser.sameExit : InternalParser.succeed(value);\n  return (input, options) => {\n    if (input === InternalParser.missing) return InternalParser.missingExit;\n    if (input === value) return succeed;\n    return Effect.fail(new SchemaIssue.InvalidType(ast, input, options));\n  };\n}\nfunction fromRefinement(ast, refinement) {\n  return (input, options) => {\n    if (input === InternalParser.missing) return InternalParser.missingExit;\n    if (refinement(input)) return InternalParser.sameExit;\n    return Effect.fail(new SchemaIssue.InvalidType(ast, input, options));\n  };\n}\nfunction segmentTemplateLiteralParts(ast, input, options) {\n  const parts = ast.encodedParts;\n  const literals = ast.literals;\n  const inputLength = input.length;\n  for (let i = 0; i < literals.length; i++) {\n    const literal = literals[i];\n    if (literal && !input.includes(literal)) return undefined;\n  }\n  if (ast.suffixLengths[0] > inputLength) return undefined;\n  const out = new Array(parts.length);\n  let failures;\n  function go(i, pos) {\n    if (i === parts.length) return pos === inputLength;\n    if (failures?.has(i * (inputLength + 1) + pos)) return false;\n    const part = parts[i];\n    if (i === parts.length - 1) {\n      const s = input.slice(pos);\n      if (part.matchPart(s, options) !== undefined) {\n        out[i] = s;\n        return true;\n      }\n    } else if (part._tag === \"Literal\") {\n      const s = literals[i];\n      if (input.startsWith(s, pos) && go(i + 1, pos + s.length)) {\n        out[i] = s;\n        return true;\n      }\n    } else {\n      const maximumEnd = inputLength - ast.suffixLengths[i + 1];\n      // Splits preceding a literal only need to consider occurrences of that literal.\n      const anchor = literals[i + 1];\n      let end = anchor === undefined ? maximumEnd : input.lastIndexOf(anchor, maximumEnd);\n      while (end >= pos) {\n        const s = input.slice(pos, end);\n        if (part.matchPart(s, options) !== undefined && go(i + 1, end)) {\n          out[i] = s;\n          return true;\n        }\n        if (end === 0) break;\n        end = anchor === undefined ? end - 1 : input.lastIndexOf(anchor, end - 1);\n      }\n    }\n    failures ??= new Set();\n    failures.add(i * (inputLength + 1) + pos);\n    return false;\n  }\n  return go(0, 0) ? out : undefined;\n}\nconst parameterFromPropertyKey = /*#__PURE__*/applyToSelfOrLastLinkEncodingIdempotent(ast => {\n  switch (ast._tag) {\n    default:\n      return ast;\n    case \"Number\":\n      return ast.toCodecStringTree();\n    case \"Union\":\n      return ast.recur(parameterFromPropertyKey);\n  }\n});\n/** @internal */\nexport const parameterFromString = /*#__PURE__*/applyToSelfOrLastLinkEncodingIdempotent(ast => {\n  switch (ast._tag) {\n    default:\n      return ast;\n    case \"Symbol\":\n    case \"UniqueSymbol\":\n      return ast.toCodecStringTree();\n    case \"Union\":\n      return ast.recur(parameterFromString);\n  }\n});\nconst partFromString = /*#__PURE__*/applyToSelfOrLastLinkEncodingIdempotent(ast => {\n  switch (ast._tag) {\n    default:\n      return ast;\n    case \"Number\":\n    case \"Literal\":\n    case \"BigInt\":\n      return ast.toCodecStringTree();\n    case \"Union\":\n      return ast.recur(partFromString);\n  }\n});\n/**\n * any string, including newlines\n * @internal\n */\nexport const STRING_PATTERN = \"[\\\\s\\\\S]*?\";\nconst isStringFiniteRegExp = /*#__PURE__*/new globalThis.RegExp(`^${FINITE_PATTERN}$`);\nconst isStringNumberRegExp = /*#__PURE__*/new globalThis.RegExp(`^(?:${FINITE_PATTERN}|Infinity|-Infinity|NaN)$`);\n/** @internal */\nexport function isStringFinite(annotations) {\n  return isPattern(isStringFiniteRegExp, {\n    expected: \"a string representing a finite number\",\n    representation: {\n      id: \"effect/schema/isStringFinite\",\n      payload: null\n    },\n    toJsonSchema: () => ({\n      pattern: isStringFiniteRegExp.source\n    }),\n    ...annotations\n  });\n}\nconst finiteString = /*#__PURE__*/appendChecks(string, [/*#__PURE__*/isStringFinite()]);\nconst finiteToString = /*#__PURE__*/new Link(finiteString, SchemaTransformation.numberFromString);\nconst numberToString = /*#__PURE__*/new Link(/*#__PURE__*/new Union([finiteString, nonFiniteLiterals]), SchemaTransformation.numberFromString);\n/**\n * signed integer only (no leading \"+\" because TypeScript doesn't support it)\n */\nconst BIGINT_PATTERN = \"-?\\\\d+\";\nconst isStringBigIntRegExp = /*#__PURE__*/new globalThis.RegExp(`^${BIGINT_PATTERN}$`);\n/** @internal */\nexport function isStringBigInt(annotations) {\n  return isPattern(isStringBigIntRegExp, {\n    expected: \"a string representing a bigint\",\n    representation: {\n      id: \"effect/schema/isStringBigInt\",\n      payload: null\n    },\n    toJsonSchema: () => ({\n      pattern: isStringBigIntRegExp.source\n    }),\n    ...annotations\n  });\n}\n/** @internal */\nexport const bigIntString = /*#__PURE__*/appendChecks(string, [/*#__PURE__*/isStringBigInt({\n  expected: \"a string representing a bigint\"\n})]);\nconst bigIntToString = /*#__PURE__*/new Link(bigIntString, SchemaTransformation.bigintFromString);\nconst REGEXP_PATTERN = \"Symbol\\\\(([\\\\s\\\\S]*)\\\\)\";\nconst isStringSymbolRegExp = /*#__PURE__*/new globalThis.RegExp(`^${REGEXP_PATTERN}$`);\n/** @internal */\nexport const symbolString = /*#__PURE__*/appendChecks(string, [/*#__PURE__*/isStringSymbol()]);\n/**\n * to distinguish between Symbol and String, we need to add a check to the string keyword\n */\nconst symbolToString = /*#__PURE__*/new Link(symbolString, /*#__PURE__*/new SchemaTransformation.Transformation(/*#__PURE__*/SchemaGetter.transform(description => globalThis.Symbol.for(isStringSymbolRegExp.exec(description)[1])), /*#__PURE__*/SchemaGetter.transformEffect((sym, options) => {\n  const key = globalThis.Symbol.keyFor(sym);\n  if (key !== undefined) {\n    return Effect.succeed(globalThis.String(sym));\n  }\n  return Effect.fail(new SchemaIssue.Forbidden({\n    message: \"cannot serialize to string, Symbol is not registered\"\n  }, sym, options));\n})));\n/** @internal */\nexport function isStringSymbol(annotations) {\n  return isPattern(isStringSymbolRegExp, {\n    expected: \"a string representing a symbol\",\n    representation: {\n      id: \"effect/schema/isStringSymbol\",\n      payload: null\n    },\n    toJsonSchema: () => ({\n      pattern: isStringSymbolRegExp.source\n    }),\n    ...annotations\n  });\n}\n/** @internal */\nexport function collectIssues(checks, value, issues, ast, options) {\n  for (let i = 0; i < checks.length; i++) {\n    const check = checks[i];\n    if (check._tag === \"FilterGroup\") {\n      issues = collectIssues(check.checks, value, issues, ast, options);\n      if (issues && (options.errors !== \"all\" || issues[issues.length - 1].filter.aborted)) {\n        return issues;\n      }\n    } else {\n      const issue = check.run(value, ast, options);\n      if (issue) {\n        const filter = new SchemaIssue.Filter(check, issue, value, options);\n        if (issues) issues.push(filter);else issues = [filter];\n        if (options.errors !== \"all\" || check.aborted) {\n          return issues;\n        }\n      }\n    }\n  }\n  return issues;\n}\n/** @internal */\nexport function runChecks(checks, s) {\n  const issues = collectIssues(checks, s, undefined, unknown, {\n    errors: \"all\"\n  });\n  if (issues) {\n    const issue = new SchemaIssue.Composite(unknown, issues);\n    return Result.fail(issue);\n  }\n  return Result.succeed(s);\n}\n/** @internal */\nexport function getConstructorDescriptor(ast) {\n  if (!isDeclaration(ast)) return undefined;\n  const getDescriptor = ast.annotations?.[InternalAnnotations.CONSTRUCTOR_ANNOTATION_KEY];\n  return Predicate.isFunction(getDescriptor) ? getDescriptor(ast.typeParameters) : undefined;\n}\n/**\n * Returns all annotations from the AST node.\n *\n * **Details**\n *\n * If the node has {@link Checks}, returns annotations from the last check\n * (which is where user-supplied annotations end up after `.pipe(Schema.annotations(...))`).\n * Otherwise returns the node's `annotations` directly.\n *\n * **Example** (Reading annotations)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaAST } from \"effect\"\n *\n * const schema = Schema.String.annotate({ title: \"Name\" })\n * const annotations = SchemaAST.resolve(schema.ast)\n * annotations?.title // => \"Name\"\n * ```\n *\n * @see {@link resolveAt}\n * @see {@link resolveIdentifier}\n * @see {@link resolveTitle}\n * @see {@link resolveDescription}\n * @category annotations\n * @since 4.0.0\n */\nexport const resolve = InternalAnnotations.resolve;\n/**\n * Returns a single annotation value by key from the AST node.\n *\n * **Details**\n *\n * Like {@link resolve}, reads from the last check's annotations when checks\n * are present. Returns `undefined` if the key is not found.\n *\n * @see {@link resolve}\n * @category annotations\n * @since 4.0.0\n */\nexport const resolveAt = InternalAnnotations.resolveAt;\n/**\n * Returns the `identifier` annotation from the AST node, if set.\n *\n * **Details**\n *\n * The identifier is typically set by `Schema.annotations({ identifier: \"...\" })`\n * and is used for error messages and schema identification.\n *\n * @see {@link resolve}\n * @see {@link resolveTitle}\n * @category annotations\n * @since 4.0.0\n */\nexport const resolveIdentifier = InternalAnnotations.resolveIdentifier;\n/**\n * Returns the `title` annotation from the AST node, if set.\n *\n * @see {@link resolve}\n * @see {@link resolveIdentifier}\n * @see {@link resolveDescription}\n *\n * @category annotations\n * @since 4.0.0\n */\nexport const resolveTitle = InternalAnnotations.resolveTitle;\n/**\n * Returns the `description` annotation from the AST node, if set.\n *\n * @see {@link resolve}\n * @see {@link resolveTitle}\n * @see {@link resolveIdentifier}\n *\n * @category annotations\n * @since 4.0.0\n */\nexport const resolveDescription = InternalAnnotations.resolveDescription;\nfunction isJsonLeaf(u) {\n  return u === null || typeof u === \"string\" || typeof u === \"boolean\" || typeof u === \"number\" && globalThis.Number.isFinite(u);\n}\nfunction isStringTreeLeaf(u) {\n  return u === undefined || typeof u === \"string\";\n}\nfunction isTree(u, isLeaf) {\n  const cache = new WeakMap();\n  const stack = [];\n  outer: while (true) {\n    if (typeof u !== \"object\" || u === null) {\n      if (!isLeaf(u)) {\n        return false;\n      }\n    } else {\n      const value = u;\n      const cached = cache.get(value);\n      // `false` marks a node on the current path, while `true` marks a fully\n      // validated node that can be safely reused by a DAG.\n      if (cached === false) {\n        return false;\n      }\n      if (cached === undefined) {\n        const isArray = Array.isArray(value);\n        if (!isArray) {\n          const prototype = Object.getPrototypeOf(value);\n          // A plain object from another realm has a different Object.prototype,\n          // but that prototype still has a null prototype.\n          if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) {\n            return false;\n          }\n        }\n        cache.set(value, false);\n        stack.push({\n          value,\n          keys: isArray ? value.length : Object.keys(value),\n          index: 0\n        });\n      }\n    }\n    while (stack.length > 0) {\n      const frame = stack[stack.length - 1];\n      const keys = frame.keys;\n      if (typeof keys === \"number\") {\n        if (frame.index < keys) {\n          // A sparse slot is read as `undefined`; the leaf predicate determines\n          // whether that is valid for the current tree.\n          u = frame.value[frame.index++];\n          continue outer;\n        }\n      } else if (frame.index < keys.length) {\n        u = frame.value[keys[frame.index++]];\n        continue outer;\n      }\n      cache.set(frame.value, true);\n      stack.pop();\n    }\n    return true;\n  }\n}\n/**\n * Returns true if the value is a JSON value.\n *\n * When a cyclic reference is detected, returns false.\n *\n * @internal\n */\nexport function isJson(u) {\n  return isTree(u, isJsonLeaf);\n}\n/** @internal */\nexport const Json = /*#__PURE__*/new Declaration([], () => (input, ast, options) => isJson(input) ? InternalParser.sameExit : Effect.fail(new SchemaIssue.InvalidType(ast, input, options)), {\n  representation: {\n    id: \"effect/schema/Json\",\n    payload: null\n  },\n  expected: \"JSON value\",\n  toCodecJson: () => undefined,\n  toCodecStringTree: () => unknownToStringTree\n});\n/** @internal */\nexport const MutableJson = /*#__PURE__*/annotate(Json, {\n  representation: {\n    id: \"effect/schema/MutableJson\",\n    payload: null\n  }\n});\n/** @internal */\nexport const unknownToJson = /*#__PURE__*/new Link(Json, /*#__PURE__*/SchemaTransformation.passthrough());\n/** @internal */\nexport const objectKeywordToJson = /*#__PURE__*/new Link(/*#__PURE__*/new Union([/*#__PURE__*/new Arrays(false, [], [Json]), /*#__PURE__*/new Objects([], [/*#__PURE__*/new IndexSignature(string, Json)])]), /*#__PURE__*/SchemaTransformation.passthrough());\n/**\n * Returns true if the value is a StringTree value.\n *\n * When a cyclic reference is detected, returns false.\n *\n * @internal\n */\nexport function isStringTree(u) {\n  return isTree(u, isStringTreeLeaf);\n}\nconst StringTree = /*#__PURE__*/new Declaration([], () => (input, ast, options) => isStringTree(input) ? InternalParser.sameExit : Effect.fail(new SchemaIssue.InvalidType(ast, input, options)), {\n  expected: \"StringTree\",\n  toCodecStringTree: () => undefined\n});\n/** @internal */\nexport const unknownToStringTree = /*#__PURE__*/new Link(StringTree, /*#__PURE__*/SchemaTransformation.passthrough());\n//# sourceMappingURL=SchemaAST.js.map","/**\n * The `Brand` module adds compile-time names to ordinary TypeScript values so\n * structurally identical values cannot be mixed accidentally. A branded value\n * has the same runtime representation as its unbranded value; the extra\n * information lives in the type system unless you choose a validating\n * constructor.\n *\n * @since 2.0.0\n */\nimport * as Arr from \"./Array.js\";\nimport * as Option from \"./Option.js\";\nimport * as Result from \"./Result.js\";\nimport * as SchemaAST from \"./SchemaAST.js\";\nimport * as SchemaIssue from \"./SchemaIssue.js\";\nconst TypeId = \"~effect/Brand\";\n/**\n * Error returned when a branded type is constructed from an invalid value.\n *\n * **Details**\n *\n * The error wraps a `SchemaIssue.Issue`, renders `message` with the default\n * schema issue formatter, and formats as `BrandError(<message>)`.\n *\n * **Gotchas**\n *\n * `BrandError` is an error-like model with `_tag`, `name`, `message`, and\n * `toString`; it does not extend JavaScript `Error`.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class BrandError {\n  constructor(issue) {\n    this.issue = issue;\n  }\n  /**\n   * Discriminant used to identify brand construction failures.\n   *\n   * @since 4.0.0\n   */\n  _tag = \"BrandError\";\n  /**\n   * Error name used by tools that inspect JavaScript error-like objects.\n   *\n   * @since 4.0.0\n   */\n  name = \"BrandError\";\n  /**\n   * Schema issue describing why brand validation failed.\n   *\n   * @since 4.0.0\n   */\n  issue;\n  /**\n   * Human-readable rendering of the validation issue.\n   *\n   * @since 4.0.0\n   */\n  get message() {\n    return SchemaIssue.defaultFormatter(this.issue);\n  }\n  /**\n   * Formats the brand error together with its validation message.\n   *\n   * @since 4.0.0\n   */\n  toString() {\n    return `BrandError(${this.message})`;\n  }\n}\n/**\n * Returns a `Constructor` that **does not apply any runtime checks** and just\n * returns the provided value.\n *\n * **When to use**\n *\n * Use to create nominal types that allow distinguishing between two values\n * of the same type but with different meanings.\n *\n * @see {@link make} for constructing branded values with validation.\n * @see {@link check} for constructing branded values from schema checks.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport function nominal() {\n  return Object.assign(input => input, {\n    option: input => Option.some(input),\n    result: input => Result.succeed(input),\n    is: _ => true\n  });\n}\n/**\n * Returns a `Constructor` that can construct a branded type from an unbranded\n * value using the provided `filter` predicate as validation of the input data.\n *\n * **When to use**\n *\n * Use when you want validation while constructing the branded type.\n *\n * @see {@link nominal} for a brand constructor that performs no validation.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport function make(filter) {\n  return check(SchemaAST.makeFilter(filter));\n}\n/**\n * Creates a branded type `Constructor` from one or more schema checks.\n *\n * **When to use**\n *\n * Use when you need a branded type constructor that performs runtime validation\n * via schema checks.\n *\n * **Details**\n *\n * Calling the returned constructor validates the unbranded value and throws on\n * failure. Use the returned `option`, `result`, or `is` methods for\n * non-throwing validation.\n *\n * @see {@link nominal} for a brand constructor without runtime validation\n * @see {@link all} for combining multiple brand constructors\n * @category constructors\n * @since 4.0.0\n */\nexport function check(...checks) {\n  const result = input => {\n    return Result.mapError(SchemaAST.runChecks(checks, input), issue => new BrandError(issue));\n  };\n  return Object.assign(input => Result.getOrThrow(result(input)), {\n    option: input => Option.getSuccess(result(input)),\n    result,\n    is: input => Result.isSuccess(result(input)),\n    checks\n  });\n}\n/**\n * Combines one or more brand constructors to form a single branded type.\n *\n * **When to use**\n *\n * Use to require an input to satisfy every runtime check collected by the\n * provided brand constructors.\n *\n * **Details**\n *\n * If the provided constructors contain runtime checks, the combined\n * constructor succeeds only when all checks pass. If no runtime checks are\n * present, it behaves as a nominal constructor.\n *\n * @category combining\n * @since 2.0.0\n */\nexport function all(...brands) {\n  const checks = brands.flatMap(brand => brand.checks ?? []);\n  return Arr.isArrayNonEmpty(checks) ? check(...checks) : nominal();\n}\n//# sourceMappingURL=Brand.js.map","/**\n * Service boundary for starting and controlling child processes.\n *\n * `ChildProcessSpawner` is the service used by `ChildProcess` commands to start\n * operating-system processes. A spawner turns a command description into a\n * handle that can write to stdin, read stdout and stderr, wait for exit, kill\n * the process, and manage whether the process keeps its parent alive. Platform\n * backends implement this service, while most application code uses the higher\n * level `ChildProcess` module.\n *\n * @since 4.0.0\n */\nimport * as Brand from \"../../Brand.js\";\nimport * as Context from \"../../Context.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as Inspectable from \"../../Inspectable.js\";\nimport * as Stream from \"../../Stream.js\";\n/**\n * Constructs branded child process `ExitCode` values.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const ExitCode = /*#__PURE__*/Brand.nominal();\n/**\n * Constructs branded child process `ProcessId` values.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const ProcessId = /*#__PURE__*/Brand.nominal();\nconst HandleTypeId = \"~effect/process/ChildProcessSpawner/ChildProcessHandle\";\nconst HandleProto = {\n  [HandleTypeId]: HandleTypeId,\n  ...Inspectable.BaseProto,\n  toJSON() {\n    return {\n      _id: \"ChildProcessHandle\",\n      pid: this.pid\n    };\n  }\n};\n/**\n * Constructs a new `ChildProcessHandle`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeHandle = params => Object.setPrototypeOf({\n  ...params\n}, HandleProto);\n/**\n * Creates a `ChildProcessSpawner` service from a `spawn` function, deriving\n * helpers for exit codes and output collection from that implementation.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = spawn => {\n  const streamString = (command, options) => spawn(command).pipe(Effect.map(handle => Stream.decodeText(options?.includeStderr === true ? handle.all : handle.stdout)), Stream.unwrap);\n  const streamLines = (command, options) => Stream.splitLines(streamString(command, options));\n  return ChildProcessSpawner.of({\n    spawn,\n    exitCode: command => Effect.scoped(Effect.flatMap(spawn(command), handle => handle.exitCode)),\n    streamString,\n    streamLines,\n    lines: (command, options) => Stream.runCollect(streamLines(command, options)),\n    string: (command, options) => Stream.mkString(streamString(command, options))\n  });\n};\n/**\n * Service tag for child process spawning.\n *\n * @category services\n * @since 4.0.0\n */\nexport class ChildProcessSpawner extends /*#__PURE__*/Context.Service()(\"effect/process/ChildProcessSpawner\") {}\n//# sourceMappingURL=ChildProcessSpawner.js.map","/**\n * Describes child processes before they are started.\n *\n * A `Command` stores the executable, arguments, environment, standard streams,\n * working directory, and other process options. Commands can also be piped\n * together. A command is an `Effect`; running it asks the\n * `ChildProcessSpawner` service to start the process and returns a\n * `ChildProcessHandle`.\n *\n * @since 4.0.0\n */\nimport * as Context from \"../../Context.js\";\nimport * as Effectable from \"../../Effectable.js\";\nimport { dual } from \"../../Function.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport { ChildProcessSpawner } from \"./ChildProcessSpawner.js\";\nconst TypeId = \"~effect/process/ChildProcess\";\n// =============================================================================\n// Constructors\n// =============================================================================\nconst Proto = {\n  ... /*#__PURE__*/Effectable.Prototype({\n    label: \"Command\",\n    evaluate(fiber) {\n      return Context.getUnsafe(fiber.context, ChildProcessSpawner).spawn(this);\n    }\n  }),\n  [TypeId]: TypeId\n};\n/**\n * Checks whether a value is a `Command`.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isCommand = u => Predicate.hasProperty(u, TypeId);\n/**\n * Checks whether a command is a `StandardCommand`.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isStandardCommand = command => command._tag === \"StandardCommand\";\n/**\n * Checks whether a command is a `PipedCommand`.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isPipedCommand = command => command._tag === \"PipedCommand\";\nconst makeStandardCommand = (command, args, options) => Object.assign(Object.create(Proto), {\n  _tag: \"StandardCommand\",\n  command,\n  args,\n  options\n});\nconst makePipedCommand = (left, right, options = {}) => Object.assign(Object.create(Proto), {\n  _tag: \"PipedCommand\",\n  left,\n  right,\n  options\n});\n/**\n * Create a command from a template literal, options + template, or array form.\n *\n * **Details**\n *\n * This function supports three calling conventions:\n * 1. Template literal: `make\\`npm run build\\``\n * 2. Options + template literal: `make({ cwd: \"/app\" })\\`npm run build\\``\n * 3. Array form: `make(\"npm\", [\"run\", \"build\"], options?)`\n *\n * Template literals are not parsed until execution time, allowing parsing\n * errors to flow through Effect's error channel.\n *\n * **Example** (Creating commands)\n *\n * ```ts import.meta.vitest\n * import { ChildProcess } from \"effect/unstable/process\"\n *\n * // Template literal form\n * const cmd1 = ChildProcess.make`echo \"hello\"`\n *\n * // With options\n * const cmd2 = ChildProcess.make({ cwd: \"/tmp\" })`ls -la`\n *\n * // Array form\n * const cmd3 = ChildProcess.make(\"git\", [\"status\"])\n *\n * const result = [cmd1.command, cmd2.options.cwd, cmd3.args[0]] // => [\"echo\", \"/tmp\", \"status\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = function make(...args) {\n  // Template literal form: make`command`\n  if (isTemplateString(args[0])) {\n    const [templates, ...expressions] = args;\n    const tokens = parseTemplates(templates, expressions);\n    return makeStandardCommand(tokens[0] ?? \"\", tokens.slice(1), {});\n  }\n  // Options form: make({ cwd: \"/tmp\" })`command`\n  if (typeof args[0] === \"object\" && !Array.isArray(args[0]) && !isTemplateString(args[0])) {\n    const options = args[0];\n    return function (templates, ...expressions) {\n      const tokens = parseTemplates(templates, expressions);\n      return makeStandardCommand(tokens[0] ?? \"\", tokens.slice(1), options);\n    };\n  }\n  // Standard form without arguments: make(\"command\", options?)\n  if (typeof args[0] === \"string\" && !Array.isArray(args[1])) {\n    const [command, options = {}] = args;\n    return makeStandardCommand(command, [], options);\n  }\n  // Standard form with arguments: make(\"command\", [\"arg1\", \"arg2\"], options?)\n  const [command, cmdArgs = [], options = {}] = args;\n  return makeStandardCommand(command, cmdArgs, options);\n};\n/**\n * Pipes the output of one command to the input of another.\n *\n * **Details**\n *\n * By default, pipes `stdout` from the source to `stdin` of the destination.\n * Use the `options` parameter to customize which streams are connected.\n *\n * **Example** (Piping command output)\n *\n * ```ts import.meta.vitest\n * import { ChildProcess } from \"effect/unstable/process\"\n *\n * // Pipe stdout (default)\n * const pipeline1 = ChildProcess.make`cat file.txt`.pipe(\n *   ChildProcess.pipeTo(ChildProcess.make`grep pattern`)\n * )\n *\n * // Pipe stderr instead of stdout\n * const pipeline2 = ChildProcess.make`my-program`.pipe(\n *   ChildProcess.pipeTo(ChildProcess.make`grep error`, { from: \"stderr\" })\n * )\n *\n * // Pipe combined stdout and stderr\n * const pipeline3 = ChildProcess.make`my-program`.pipe(\n *   ChildProcess.pipeTo(ChildProcess.make`tee output.log`, { from: \"all\" })\n * )\n *\n * const result = [pipeline1._tag, pipeline2.options.from, pipeline3.options.from]\n * result // => [\"PipedCommand\", \"stderr\", \"all\"]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const pipeTo = /*#__PURE__*/dual(args => isCommand(args[0]) && isCommand(args[1]), (self, that, options) => makePipedCommand(self, that, options ?? {}));\n/**\n * Prepends another command to a command.\n *\n * **Details**\n *\n * For pipelines, only the leftmost command is prefixed.\n *\n * **Example** (Prefixing commands)\n *\n * ```ts import.meta.vitest\n * import { ChildProcess } from \"effect/unstable/process\"\n *\n * const command = ChildProcess.make`echo \"foo\"`\n *\n * const prefixed = command.pipe(\n *   ChildProcess.prefix`time`\n * )\n *\n * // now prefixed will execute `time echo \"foo\"`\n * const result = prefixed._tag === \"StandardCommand\" ? `${prefixed.command} ${prefixed.args[0]}` : prefixed._tag\n * result // => \"time echo\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const prefix = function prefix(...args) {\n  if (isCommand(args[0]) && args.length > 1) {\n    const [self, ...rest] = args;\n    const prefixSpec = parsePrefixArgs(rest);\n    return applyPrefix(self, prefixSpec);\n  }\n  const prefixSpec = parsePrefixArgs(args);\n  return self => applyPrefix(self, prefixSpec);\n};\nconst parsePrefixArgs = args => {\n  if (isTemplateString(args[0])) {\n    const [templates, ...expressions] = args;\n    const tokens = parseTemplates(templates, expressions);\n    return {\n      command: tokens[0] ?? \"\",\n      args: tokens.slice(1)\n    };\n  }\n  const [command, cmdArgs = []] = args;\n  return {\n    command,\n    args: cmdArgs\n  };\n};\nconst applyPrefix = (self, prefixSpec) => {\n  switch (self._tag) {\n    case \"StandardCommand\":\n      {\n        return makeStandardCommand(prefixSpec.command, [...prefixSpec.args, self.command, ...self.args], self.options);\n      }\n    case \"PipedCommand\":\n      {\n        return makePipedCommand(applyPrefix(self.left, prefixSpec), self.right, self.options);\n      }\n  }\n};\n/**\n * Sets the current working directory for a command.\n *\n * **Details**\n *\n * For pipelines, applies to each command in the pipeline.\n *\n * **Example** (Setting command working directories)\n *\n * ```ts import.meta.vitest\n * import { ChildProcess } from \"effect/unstable/process\"\n *\n * const cmd = ChildProcess.make`ls -la`.pipe(\n *   ChildProcess.setCwd(\"/tmp\")\n * )\n * const result = cmd._tag === \"StandardCommand\" && cmd.options.cwd // => \"/tmp\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const setCwd = /*#__PURE__*/dual(2, (self, cwd) => {\n  switch (self._tag) {\n    case \"StandardCommand\":\n      {\n        return makeStandardCommand(self.command, self.args, {\n          ...self.options,\n          cwd\n        });\n      }\n    case \"PipedCommand\":\n      {\n        return makePipedCommand(setCwd(self.left, cwd), setCwd(self.right, cwd), self.options);\n      }\n  }\n});\n/**\n * Adds environment variables to a command, merging them with any existing\n * command environment and overriding duplicate keys.\n *\n * **Details**\n *\n * For pipelines, applies to each command in the pipeline.\n *\n * **Example** (Setting command environment variables)\n *\n * ```ts import.meta.vitest\n * import { ChildProcess } from \"effect/unstable/process\"\n *\n * const cmd = ChildProcess.make`node script.js`.pipe(\n *   ChildProcess.setEnv({ NODE_ENV: \"test\" })\n * )\n * const result = cmd._tag === \"StandardCommand\" && cmd.options.env?.NODE_ENV // => \"test\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const setEnv = /*#__PURE__*/dual(2, (self, env) => {\n  switch (self._tag) {\n    case \"StandardCommand\":\n      {\n        const nextEnv = self.options.env === undefined ? env : {\n          ...self.options.env,\n          ...env\n        };\n        return makeStandardCommand(self.command, self.args, {\n          ...self.options,\n          env: nextEnv\n        });\n      }\n    case \"PipedCommand\":\n      {\n        return makePipedCommand(setEnv(self.left, env), setEnv(self.right, env), self.options);\n      }\n  }\n});\nconst isTemplateString = u => Array.isArray(u) && \"raw\" in u && Array.isArray(u.raw);\n// =============================================================================\n// Utilities\n// =============================================================================\n/**\n * Parses an fd name like \"fd3\" to its numeric index.\n * Returns undefined if the name is invalid.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const parseFdName = name => {\n  const match = /^fd(\\d+)$/.exec(name);\n  if (match === null) return undefined;\n  const fd = parseInt(match[1], 10);\n  return fd >= 3 ? fd : undefined;\n};\n/**\n * Create an fd name from its numeric index.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const fdName = fd => `fd${fd}`;\n// =============================================================================\n// Template Parsing\n// =============================================================================\nconst parseTemplates = (templates, expressions) => {\n  let tokens = [];\n  for (const [index, template] of templates.entries()) {\n    tokens = parseTemplate(templates, expressions, tokens, template, index);\n  }\n  return tokens;\n};\nconst parseTemplate = (templates, expressions, prevTokens, template, index) => {\n  const rawTemplate = templates.raw[index];\n  if (rawTemplate === undefined) {\n    throw new Error(`Invalid backslash sequence: ${templates.raw[index]}`);\n  }\n  const {\n    hasLeadingWhitespace,\n    hasTrailingWhitespace,\n    tokens\n  } = splitByWhitespaces(template, rawTemplate);\n  const nextTokens = concatTokens(prevTokens, tokens, hasLeadingWhitespace);\n  if (index === expressions.length) {\n    return nextTokens;\n  }\n  const expression = expressions[index];\n  const expressionTokens = Array.isArray(expression) ? expression.map(expression => parseExpression(expression)) : [parseExpression(expression)];\n  return concatTokens(nextTokens, expressionTokens, hasTrailingWhitespace);\n};\n/**\n * Convert valid expressions defined in a template string command (i.e. using\n * `${expression}` into strings.\n */\nconst parseExpression = expression => {\n  const type = typeof expression;\n  if (type === \"string\") {\n    return expression; // Return strings directly\n  }\n  return String(expression); // Convert numbers to strings\n};\nconst DELIMITERS = /*#__PURE__*/new Set([\" \", \"\\t\", \"\\r\", \"\\n\"]);\n/**\n * Number of characters in backslash escape sequences: \\0 \\xXX or \\uXXXX\n * \\cX is allowed in RegExps but not in strings\n * Octal sequences are not allowed in strict mode\n */\nconst ESCAPE_LENGTH = {\n  x: 3,\n  u: 5\n};\n/**\n * Splits a template string by whitespace while also properly handling escape\n * sequences.\n *\n * As an example, let's review the following valid commands:\n *\n * ```ts\n * ChildProcess.exec`echo foo\\n bar`\n * // We should run `[\"echo\", \"foo\\n\", \"bar\"]`\n *\n * ChildProcess.exec`echo foo\n *  bar`\n * // We should run `[\"echo\", \"foo\", \"bar]`\n * ```\n *\n * The problem is that when we evaluate the template string for both of the above\n * commands, we will end up with the same string \"echo foo\\n bar\".\n *\n * What we really want is to include the escaped character in the arguments for\n * the first command, since it was written explicitly by the user.\n *\n * This is why also having access to the raw template string is useful - in a\n * template string, there are two representations of the same string:\n * 1. `template`     - The processed string (escape sequences are evaluated).\n * 2. `template.raw` - The raw string (escape sequences are literal).\n */\nconst splitByWhitespaces = (template, rawTemplate) => {\n  if (rawTemplate.length === 0) {\n    return {\n      tokens: [],\n      hasLeadingWhitespace: false,\n      hasTrailingWhitespace: false\n    };\n  }\n  const hasLeadingWhitespace = DELIMITERS.has(rawTemplate[0]);\n  const tokens = [];\n  // Given that escape sequences will have different lengths in the template\n  // versus the raw template, we must maintain two indices:\n  // - One for the index into the template string\n  // - One for the index into the raw template string\n  // We also maintain the current cursor position for where we are in the template\n  let templateCursor = 0;\n  for (let templateIndex = 0, rawIndex = 0; templateIndex < template.length; templateIndex += 1, rawIndex += 1) {\n    // Use the raw template character to check for actual whitespace\n    const rawCharacter = rawTemplate[rawIndex];\n    if (DELIMITERS.has(rawCharacter)) {\n      // Whitespace found, extract token from template if necessary\n      if (templateCursor !== templateIndex) {\n        tokens.push(template.slice(templateCursor, templateIndex));\n      }\n      // Advance the template start index to the current position\n      templateCursor = templateIndex + 1;\n    } else if (rawCharacter === \"\\\\\") {\n      // Escape sequence detected, check the next raw character\n      const nextRawCharacter = rawTemplate[rawIndex + 1];\n      if (nextRawCharacter === \"\\n\") {\n        // Handle `\\` character followed by a newline (i.e. a line continuation) by:\n        // - Reversing the template index (backslash-newline is erased in template)\n        // - Advancing the raw template index past the line continuation\n        templateIndex -= 1;\n        rawIndex += 1;\n      } else if (nextRawCharacter === \"u\" && rawTemplate[rawIndex + 2] === \"{\") {\n        // Handle variable-length unicode escape sequences (i.e. `\\u{1F600}`) by:\n        // - Advancing the template index an extra code unit for astral code points\n        // - Advancing the raw template index past the unicode escape sequence\n        const end = rawTemplate.indexOf(\"}\", rawIndex + 3);\n        if (parseInt(rawTemplate.slice(rawIndex + 3, end), 16) > 0xffff) {\n          templateIndex += 1;\n        }\n        rawIndex = end;\n      } else {\n        // Advance raw template index past fixed-length escape sequences:\n        // - \\n    → 2 chars (backslash + n)\n        // - \\t    → 2 chars (backslash + t)\n        // - \\xHH  → 4 chars (backslash + x + H + H)\n        // - \\uHHHH → 6 chars (backslash + u + H + H + H + H)\n        rawIndex += ESCAPE_LENGTH[nextRawCharacter] ?? 1;\n      }\n    }\n  }\n  // Trailing whitespace only exists if the template cursor is equivalent to the\n  // length of the template\n  const hasTrailingWhitespace = templateCursor === template.length;\n  // If we did not end with trailing whitespace, ensure the final token is added\n  if (!hasTrailingWhitespace) {\n    tokens.push(template.slice(templateCursor));\n  }\n  return {\n    tokens,\n    hasLeadingWhitespace,\n    hasTrailingWhitespace\n  };\n};\n/**\n * Concatenates two separate sets of string tokens together.\n *\n * If either set is empty or `isSeparated=false`, the last element of `prevTokens`\n * and the first element of `nextTokens` will be joined into a single token.\n */\nconst concatTokens = (prevTokens, nextTokens, isSeparated) => isSeparated || prevTokens.length === 0 || nextTokens.length === 0\n// Keep the previous and next tokens separate from one another\n? [...prevTokens, ...nextTokens]\n// Join the last token from the previous set and the first token from the next set\n: [...prevTokens.slice(0, -1), `${prevTokens.at(-1)}${nextTokens.at(0)}`, ...nextTokens.slice(1)];\n//# sourceMappingURL=ChildProcess.js.map","export const buildSpawnOptions = (options, base, platform) => {\n  const detached = options.detached ?? platform !== \"win32\";\n  return {\n    ...base,\n    detached,\n    shell: options.shell,\n    windowsHide: options.windowsHide ?? !detached\n  };\n};\n//# sourceMappingURL=nodeChildProcessSpawner.js.map","import * as PlatformError from \"effect/PlatformError\";\n/** @internal */\nexport const handleErrnoException = (module, method) => (err, [path]) => {\n  let reason = \"Unknown\";\n  switch (err.code) {\n    case \"ENOENT\":\n      reason = \"NotFound\";\n      break;\n    case \"EACCES\":\n      reason = \"PermissionDenied\";\n      break;\n    case \"EEXIST\":\n      reason = \"AlreadyExists\";\n      break;\n    case \"EISDIR\":\n      reason = \"BadResource\";\n      break;\n    case \"ENOTDIR\":\n      reason = \"BadResource\";\n      break;\n    case \"EBUSY\":\n      reason = \"Busy\";\n      break;\n    case \"ELOOP\":\n      reason = \"BadResource\";\n      break;\n  }\n  return PlatformError.systemError({\n    _tag: reason,\n    module,\n    method,\n    pathOrDescriptor: path,\n    syscall: err.syscall,\n    cause: err\n  });\n};\n//# sourceMappingURL=utils.js.map","import * as Cause from \"effect/Cause\";\nimport * as Channel from \"effect/Channel\";\nimport * as Effect from \"effect/Effect\";\nimport { identity } from \"effect/Function\";\nimport * as Pull from \"effect/Pull\";\nimport * as Sink from \"effect/Sink\";\n/**\n * Creates a `Sink` that writes chunks to a Node writable stream, respecting\n * backpressure, mapping writable errors with `onError`, and ending the stream\n * on completion unless `endOnDone` is `false`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromWritable = options => Sink.fromChannel(Channel.mapDone(fromWritableChannel(options), _ => [_]));\n/**\n * Creates a `Channel` that pulls chunks from upstream and writes them to a\n * Node writable stream, respecting backpressure and optionally ending the\n * writable when upstream is done.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromWritableChannel = options => Channel.fromTransform(pull => {\n  const writable = options.evaluate();\n  return Effect.succeed(pullIntoWritable({\n    ...options,\n    writable,\n    pull\n  }));\n});\n/**\n * Writes Effect chunks into a Node writable stream.\n *\n * **When to use**\n *\n * Use to implement custom Node stream adapters that already have an upstream\n * pull and need direct control over a writable stream.\n *\n * **Details**\n *\n * The loop waits for `drain` when needed, fails on writable errors, and ends\n * the writable on upstream completion unless `endOnDone` is `false`.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const pullIntoWritable = options => options.pull.pipe(Effect.flatMap(chunk => {\n  let i = 0;\n  return Effect.callback(resume => {\n    let cancelled = false;\n    const loop = () => {\n      for (; i < chunk.length;) {\n        if (cancelled) {\n          return;\n        }\n        const success = options.writable.write(chunk[i++], options.encoding);\n        if (!success) {\n          if (!cancelled) {\n            options.writable.once(\"drain\", loop);\n          }\n          return;\n        }\n      }\n      if (!cancelled) {\n        resume(Effect.void);\n      }\n    };\n    loop();\n    return Effect.sync(() => {\n      cancelled = true;\n      options.writable.off(\"drain\", loop);\n    });\n  });\n}), Effect.forever({\n  disableYield: true\n}), options.endOnDone !== false ? Pull.catchDone(_ => {\n  if (\"closed\" in options.writable && options.writable.closed) {\n    return Cause.done(_);\n  }\n  return Effect.callback(resume => {\n    const onFinish = () => resume(Cause.done(_));\n    options.writable.once(\"finish\", onFinish);\n    options.writable.end();\n    return Effect.sync(() => {\n      options.writable.off(\"finish\", onFinish);\n    });\n  });\n}) : identity, Effect.raceFirst(Effect.callback(resume => {\n  const onError = error => resume(Effect.fail(options.onError(error)));\n  options.writable.once(\"error\", onError);\n  return Effect.sync(() => {\n    options.writable.off(\"error\", onError);\n  });\n})));\n//# sourceMappingURL=NodeSink.js.map","/**\n * Adapters between Node streams and Effect streams, channels, and readables.\n *\n * This module is the stream boundary for Node APIs. It wraps `Readable` and\n * `Duplex` values as Effect `Stream`s and `Channel`s, pipes Effect streams\n * through Node duplex streams, exposes an Effect `Stream` back to Node as a\n * `Readable`, and collects readable payloads into strings, array buffers, or\n * `Uint8Array`s with optional byte limits.\n *\n * @since 4.0.0\n */\nimport * as Arr from \"effect/Array\";\nimport * as ByteSize from \"effect/ByteSize\";\nimport * as Cause from \"effect/Cause\";\nimport * as Channel from \"effect/Channel\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Fiber from \"effect/Fiber\";\nimport { dual } from \"effect/Function\";\nimport * as Latch from \"effect/Latch\";\nimport * as MutableRef from \"effect/MutableRef\";\nimport * as Pull from \"effect/Pull\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport { Readable } from \"node:stream\";\nimport { pullIntoWritable } from \"./NodeSink.js\";\n/**\n * Converts a Node readable stream into an Effect `Stream`, reading chunks with\n * an optional chunk size, mapping stream errors with `onError`, and destroying\n * the readable on completion unless `closeOnDone` is `false`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromReadable = options => Stream.fromChannel(fromReadableChannel(options));\n/**\n * Creates a `Channel` that pulls chunks from a Node readable stream, mapping\n * errors with `onError` and destroying the readable on completion unless\n * `closeOnDone` is `false`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromReadableChannel = options => Channel.fromTransform((_, scope) => readableToPullUnsafe({\n  scope,\n  readable: options.evaluate(),\n  onError: options.onError ?? defaultOnError,\n  chunkSize: options.chunkSize,\n  closeOnDone: options.closeOnDone\n}));\n/**\n * Creates a `Channel` over a Node `Duplex`, writing upstream chunks with\n * backpressure while emitting chunks read from the duplex and optionally ending\n * the writable side when upstream completes.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromDuplex = options => Channel.fromTransform((upstream, scope) => {\n  const duplex = options.evaluate();\n  const exit = MutableRef.make(undefined);\n  const latch = Latch.makeUnsafe(false);\n  return pullIntoWritable({\n    pull: upstream,\n    writable: duplex,\n    onError: options.onError ?? defaultOnError,\n    endOnDone: options.endOnDone,\n    encoding: options.encoding\n  }).pipe(Effect.catchCause(cause => {\n    if (Pull.isDoneCause(cause)) return Effect.void;\n    exit.current = Exit.failCause(cause);\n    latch.openUnsafe();\n    return Effect.void;\n  }), Effect.forkIn(scope), Effect.flatMap(() => readableToPullUnsafe({\n    scope,\n    exit,\n    latch,\n    readable: duplex,\n    onError: options.onError ?? defaultOnError,\n    chunkSize: options.chunkSize\n  })));\n});\n/**\n * Pipes an Effect `Stream` through a Node `Duplex`, writing the stream's\n * chunks to the duplex and emitting chunks read back from it.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const pipeThroughDuplex = /*#__PURE__*/dual(2, (self, options) => Stream.pipeThroughChannelOrFail(self, fromDuplex(options)));\n/**\n * Pipes a stream of strings or bytes through a Node `Duplex` using default\n * options and `Cause.UnknownError` for stream failures.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const pipeThroughSimple = /*#__PURE__*/dual(2, (self, duplex) => pipeThroughDuplex(self, {\n  evaluate: duplex\n}));\n/**\n * Converts an Effect `Stream` into a Node `Readable`, using the caller's\n * Effect context to run the stream and destroying the readable if the stream\n * fails.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toReadable = stream => Effect.map(Effect.context(), context => new StreamAdapter(context, stream));\n/**\n * Converts a service-free Effect `Stream` into a Node `Readable` using an\n * empty Effect context.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toReadableNever = stream => new StreamAdapter(Context.empty(), stream);\n/**\n * Consumes a Node readable stream into a string using the selected encoding,\n * failing through `onError` on stream errors or when `maxBytes` is exceeded\n * and destroying the stream on interruption or failure.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toString = (readable, options) => {\n  const maxBytesNumber = toMaxBytes(options?.maxBytes);\n  const onError = options?.onError ?? defaultOnError;\n  const encoding = options?.encoding ?? \"utf8\";\n  return Effect.callback(resume => {\n    const stream = readable();\n    stream.setEncoding(encoding);\n    stream.once(\"error\", err => {\n      if (\"closed\" in stream && !stream.closed) {\n        stream.destroy();\n      }\n      resume(Effect.fail(onError(err)));\n    });\n    let string = \"\";\n    let bytes = 0;\n    stream.once(\"end\", () => {\n      resume(Effect.succeed(string));\n    });\n    stream.on(\"data\", chunk => {\n      string += chunk;\n      bytes += Buffer.byteLength(chunk);\n      if (maxBytesNumber !== undefined && bytes > maxBytesNumber) {\n        if (\"closed\" in stream && !stream.closed) {\n          stream.destroy();\n        }\n        resume(Effect.fail(onError(new Error(\"maxBytes exceeded\"))));\n      }\n    });\n    return Effect.sync(() => {\n      if (\"closed\" in stream && !stream.closed) {\n        stream.destroy();\n      }\n    });\n  });\n};\n/**\n * Consumes a Node readable stream into an `ArrayBuffer`, failing through\n * `onError` on stream errors or when `maxBytes` is exceeded and destroying the\n * stream on interruption or failure.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toArrayBuffer = (readable, options) => {\n  const maxBytesNumber = toMaxBytes(options?.maxBytes);\n  const onError = options?.onError ?? defaultOnError;\n  return Effect.callback(resume => {\n    const stream = readable();\n    const buffers = [];\n    let bytes = 0;\n    stream.once(\"error\", err => {\n      if (\"closed\" in stream && !stream.closed) {\n        stream.destroy();\n      }\n      resume(Effect.fail(onError(err)));\n    });\n    stream.once(\"end\", () => {\n      const buffer = buffers.length === 1 ? buffers[0] : Buffer.concat(buffers);\n      if (buffer.byteOffset === 0 && buffer.buffer.byteLength === buffer.byteLength) {\n        return resume(Effect.succeed(buffer.buffer));\n      }\n      resume(Effect.succeed(buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength)));\n    });\n    stream.on(\"data\", chunk => {\n      buffers.push(chunk);\n      bytes += chunk.length;\n      if (maxBytesNumber !== undefined && bytes > maxBytesNumber) {\n        if (\"closed\" in stream && !stream.closed) {\n          stream.destroy();\n        }\n        resume(Effect.fail(onError(new Error(\"maxBytes exceeded\"))));\n      }\n    });\n    return Effect.sync(() => {\n      if (\"closed\" in stream && !stream.closed) {\n        stream.destroy();\n      }\n    });\n  });\n};\n/**\n * Consumes a Node readable stream into a `Uint8Array`, using the same error\n * mapping and `maxBytes` handling as `toArrayBuffer`.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toUint8Array = (readable, options) => Effect.map(toArrayBuffer(readable, options), buffer => new Uint8Array(buffer));\n// ----------------------------------------------------------------------------\n// internal\n// ----------------------------------------------------------------------------\nconst readableToPullUnsafe = options => {\n  const readable = options.readable;\n  const closeOnDone = options.closeOnDone ?? true;\n  const exit = options.exit ?? MutableRef.make(undefined);\n  const latch = options.latch ?? Latch.makeUnsafe(false);\n  function onReadable() {\n    latch.openUnsafe();\n  }\n  function onError(error) {\n    exit.current = Exit.fail(options.onError(error));\n    latch.openUnsafe();\n  }\n  function onEnd() {\n    exit.current = Exit.fail(Cause.Done());\n    latch.openUnsafe();\n  }\n  readable.on(\"readable\", onReadable);\n  readable.once(\"error\", onError);\n  readable.once(\"end\", onEnd);\n  const pull = Effect.suspend(function loop() {\n    let item = options.readable.read(options.chunkSize);\n    if (item === null) {\n      if (exit.current) {\n        return exit.current;\n      }\n      if (readable.readableEnded) {\n        return Effect.fail(Cause.Done());\n      }\n      latch.closeUnsafe();\n      return Effect.flatMap(latch.await, loop);\n    }\n    const chunk = Arr.of(item);\n    while (true) {\n      item = options.readable.read(options.chunkSize);\n      if (item === null) break;\n      chunk.push(item);\n    }\n    return Effect.succeed(chunk);\n  });\n  return Effect.as(Scope.addFinalizer(options.scope, Effect.sync(() => {\n    readable.off(\"readable\", onReadable);\n    readable.off(\"error\", onError);\n    readable.off(\"end\", onEnd);\n    if (closeOnDone && \"closed\" in options.readable && !options.readable.closed) {\n      options.readable.destroy();\n    }\n  })), pull);\n};\nclass StreamAdapter extends Readable {\n  readLatch;\n  fiber = undefined;\n  constructor(context, stream) {\n    super({});\n    this.readLatch = Latch.makeUnsafe(false);\n    this.fiber = Stream.runForEachArray(stream, chunk => this.readLatch.whenOpen(Effect.sync(() => {\n      this.readLatch.closeUnsafe();\n      for (let i = 0; i < chunk.length; i++) {\n        const item = chunk[i];\n        if (typeof item === \"string\") {\n          this.push(item, \"utf8\");\n        } else {\n          this.push(item);\n        }\n      }\n    }))).pipe(this.readLatch.whenOpen, Effect.provideContext(context), Effect.runFork);\n    this.fiber.addObserver(exit => {\n      this.fiber = undefined;\n      if (Exit.isSuccess(exit)) {\n        this.push(null);\n      } else {\n        this.destroy(Cause.squash(exit.cause));\n      }\n    });\n  }\n  _read(_size) {\n    this.readLatch.openUnsafe();\n  }\n  _destroy(error, callback) {\n    if (!this.fiber) {\n      return callback(error);\n    }\n    Effect.runFork(Fiber.interrupt(this.fiber)).addObserver(exit => {\n      callback(exit._tag === \"Failure\" ? Cause.squash(exit.cause) : error);\n    });\n  }\n}\nconst defaultOnError = error => new Cause.UnknownError(error);\nconst toMaxBytes = maxBytes => maxBytes === undefined || maxBytes === Infinity ? undefined : Number(ByteSize.fromInputUnsafe(maxBytes));\n//# sourceMappingURL=NodeStream.js.map","import * as Deferred from \"effect/Deferred\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Path from \"effect/Path\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Sink from \"effect/Sink\";\nimport * as Stream from \"effect/Stream\";\nimport * as ChildProcess from \"effect/unstable/process/ChildProcess\";\nimport { ChildProcessSpawner, ExitCode, make as makeSpawner, makeHandle, ProcessId } from \"effect/unstable/process/ChildProcessSpawner\";\nimport * as NodeChildProcess from \"node:child_process\";\nimport { PassThrough } from \"node:stream\";\nimport { buildSpawnOptions } from \"./internal/nodeChildProcessSpawner.js\";\nimport { handleErrnoException } from \"./internal/utils.js\";\nimport * as NodeSink from \"./NodeSink.js\";\nimport * as NodeStream from \"./NodeStream.js\";\nconst toError = error => error instanceof globalThis.Error ? error : new globalThis.Error(String(error));\nconst toPlatformError = (method, error, command) => {\n  const {\n    commands\n  } = flattenCommand(command);\n  const commandStr = commands.reduce((acc, curr) => {\n    const cmd = `${curr.command} ${curr.args.join(\" \")}`;\n    return acc.length === 0 ? cmd : `${acc} | ${cmd}`;\n  }, \"\");\n  return handleErrnoException(\"ChildProcess\", method)(error, [commandStr]);\n};\nconst processGroupGraceMillis = 1_000;\nconst processGroupPollIntervalMillis = 10;\n/** The leader has not exited, or a member of its process group still exists. */\nconst isProcessAlive = (childProcess, exitSignal) => {\n  if (!Deferred.isDoneUnsafe(exitSignal)) {\n    return true;\n  }\n  if (globalThis.process.platform === \"win32\") {\n    return false;\n  }\n  try {\n    globalThis.process.kill(-childProcess.pid, 0);\n    return true;\n  } catch {\n    return false;\n  }\n};\nconst taskkill = (childProcess, onExit = () => {}) => NodeChildProcess.execFile(\"taskkill\", [\"/pid\", String(childProcess.pid), \"/T\", \"/F\"], {\n  windowsHide: true\n}, onExit);\nconst make = /*#__PURE__*/Effect.gen(function* () {\n  const fs = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const resolveWorkingDirectory = Effect.fnUntraced(function* (options) {\n    if (Predicate.isUndefined(options.cwd)) return undefined;\n    // Validate that the specified directory is accessible\n    yield* fs.access(options.cwd);\n    return path.resolve(options.cwd);\n  });\n  const resolveEnvironment = options => {\n    return options.extendEnv ? {\n      ...globalThis.process.env,\n      ...options.env\n    } : options.env;\n  };\n  const inputToStdioOption = input => Stream.isStream(input) ? \"pipe\" : input;\n  const outputToStdioOption = input => Sink.isSink(input) ? \"pipe\" : input;\n  const resolveStdinOption = options => {\n    const defaultConfig = {\n      stream: \"pipe\",\n      encoding: \"utf-8\",\n      endOnDone: true\n    };\n    if (Predicate.isUndefined(options.stdin)) {\n      return defaultConfig;\n    }\n    if (typeof options.stdin === \"string\") {\n      return {\n        ...defaultConfig,\n        stream: options.stdin\n      };\n    }\n    if (Stream.isStream(options.stdin)) {\n      return {\n        ...defaultConfig,\n        stream: options.stdin\n      };\n    }\n    return {\n      stream: options.stdin.stream,\n      encoding: options.stdin.encoding ?? defaultConfig.encoding,\n      endOnDone: options.stdin.endOnDone ?? defaultConfig.endOnDone\n    };\n  };\n  const resolveOutputOption = (options, streamName) => {\n    const option = options[streamName];\n    if (Predicate.isUndefined(option)) {\n      return {\n        stream: \"pipe\"\n      };\n    }\n    if (typeof option === \"string\") {\n      return {\n        stream: option\n      };\n    }\n    if (Sink.isSink(option)) {\n      return {\n        stream: option\n      };\n    }\n    return {\n      stream: option.stream\n    };\n  };\n  const resolveAdditionalFds = options => {\n    if (Predicate.isUndefined(options.additionalFds)) {\n      return [];\n    }\n    const result = [];\n    for (const [name, config] of Object.entries(options.additionalFds)) {\n      const fd = ChildProcess.parseFdName(name);\n      if (Predicate.isNotUndefined(fd)) {\n        result.push({\n          fd,\n          config\n        });\n      }\n    }\n    // Sort by fd number to ensure correct ordering\n    return result.sort((a, b) => a.fd - b.fd);\n  };\n  const buildStdioArray = (stdinConfig, stdoutConfig, stderrConfig, additionalFds) => {\n    const stdio = [inputToStdioOption(stdinConfig.stream), outputToStdioOption(stdoutConfig.stream), outputToStdioOption(stderrConfig.stream)];\n    if (additionalFds.length === 0) {\n      return stdio;\n    }\n    // Find the maximum fd number to size the array correctly\n    const maxFd = additionalFds.reduce((max, {\n      fd\n    }) => Math.max(max, fd), 2);\n    // Fill gaps with \"ignore\"\n    for (let i = 3; i <= maxFd; i++) {\n      stdio[i] = \"ignore\";\n    }\n    // Set up additional fds as \"pipe\"\n    for (const {\n      fd\n    } of additionalFds) {\n      stdio[fd] = \"pipe\";\n    }\n    return stdio;\n  };\n  const setupAdditionalFds = Effect.fnUntraced(function* (command, childProcess, additionalFds) {\n    if (additionalFds.length === 0) {\n      return {\n        getInputFd: () => Sink.drain,\n        getOutputFd: () => Stream.empty\n      };\n    }\n    const inputSinks = new Map();\n    const outputStreams = new Map();\n    for (const {\n      config,\n      fd\n    } of additionalFds) {\n      const nodeStream = childProcess.stdio[fd];\n      switch (config.type) {\n        case \"input\":\n          {\n            // Create a sink to write to for input file descriptors\n            let sink = Sink.drain;\n            if (nodeStream && \"write\" in nodeStream) {\n              sink = NodeSink.fromWritable({\n                evaluate: () => nodeStream,\n                onError: error => toPlatformError(`fromWritable(fd${fd})`, toError(error), command)\n              });\n            }\n            // If user provided a stream, pipe it into the sink\n            if (config.stream) {\n              yield* Effect.forkScoped(Stream.run(config.stream, sink));\n            }\n            inputSinks.set(fd, sink);\n            break;\n          }\n        case \"output\":\n          {\n            // Create a stream to read from for output file descriptors\n            let stream = Stream.empty;\n            if (nodeStream && \"read\" in nodeStream) {\n              const passThrough = new PassThrough();\n              nodeStream.on(\"error\", error => passThrough.destroy(error));\n              nodeStream.pipe(passThrough);\n              stream = NodeStream.fromReadable({\n                evaluate: () => passThrough,\n                onError: error => toPlatformError(`fromReadable(fd${fd})`, toError(error), command)\n              });\n            }\n            // If user provided a sink, transduce the stream through it\n            if (config.sink) {\n              stream = Stream.transduce(stream, config.sink);\n            }\n            outputStreams.set(fd, stream);\n            break;\n          }\n      }\n    }\n    return {\n      getInputFd: fd => inputSinks.get(fd) ?? Sink.drain,\n      getOutputFd: fd => outputStreams.get(fd) ?? Stream.empty\n    };\n  });\n  const setupChildStdin = (command, childProcess, config) => Effect.suspend(() => {\n    // If the child process has a standard input stream, connect it to the\n    // sink that will attached to the process handle\n    let sink = Sink.drain;\n    if (Predicate.isNotNull(childProcess.stdin)) {\n      sink = NodeSink.fromWritable({\n        evaluate: () => childProcess.stdin,\n        onError: error => toPlatformError(\"fromWritable(stdin)\", toError(error), command),\n        endOnDone: config.endOnDone,\n        encoding: config.encoding\n      });\n    }\n    // If the user provided a `Stream`, run it into the stdin sink\n    if (Stream.isStream(config.stream)) {\n      return Effect.as(Effect.forkScoped(Stream.run(config.stream, sink)), sink);\n    }\n    return Effect.succeed(sink);\n  });\n  const setupChildOutputStreams = (command, childProcess, stdoutConfig, stderrConfig) => {\n    let stdout = childProcess.stdout ? (() => {\n      const passThrough = new PassThrough();\n      childProcess.stdout.on(\"error\", error => passThrough.destroy(error));\n      childProcess.stdout.pipe(passThrough);\n      return NodeStream.fromReadable({\n        evaluate: () => passThrough,\n        onError: error => toPlatformError(\"fromReadable(stdout)\", toError(error), command)\n      });\n    })() : Stream.empty;\n    let stderr = childProcess.stderr ? (() => {\n      const passThrough = new PassThrough();\n      childProcess.stderr.on(\"error\", error => passThrough.destroy(error));\n      childProcess.stderr.pipe(passThrough);\n      return NodeStream.fromReadable({\n        evaluate: () => passThrough,\n        onError: error => toPlatformError(\"fromReadable(stderr)\", toError(error), command)\n      });\n    })() : Stream.empty;\n    if (Sink.isSink(stdoutConfig.stream)) {\n      stdout = Stream.transduce(stdout, stdoutConfig.stream);\n    }\n    if (Sink.isSink(stderrConfig.stream)) {\n      stderr = Stream.transduce(stderr, stderrConfig.stream);\n    }\n    const all = Stream.merge(stdout, stderr);\n    return {\n      stdout,\n      stderr,\n      all\n    };\n  };\n  const spawn = (command, spawnOptions) => Effect.callback(resume => {\n    const deferred = Deferred.makeUnsafe();\n    const handle = NodeChildProcess.spawn(command.command, command.args, spawnOptions);\n    handle.on(\"error\", error => {\n      resume(Effect.fail(toPlatformError(\"spawn\", error, command)));\n    });\n    handle.on(\"exit\", (...args) => {\n      Deferred.doneUnsafe(deferred, Exit.succeed(args));\n    });\n    handle.on(\"spawn\", () => {\n      resume(Effect.succeed([handle, deferred]));\n    });\n    return Effect.sync(() => {\n      handle.kill(\"SIGTERM\");\n    });\n  });\n  const killProcessGroup = (command, childProcess, signal) => {\n    if (globalThis.process.platform === \"win32\") {\n      return Effect.callback(resume => {\n        taskkill(childProcess, error => {\n          if (error) {\n            resume(Effect.fail(toPlatformError(\"kill\", toError(error), command)));\n          } else {\n            resume(Effect.void);\n          }\n        });\n      });\n    }\n    return Effect.try({\n      try: () => {\n        globalThis.process.kill(-childProcess.pid, signal);\n      },\n      catch: error => toPlatformError(\"kill\", toError(error), command)\n    });\n  };\n  const killProcessGroupOnExit = (childProcess, signal) => {\n    if (globalThis.process.platform === \"win32\") {\n      // ignore errors during best-effort cleanup\n      taskkill(childProcess);\n      return;\n    }\n    try {\n      globalThis.process.kill(-childProcess.pid, signal);\n    } catch {\n      // ignore errors during best-effort cleanup\n    }\n  };\n  const killProcess = (command, childProcess, signal) => Effect.suspend(() => {\n    const killed = childProcess.kill(signal);\n    if (!killed) {\n      const error = new globalThis.Error(\"Failed to kill child process\");\n      return Effect.fail(toPlatformError(\"kill\", error, command));\n    }\n    return Effect.void;\n  });\n  /** Waits for the leader and its process group, bounded by native time. */\n  const awaitProcessExit = (childProcess, exitSignal, timeoutMillis) => Effect.callback(resume => {\n    const deadline = Date.now() + timeoutMillis;\n    let timer;\n    const stop = () => {\n      clearTimeout(timer);\n      childProcess.removeListener(\"exit\", poll);\n    };\n    const poll = () => {\n      clearTimeout(timer);\n      if (Date.now() >= deadline || !isProcessAlive(childProcess, exitSignal)) {\n        stop();\n        resume(Effect.void);\n        return;\n      }\n      timer = setTimeout(poll, processGroupPollIntervalMillis);\n    };\n    // spawn's exit listener completes exitSignal before this listener runs\n    childProcess.on(\"exit\", poll);\n    poll();\n    return Effect.sync(stop);\n  });\n  const terminateProcessGroup = Effect.fnUntraced(function* (command, childProcess, exitSignal, options) {\n    const signalGroup = signal => killProcessGroup(command, childProcess, signal).pipe(Effect.catch(() => killProcess(command, childProcess, signal)));\n    yield* signalGroup(options?.killSignal ?? \"SIGTERM\");\n    if (Predicate.isUndefined(options?.forceKillAfter)) {\n      yield* awaitProcessExit(childProcess, exitSignal, processGroupGraceMillis);\n    } else {\n      yield* awaitProcessExit(childProcess, exitSignal, Duration.toMillis(options.forceKillAfter));\n      if (isProcessAlive(childProcess, exitSignal)) {\n        yield* signalGroup(\"SIGKILL\");\n        yield* awaitProcessExit(childProcess, exitSignal, processGroupGraceMillis);\n      }\n    }\n    yield* Deferred.await(exitSignal);\n  });\n  /**\n   * Get the appropriate source stream from a process handle based on the\n   * `from` pipe option.\n   */\n  const getSourceStream = (handle, from) => {\n    const fromOption = from ?? \"stdout\";\n    switch (fromOption) {\n      case \"stdout\":\n        return handle.stdout;\n      case \"stderr\":\n        return handle.stderr;\n      case \"all\":\n        return handle.all;\n      default:\n        {\n          // Handle fd3, fd4, etc.\n          const fd = ChildProcess.parseFdName(fromOption);\n          if (Predicate.isNotUndefined(fd)) {\n            return handle.getOutputFd(fd);\n          }\n          // Fallback to stdout for invalid fd names\n          return handle.stdout;\n        }\n    }\n  };\n  const spawnCommand = Effect.fnUntraced(function* (cmd) {\n    switch (cmd._tag) {\n      case \"StandardCommand\":\n        {\n          const stdinConfig = resolveStdinOption(cmd.options);\n          const stdoutConfig = resolveOutputOption(cmd.options, \"stdout\");\n          const stderrConfig = resolveOutputOption(cmd.options, \"stderr\");\n          const resolvedAdditionalFds = resolveAdditionalFds(cmd.options);\n          let isReferenced = true;\n          const cwd = yield* resolveWorkingDirectory(cmd.options);\n          const env = resolveEnvironment(cmd.options);\n          const stdio = buildStdioArray(stdinConfig, stdoutConfig, stderrConfig, resolvedAdditionalFds);\n          const [childProcess, exitSignal] = yield* Effect.acquireRelease(spawn(cmd, buildSpawnOptions(cmd.options, {\n            cwd,\n            env,\n            stdio\n          }, process.platform)), Effect.fnUntraced(function* ([childProcess, exitSignal]) {\n            const exited = yield* Deferred.isDone(exitSignal);\n            if (exited) {\n              const [code] = yield* Deferred.await(exitSignal);\n              if (code !== 0 && Predicate.isNotNull(code)) {\n                yield* Effect.ignore(killProcessGroup(cmd, childProcess, cmd.options.killSignal ?? \"SIGTERM\"));\n              }\n              return;\n            }\n            if (!isReferenced) {\n              return;\n            }\n            yield* Effect.ignore(terminateProcessGroup(cmd, childProcess, exitSignal, cmd.options));\n          }));\n          const pid = ProcessId(childProcess.pid);\n          childProcess.on(\"exit\", code => {\n            if (code !== 0 && Predicate.isNotNull(code)) {\n              killProcessGroupOnExit(childProcess, cmd.options.killSignal ?? \"SIGTERM\");\n            }\n          });\n          const reref = Effect.sync(() => {\n            if (!isReferenced) {\n              childProcess.ref();\n              isReferenced = true;\n            }\n          });\n          const unref = Effect.sync(() => {\n            if (isReferenced) {\n              childProcess.unref();\n              isReferenced = false;\n            }\n            return reref;\n          });\n          const stdin = yield* setupChildStdin(cmd, childProcess, stdinConfig);\n          const {\n            all,\n            stderr,\n            stdout\n          } = setupChildOutputStreams(cmd, childProcess, stdoutConfig, stderrConfig);\n          const {\n            getInputFd,\n            getOutputFd\n          } = yield* setupAdditionalFds(cmd, childProcess, resolvedAdditionalFds);\n          const isRunning = Effect.map(Deferred.isDone(exitSignal), done => !done);\n          const exitCode = Effect.flatMap(Deferred.await(exitSignal), ([code, signal]) => {\n            if (Predicate.isNotNull(code)) {\n              return Effect.succeed(ExitCode(code));\n            }\n            // If code is `null`, then `signal` must be defined. See the NodeJS\n            // documentation for the `\"exit\"` event on a `child_process`.\n            // https://nodejs.org/api/child_process.html#child_process_event_exit\n            const error = new globalThis.Error(`Process interrupted due to receipt of signal: '${signal}'`);\n            return Effect.fail(toPlatformError(\"exitCode\", error, cmd));\n          });\n          const kill = options => terminateProcessGroup(cmd, childProcess, exitSignal, options);\n          return makeHandle({\n            pid,\n            exitCode,\n            isRunning,\n            kill,\n            stdin,\n            stdout,\n            stderr,\n            all,\n            getInputFd,\n            getOutputFd,\n            unref\n          });\n        }\n      case \"PipedCommand\":\n        {\n          const {\n            commands,\n            pipeOptions\n          } = flattenCommand(cmd);\n          const [root, ...pipeline] = commands;\n          const handles = [yield* spawnCommand(root)];\n          for (let i = 0; i < pipeline.length; i++) {\n            const command = pipeline[i];\n            const options = pipeOptions[i] ?? {};\n            const stdinConfig = resolveStdinOption(command.options);\n            // Get the appropriate stream from the source based on `from` option\n            const sourceStream = Stream.unwrap(Effect.succeed(getSourceStream(handles[handles.length - 1], options.from)));\n            // Determine where to pipe: stdin or custom fd\n            const toOption = options.to ?? \"stdin\";\n            if (toOption === \"stdin\") {\n              // Pipe to stdin (default behavior)\n              handles.push(yield* spawnCommand(ChildProcess.make(command.command, command.args, {\n                ...command.options,\n                stdin: {\n                  ...stdinConfig,\n                  stream: sourceStream\n                }\n              })));\n            } else {\n              // Pipe to custom fd (fd3, fd4, etc.)\n              const fd = ChildProcess.parseFdName(toOption);\n              if (Predicate.isNotUndefined(fd)) {\n                const fdName = ChildProcess.fdName(fd);\n                const existingFds = command.options.additionalFds ?? {};\n                handles.push(yield* spawnCommand(ChildProcess.make(command.command, command.args, {\n                  ...command.options,\n                  additionalFds: {\n                    ...existingFds,\n                    [fdName]: {\n                      type: \"input\",\n                      stream: sourceStream\n                    }\n                  }\n                })));\n              } else {\n                // Invalid fd name, fall back to stdin\n                handles.push(yield* spawnCommand(ChildProcess.make(command.command, command.args, {\n                  ...command.options,\n                  stdin: {\n                    ...stdinConfig,\n                    stream: sourceStream\n                  }\n                })));\n              }\n            }\n          }\n          const handle = handles[handles.length - 1];\n          const kill = options => Effect.forEach([...handles].reverse(), handle => Effect.ignore(handle.kill(options)), {\n            discard: true\n          });\n          const unref = Effect.gen(function* () {\n            const rerefs = [];\n            for (const handle of handles) {\n              rerefs.push(yield* handle.unref);\n            }\n            return Effect.forEach([...rerefs].reverse(), reref => reref, {\n              discard: true\n            });\n          });\n          return makeHandle({\n            pid: handle.pid,\n            exitCode: handle.exitCode,\n            isRunning: handle.isRunning,\n            kill,\n            stdin: handles[0].stdin,\n            stdout: handle.stdout,\n            stderr: handle.stderr,\n            all: handle.all,\n            getInputFd: handle.getInputFd,\n            getOutputFd: handle.getOutputFd,\n            unref\n          });\n        }\n    }\n  });\n  return makeSpawner(spawnCommand);\n});\n/**\n * Layer that provides the `NodeChildProcessSpawner` implementation.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.effect(ChildProcessSpawner, make);\n/**\n * Flattens a `Command` into an array of `StandardCommand`s along with pipe\n * options for each connection.\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const flattenCommand = command => {\n  const commands = [];\n  const pipeOptions = [];\n  const flatten = cmd => {\n    switch (cmd._tag) {\n      case \"StandardCommand\":\n        {\n          commands.push(cmd);\n          break;\n        }\n      case \"PipedCommand\":\n        {\n          // Recursively flatten left side first\n          flatten(cmd.left);\n          // Store the pipe options for this connection\n          pipeOptions.push(cmd.options);\n          // Then flatten right side\n          flatten(cmd.right);\n          break;\n        }\n    }\n  };\n  flatten(command);\n  // The commands array is guaranteed to be non-empty since we always have at\n  // least one command in the input. We validate this at runtime and return a\n  // properly typed tuple.\n  if (commands.length === 0) {\n    // This should never happen given a valid Command input\n    throw new Error(\"flattenCommand produced empty commands array\");\n  }\n  const [first, ...rest] = commands;\n  const nonEmptyCommands = [first, ...rest];\n  return {\n    commands: nonEmptyCommands,\n    pipeOptions\n  };\n};\n//# sourceMappingURL=NodeChildProcessSpawner.js.map","const hex = byte => byte.toString(16).padStart(2, \"0\");\n/** @internal */\nexport const stringify = bytes => {\n  const segments = [bytes.subarray(0, 4), bytes.subarray(4, 6), bytes.subarray(6, 8), bytes.subarray(8, 10), bytes.subarray(10, 16)];\n  return segments.map(segment => Array.from(segment, hex).join(\"\")).join(\"-\");\n};\nconst randomBytes = () => globalThis.crypto.getRandomValues(new Uint8Array(16));\n/** @internal */\nexport function v4Bytes(bytes = randomBytes()) {\n  bytes[6] = bytes[6] & 0x0f | 0x40;\n  bytes[8] = bytes[8] & 0x3f | 0x80;\n  return bytes;\n}\n/** @internal */\nexport const v4String = bytes => stringify(bytes === undefined ? v4Bytes() : v4Bytes(bytes));\nconst maxV7Timestamp = 2 ** 48 - 1;\n/** @internal */\nexport function v7Bytes(timestampMillis, bytes = randomBytes()) {\n  const timestamp = Math.min(Math.max(0, Math.trunc(timestampMillis)), maxV7Timestamp);\n  bytes[0] = Math.floor(timestamp / 2 ** 40);\n  bytes[1] = Math.floor(timestamp / 2 ** 32) & 0xff;\n  bytes[2] = Math.floor(timestamp / 2 ** 24) & 0xff;\n  bytes[3] = Math.floor(timestamp / 2 ** 16) & 0xff;\n  bytes[4] = Math.floor(timestamp / 2 ** 8) & 0xff;\n  bytes[5] = timestamp & 0xff;\n  bytes[6] = bytes[6] & 0x0f | 0x70;\n  bytes[8] = bytes[8] & 0x3f | 0x80;\n  return bytes;\n}\n/** @internal */\nexport const v7String = (timestampMillis, bytes) => stringify(bytes === undefined ? v7Bytes(timestampMillis) : v7Bytes(timestampMillis, bytes));\n//# sourceMappingURL=uuid.js.map","/**\n * Defines a platform-independent service for cryptographic operations.\n *\n * Runtime packages provide concrete implementations backed by the host\n * platform's cryptography APIs. This module defines the service interface and a\n * constructor from random-byte and digest primitives. The service provides\n * secure random bytes and numbers, UUIDv4 and UUIDv7 generation, shuffling, and\n * SHA message digests.\n *\n * @since 4.0.0\n */\nimport * as Context from \"./Context.js\";\nimport * as Effect from \"./Effect.js\";\nimport * as random from \"./internal/random.js\";\nimport * as Uuid from \"./internal/uuid.js\";\nimport * as PlatformError from \"./PlatformError.js\";\nconst TypeId = \"~effect/Crypto\";\n/**\n * Service tag for platform cryptography.\n *\n * **When to use**\n *\n * Use when you need to provide or retrieve the full platform cryptography\n * service from an effect's context.\n *\n * **Details**\n *\n * Providing this service supplies platform-agnostic cryptographic operations\n * such as hashing, UUID generation, and secure random values.\n *\n * @see {@link make} for constructing a Crypto service from primitive operations\n *\n * @category services\n * @since 4.0.0\n */\nexport const Crypto = /*#__PURE__*/Context.Service(\"effect/Crypto\");\n/**\n * Creates a `Crypto` service from the primitive implementation, deriving the\n * random generator helpers and UUID generation from those primitives.\n *\n * **When to use**\n *\n * Use to build a Crypto service for a platform integration, test layer, or\n * custom runtime from primitive random-byte and digest operations.\n *\n * **Details**\n *\n * The constructor derives random numbers, booleans, integer ranges, shuffling,\n * and UUID generation from `impl.randomBytes`. Digest operations delegate to\n * `impl.digest`.\n *\n * **Gotchas**\n *\n * `impl.randomBytes` must return cryptographically secure bytes of the\n * requested length. UUID formatting mutates the byte array returned for UUID\n * generation, so the implementation should return a fresh array for each call.\n *\n * **Example** (Creating a Crypto service)\n *\n * ```ts import.meta.vitest\n * import { Crypto, Effect } from \"effect\"\n *\n * const testCrypto = Crypto.make({\n *   randomBytes: (size) => new Uint8Array(size),\n *   digest: (_algorithm, data) => Effect.succeed(data)\n * })\n *\n * await Effect.runPromise(testCrypto.randomBytes(4)) // => new Uint8Array([0, 0, 0, 0])\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = impl => {\n  const randomBytesUnsafe = impl.randomBytes;\n  const randomBytes = size => Effect.map(validateSize(\"randomBytes\", size), randomBytesUnsafe);\n  const readUint53 = bytes => (bytes[0] & 0x1f) * 2 ** 48 + bytes[1] * 2 ** 40 + bytes[2] * 2 ** 32 + bytes[3] * 2 ** 24 + bytes[4] * 2 ** 16 + bytes[5] * 2 ** 8 + bytes[6];\n  const nextDoubleUnsafe = () => readUint53(randomBytesUnsafe(7)) / 2 ** 53;\n  const nextIntUnsafe = () => {\n    while (true) {\n      const bytes = randomBytesUnsafe(7);\n      const value = readUint53(bytes);\n      if ((bytes[0] & 0x20) === 0) {\n        return value + Number.MIN_SAFE_INTEGER;\n      }\n      if (value < Number.MAX_SAFE_INTEGER) {\n        return value + 1;\n      }\n    }\n  };\n  return Crypto.of({\n    [TypeId]: TypeId,\n    randomBytes,\n    nextDoubleUnsafe,\n    nextIntUnsafe,\n    digest: impl.digest,\n    random: Effect.sync(() => nextDoubleUnsafe()),\n    randomBoolean: Effect.sync(() => nextDoubleUnsafe() > 0.5),\n    randomInt: Effect.sync(() => nextIntUnsafe()),\n    randomBetween: (min, max) => Effect.sync(() => random.nextBetween(min, max, nextDoubleUnsafe())),\n    randomIntBetween(min, max, options) {\n      const extra = options?.halfOpen === true ? 0 : 1;\n      return Effect.sync(() => {\n        const minInt = Math.ceil(min);\n        const maxInt = Math.floor(max);\n        return Math.floor(nextDoubleUnsafe() * (maxInt - minInt + extra)) + minInt;\n      });\n    },\n    randomShuffle: elements => Effect.sync(() => {\n      const buffer = Array.from(elements);\n      for (let i = buffer.length - 1; i >= 1; i = i - 1) {\n        const index = Math.min(i, Math.floor(nextDoubleUnsafe() * (i + 1)));\n        const value = buffer[i];\n        buffer[i] = buffer[index];\n        buffer[index] = value;\n      }\n      return buffer;\n    }),\n    randomUUIDv4: Effect.sync(() => Uuid.v4String(randomBytesUnsafe(16))),\n    randomUUIDv7: Effect.clockWith(clock => Effect.succeed(Uuid.v7String(clock.currentTimeMillisUnsafe(), randomBytesUnsafe(16))))\n  });\n};\nconst validateSize = (method, size) => Number.isSafeInteger(size) && size >= 0 ? Effect.succeed(size) : Effect.fail(PlatformError.badArgument({\n  module: \"Crypto\",\n  method,\n  description: \"size must be a non-negative safe integer\"\n}));\n//# sourceMappingURL=Crypto.js.map","/**\n * Node-compatible implementation of Effect's `Crypto` service.\n *\n * This module builds the service from `node:crypto`, using `randomBytes` for\n * random data and `createHash` for supported digest algorithms. It exports\n * `make` as the concrete service value and `layer` for providing it through\n * Effect context.\n *\n * @since 1.0.0\n */\nimport * as EffectCrypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as PlatformError from \"effect/PlatformError\";\nimport * as NodeCrypto from \"node:crypto\";\nconst toHashAlgorithm = algorithm => {\n  switch (algorithm) {\n    case \"SHA-1\":\n      return \"sha1\";\n    case \"SHA-256\":\n      return \"sha256\";\n    case \"SHA-384\":\n      return \"sha384\";\n    case \"SHA-512\":\n      return \"sha512\";\n  }\n};\nconst digest = (algorithm, data) => Effect.try({\n  try: () => Uint8Array.from(NodeCrypto.createHash(toHashAlgorithm(algorithm)).update(data).digest()),\n  catch: cause => PlatformError.systemError({\n    module: \"Crypto\",\n    method: \"digest\",\n    _tag: \"Unknown\",\n    description: \"Could not compute digest\",\n    cause\n  })\n});\n/**\n * The default Node.js Crypto service implementation.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const make = /*#__PURE__*/EffectCrypto.make({\n  randomBytes: NodeCrypto.randomBytes,\n  digest\n});\n/**\n * Layer that provides the Node.js Crypto service implementation.\n *\n * @category layers\n * @since 1.0.0\n */\nexport const layer = /*#__PURE__*/Layer.succeed(EffectCrypto.Crypto, make);\n//# sourceMappingURL=NodeCrypto.js.map","/**\n * The `NodeCrypto` module provides the Node.js `Crypto` service layer for\n * Effect programs. Provide {@link layer} at the edge of a Node application,\n * CLI, script, or test to satisfy `effect/Crypto` with Node's `node:crypto`\n * implementation for secure random bytes, UUID generation, random values, and\n * SHA digest operations.\n *\n * This module is the public Node adapter around the shared Node-compatible\n * implementation. Digest failures are reported as platform errors, and SHA-1\n * remains available only for interoperability with existing protocols.\n *\n * @since 1.0.0\n */\nimport * as NodeCrypto from \"@effect/platform-node-shared/NodeCrypto\";\n/**\n * Layer that provides the Node.js Crypto service implementation.\n *\n * @category layers\n * @since 1.0.0\n */\nexport const layer = NodeCrypto.layer;\n//# sourceMappingURL=NodeCrypto.js.map","/**\n * Shared Node-compatible implementation of Effect's `FileSystem` service.\n *\n * This module adapts Node's `node:fs`, `node:os`, and `node:path` APIs into a\n * `FileSystem` layer for Effect programs running on Node-compatible runtimes.\n * Platform packages use it to provide file and directory I/O, permissions,\n * links, metadata, temporary files and directories, and file watching through\n * the shared `FileSystem` service.\n *\n * @since 4.0.0\n */\nimport * as BI from \"effect/BigInt\";\nimport * as ByteSize from \"effect/ByteSize\";\nimport * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport { effectify } from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport { pipe } from \"effect/Function\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Error from \"effect/PlatformError\";\nimport * as Queue from \"effect/Queue\";\nimport * as Stream from \"effect/Stream\";\nimport * as Crypto from \"node:crypto\";\nimport * as NFS from \"node:fs\";\nimport * as OS from \"node:os\";\nimport * as Path from \"node:path\";\nimport { handleErrnoException } from \"./internal/utils.js\";\nconst handleBadArgument = method => err => Error.badArgument({\n  module: \"FileSystem\",\n  method,\n  description: err.message ?? String(err)\n});\nconst bigintToNumber = (value, field) => {\n  const number = Number(value);\n  if (!Number.isSafeInteger(number)) {\n    throw new RangeError(`${field} exceeds the safe integer range: ${value}`);\n  }\n  return number;\n};\nconst bigintToNumberOption = value => Option.flatMap(Option.fromNullishOr(value), BI.toNumber);\n// fs.write ignores bigint positions.\nconst positionToNumber = (position, method) => Effect.try({\n  try: () => bigintToNumber(position, \"position\"),\n  catch: handleBadArgument(method)\n});\n// == access\nconst access = /*#__PURE__*/(() => {\n  const nodeAccess = /*#__PURE__*/effectify(NFS.access, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"access\"), /*#__PURE__*/handleBadArgument(\"access\"));\n  return (path, options) => {\n    let mode = NFS.constants.F_OK;\n    if (options?.readable) {\n      mode |= NFS.constants.R_OK;\n    }\n    if (options?.writable) {\n      mode |= NFS.constants.W_OK;\n    }\n    return nodeAccess(path, mode);\n  };\n})();\n// == copy\nconst copy = /*#__PURE__*/(() => {\n  const nodeCp = /*#__PURE__*/effectify(NFS.cp, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"copy\"), /*#__PURE__*/handleBadArgument(\"copy\"));\n  return (fromPath, toPath, options) => nodeCp(fromPath, toPath, {\n    force: options?.overwrite ?? false,\n    preserveTimestamps: options?.preserveTimestamps ?? false,\n    recursive: true\n  });\n})();\n// == copyFile\nconst copyFile = /*#__PURE__*/(() => {\n  const nodeCopyFile = /*#__PURE__*/effectify(NFS.copyFile, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"copyFile\"), /*#__PURE__*/handleBadArgument(\"copyFile\"));\n  return (fromPath, toPath) => nodeCopyFile(fromPath, toPath);\n})();\n// == chmod\nconst chmod = /*#__PURE__*/(() => {\n  const nodeChmod = /*#__PURE__*/effectify(NFS.chmod, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"chmod\"), /*#__PURE__*/handleBadArgument(\"chmod\"));\n  return (path, mode) => nodeChmod(path, mode);\n})();\n// == chown\nconst chown = /*#__PURE__*/(() => {\n  const nodeChown = /*#__PURE__*/effectify(NFS.chown, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"chown\"), /*#__PURE__*/handleBadArgument(\"chown\"));\n  return (path, uid, gid) => nodeChown(path, uid, gid);\n})();\n// == glob\nconst glob = /*#__PURE__*/(() => {\n  const nodeGlob = /*#__PURE__*/effectify(NFS.glob, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"glob\"), /*#__PURE__*/handleBadArgument(\"glob\"));\n  return (pattern, options) => nodeGlob(pattern, {\n    cwd: options?.root,\n    exclude: options?.exclude\n  });\n})();\n// == link\nconst link = /*#__PURE__*/(() => {\n  const nodeLink = /*#__PURE__*/effectify(NFS.link, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"link\"), /*#__PURE__*/handleBadArgument(\"link\"));\n  return (existingPath, newPath) => nodeLink(existingPath, newPath);\n})();\n// == makeDirectory\nconst makeDirectory = /*#__PURE__*/(() => {\n  const nodeMkdir = /*#__PURE__*/effectify(NFS.mkdir, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"makeDirectory\"), /*#__PURE__*/handleBadArgument(\"makeDirectory\"));\n  return (path, options) => nodeMkdir(path, {\n    recursive: options?.recursive ?? false,\n    mode: options?.mode\n  });\n})();\n// == makeTempDirectory\nconst makeTempDirectoryFactory = method => {\n  const nodeMkdtemp = effectify(NFS.mkdtemp, handleErrnoException(\"FileSystem\", method), handleBadArgument(method));\n  return options => Effect.suspend(() => {\n    const prefix = options?.prefix ?? \"\";\n    const directory = typeof options?.directory === \"string\" ? Path.join(options.directory, \".\") : OS.tmpdir();\n    return nodeMkdtemp(prefix ? Path.join(directory, prefix) : directory + \"/\");\n  });\n};\nconst makeTempDirectory = /*#__PURE__*/makeTempDirectoryFactory(\"makeTempDirectory\");\n// == remove\nconst removeFactory = method => {\n  const nodeRm = effectify(NFS.rm, handleErrnoException(\"FileSystem\", method), handleBadArgument(method));\n  return (path, options) => nodeRm(path, {\n    recursive: options?.recursive ?? false,\n    force: options?.force ?? false\n  });\n};\nconst remove = /*#__PURE__*/removeFactory(\"remove\");\n// == makeTempDirectoryScoped\nconst makeTempDirectoryScoped = /*#__PURE__*/(() => {\n  const makeDirectory = /*#__PURE__*/makeTempDirectoryFactory(\"makeTempDirectoryScoped\");\n  const removeDirectory = /*#__PURE__*/removeFactory(\"makeTempDirectoryScoped\");\n  return options => Effect.acquireRelease(makeDirectory(options), directory => Effect.orDie(removeDirectory(directory, {\n    recursive: true\n  })));\n})();\n// == open\nconst openFactory = method => {\n  const nodeOpen = effectify(NFS.open, handleErrnoException(\"FileSystem\", method), handleBadArgument(method));\n  const nodeClose = effectify(NFS.close, handleErrnoException(\"FileSystem\", method), handleBadArgument(method));\n  return (path, options) => pipe(Effect.acquireRelease(nodeOpen(path, options?.flag ?? \"r\", options?.mode), fd => Effect.orDie(nodeClose(fd))), Effect.map(fd => makeFile(fd, options?.flag?.startsWith(\"a\") ?? false)));\n};\nconst open = /*#__PURE__*/openFactory(\"open\");\nconst makeFile = /*#__PURE__*/(() => {\n  const nodeReadFactory = method => effectify(NFS.read, handleErrnoException(\"FileSystem\", method), handleBadArgument(method));\n  const nodeRead = /*#__PURE__*/nodeReadFactory(\"read\");\n  const nodeReadAlloc = /*#__PURE__*/nodeReadFactory(\"readAlloc\");\n  const nodeStat = /*#__PURE__*/effectify(NFS.fstat, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"stat\"), /*#__PURE__*/handleBadArgument(\"stat\"));\n  const nodeTruncate = /*#__PURE__*/effectify(NFS.ftruncate, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"truncate\"), /*#__PURE__*/handleBadArgument(\"truncate\"));\n  const nodeSync = /*#__PURE__*/effectify(NFS.fsync, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"sync\"), /*#__PURE__*/handleBadArgument(\"sync\"));\n  const nodeWriteFactory = method => effectify(NFS.write, handleErrnoException(\"FileSystem\", method), handleBadArgument(method));\n  const nodeWrite = /*#__PURE__*/nodeWriteFactory(\"write\");\n  const nodeWriteAll = /*#__PURE__*/nodeWriteFactory(\"writeAll\");\n  class FileImpl {\n    [FileSystem.FileTypeId];\n    fd;\n    append;\n    position = /*#__PURE__*/BigInt(0);\n    constructor(fd, append) {\n      this[FileSystem.FileTypeId] = FileSystem.FileTypeId;\n      this.fd = fd;\n      this.append = append;\n    }\n    get stat() {\n      return Effect.flatMap(nodeStat(this.fd, {\n        bigint: true\n      }), makeFileInfo);\n    }\n    get sync() {\n      return nodeSync(this.fd);\n    }\n    seek(offset, from) {\n      return Effect.suspend(() => {\n        const position = from === \"start\" ? offset : this.position + offset;\n        if (position < BigInt(0)) {\n          return Effect.fail(Error.badArgument({\n            module: \"FileSystem\",\n            method: \"seek\",\n            description: \"Cannot seek before the start of the file\"\n          }));\n        }\n        this.position = position;\n        return Effect.succeed(position);\n      });\n    }\n    read(buffer) {\n      return Effect.suspend(() => {\n        const position = this.position;\n        return Effect.map(nodeRead(this.fd, {\n          buffer,\n          position\n        }), bytesRead => {\n          this.position = position + BigInt(bytesRead);\n          return bytesRead;\n        });\n      });\n    }\n    readAlloc(size) {\n      return Effect.suspend(() => {\n        try {\n          if (!Number.isInteger(size) || size < 0) {\n            throw new RangeError(\"size must be a non-negative integer\");\n          }\n          const buffer = Buffer.allocUnsafeSlow(size);\n          const position = this.position;\n          return Effect.map(nodeReadAlloc(this.fd, {\n            buffer,\n            position\n          }), bytesRead => {\n            if (bytesRead === 0) {\n              return Option.none();\n            }\n            this.position = position + BigInt(bytesRead);\n            if (bytesRead === size) {\n              return Option.some(buffer);\n            }\n            const dst = Buffer.allocUnsafeSlow(bytesRead);\n            buffer.copy(dst, 0, 0, bytesRead);\n            return Option.some(dst);\n          });\n        } catch (cause) {\n          return Effect.fail(handleBadArgument(\"readAlloc\")(cause));\n        }\n      });\n    }\n    truncate(length) {\n      return Effect.map(nodeTruncate(this.fd, length || undefined), () => {\n        if (!this.append) {\n          const len = BigInt(length ?? 0);\n          if (this.position > len) {\n            this.position = len;\n          }\n        }\n      });\n    }\n    write(buffer) {\n      return Effect.suspend(() => {\n        const position = this.position;\n        return Effect.flatMap(this.append ? Effect.succeed(undefined) : positionToNumber(position, \"write\"), nodePosition => Effect.map(nodeWrite(this.fd, buffer, undefined, undefined, nodePosition), bytesWritten => {\n          if (!this.append) {\n            this.position = position + BigInt(bytesWritten);\n          }\n          return bytesWritten;\n        }));\n      });\n    }\n    writeAllChunk(buffer) {\n      return Effect.suspend(() => {\n        const position = this.position;\n        return Effect.flatMap(this.append ? Effect.succeed(undefined) : positionToNumber(position, \"writeAll\"), nodePosition => Effect.flatMap(nodeWriteAll(this.fd, buffer, undefined, undefined, nodePosition), bytesWritten => {\n          if (bytesWritten === 0) {\n            return Effect.fail(Error.systemError({\n              module: \"FileSystem\",\n              method: \"writeAll\",\n              _tag: \"WriteZero\",\n              pathOrDescriptor: this.fd,\n              description: \"write returned 0 bytes written\"\n            }));\n          }\n          if (!this.append) {\n            this.position = position + BigInt(bytesWritten);\n          }\n          return bytesWritten < buffer.length ? this.writeAllChunk(buffer.subarray(bytesWritten)) : Effect.void;\n        }));\n      });\n    }\n    writeAll(buffer) {\n      return buffer.length === 0 ? Effect.void : this.writeAllChunk(buffer);\n    }\n  }\n  return (fd, append) => new FileImpl(fd, append);\n})();\n// == makeTempFile\nconst makeTempFileFactory = method => {\n  const makeDirectory = makeTempDirectoryFactory(method);\n  return Effect.fnUntraced(function* (options) {\n    const directory = yield* makeDirectory(options);\n    const random = Crypto.randomBytes(6).toString(\"hex\");\n    const name = Path.join(directory, options?.suffix ? `${random}${options.suffix}` : random);\n    yield* writeFile(name, new Uint8Array(0));\n    return name;\n  });\n};\nconst makeTempFile = /*#__PURE__*/makeTempFileFactory(\"makeTempFile\");\n// == makeTempFileScoped\nconst makeTempFileScoped = /*#__PURE__*/(() => {\n  const makeFile = /*#__PURE__*/makeTempFileFactory(\"makeTempFileScoped\");\n  const removeDirectory = /*#__PURE__*/removeFactory(\"makeTempFileScoped\");\n  return options => Effect.acquireRelease(makeFile(options), file => Effect.orDie(removeDirectory(Path.dirname(file), {\n    recursive: true\n  })));\n})();\n// == readDirectory\nconst readDirectory = (path, options) => Effect.tryPromise({\n  try: () => NFS.promises.readdir(path, options),\n  catch: err => handleErrnoException(\"FileSystem\", \"readDirectory\")(err, [path])\n});\n// == readFile\nconst readFile = path => Effect.callback((resume, signal) => {\n  try {\n    NFS.readFile(path, {\n      signal\n    }, (err, data) => {\n      if (err) {\n        resume(Effect.fail(handleErrnoException(\"FileSystem\", \"readFile\")(err, [path])));\n      } else {\n        resume(Effect.succeed(data));\n      }\n    });\n  } catch (err) {\n    resume(Effect.fail(handleBadArgument(\"readFile\")(err)));\n  }\n});\n// == readLink\nconst readLink = /*#__PURE__*/(() => {\n  const nodeReadLink = /*#__PURE__*/effectify(NFS.readlink, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"readLink\"), /*#__PURE__*/handleBadArgument(\"readLink\"));\n  return path => nodeReadLink(path);\n})();\n// == realPath\nconst realPath = /*#__PURE__*/(() => {\n  const nodeRealPath = /*#__PURE__*/effectify(NFS.realpath, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"realPath\"), /*#__PURE__*/handleBadArgument(\"realPath\"));\n  return path => nodeRealPath(path);\n})();\n// == rename\nconst rename = /*#__PURE__*/(() => {\n  const nodeRename = /*#__PURE__*/effectify(NFS.rename, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"rename\"), /*#__PURE__*/handleBadArgument(\"rename\"));\n  return (oldPath, newPath) => nodeRename(oldPath, newPath);\n})();\n// == stat\nconst makeFileInfo = stat => Effect.try({\n  try: () => ({\n    type: stat.isFile() ? \"File\" : stat.isDirectory() ? \"Directory\" : stat.isSymbolicLink() ? \"SymbolicLink\" : stat.isBlockDevice() ? \"BlockDevice\" : stat.isCharacterDevice() ? \"CharacterDevice\" : stat.isFIFO() ? \"FIFO\" : stat.isSocket() ? \"Socket\" : \"Unknown\",\n    mtime: Option.fromNullishOr(stat.mtime),\n    atime: Option.fromNullishOr(stat.atime),\n    birthtime: Option.fromNullishOr(stat.birthtime),\n    dev: bigintToNumber(stat.dev, \"dev\"),\n    rdev: bigintToNumberOption(stat.rdev),\n    ino: bigintToNumberOption(stat.ino),\n    mode: bigintToNumber(stat.mode, \"mode\"),\n    nlink: bigintToNumberOption(stat.nlink),\n    uid: bigintToNumberOption(stat.uid),\n    gid: bigintToNumberOption(stat.gid),\n    size: ByteSize.bytes(stat.size),\n    blksize: stat.blksize !== undefined ? Option.some(ByteSize.bytes(stat.blksize)) : Option.none(),\n    blocks: bigintToNumberOption(stat.blocks)\n  }),\n  catch: handleBadArgument(\"stat\")\n});\nconst stat = /*#__PURE__*/(() => {\n  const nodeStat = /*#__PURE__*/effectify(NFS.stat, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"stat\"), /*#__PURE__*/handleBadArgument(\"stat\"));\n  return path => Effect.flatMap(nodeStat(path, {\n    bigint: true\n  }), makeFileInfo);\n})();\n// == symlink\nconst symlink = /*#__PURE__*/(() => {\n  const nodeSymlink = /*#__PURE__*/effectify(NFS.symlink, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"symlink\"), /*#__PURE__*/handleBadArgument(\"symlink\"));\n  return (target, path) => nodeSymlink(target, path);\n})();\n// == truncate\nconst truncate = /*#__PURE__*/(() => {\n  const nodeTruncate = /*#__PURE__*/effectify(NFS.truncate, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"truncate\"), /*#__PURE__*/handleBadArgument(\"truncate\"));\n  return (path, length) => nodeTruncate(path, length);\n})();\n// == utimes\nconst utimes = /*#__PURE__*/(() => {\n  const nodeUtimes = /*#__PURE__*/effectify(NFS.utimes, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"utime\"), /*#__PURE__*/handleBadArgument(\"utime\"));\n  return (path, atime, mtime) => nodeUtimes(path, atime, mtime);\n})();\n// == watch\nconst watchNode = (path, info, options) => Stream.callback(queue => Effect.acquireRelease(Effect.sync(() => {\n  const directory = info.type === \"Directory\" ? path : Path.dirname(path);\n  const watcher = NFS.watch(path, {\n    recursive: options?.recursive ?? false\n  }, (event, path) => {\n    if (!path) return;\n    switch (event) {\n      case \"rename\":\n        {\n          Effect.runFork(Effect.matchEffect(stat(Path.resolve(directory, path)), {\n            onSuccess: _ => Queue.offer(queue, {\n              _tag: \"Create\",\n              path\n            }),\n            onFailure: _ => Queue.offer(queue, {\n              _tag: \"Remove\",\n              path\n            })\n          }));\n          return;\n        }\n      case \"change\":\n        {\n          Queue.offerUnsafe(queue, {\n            _tag: \"Update\",\n            path\n          });\n          return;\n        }\n    }\n  });\n  watcher.on(\"error\", error => {\n    Queue.failCauseUnsafe(queue, Cause.fail(Error.systemError({\n      module: \"FileSystem\",\n      _tag: \"Unknown\",\n      method: \"watch\",\n      pathOrDescriptor: path,\n      cause: error\n    })));\n  });\n  watcher.on(\"close\", () => {\n    Queue.endUnsafe(queue);\n  });\n  return watcher;\n}), watcher => Effect.sync(() => watcher.close())));\nconst watch = (backend, path, options) => stat(path).pipe(Effect.map(stat => backend.pipe(Option.flatMap(_ => _.register(path, stat, options)), Option.getOrElse(() => watchNode(path, stat, options)))), Stream.unwrap);\n// == writeFile\nconst writeFile = (path, data, options) => Effect.callback((resume, signal) => {\n  try {\n    NFS.writeFile(path, data, {\n      signal,\n      flag: options?.flag,\n      mode: options?.mode\n    }, err => {\n      if (err) {\n        resume(Effect.fail(handleErrnoException(\"FileSystem\", \"writeFile\")(err, [path])));\n      } else {\n        resume(Effect.void);\n      }\n    });\n  } catch (err) {\n    resume(Effect.fail(handleBadArgument(\"writeFile\")(err)));\n  }\n});\nconst makeFileSystem = /*#__PURE__*/Effect.map(/*#__PURE__*/Effect.serviceOption(FileSystem.WatchBackend), backend => FileSystem.make({\n  access,\n  chmod,\n  chown,\n  copy,\n  copyFile,\n  glob,\n  link,\n  makeDirectory,\n  makeTempDirectory,\n  makeTempDirectoryScoped,\n  makeTempFile,\n  makeTempFileScoped,\n  open,\n  readDirectory,\n  readFile,\n  readLink,\n  realPath,\n  remove,\n  rename,\n  stat,\n  symlink,\n  truncate,\n  utimes,\n  watch(path, options) {\n    return watch(backend, path, options);\n  },\n  writeFile\n}));\n/**\n * Provides the `FileSystem` service backed by Node filesystem APIs, including\n * file operations, directory operations, links, metadata, and file watching.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.effect(FileSystem.FileSystem)(makeFileSystem);\n//# sourceMappingURL=NodeFileSystem.js.map","/**\n * Node.js `FileSystem` layer for programs that perform real filesystem I/O.\n *\n * The exported layer satisfies the platform-independent `FileSystem` service\n * with Node-backed operations for files, directories, metadata, permissions,\n * links, temporary paths, and path watching. Effects still call the service from\n * `effect/FileSystem`; this module only chooses the Node implementation.\n *\n * @since 4.0.0\n */\nimport * as NodeFileSystem from \"@effect/platform-node-shared/NodeFileSystem\";\n/**\n * Provides the `FileSystem` service backed by Node filesystem APIs.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = NodeFileSystem.layer;\n//# sourceMappingURL=NodeFileSystem.js.map","/**\n * Node-backed provider for Effect's `Path` service.\n *\n * This module turns Node's `node:path` and `node:url` APIs into `Path` layers.\n * `layer` uses the host platform path implementation, while `layerPosix` and\n * `layerWin32` provide fixed POSIX and Windows variants. All three layers also\n * include helpers for converting between file paths and file URLs.\n *\n * @since 4.0.0\n */\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport { Path, TypeId } from \"effect/Path\";\nimport { BadArgument } from \"effect/PlatformError\";\nimport * as NodePath from \"node:path\";\nimport * as NodeUrl from \"node:url\";\nconst fileUrlOps = windows => ({\n  fromFileUrl: url => Effect.try({\n    try: () => NodeUrl.fileURLToPath(url, {\n      windows\n    }),\n    catch: cause => new BadArgument({\n      module: \"Path\",\n      method: \"fromFileUrl\",\n      cause\n    })\n  }),\n  toFileUrl: path => Effect.try({\n    try: () => NodeUrl.pathToFileURL(path, {\n      windows\n    }),\n    catch: cause => new BadArgument({\n      module: \"Path\",\n      method: \"toFileUrl\",\n      cause\n    })\n  })\n});\n/**\n * Provides the `Path` service using Node's POSIX path implementation plus\n * file URL conversion helpers.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerPosix = /*#__PURE__*/Layer.succeed(Path)({\n  [TypeId]: TypeId,\n  ...NodePath.posix,\n  ... /*#__PURE__*/fileUrlOps(false)\n});\n/**\n * Provides the `Path` service using Node's Windows path implementation plus\n * file URL conversion helpers.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerWin32 = /*#__PURE__*/Layer.succeed(Path)({\n  [TypeId]: TypeId,\n  ...NodePath.win32,\n  ... /*#__PURE__*/fileUrlOps(true)\n});\n/**\n * Provides the default `Path` service using the host platform's Node path\n * implementation plus file URL conversion helpers.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.succeed(Path)({\n  [TypeId]: TypeId,\n  ...NodePath,\n  ... /*#__PURE__*/fileUrlOps(undefined)\n});\n//# sourceMappingURL=NodePath.js.map","/**\n * Node.js layers for Effect's `Path` service.\n *\n * This module provides the default, POSIX, and Windows variants of the\n * platform-independent `Path` service by reusing the shared Node path\n * implementation. The provided path services include Node file URL conversion\n * behavior.\n *\n * @since 4.0.0\n */\nimport * as NodePath from \"@effect/platform-node-shared/NodePath\";\n/**\n * Provides the default Node `Path` service using the platform's `node:path`\n * implementation.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = NodePath.layer;\n/**\n * Provides the `Path` service using Node's POSIX path implementation,\n * regardless of the host platform.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerPosix = NodePath.layerPosix;\n/**\n * Provides the `Path` service using Node's Windows path implementation,\n * regardless of the host platform.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerWin32 = NodePath.layerWin32;\n//# sourceMappingURL=NodePath.js.map","/**\n * Service contract for command-line arguments and standard input, output, and\n * error output. It lets programs depend on standard I/O through the Effect\n * environment instead of reading from or writing to global process handles\n * directly.\n *\n * The service exposes arguments as an `Effect`, stdout and stderr as `Sink`s\n * that accept strings or bytes, and stdin as a byte `Stream`. This module also\n * provides a constructor for service values and a small test layer with\n * overridable defaults.\n *\n * @since 4.0.0\n */\nimport * as Context from \"./Context.js\";\nimport * as Effect from \"./Effect.js\";\nimport * as Layer from \"./Layer.js\";\nimport * as Sink from \"./Sink.js\";\nimport * as Stream from \"./Stream.js\";\n/**\n * Runtime identifier stored on `Stdio` service implementations.\n *\n * **Details**\n *\n * This marker is part of the runtime representation of `Stdio` service\n * implementations.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const TypeId = \"~effect/Stdio\";\n/**\n * Service tag for process standard I/O.\n *\n * **When to use**\n *\n * Use when you need command-line arguments or standard I/O streams supplied by\n * an effect's environment.\n *\n * @see {@link make} for constructing a `Stdio` service directly\n * @see {@link layerTest} for a test layer with defaults and overrides\n *\n * @category services\n * @since 4.0.0\n */\nexport const Stdio = /*#__PURE__*/Context.Service(TypeId);\n/**\n * Creates a `Stdio` service implementation from the provided fields and\n * attaches the `Stdio` type identifier.\n *\n * **When to use**\n *\n * Use when you need to assemble a concrete `Stdio` service from command-line\n * arguments and standard I/O implementations.\n *\n * **Details**\n *\n * The returned service reuses the supplied fields unchanged and adds the\n * `Stdio` type identifier. Omitted terminal-detection fields default to\n * effects that succeed with `false`.\n *\n * @see {@link layerTest} for a test layer with default fields that can be overridden\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = options => ({\n  [TypeId]: TypeId,\n  stdinIsTerminal: Effect.succeed(false),\n  stdoutIsTerminal: Effect.succeed(false),\n  ...options\n});\n/**\n * Creates a test layer for `Stdio`.\n *\n * **When to use**\n *\n * Use to provide deterministic standard I/O in tests while overriding only the\n * command-line arguments, input stream, or output sinks relevant to the case.\n *\n * **Details**\n *\n * Any provided fields override defaults. By default, arguments are empty,\n * standard output and error are draining sinks, and standard input is an empty\n * stream, and terminal-detection effects succeed with `false`.\n *\n * @see {@link make} for constructing a `Stdio` service directly without a `Layer` or defaults\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerTest = impl => Layer.succeed(Stdio, make({\n  args: Effect.succeed([]),\n  stdout: () => Sink.drain,\n  stderr: () => Sink.drain,\n  stdin: Stream.empty,\n  ...impl\n}));\n//# sourceMappingURL=Stdio.js.map","/**\n * Shared Node.js implementation of the Effect `Stdio` service.\n *\n * `NodeStdio` provides {@link Stdio.Stdio} from the current Node process. The\n * exported {@link layer} reads command-line arguments from `process.argv`,\n * consumes input from `process.stdin`, and writes normal and error output to\n * `process.stdout` and `process.stderr`. Standard input remains open, and\n * standard output and error output are not ended unless requested.\n *\n * @since 4.0.0\n */\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport { systemError } from \"effect/PlatformError\";\nimport * as Stdio from \"effect/Stdio\";\nimport { fromWritable } from \"./NodeSink.js\";\nimport { fromReadable } from \"./NodeStream.js\";\n/**\n * Provides `Stdio` from `process.argv`, `process.stdin`, `process.stdout`,\n * and `process.stderr`; stdin remains open and stdout/stderr are not ended by\n * default.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.succeed(Stdio.Stdio, /*#__PURE__*/Stdio.make({\n  args: /*#__PURE__*/Effect.sync(() => process.argv.slice(2)),\n  stdinIsTerminal: /*#__PURE__*/Effect.sync(() => process.stdin.isTTY === true),\n  stdoutIsTerminal: /*#__PURE__*/Effect.sync(() => process.stdout.isTTY === true),\n  stdout: options => fromWritable({\n    evaluate: () => process.stdout,\n    onError: cause => systemError({\n      module: \"Stdio\",\n      method: \"stdout\",\n      _tag: \"Unknown\",\n      cause\n    }),\n    endOnDone: options?.endOnDone ?? false\n  }),\n  stderr: options => fromWritable({\n    evaluate: () => process.stderr,\n    onError: cause => systemError({\n      module: \"Stdio\",\n      method: \"stderr\",\n      _tag: \"Unknown\",\n      cause\n    }),\n    endOnDone: options?.endOnDone ?? false\n  }),\n  stdin: /*#__PURE__*/fromReadable({\n    evaluate: () => process.stdin,\n    onError: cause => systemError({\n      module: \"Stdio\",\n      method: \"stdin\",\n      _tag: \"Unknown\",\n      cause\n    }),\n    closeOnDone: false\n  })\n}));\n//# sourceMappingURL=NodeStdio.js.map","/**\n * Node.js `Stdio` layer for the current process.\n *\n * The exported layer reuses the shared Node stdio implementation. It satisfies\n * the platform-independent `Stdio` service by reading command-line arguments\n * from `process.argv`, consuming input from `process.stdin`, and writing output\n * streams to `process.stdout` and `process.stderr`.\n *\n * @since 4.0.0\n */\nimport * as NodeStdio from \"@effect/platform-node-shared/NodeStdio\";\n/**\n * Provides the `Stdio` service backed by the current process arguments,\n * stdin, stdout, and stderr streams.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = NodeStdio.layer;\n//# sourceMappingURL=NodeStdio.js.map","/**\n * Runs schemas against real values.\n *\n * Schema parsers construct values from schema input, check whether a value\n * matches a schema, decode encoded input, and encode decoded values back to\n * their external form. This module exposes those operations through several\n * result styles, including `Effect`, `Promise`, `Exit`, `Option`, `Result`, and\n * synchronous functions that throw. It also contains the lower-level runner that\n * walks a schema AST and reports schema failures as `SchemaIssue.Issue` values.\n *\n * @since 4.0.0\n */\nimport * as Cause from \"./Cause.js\";\nimport * as Effect from \"./Effect.js\";\nimport * as Exit from \"./Exit.js\";\nimport { memoize } from \"./Function.js\";\nimport { effectIsExit } from \"./internal/effect.js\";\nimport * as InternalSchemaCause from \"./internal/schema/cause.js\";\nimport * as InternalParser from \"./internal/schema/parser.js\";\nimport * as Option from \"./Option.js\";\nimport * as Result from \"./Result.js\";\nimport * as SchemaAST from \"./SchemaAST.js\";\nimport * as SchemaIssue from \"./SchemaIssue.js\";\n/**\n * Creates an effectful maker for the schema's decoded type side.\n *\n * **When to use**\n *\n * Use to construct decoded schema values in `Effect` while preserving\n * construction failures as `SchemaIssue.Issue` values in the error channel.\n *\n * **Details**\n *\n * The returned function accepts constructor input, applies constructor defaults,\n * runs type-side validation unless checks are disabled, and fails with a\n * `SchemaIssue.Issue` when construction fails.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport function makeEffect(schema) {\n  const ast = schema.ast;\n  let parser;\n  return (input, options) => {\n    return (parser ??= runWithCompiler(constructorCompiler, SchemaAST.toType(ast)))(input, options?.disableChecks ? options?.parseOptions ? {\n      ...options.parseOptions,\n      disableChecks: true\n    } : {\n      disableChecks: true\n    } : options?.parseOptions);\n  };\n}\n/**\n * Creates a synchronous maker that returns `Option.some` with the constructed\n * value on success, or `Option.none` when construction fails with schema issues.\n *\n * **When to use**\n *\n * Use when you need to validate schema constructor input and only care whether\n * construction succeeds, without exposing `SchemaIssue.Issue` details.\n *\n * **Gotchas**\n *\n * Only causes made entirely of schema issues are converted to `Option.none`.\n * Causes that contain defects, interruptions, or asynchronous work at this\n * synchronous boundary throw an `Error` whose cause is the underlying `Cause`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport function makeOption(schema) {\n  const parser = makeEffect(schema);\n  return (input, options) => {\n    const exit = Effect.runSyncExit(parser(input, options));\n    if (Exit.isSuccess(exit)) {\n      return Option.some(exit.value);\n    }\n    InternalSchemaCause.getSchemaIssueOrThrow(exit.cause, \"Option adapter can only return none for schema issues\");\n    return Option.none();\n  };\n}\n/**\n * Creates a synchronous maker for the schema's decoded type side.\n *\n * **When to use**\n *\n * Use to construct decoded schema values synchronously when invalid input\n * should throw an `Error` whose cause is `SchemaIssue.Issue`.\n *\n * **Details**\n *\n * The returned function constructs a value from constructor input and throws an\n * `Error` with the `SchemaIssue.Issue` in its `cause` when construction fails.\n * Schema validation failures use the generic message `\"Schema validation failed\"`.\n * Format the `cause` explicitly with `SchemaIssue.makeFormatterDefault()` when\n * human-readable details are needed.\n *\n * **Gotchas**\n *\n * Causes that contain defects, interruptions, or asynchronous work at this\n * synchronous boundary throw an `Error` whose cause is the underlying `Cause`,\n * instead of being converted to a schema validation error.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport function make(schema) {\n  const parser = makeEffect(schema);\n  return (input, options) => {\n    const exit = Effect.runSyncExit(parser(input, options));\n    if (Exit.isSuccess(exit)) {\n      return exit.value;\n    }\n    const issue = InternalSchemaCause.getSchemaIssueOrThrow(exit.cause, \"Constructor adapter can only throw schema issues\");\n    throw new Error(\"Schema validation failed\", {\n      cause: issue\n    });\n  };\n}\n/**\n * Creates a type guard that checks whether an input satisfies the schema's decoded\n * type side.\n *\n * **When to use**\n *\n * Use to build a type guard for checking the decoded side of a schema without\n * exposing issue details.\n *\n * **Details**\n *\n * The guard returns `true` on successful validation and `false` when validation\n * fails only with schema issues, without exposing issue details.\n *\n * **Gotchas**\n *\n * Only causes made entirely of schema issues are converted to `false`. Causes\n * that contain defects, interruptions, or asynchronous work at this synchronous\n * boundary throw an `Error` whose cause is the underlying `Cause`.\n *\n * @category guards\n * @since 3.10.0\n */\nexport function is(schema) {\n  return _is(schema.ast);\n}\n/** @internal */\nexport function _is(ast) {\n  const parser = asExit(run(SchemaAST.toType(ast)));\n  return input => {\n    const exit = parser(input, SchemaAST.defaultParseOptions);\n    if (Exit.isSuccess(exit)) {\n      return true;\n    }\n    InternalSchemaCause.getSchemaIssueOrThrow(exit.cause, \"Type guard adapter can only return false for schema issues\");\n    return false;\n  };\n}\n/** @internal */\nexport function _issue(ast) {\n  const parser = run(ast);\n  return (input, options) => {\n    const exit = Effect.runSyncExit(parser(input, options));\n    if (Exit.isSuccess(exit)) {\n      return undefined;\n    }\n    return InternalSchemaCause.getSchemaIssueOrThrow(exit.cause, \"Issue adapter can only return schema issues\");\n  };\n}\n/**\n * Asserts that an input satisfies the schema's decoded type side.\n *\n * **When to use**\n *\n * Use to assert that an input satisfies the decoded side of a schema when schema\n * validation failures should throw an `Error` whose cause is `SchemaIssue.Issue`.\n *\n * **Details**\n *\n * The assertion returns normally when validation succeeds. When the input does\n * not satisfy the schema with a schema-only failure, it throws an `Error` with\n * the `SchemaIssue.Issue` in its `cause`.\n * Schema validation failures use the generic message `\"Schema validation failed\"`.\n * Format the `cause` explicitly with `SchemaIssue.makeFormatterDefault()` when\n * human-readable details are needed.\n *\n * **Gotchas**\n *\n * Causes that contain defects, interruptions, or asynchronous work at this\n * synchronous boundary throw an `Error` whose cause is the underlying `Cause`,\n * instead of being converted to a schema validation error.\n *\n * @category guards\n * @since 4.0.0\n */\nexport function asserts(schema, input) {\n  const parser = asExit(run(SchemaAST.toType(schema.ast)));\n  const exit = parser(input, SchemaAST.defaultParseOptions);\n  if (Exit.isFailure(exit)) {\n    const issue = InternalSchemaCause.getSchemaIssueOrThrow(exit.cause, \"Assertion adapter can only throw schema issues\");\n    throw new Error(\"Schema validation failed\", {\n      cause: issue\n    });\n  }\n}\n/**\n * Creates an effectful decoder for `unknown` input.\n *\n * **When to use**\n *\n * Use when you need to decode untyped boundary input in an `Effect` whose\n * failure channel is `SchemaIssue.Issue`, while preserving transformations\n * and service requirements.\n *\n * **Details**\n *\n * The returned function succeeds with the schema's decoded `Type` or fails with a\n * `SchemaIssue.Issue`. Decoding service requirements are preserved in the returned\n * `Effect`. Parse options may be provided when creating the decoder and overridden\n * when applying it.\n *\n * @see {@link decodeEffect} for input already typed as the schema's `Encoded` type\n *\n * @category decoding\n * @since 4.0.0\n */\nexport function decodeUnknownEffect(schema, options) {\n  const parser = run(schema.ast);\n  return options === undefined ? parser : (input, overrideOptions) => parser(input, mergeParseOptions(options, overrideOptions));\n}\n/**\n * Creates an effectful decoder for input already typed as the schema's `Encoded`\n * type.\n *\n * **When to use**\n *\n * Use when you already have input typed as the schema's `Encoded` type and\n * need an `Effect` whose failure channel is `SchemaIssue.Issue`, while\n * preserving decoding service requirements.\n *\n * **Details**\n *\n * The returned function succeeds with the decoded `Type` or fails with a\n * `SchemaIssue.Issue`, preserving any decoding service requirements in the\n * returned `Effect`.\n *\n * @see {@link decodeUnknownEffect} for untyped boundary input\n * @see {@link encodeEffect} for the opposite direction\n *\n * @category decoding\n * @since 4.0.0\n */\nexport const decodeEffect = decodeUnknownEffect;\n/**\n * Creates a Promise-based decoder for `unknown` input.\n *\n * **When to use**\n *\n * Use when you need to decode untyped input with a service-free schema and\n * return a JavaScript `Promise`.\n *\n * **Details**\n *\n * The returned function resolves with the decoded `Type` on success and rejects\n * with an `Error` whose cause is a `SchemaIssue.Issue` on decoding failure.\n * Schema validation failures use the generic message `\"Schema validation failed\"`.\n * Format the `cause` explicitly with `SchemaIssue.makeFormatterDefault()` when\n * human-readable details are needed.\n *\n * **Gotchas**\n *\n * Causes that contain defects, interruptions, or other non-schema reasons reject\n * with an `Error` whose cause is the underlying `Cause`.\n *\n * @see {@link decodePromise} for input already typed as the schema's `Encoded` type\n * @see {@link decodeUnknownEffect} for schemas that require decoding services or when failures should remain in `Effect`\n *\n * @category decoding\n * @since 3.10.0\n */\nexport function decodeUnknownPromise(schema, options) {\n  return asPromise(decodeUnknownEffect(schema, options));\n}\n/**\n * Creates a Promise-based decoder for input already typed as the schema's\n * `Encoded` type.\n *\n * **When to use**\n *\n * Use when you already have input typed as the schema's `Encoded` type and need\n * decoding to return a JavaScript `Promise`.\n *\n * **Details**\n *\n * The returned function resolves with the decoded `Type` on success and rejects\n * with an `Error` whose cause is a `SchemaIssue.Issue` on decoding failure.\n * Schema validation failures use the generic message `\"Schema validation failed\"`.\n * Format the `cause` explicitly with `SchemaIssue.makeFormatterDefault()` when\n * human-readable details are needed.\n *\n * **Gotchas**\n *\n * Causes that contain defects, interruptions, or other non-schema reasons reject\n * with an `Error` whose cause is the underlying `Cause`.\n *\n * @see {@link decodeUnknownPromise} for untyped input returning a JavaScript `Promise`\n * @see {@link decodeEffect} for preserving decoding services and failures in `Effect`\n *\n * @category decoding\n * @since 3.10.0\n */\nexport function decodePromise(schema, options) {\n  return asPromise(decodeEffect(schema, options));\n}\n/**\n * Creates a synchronous decoder for `unknown` input that reports failure safely\n * as an `Exit`.\n *\n * **When to use**\n *\n * Use when you need to decode unknown input synchronously into an `Exit` whose\n * failure contains `SchemaIssue.Issue`.\n *\n * **Details**\n *\n * The returned function produces `Exit.Success` with the decoded `Type`.\n * Schema issues are represented by an `Exit.Failure` cause containing a\n * `SchemaIssue.Issue`.\n *\n * **Gotchas**\n *\n * Because this adapter runs synchronously, async decoding work can produce an\n * `Exit.Failure` with a defect cause. When the cause contains both schema\n * issues and non-schema reasons, all reasons remain in the returned `Cause`.\n *\n * @see {@link decodeExit} for input already typed as the schema's `Encoded` type\n * @see {@link decodeUnknownEffect} for preserving decoding services and failures in `Effect`\n * @see {@link decodeUnknownResult} for returning schema issues as data\n * @see {@link decodeUnknownSync} for throwing on decoding failure\n *\n * @category decoding\n * @since 4.0.0\n */\nexport function decodeUnknownExit(schema, options) {\n  return asExit(decodeUnknownEffect(schema, options));\n}\n/**\n * Creates a synchronous decoder for input already typed as the schema's `Encoded`\n * type, reporting failure safely as an `Exit`.\n *\n * **When to use**\n *\n * Use when you need synchronous decoding of already typed `Encoded` input into\n * an `Exit` whose failure contains `SchemaIssue.Issue`.\n *\n * **Details**\n *\n * The returned function produces `Exit.Success` with the decoded `Type` or\n * `Exit.Failure` with a `SchemaIssue.Issue`.\n *\n * **Gotchas**\n *\n * Because this adapter runs synchronously, async decoding work can produce an\n * `Exit.Failure` with a defect cause. When the cause contains both schema\n * issues and non-schema reasons, all reasons remain in the returned `Cause`.\n *\n * @see {@link decodeUnknownExit} for untyped input with the same `Exit` result shape\n * @see {@link decodeEffect} for preserving decoding services and failures in `Effect`\n *\n * @category decoding\n * @since 4.0.0\n */\nexport const decodeExit = decodeUnknownExit;\n/** @internal */\nexport function decodeUnknownOption(schema, options) {\n  return asOption(decodeUnknownEffect(schema, options));\n}\n/** @internal */\nexport const decodeOption = decodeUnknownOption;\n/**\n * Creates a decoder for `unknown` input that reports failure safely as a\n * `Result`.\n *\n * **When to use**\n *\n * Use when decoding untyped boundary input and you want `SchemaIssue.Issue`\n * failures returned as data in a `Result`.\n *\n * **Details**\n *\n * The returned function produces `Result.succeed` with the decoded `Type` on\n * success or `Result.fail` with a `SchemaIssue.Issue` on decoding failure.\n *\n * **Gotchas**\n *\n * This adapter runs synchronously. Causes made entirely of schema issues become\n * `Result.fail`, but causes that contain defects, interruptions, or asynchronous\n * work at this synchronous boundary throw instead.\n *\n * @see {@link decodeResult} for input already typed as the schema's `Encoded` type\n * @see {@link decodeUnknownEffect} for effectful or service-requiring decoding\n *\n * @category decoding\n * @since 4.0.0\n */\nexport function decodeUnknownResult(schema, options) {\n  return asResult(decodeUnknownEffect(schema, options));\n}\n/**\n * Creates a decoder for input already typed as the schema's `Encoded` type,\n * reporting failure safely as a `Result`.\n *\n * **When to use**\n *\n * Use when you already have input typed as the schema's `Encoded` type and want\n * schema decoding failures represented as `Result.fail` with `SchemaIssue.Issue`.\n *\n * **Details**\n *\n * The returned function produces `Result.succeed` with the decoded `Type` on\n * success or `Result.fail` with a `SchemaIssue.Issue` on decoding failure.\n *\n * **Gotchas**\n *\n * This synchronous adapter returns `Result.fail` for causes made entirely of\n * schema issues, but causes that contain defects, interruptions, or other\n * non-schema reasons throw instead.\n *\n * @see {@link decodeUnknownResult} for untyped input with the same `Result` shape\n * @see {@link decodeEffect} for effectful or service-requiring decoding\n *\n * @category decoding\n * @since 4.0.0\n */\nexport const decodeResult = decodeUnknownResult;\n/**\n * Creates a synchronous decoder for `unknown` input.\n *\n * **When to use**\n *\n * Use to decode untrusted or dynamically typed input at a synchronous boundary\n * where invalid data should throw an `Error` whose cause is `SchemaIssue.Issue`.\n *\n * **Details**\n *\n * The returned function returns the decoded `Type` on success and throws an\n * `Error` with the `SchemaIssue.Issue` in its `cause` on decoding failure.\n * Schema validation failures use the generic message `\"Schema validation failed\"`.\n * Format the `cause` explicitly with `SchemaIssue.makeFormatterDefault()` when\n * human-readable details are needed.\n *\n * **Gotchas**\n *\n * Causes that contain defects, interruptions, or asynchronous work at this\n * synchronous boundary throw an `Error` whose cause is the underlying `Cause`,\n * instead of being converted to a schema validation error.\n *\n * @see {@link decodeSync} for input already typed as the schema's `Encoded` type\n * @see {@link decodeUnknownEffect} for preserving decoding failures in `Effect`\n * @see {@link decodeUnknownResult} for returning schema issues as data\n *\n * @category decoding\n * @since 3.10.0\n */\nexport function decodeUnknownSync(schema, options) {\n  return asSync(decodeUnknownEffect(schema, options));\n}\n/**\n * Creates a synchronous decoder for input already typed as the schema's `Encoded`\n * type.\n *\n * **When to use**\n *\n * Use to decode values already typed as the schema's `Encoded` input when\n * decoding failure should throw an `Error` whose cause is `SchemaIssue.Issue`.\n *\n * **Details**\n *\n * The returned function returns the decoded `Type` on success and throws an\n * `Error` with the `SchemaIssue.Issue` in its `cause` on decoding failure.\n * Schema validation failures use the generic message `\"Schema validation failed\"`.\n * Format the `cause` explicitly with `SchemaIssue.makeFormatterDefault()` when\n * human-readable details are needed.\n *\n * **Gotchas**\n *\n * Causes that contain defects, interruptions, or asynchronous work at this\n * synchronous boundary throw an `Error` whose cause is the underlying `Cause`,\n * instead of being converted to a schema validation error.\n *\n * @see {@link decodeUnknownSync} for untrusted or dynamically typed input\n * @see {@link decodeResult} for returning schema issues as data\n * @see {@link decodeEffect} for preserving decoding failures in `Effect`\n *\n * @category decoding\n * @since 3.10.0\n */\nexport const decodeSync = decodeUnknownSync;\n/**\n * Creates an effectful encoder for `unknown` input.\n *\n * **When to use**\n *\n * Use when you need to encode untyped boundary input in an `Effect` whose\n * failure channel is `SchemaIssue.Issue`, while preserving service\n * requirements.\n *\n * **Details**\n *\n * The returned function succeeds with the schema's `Encoded` value or fails with a\n * `SchemaIssue.Issue`. Encoding service requirements are preserved in the returned\n * `Effect`. Parse options may be provided when creating the encoder and overridden\n * when applying it.\n *\n * @see {@link encodeEffect} for the typed-input variant when the value is already typed as the schema's decoded `Type`\n *\n * @category encoding\n * @since 4.0.0\n */\nexport function encodeUnknownEffect(schema, options) {\n  const parser = run(SchemaAST.flip(schema.ast));\n  return options === undefined ? parser : (input, overrideOptions) => parser(input, mergeParseOptions(options, overrideOptions));\n}\n/**\n * Creates an effectful encoder for input already typed as the schema's decoded\n * `Type`.\n *\n * **When to use**\n *\n * Use when you need to encode values already typed as the schema's decoded\n * `Type` in an `Effect` whose failure channel is `SchemaIssue.Issue`, while\n * preserving service requirements.\n *\n * **Details**\n *\n * The returned function succeeds with the schema's `Encoded` value or fails with a\n * `SchemaIssue.Issue`, preserving any encoding service requirements in the\n * returned `Effect`.\n *\n * @see {@link encodeUnknownEffect} for encoding unknown input before the value is statically typed as the schema's `Type`\n *\n * @category encoding\n * @since 4.0.0\n */\nexport const encodeEffect = encodeUnknownEffect;\n/**\n * Creates a Promise-based encoder for `unknown` input.\n *\n * **When to use**\n *\n * Use when you need to encode untrusted or dynamically typed values with a\n * service-free schema and return a JavaScript `Promise`.\n *\n * **Details**\n *\n * The returned function resolves with the schema's `Encoded` value on success and\n * rejects with an `Error` whose cause is a `SchemaIssue.Issue` on encoding failure.\n * Schema validation failures use the generic message `\"Schema validation failed\"`.\n * Format the `cause` explicitly with `SchemaIssue.makeFormatterDefault()` when\n * human-readable details are needed.\n *\n * **Gotchas**\n *\n * Causes that contain defects, interruptions, or other non-schema reasons reject\n * with an `Error` whose cause is the underlying `Cause`.\n *\n * @see {@link encodePromise} for input already typed as the schema's decoded `Type`\n * @see {@link encodeUnknownEffect} for schemas that require encoding services or when failures should remain in `Effect`\n *\n * @category encoding\n * @since 3.10.0\n */\nexport const encodeUnknownPromise = (schema, options) => asPromise(encodeUnknownEffect(schema, options));\n/**\n * Creates a Promise-based encoder for input already typed as the schema's decoded\n * `Type`.\n *\n * **When to use**\n *\n * Use when you already have values typed as the schema's decoded `Type` and\n * need encoding to return a JavaScript `Promise`.\n *\n * **Details**\n *\n * The returned function resolves with the schema's `Encoded` value on success and\n * rejects with an `Error` whose cause is a `SchemaIssue.Issue` on encoding failure.\n * Schema validation failures use the generic message `\"Schema validation failed\"`.\n * Format the `cause` explicitly with `SchemaIssue.makeFormatterDefault()` when\n * human-readable details are needed.\n *\n * **Gotchas**\n *\n * Causes that contain defects, interruptions, or other non-schema reasons reject\n * with an `Error` whose cause is the underlying `Cause`.\n *\n * @see {@link encodeUnknownPromise} for encoding untyped input\n * @see {@link encodeEffect} for effectful encoding or schemas with encoding service requirements\n *\n * @category encoding\n * @since 3.10.0\n */\nexport const encodePromise = encodeUnknownPromise;\n/**\n * Creates a synchronous encoder for `unknown` input that reports failure safely\n * as an `Exit`.\n *\n * **When to use**\n *\n * Use when you need synchronous encoding of unknown input into an `Exit` whose\n * failure contains `SchemaIssue.Issue`.\n *\n * **Details**\n *\n * The returned function produces `Exit.Success` with the schema's `Encoded` value\n * or `Exit.Failure` with a `SchemaIssue.Issue`.\n *\n * **Gotchas**\n *\n * Because this adapter runs synchronously, async encoding work can produce an\n * `Exit.Failure` with a defect cause. When the cause contains both schema\n * issues and non-schema reasons, all reasons remain in the returned `Cause`.\n *\n * @see {@link encodeExit} for input already typed as the schema's decoded `Type`\n * @see {@link encodeUnknownEffect} for effectful encoding that preserves service requirements\n *\n * @category encoding\n * @since 4.0.0\n */\nexport function encodeUnknownExit(schema, options) {\n  return asExit(encodeUnknownEffect(schema, options));\n}\n/**\n * Creates a synchronous encoder for input already typed as the schema's decoded\n * `Type`, reporting failure safely as an `Exit`.\n *\n * **When to use**\n *\n * Use when you need synchronous encoding of already typed schema values into\n * an `Exit` whose failure contains `SchemaIssue.Issue`.\n *\n * **Details**\n *\n * The returned function produces `Exit.Success` with the schema's `Encoded` value\n * or `Exit.Failure` with a `SchemaIssue.Issue`.\n *\n * **Gotchas**\n *\n * Because this adapter runs synchronously, async encoding work can produce an\n * `Exit.Failure` with a defect cause. When the cause contains both schema\n * issues and non-schema reasons, all reasons remain in the returned `Cause`.\n *\n * @see {@link encodeUnknownExit} for unknown input with the same `Exit` result shape\n * @see {@link encodeEffect} for effectful encoding that preserves service requirements\n *\n * @category encoding\n * @since 4.0.0\n */\nexport const encodeExit = encodeUnknownExit;\n/** @internal */\nexport function encodeUnknownOption(schema, options) {\n  return asOption(encodeUnknownEffect(schema, options));\n}\n/** @internal */\nexport const encodeOption = encodeUnknownOption;\n/**\n * Creates an encoder for `unknown` input that reports failure safely as a\n * `Result`.\n *\n * **When to use**\n *\n * Use when encoding values from an unknown or dynamically typed boundary\n * synchronously, and you want `SchemaIssue.Issue` failures returned as `Result`\n * data.\n *\n * **Details**\n *\n * The returned function produces `Result.succeed` with the schema's `Encoded`\n * value on success or `Result.fail` with a `SchemaIssue.Issue` on encoding\n * failure.\n *\n * **Gotchas**\n *\n * This adapter runs synchronously. Causes made entirely of schema issues become\n * `Result.fail`, but causes that contain defects, interruptions, or asynchronous\n * work at this synchronous boundary throw instead.\n *\n * @see {@link encodeResult} for input already typed as the schema's decoded `Type`\n * @see {@link encodeUnknownEffect} for effectful encoding, including schemas with encoding service requirements\n *\n * @category encoding\n * @since 4.0.0\n */\nexport function encodeUnknownResult(schema, options) {\n  return asResult(encodeUnknownEffect(schema, options));\n}\n/**\n * Creates an encoder for input already typed as the schema's decoded `Type`,\n * reporting failure safely as a `Result`.\n *\n * **When to use**\n *\n * Use when you already have input typed as the schema's decoded `Type` and want\n * encoding failures returned as `Result.fail` with `SchemaIssue.Issue`.\n *\n * **Details**\n *\n * The returned function produces `Result.succeed` with the schema's `Encoded`\n * value on success or `Result.fail` with a `SchemaIssue.Issue` on encoding\n * failure.\n *\n * **Gotchas**\n *\n * This synchronous adapter returns `Result.fail` for causes made entirely of\n * schema issues, but causes that contain defects, interruptions, or other\n * non-schema reasons throw instead.\n *\n * @see {@link encodeUnknownResult} for the same `Result` shape when the input is not already typed\n *\n * @category encoding\n * @since 4.0.0\n */\nexport const encodeResult = encodeUnknownResult;\n/**\n * Creates a synchronous encoder for `unknown` input.\n *\n * **When to use**\n *\n * Use when you need to encode values from untyped input in synchronous code and\n * want encoding failures to throw an `Error` whose cause is `SchemaIssue.Issue`.\n *\n * **Details**\n *\n * The returned function returns the schema's `Encoded` value on success and throws\n * an `Error` with the `SchemaIssue.Issue` in its `cause` on encoding failure.\n * Schema validation failures use the generic message `\"Schema validation failed\"`.\n * Format the `cause` explicitly with `SchemaIssue.makeFormatterDefault()` when\n * human-readable details are needed.\n *\n * **Gotchas**\n *\n * Causes that contain defects, interruptions, or asynchronous work at this\n * synchronous boundary throw an `Error` whose cause is the underlying `Cause`,\n * instead of being converted to a schema validation error.\n *\n * @see {@link encodeSync} for input already typed as the schema's decoded `Type`\n * @see {@link encodeUnknownEffect} for effectful encoding that preserves service requirements\n *\n * @category encoding\n * @since 3.10.0\n */\nexport function encodeUnknownSync(schema, options) {\n  return asSync(encodeUnknownEffect(schema, options));\n}\n/**\n * Creates a synchronous encoder for input already typed as the schema's decoded\n * `Type`.\n *\n * **When to use**\n *\n * Use to encode already typed schema values synchronously when encoding failure\n * should throw an `Error` whose cause is `SchemaIssue.Issue`.\n *\n * **Details**\n *\n * The returned function returns the schema's `Encoded` value on success and throws\n * an `Error` with the `SchemaIssue.Issue` in its `cause` on encoding failure.\n * Schema validation failures use the generic message `\"Schema validation failed\"`.\n * Format the `cause` explicitly with `SchemaIssue.makeFormatterDefault()` when\n * human-readable details are needed.\n *\n * **Gotchas**\n *\n * Causes that contain defects, interruptions, or asynchronous work at this\n * synchronous boundary throw an `Error` whose cause is the underlying `Cause`,\n * instead of being converted to a schema validation error.\n *\n * @see {@link encodeUnknownSync} for unknown input with the same throwing boundary\n * @see {@link encodeResult} for returning schema issues as data\n * @see {@link encodeEffect} for effectful encoding that preserves service requirements\n *\n * @category encoding\n * @since 3.10.0\n */\nexport const encodeSync = encodeUnknownSync;\nconst mergeParseOptions = (options, overrideOptions) => overrideOptions ? {\n  ...options,\n  ...overrideOptions\n} : options;\nconst getValue = value => {\n  if (value === InternalParser.missing) {\n    return Effect.fail(new SchemaIssue.InvalidValue());\n  }\n  return Effect.succeed(value);\n};\n/** @internal */\nexport function run(ast) {\n  return runWithCompiler(normalCompiler, ast);\n}\nfunction runWithCompiler(compiler, ast) {\n  let parser;\n  return (input, options) => {\n    const result = (parser ??= compiler(ast))(input, options ?? SchemaAST.defaultParseOptions);\n    if (result === InternalParser.sameExit) {\n      return Effect.succeed(input);\n    }\n    if (!effectIsExit(result)) {\n      return Effect.flatMapEager(result, getValue);\n    }\n    return result[InternalParser.args] === InternalParser.missing ? getValue(InternalParser.missing) : result;\n  };\n}\nfunction asPromise(parser) {\n  return (input, options) => Effect.runPromiseExit(parser(input, options)).then(exit => {\n    if (Exit.isSuccess(exit)) {\n      return exit.value;\n    }\n    const issue = InternalSchemaCause.getSchemaIssueOrThrow(exit.cause, \"Promise adapter can only reject schema issues\");\n    throw new Error(\"Schema validation failed\", {\n      cause: issue\n    });\n  });\n}\nfunction asExit(parser) {\n  return (input, options) => Effect.runSyncExit(parser(input, options));\n}\n/** @internal */\nexport function asOption(parser) {\n  const parserExit = asExit(parser);\n  return (input, options) => {\n    const exit = parserExit(input, options);\n    if (Exit.isSuccess(exit)) {\n      return Option.some(exit.value);\n    }\n    InternalSchemaCause.getSchemaIssueOrThrow(exit.cause, \"Option adapter can only return none for schema issues\");\n    return Option.none();\n  };\n}\nfunction asResult(parser) {\n  const parserExit = asExit(parser);\n  return (input, options) => {\n    const exit = parserExit(input, options);\n    if (Exit.isSuccess(exit)) {\n      return Result.succeed(exit.value);\n    }\n    return Result.fail(InternalSchemaCause.getSchemaIssueOrThrow(exit.cause, \"Result adapter can only return schema issues\"));\n  };\n}\nfunction asSync(parser) {\n  const parserExit = asExit(parser);\n  return (input, options) => {\n    const exit = parserExit(input, options);\n    if (Exit.isSuccess(exit)) {\n      return exit.value;\n    }\n    const issue = InternalSchemaCause.getSchemaIssueOrThrow(exit.cause, \"Sync adapter can only throw schema issues\");\n    throw new Error(\"Schema validation failed\", {\n      cause: issue\n    });\n  };\n}\nconst normalCompiler = /*#__PURE__*/memoize(ast => makeParser(ast, normalCompiler));\nconst constructorCompiler = /*#__PURE__*/memoize(ast => makeParser(ast, constructorCompiler, compileConstructorDefault));\nconst compileDefaulted = /*#__PURE__*/memoize(ast => makeParser(ast, constructorCompiler, compileConstructorDefault, ast.context?.constructorDefault));\nfunction compileConstructorDefault(ast) {\n  return ast.context?.constructorDefault ? compileDefaulted(ast) : constructorCompiler(ast);\n}\nfunction applyTransformation(result, current, transformation, options) {\n  let transformed;\n  if (effectIsExit(result) && result._tag === \"Success\") {\n    const optional = InternalParser.toOption(result === InternalParser.sameExit ? current : result[InternalParser.args]);\n    transformed = transformation._tag === \"Transformation\" ? transformation.decode.run(optional, options) : transformation.decode(InternalParser.succeed(optional), options);\n  } else if (transformation._tag === \"Transformation\") {\n    transformed = Effect.flatMapEager(result, value => transformation.decode.run(InternalParser.toOption(value), options));\n  } else {\n    transformed = transformation.decode(Effect.mapEager(result, InternalParser.toOption), options);\n  }\n  return effectIsExit(transformed) && transformed._tag === \"Success\" ? InternalParser.fromOptionExit(transformed[InternalParser.args]) : Effect.flatMapEager(transformed, InternalParser.fromOptionExit);\n}\nfunction makeConstructorParser(descriptor, compile) {\n  let sourceParser;\n  return (input, options) => {\n    if (input === InternalParser.missing) return InternalParser.missingExit;\n    if (descriptor.isConstructed(input)) return InternalParser.sameExit;\n    const result = (sourceParser ??= compile(descriptor.link.to))(input, options);\n    return applyTransformation(result, input, descriptor.link.transformation, options);\n  };\n}\nfunction makeParser(ast, compile, compileConstructorDefault, constructorDefault) {\n  const descriptor = compileConstructorDefault ? SchemaAST.getConstructorDescriptor(ast) : undefined;\n  const parser = descriptor ? makeConstructorParser(descriptor, compile) : ast.getParser(compile, compileConstructorDefault);\n  const checks = ast.checks;\n  const links = constructorDefault ? ast.encoding ? [...ast.encoding, constructorDefault] : [constructorDefault] : ast.encoding;\n  const encodingChecks = ast.encodingChecks;\n  if (!links && !checks && !encodingChecks) {\n    return parser;\n  }\n  let encodingParsers;\n  const parseLocal = (input, options) => {\n    let result = parser(input, options);\n    if (encodingChecks && !options.disableChecks) {\n      if (effectIsExit(result)) {\n        if (result._tag === \"Success\") {\n          const output = result === InternalParser.sameExit ? input : result[InternalParser.args];\n          if (input !== InternalParser.missing && output !== InternalParser.missing) {\n            const issues = SchemaAST.collectIssues(encodingChecks, input, undefined, ast, options);\n            if (issues) {\n              result = Effect.fail(new SchemaIssue.Composite(ast, issues, input, options));\n            }\n          }\n        }\n      } else {\n        result = Effect.flatMap(result, value => {\n          if (input !== InternalParser.missing && value !== InternalParser.missing) {\n            const issues = SchemaAST.collectIssues(encodingChecks, input, undefined, ast, options);\n            if (issues) {\n              return Effect.fail(new SchemaIssue.Composite(ast, issues, input, options));\n            }\n          }\n          return Effect.succeed(value);\n        });\n      }\n    }\n    if (checks && !options.disableChecks) {\n      if (effectIsExit(result)) {\n        if (result._tag === \"Success\") {\n          const value = result === InternalParser.sameExit ? input : result[InternalParser.args];\n          if (value === InternalParser.missing) return result;\n          const issues = SchemaAST.collectIssues(checks, value, undefined, ast, options);\n          if (issues) {\n            result = Effect.fail(new SchemaIssue.Composite(ast, issues, value, options));\n          }\n        }\n      } else {\n        result = Effect.flatMap(result, value => {\n          if (value !== InternalParser.missing) {\n            const issues = SchemaAST.collectIssues(checks, value, undefined, ast, options);\n            if (issues) {\n              return Effect.fail(new SchemaIssue.Composite(ast, issues, value, options));\n            }\n          }\n          return Effect.succeed(value);\n        });\n      }\n    }\n    return result;\n  };\n  if (!links) {\n    return parseLocal;\n  }\n  return (input, options) => {\n    const parsers = encodingParsers ??= links.map(link => compile(link.to));\n    let current = input;\n    let result = parsers[parsers.length - 1](input, options);\n    for (let i = links.length - 1; i >= 0; i--) {\n      result = applyTransformation(result, current, links[i].transformation, options);\n      if (i !== 0) {\n        const next = parsers[i - 1];\n        if (result._tag === \"Success\") {\n          current = result[InternalParser.args];\n          result = next(current, options);\n        } else {\n          result = Effect.flatMapEager(result, value => {\n            const nextResult = next(value, options);\n            return nextResult === InternalParser.sameExit ? InternalParser.succeed(value) : nextResult;\n          });\n        }\n      }\n    }\n    if (result._tag === \"Success\") {\n      const value = result[InternalParser.args];\n      const local = parseLocal(value, options);\n      return local === InternalParser.sameExit ? result : local;\n    }\n    result = Effect.catchCause(result, cause => Effect.failCauseSync(() => Cause.map(cause, issue => new SchemaIssue.Encoding(ast, issue, input, options))));\n    return Effect.flatMapEager(result, value => {\n      const local = parseLocal(value, options);\n      return local === InternalParser.sameExit ? InternalParser.succeed(value) : local;\n    });\n  };\n}\n//# sourceMappingURL=SchemaParser.js.map","import * as Pipeable from \"../../Pipeable.js\";\nimport * as SchemaAST from \"../../SchemaAST.js\";\nimport * as SchemaParser from \"../../SchemaParser.js\";\n/** @internal */\nexport const TypeId = \"~effect/Schema/Schema\";\nconst SchemaProto = {\n  [TypeId]: TypeId,\n  pipe() {\n    return Pipeable.pipeArguments(this, arguments);\n  },\n  annotate(annotations) {\n    return this.rebuild(SchemaAST.annotate(this.ast, annotations));\n  },\n  annotateKey(annotations) {\n    return this.rebuild(SchemaAST.annotateKey(this.ast, annotations));\n  },\n  check(...checks) {\n    return this.rebuild(SchemaAST.appendChecks(this.ast, checks));\n  }\n};\n/** @internal */\nexport function make(ast, options) {\n  function Schema() {}\n  const self = Object.setPrototypeOf(Schema, SchemaProto);\n  if (options && (Object.hasOwn(options, \"name\") || Object.hasOwn(options, \"length\") || Object.hasOwn(options, \"__proto__\"))) {\n    Object.defineProperties(self, Object.getOwnPropertyDescriptors({\n      ...options\n    }));\n  } else {\n    Object.assign(self, options);\n  }\n  self.ast = ast;\n  self.rebuild = ast => make(ast, options);\n  self.makeEffect = SchemaParser.makeEffect(self);\n  self.make = SchemaParser.make(self);\n  self.makeOption = SchemaParser.makeOption(self);\n  return self;\n}\n//# sourceMappingURL=make.js.map","/**\n * Works with plain TypeScript objects, also called structs.\n *\n * The runtime helpers in this module create new objects instead of mutating\n * their inputs. They cover common object workflows such as reading properties,\n * listing typed keys, picking or omitting fields, assigning and renaming keys,\n * transforming values, deriving comparison helpers, and creating records from a\n * list of keys. The module also includes type-level helpers for simplifying and\n * merging object shapes.\n *\n * @since 2.0.0\n */\nimport * as Combiner from \"./Combiner.js\";\nimport * as Equivalence from \"./Equivalence.js\";\nimport { dual } from \"./Function.js\";\nimport * as InternalRecord from \"./internal/record.js\";\nimport * as order from \"./Order.js\";\nimport * as Reducer from \"./Reducer.js\";\n/**\n * Retrieves the value at `key` from a struct.\n *\n * **When to use**\n *\n * Use to extract a single property from a struct in a pipeline.\n *\n * **Details**\n *\n * The return type is narrowed to `S[K]`.\n *\n * **Example** (Extracting a property in a pipeline)\n *\n * ```ts import.meta.vitest\n * import { pipe, Struct } from \"effect\"\n *\n * pipe({ name: \"Alice\", age: 30 }, Struct.get(\"name\")) // => \"Alice\"\n * ```\n *\n * @see {@link keys} – list all string keys of a struct\n * @see {@link pick} – extract multiple properties into a new struct\n * @category getters\n * @since 2.0.0\n */\nexport const get = /*#__PURE__*/dual(2, (self, key) => self[key]);\n/**\n * Returns the string keys of a struct as a properly typed `Array<keyof S & string>`.\n *\n * **When to use**\n *\n * Use when you want a typed replacement for `Object.keys` that narrows the result\n * to the known string keys of the struct.\n *\n * **Gotchas**\n *\n * Symbol keys are excluded; only string keys are returned.\n *\n * **Example** (Reading typed keys)\n *\n * ```ts import.meta.vitest\n * import { Struct } from \"effect\"\n *\n * const user = { name: \"Alice\", age: 30, [Symbol.for(\"id\")]: 1 }\n *\n * const k: Array<\"name\" | \"age\"> = Struct.keys(user)\n * k // => [\"name\", \"age\"]\n * ```\n *\n * @see {@link get} – access a single key's value\n * @see {@link pick} – select a subset of keys into a new struct\n * @category getters\n * @since 3.6.0\n */\nexport const keys = self => Object.keys(self);\n/**\n * Creates a new struct containing only the specified keys.\n *\n * **When to use**\n *\n * Use to narrow a struct down to a subset of its properties.\n *\n * **Gotchas**\n *\n * Keys not present in the struct are silently ignored.\n *\n * **Example** (Selecting specific properties)\n *\n * ```ts import.meta.vitest\n * import { pipe, Struct } from \"effect\"\n *\n * const user = { name: \"Alice\", age: 30, admin: true }\n * pipe(user, Struct.pick([\"name\", \"age\"])) // => { name: \"Alice\", age: 30 }\n * ```\n *\n * @see {@link omit} – the inverse (exclude keys instead)\n * @see {@link get} – extract a single value\n * @category filtering\n * @since 2.0.0\n */\nexport const pick = /*#__PURE__*/dual(2, (self, keys) => {\n  return buildStruct(self, (k, v) => hasPropertyKey(keys, k) ? [k, v] : undefined);\n});\n/**\n * Creates a new struct with the specified keys removed.\n *\n * **When to use**\n *\n * Use to exclude sensitive or irrelevant fields from a struct.\n *\n * **Gotchas**\n *\n * Keys not present in the struct are silently ignored.\n *\n * **Example** (Removing a property)\n *\n * ```ts import.meta.vitest\n * import { pipe, Struct } from \"effect\"\n *\n * const user = { name: \"Alice\", age: 30, password: \"secret\" }\n * pipe(user, Struct.omit([\"password\"])) // => { name: \"Alice\", age: 30 }\n * ```\n *\n * @see {@link pick} – the inverse (keep only specified keys)\n * @category filtering\n * @since 2.0.0\n */\nexport const omit = /*#__PURE__*/dual(2, (self, keys) => {\n  return buildStruct(self, (k, v) => !hasPropertyKey(keys, k) ? [k, v] : undefined);\n});\n/**\n * Merges two structs into a new struct. When both structs share a key, the\n * value from `that` (the second struct) wins.\n *\n * **When to use**\n *\n * Use when you want `{ ...self, ...that }` with proper types.\n *\n * **Details**\n *\n * The result type is `Simplify<Assign<S, O>>`.\n *\n * **Example** (Merging structs with overlapping keys)\n *\n * ```ts import.meta.vitest\n * import { pipe, Struct } from \"effect\"\n *\n * const defaults = { theme: \"light\", lang: \"en\" }\n * const overrides = { theme: \"dark\", fontSize: 14 }\n * pipe(defaults, Struct.assign(overrides)) // => { theme: \"dark\", lang: \"en\", fontSize: 14 }\n * ```\n *\n * @see {@link Assign} – the type-level equivalent\n * @see {@link evolve} – transform individual values instead of replacing them\n * @category combining\n * @since 4.0.0\n */\nexport const assign = /*#__PURE__*/dual(2, (self, that) => {\n  return {\n    ...self,\n    ...that\n  };\n});\n/**\n * Transforms values of a struct selectively using per-key functions. Keys\n * without a corresponding function are copied unchanged.\n *\n * **When to use**\n *\n * Use when you want to update specific fields while keeping the rest intact.\n *\n * **Details**\n *\n * Each transform function receives the current value and returns the new value;\n * the return type can differ from the input type.\n *\n * **Example** (Transforming selected values)\n *\n * ```ts import.meta.vitest\n * import { pipe, Struct } from \"effect\"\n *\n * const result = pipe(\n *   { name: \"alice\", age: 30, active: true },\n *   Struct.evolve({\n *     name: (s) => s.toUpperCase(),\n *     age: (n) => n + 1\n *   })\n * )\n * result // => { name: \"ALICE\", age: 31, active: true }\n * ```\n *\n * @see {@link evolveKeys} – transform keys instead of values\n * @see {@link evolveEntries} – transform both keys and values\n * @see {@link map} – apply the same transformation to all values\n * @category transforming\n * @since 2.0.0\n */\nexport const evolve = /*#__PURE__*/dual(2, (self, e) => {\n  return buildStruct(self, (k, v) => [k, Object.hasOwn(e, k) ? e[k](v) : v]);\n});\n/**\n * Transforms keys of a struct selectively using per-key functions. Keys without\n * a corresponding function are copied unchanged.\n *\n * **When to use**\n *\n * Use when you need computed key names, such as uppercasing or prefixing.\n *\n * **Details**\n *\n * Each transform function receives the key name and must return a new\n * `PropertyKey`.\n *\n * **Example** (Renaming keys with functions)\n *\n * ```ts import.meta.vitest\n * import { pipe, Struct } from \"effect\"\n *\n * const result = pipe(\n *   { name: \"Alice\", age: 30 },\n *   Struct.evolveKeys({\n *     name: (k) => k.toUpperCase()\n *   })\n * )\n * result // => { NAME: \"Alice\", age: 30 }\n * ```\n *\n * @see {@link renameKeys} – rename keys with a static mapping\n * @see {@link evolve} – transform values instead of keys\n * @see {@link evolveEntries} – transform both keys and values\n * @category transforming\n * @since 4.0.0\n */\nexport const evolveKeys = /*#__PURE__*/dual(2, (self, e) => {\n  return buildStruct(self, (k, v) => [Object.hasOwn(e, k) ? e[k](k) : k, v]);\n});\n/**\n * Transforms both keys and values of a struct selectively. Each per-key\n * function receives `(key, value)` and must return a `[newKey, newValue]`\n * tuple. Keys without a corresponding function are copied unchanged.\n *\n * **When to use**\n *\n * Use when you need to rename a key and change its value in one step.\n *\n * **Details**\n *\n * The return type is fully tracked at the type level.\n *\n * **Example** (Transforming keys and values together)\n *\n * ```ts import.meta.vitest\n * import { pipe, Struct } from \"effect\"\n *\n * const result = pipe(\n *   { amount: 100, label: \"total\" },\n *   Struct.evolveEntries({\n *     amount: (k, v) => [`${k}Cents`, v * 100],\n *     label: (k, v) => [k, v.toUpperCase()]\n *   })\n * )\n * result // => { amountCents: 10000, label: \"TOTAL\" }\n * ```\n *\n * @see {@link evolve} – transform values only\n * @see {@link evolveKeys} – transform keys only\n * @category transforming\n * @since 4.0.0\n */\nexport const evolveEntries = /*#__PURE__*/dual(2, (self, e) => {\n  return buildStruct(self, (k, v) => Object.hasOwn(e, k) ? e[k](k, v) : [k, v]);\n});\n/**\n * Renames keys in a struct using a static `{ oldKey: newKey }` mapping. Keys\n * not mentioned in the mapping are copied unchanged.\n *\n * **When to use**\n *\n * Use when you need simple, declarative key renaming without custom logic.\n *\n * **Details**\n *\n * For computed key names, use {@link evolveKeys} instead.\n *\n * **Example** (Renaming keys)\n *\n * ```ts import.meta.vitest\n * import { pipe, Struct } from \"effect\"\n *\n * const result = pipe(\n *   { firstName: \"Alice\", lastName: \"Smith\", age: 30 },\n *   Struct.renameKeys({ firstName: \"first\", lastName: \"last\" })\n * )\n * result // => { first: \"Alice\", last: \"Smith\", age: 30 }\n * ```\n *\n * @see {@link evolveKeys} – rename keys using functions\n * @see {@link evolveEntries} – rename keys and transform values\n * @category transforming\n * @since 4.0.0\n */\nexport const renameKeys = /*#__PURE__*/dual(2, (self, mapping) => {\n  return buildStruct(self, (k, v) => [Object.hasOwn(mapping, k) ? mapping[k] : k, v]);\n});\n/**\n * Creates an `Equivalence` for a struct by providing an `Equivalence` for each\n * property. Two structs are equivalent when all their corresponding properties\n * are equivalent.\n *\n * **When to use**\n *\n * Use when you need equality for a record-like object to be decided field by\n * field, with a custom equality rule for each property.\n *\n * **Details**\n *\n * This is an alias of `Equivalence.Struct`. Each property's equivalence is\n * checked independently; all must return `true` for the overall result to be\n * `true`.\n *\n * **Example** (Comparing structs for equivalence)\n *\n * ```ts import.meta.vitest\n * import { Equivalence, Struct } from \"effect\"\n *\n * const PersonEquivalence = Struct.makeEquivalence({\n *   name: Equivalence.strictEqual<string>(),\n *   age: Equivalence.strictEqual<number>()\n * })\n *\n * PersonEquivalence({ name: \"Alice\", age: 30 }, { name: \"Alice\", age: 30 }) // => true\n * PersonEquivalence({ name: \"Alice\", age: 30 }, { name: \"Bob\", age: 30 }) // => false\n * ```\n *\n * @see {@link makeOrder} – create an `Order` for structs\n * @category instances\n * @since 4.0.0\n */\nexport const makeEquivalence = Equivalence.Struct;\n/**\n * Creates an `Order` for a struct by providing an `Order` for each property.\n * Properties are compared in the order they appear in the fields object; the\n * first non-zero comparison determines the result.\n *\n * **When to use**\n *\n * Use when you need to sort record-like objects lexicographically by several\n * fields, with each field using its own ordering rule.\n *\n * **Details**\n *\n * This is an alias of `Order.Struct`. The order of keys in the `fields` object\n * determines comparison priority.\n *\n * **Example** (Ordering structs by name then age)\n *\n * ```ts import.meta.vitest\n * import { Number, String, Struct } from \"effect\"\n *\n * const PersonOrder = Struct.makeOrder({\n *   name: String.Order,\n *   age: Number.Order\n * })\n *\n * PersonOrder({ name: \"Alice\", age: 30 }, { name: \"Bob\", age: 25 }) // => -1\n * ```\n *\n * @see {@link makeEquivalence} – create an `Equivalence` for structs\n * @category ordering\n * @since 4.0.0\n */\nexport const makeOrder = order.Struct;\n/**\n * Wraps a plain function as a {@link Lambda} value so it can be used with\n * {@link map}, {@link mapPick}, and {@link mapOmit}.\n *\n * **When to use**\n *\n * Use to create a typed lambda for struct mapping APIs that need type-level\n * input and output tracking.\n *\n * **Details**\n *\n * The type parameter `L` encodes both the input and output types at the type\n * level, allowing the compiler to track how struct value types change. At\n * runtime, the returned value is the same function; `lambda` only adjusts the\n * type.\n *\n * **Example** (Wrapping values in arrays)\n *\n * ```ts import.meta.vitest\n * import { pipe, Struct } from \"effect\"\n *\n * interface AsArray extends Struct.Lambda {\n *   <A>(self: A): Array<A>\n *   readonly \"~lambda.out\": Array<this[\"~lambda.in\"]>\n * }\n *\n * const asArray = Struct.lambda<AsArray>((a) => [a])\n * const result = pipe({ x: 1, y: \"hello\" }, Struct.map(asArray))\n * result // => { x: [1], y: [\"hello\"] }\n * ```\n *\n * @see {@link Lambda} – the type-level interface\n * @see {@link map} – apply a lambda to all struct values\n * @category constructors\n * @since 4.0.0\n */\nexport const lambda = f => f;\n/**\n * Applies a {@link Lambda} transformation to every value in a struct.\n *\n * **When to use**\n *\n * Use when you want to apply the same function to every value in a struct.\n *\n * **Details**\n *\n * The lambda must be created with {@link lambda} so the compiler can track the\n * output types.\n *\n * **Example** (Wrapping every value in an array)\n *\n * ```ts import.meta.vitest\n * import { pipe, Struct } from \"effect\"\n *\n * interface AsArray extends Struct.Lambda {\n *   <A>(self: A): Array<A>\n *   readonly \"~lambda.out\": Array<this[\"~lambda.in\"]>\n * }\n *\n * const asArray = Struct.lambda<AsArray>((a) => [a])\n * const result = pipe({ width: 10, height: 20 }, Struct.map(asArray))\n * result // => { width: [10], height: [20] }\n * ```\n *\n * @see {@link mapPick} – apply a lambda only to selected keys\n * @see {@link mapOmit} – apply a lambda to all keys except selected ones\n * @see {@link evolve} – apply different functions to different keys\n * @category mapping\n * @since 4.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, lambda) => {\n  return buildStruct(self, (k, v) => [k, lambda(v)]);\n});\n/**\n * Applies a {@link Lambda} transformation only to the specified keys; all\n * other keys are copied unchanged.\n *\n * **When to use**\n *\n * Use when you want to apply the same transformation to a subset of properties.\n *\n * **Example** (Wrapping only selected values in arrays)\n *\n * ```ts import.meta.vitest\n * import { pipe, Struct } from \"effect\"\n *\n * interface AsArray extends Struct.Lambda {\n *   <A>(self: A): Array<A>\n *   readonly \"~lambda.out\": Array<this[\"~lambda.in\"]>\n * }\n *\n * const asArray = Struct.lambda<AsArray>((a) => [a])\n * const result = pipe(\n *   { x: 1, y: 2, z: 3 },\n *   Struct.mapPick([\"x\", \"z\"], asArray)\n * )\n * result // => { x: [1], y: 2, z: [3] }\n * ```\n *\n * @see {@link map} – apply a lambda to all keys\n * @see {@link mapOmit} – apply a lambda to all keys except selected ones\n * @category mapping\n * @since 4.0.0\n */\nexport const mapPick = /*#__PURE__*/dual(3, (self, keys, lambda) => {\n  return buildStruct(self, (k, v) => [k, hasPropertyKey(keys, k) ? lambda(v) : v]);\n});\n/**\n * Applies a {@link Lambda} transformation to all keys except the specified\n * ones; the excluded keys are copied unchanged.\n *\n * **When to use**\n *\n * Use when most keys should be transformed but a few should be preserved.\n *\n * **Example** (Wrapping all values except one in arrays)\n *\n * ```ts import.meta.vitest\n * import { pipe, Struct } from \"effect\"\n *\n * interface AsArray extends Struct.Lambda {\n *   <A>(self: A): Array<A>\n *   readonly \"~lambda.out\": Array<this[\"~lambda.in\"]>\n * }\n *\n * const asArray = Struct.lambda<AsArray>((a) => [a])\n * const result = pipe(\n *   { x: 1, y: 2, z: 3 },\n *   Struct.mapOmit([\"y\"], asArray)\n * )\n * result // => { x: [1], y: 2, z: [3] }\n * ```\n *\n * @see {@link map} – apply a lambda to all keys\n * @see {@link mapPick} – apply a lambda only to selected keys\n * @category mapping\n * @since 4.0.0\n */\nexport const mapOmit = /*#__PURE__*/dual(3, (self, keys, lambda) => {\n  return buildStruct(self, (k, v) => [k, !hasPropertyKey(keys, k) ? lambda(v) : v]);\n});\nfunction hasPropertyKey(keys, key) {\n  return keys.some(candidate => candidate === key || typeof candidate === \"number\" && String(candidate) === key);\n}\n/**\n * Walk `source`; for each key decide what to emit via the small callback.\n *\n * The callback returns either\n *   • `undefined`  → nothing is copied, or\n *   • `[newKey, newVal]`\n *\n * so every public API just supplies a different callback.\n */\nfunction buildStruct(source, f) {\n  const out = {};\n  for (const k of Reflect.ownKeys(source)) {\n    if (!Object.prototype.propertyIsEnumerable.call(source, k)) continue;\n    const res = f(k, source[k]);\n    if (res) {\n      const [nk, nv] = res;\n      InternalRecord.assignProperty(out, nk, nv);\n    }\n  }\n  return out;\n}\n/**\n * Creates a `Combiner` for a struct shape by providing a `Combiner` for each\n * property. When two structs are combined, each property is merged using its\n * corresponding combiner.\n *\n * **When to use**\n *\n * Use when you need to merge two same-shape records by combining each property\n * independently, such as summing counters or concatenating strings.\n *\n * **Details**\n *\n * Pass `omitKeyWhen` to drop properties whose merged value matches a predicate,\n * such as omitting zero counters.\n *\n * **Example** (Combining struct properties)\n *\n * ```ts import.meta.vitest\n * import { Number, String, Struct } from \"effect\"\n *\n * const C = Struct.makeCombiner<{ readonly n: number; readonly s: string }>({\n *   n: Number.ReducerSum,\n *   s: String.ReducerConcat\n * })\n *\n * C.combine({ n: 1, s: \"hello\" }, { n: 2, s: \" world\" }) // => { n: 3, s: \"hello world\" }\n * ```\n *\n * @see {@link makeReducer} – like `makeCombiner` but with an initial value\n * @category combining\n * @since 4.0.0\n */\nexport function makeCombiner(combiners, options) {\n  const omitKeyWhen = options?.omitKeyWhen ?? (() => false);\n  return Combiner.make((self, that) => {\n    const keys = Reflect.ownKeys(combiners);\n    const out = {};\n    for (const key of keys) {\n      const merge = combiners[key].combine(self[key], that[key]);\n      if (omitKeyWhen(merge)) continue;\n      InternalRecord.assignProperty(out, key, merge);\n    }\n    return out;\n  });\n}\n/**\n * Creates a `Reducer` for a struct shape by providing a `Reducer` for each\n * property. The initial value is derived from each property's\n * `Reducer.initialValue`. When reducing a collection of structs, each property\n * is combined independently.\n *\n * **When to use**\n *\n * Use when you need to fold same-shape records by accumulating each property\n * independently into one summary record.\n *\n * **Details**\n *\n * Pass `omitKeyWhen` to drop properties whose reduced value matches a\n * predicate.\n *\n * **Example** (Reducing a collection of structs)\n *\n * ```ts import.meta.vitest\n * import { Number, String, Struct } from \"effect\"\n *\n * const R = Struct.makeReducer<{ readonly n: number; readonly s: string }>({\n *   n: Number.ReducerSum,\n *   s: String.ReducerConcat\n * })\n *\n * const result = R.combineAll([\n *   { n: 1, s: \"a\" },\n *   { n: 2, s: \"b\" },\n *   { n: 3, s: \"c\" }\n * ])\n * result // => { n: 6, s: \"abc\" }\n * ```\n *\n * @see {@link makeCombiner} – like `makeReducer` but without an initial value\n * @category folding\n * @since 4.0.0\n */\nexport function makeReducer(reducers, options) {\n  const combine = makeCombiner(reducers, options).combine;\n  const initialValue = {};\n  for (const key of Reflect.ownKeys(reducers)) {\n    const iv = reducers[key].initialValue;\n    if (options?.omitKeyWhen?.(iv)) continue;\n    InternalRecord.assignProperty(initialValue, key, iv);\n  }\n  return Reducer.make(combine, initialValue);\n}\n/**\n * Creates a record with the given keys and value.\n *\n * **When to use**\n *\n * Use to build an object where each provided key receives the same value.\n *\n * **Example** (Creating a record)\n *\n * ```ts import.meta.vitest\n * import { Struct } from \"effect\"\n *\n * Struct.Record([\"a\", \"b\"], \"value\") // => { a: \"value\", b: \"value\" }\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport function Record(keys, value) {\n  const out = {};\n  for (const key of keys) {\n    InternalRecord.assignProperty(out, key, value);\n  }\n  return out;\n}\n//# sourceMappingURL=Struct.js.map","import * as Predicate from \"../Predicate.js\";\nexport const SchemaErrorTypeId = \"~effect/Schema/SchemaError\";\nexport function isSchemaError(u) {\n  return Predicate.hasProperty(u, SchemaErrorTypeId) && u[SchemaErrorTypeId] === SchemaErrorTypeId;\n}\n//# sourceMappingURL=schemaError.js.map","/**\n * Models HTTP cookies and cookie collections for requests and responses.\n *\n * A `Cookie` stores a name, value, encoded value, and standard cookie\n * attributes. A `Cookies` value is an immutable collection keyed by cookie\n * name. This module parses request `Cookie` headers, builds response\n * `Set-Cookie` headers, and provides helpers for adding, removing, merging, and\n * expiring cookies.\n *\n * @since 4.0.0\n */\nimport * as Data from \"../../Data.js\";\nimport * as Duration from \"../../Duration.js\";\nimport { dual } from \"../../Function.js\";\nimport * as Inspectable from \"../../Inspectable.js\";\nimport * as InternalRecord from \"../../internal/record.js\";\nimport * as Option from \"../../Option.js\";\nimport { pipeArguments } from \"../../Pipeable.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport * as Record from \"../../Record.js\";\nimport * as Result from \"../../Result.js\";\nconst TypeId = \"~effect/http/Cookies\";\n/**\n * Returns `true` when a value is a `Cookies` collection.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isCookies = u => Predicate.hasProperty(u, TypeId);\nconst CookieTypeId = \"~effect/http/Cookies/Cookie\";\n/**\n * Returns `true` when a value is a `Cookie`.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isCookie = u => Predicate.hasProperty(u, CookieTypeId);\nconst CookieErrorTypeId = \"~effect/http/Cookies/CookieError\";\n/**\n * Error reason describing why cookie construction failed, such as invalid name,\n * value, domain, path, or infinite max-age.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class CookiesErrorReason extends Data.Error {}\n/**\n * Error returned when a cookie name, value, domain, path, or max-age option is invalid.\n *\n * **Details**\n *\n * Inspect `reason` to determine the specific validation failure.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class CookiesError extends /*#__PURE__*/Data.TaggedError(\"CookiesError\") {\n  /**\n   * Creates a cookie error from a reason tag and optional cause.\n   *\n   * @since 4.0.0\n   */\n  static fromReason(reason, cause) {\n    return new CookiesError({\n      reason: new CookiesErrorReason({\n        _tag: reason,\n        cause\n      })\n    });\n  }\n  /**\n   * Marks this value as a cookie validation error for runtime guards.\n   *\n   * @since 4.0.0\n   */\n  [CookieErrorTypeId] = CookieErrorTypeId;\n  /**\n   * Uses the concrete cookie error reason as the public message.\n   *\n   * @since 4.0.0\n   */\n  get message() {\n    return this.reason._tag;\n  }\n}\nconst Proto = {\n  [TypeId]: TypeId,\n  ...Inspectable.BaseProto,\n  toJSON() {\n    return {\n      _id: \"effect/Cookies\",\n      cookies: Record.map(this.cookies, cookie => cookie.toJSON())\n    };\n  },\n  pipe() {\n    return pipeArguments(this, arguments);\n  }\n};\n/**\n * Creates a `Cookies` collection from an existing readonly record of cookies keyed by cookie name.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromReadonlyRecord = cookies => {\n  const self = Object.create(Proto);\n  self.cookies = cookies;\n  return self;\n};\n/**\n * Create a Cookies object from an Iterable\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromIterable = cookies => {\n  const record = {};\n  for (const cookie of cookies) {\n    InternalRecord.assignProperty(record, cookie.name, cookie);\n  }\n  return fromReadonlyRecord(record);\n};\n/**\n * Create a Cookies object from a set of Set-Cookie headers\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromSetCookie = headers => {\n  const arrayHeaders = typeof headers === \"string\" ? [headers] : headers;\n  const cookies = [];\n  for (const header of arrayHeaders) {\n    const cookie = parseSetCookie(header.trim());\n    if (cookie) {\n      cookies.push(cookie);\n    }\n  }\n  return fromIterable(cookies);\n};\nfunction parseSetCookie(header) {\n  const parts = header.split(\";\").map(_ => _.trim()).filter(_ => _ !== \"\");\n  if (parts.length === 0) {\n    return undefined;\n  }\n  const firstEqual = parts[0].indexOf(\"=\");\n  if (firstEqual === -1) {\n    return undefined;\n  }\n  const name = parts[0].slice(0, firstEqual);\n  if (!cookieNameRegExp.test(name)) {\n    return undefined;\n  }\n  const valueEncoded = parts[0].slice(firstEqual + 1);\n  const value = tryDecodeURIComponent(valueEncoded);\n  if (parts.length === 1) {\n    return Object.assign(Object.create(CookieProto), {\n      name,\n      value,\n      valueEncoded\n    });\n  }\n  const options = {};\n  for (let i = 1; i < parts.length; i++) {\n    const part = parts[i];\n    const equalIndex = part.indexOf(\"=\");\n    const key = equalIndex === -1 ? part : part.slice(0, equalIndex).trim();\n    const value = equalIndex === -1 ? undefined : part.slice(equalIndex + 1).trim();\n    switch (key.toLowerCase()) {\n      case \"domain\":\n        {\n          if (value === undefined) {\n            break;\n          }\n          const domain = value.trim().replace(/^\\./, \"\");\n          if (domain) {\n            options.domain = domain;\n          }\n          break;\n        }\n      case \"expires\":\n        {\n          if (value === undefined) {\n            break;\n          }\n          const date = new Date(value);\n          if (!isNaN(date.getTime())) {\n            options.expires = date;\n          }\n          break;\n        }\n      case \"max-age\":\n        {\n          if (value === undefined) {\n            break;\n          }\n          const maxAge = parseInt(value, 10);\n          if (!isNaN(maxAge)) {\n            options.maxAge = Duration.seconds(maxAge);\n          }\n          break;\n        }\n      case \"path\":\n        {\n          if (value === undefined) {\n            break;\n          }\n          if (value[0] === \"/\") {\n            options.path = value;\n          }\n          break;\n        }\n      case \"priority\":\n        {\n          if (value === undefined) {\n            break;\n          }\n          switch (value.toLowerCase()) {\n            case \"low\":\n              options.priority = \"low\";\n              break;\n            case \"medium\":\n              options.priority = \"medium\";\n              break;\n            case \"high\":\n              options.priority = \"high\";\n              break;\n          }\n          break;\n        }\n      case \"httponly\":\n        {\n          options.httpOnly = true;\n          break;\n        }\n      case \"secure\":\n        {\n          options.secure = true;\n          break;\n        }\n      case \"partitioned\":\n        {\n          options.partitioned = true;\n          break;\n        }\n      case \"samesite\":\n        {\n          if (value === undefined) {\n            break;\n          }\n          switch (value.toLowerCase()) {\n            case \"lax\":\n              options.sameSite = \"lax\";\n              break;\n            case \"strict\":\n              options.sameSite = \"strict\";\n              break;\n            case \"none\":\n              options.sameSite = \"none\";\n              break;\n          }\n          break;\n        }\n    }\n  }\n  return Object.assign(Object.create(CookieProto), {\n    name,\n    value,\n    valueEncoded,\n    options: Object.keys(options).length > 0 ? options : undefined\n  });\n}\n/**\n * An empty Cookies object\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const empty = /*#__PURE__*/fromIterable([]);\n/**\n * Returns `true` when the `Cookies` collection contains no cookies.\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isEmpty = self => Record.isEmptyRecord(self.cookies);\n// oxlint-disable-next-line no-control-regex\nconst fieldContentRegExp = /^[\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+$/;\nconst cookieNameRegExp = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\n// oxlint-disable-next-line no-control-regex\nconst cookieDomainRegExp = /^[\\u0009\\u0020-\\u003a\\u003c-\\u007e\\u0080-\\u00ff]+$/;\nconst cookiePathRegExp = /^[\\u0020-\\u003a\\u003c-\\u007e]+$/;\nconst CookieProto = {\n  [CookieTypeId]: CookieTypeId,\n  ...Inspectable.BaseProto,\n  toJSON() {\n    return {\n      _id: \"effect/Cookies/Cookie\",\n      name: this.name,\n      value: this.value,\n      options: this.options\n    };\n  }\n};\n/**\n * Creates a cookie, validating the name, encoded value, domain, path, and finite `maxAge`.\n *\n * **Details**\n *\n * Returns a `CookiesError` in the `Result` failure channel when validation fails.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport function makeCookie(name, value, options) {\n  const encodedValue = encodeURIComponent(value);\n  const error = validateCookie(name, encodedValue, options);\n  if (error !== undefined) {\n    return Result.fail(error);\n  }\n  return Result.succeed(Object.assign(Object.create(CookieProto), {\n    name,\n    value,\n    valueEncoded: encodedValue,\n    options\n  }));\n}\nfunction validateCookie(name, encodedValue, options) {\n  if (!cookieNameRegExp.test(name)) {\n    return CookiesError.fromReason(\"InvalidCookieName\");\n  }\n  if (encodedValue && !fieldContentRegExp.test(encodedValue)) {\n    return CookiesError.fromReason(\"InvalidCookieValue\");\n  }\n  if (options?.domain !== undefined && !cookieDomainRegExp.test(options.domain)) {\n    return CookiesError.fromReason(\"InvalidCookieDomain\");\n  }\n  if (options?.path !== undefined && !cookiePathRegExp.test(options.path)) {\n    return CookiesError.fromReason(\"InvalidCookiePath\");\n  }\n  if (options?.maxAge !== undefined && !Duration.isFinite(Duration.fromInputUnsafe(options.maxAge))) {\n    return CookiesError.fromReason(\"CookieInfinityMaxAge\");\n  }\n}\n/**\n * Create a new cookie, throwing an error if invalid\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeCookieUnsafe = (name, value, options) => Result.getOrThrow(makeCookie(name, value, options));\n/**\n * Adds a cookie to a Cookies object\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const setCookie = /*#__PURE__*/dual(2, (self, cookie) => fromReadonlyRecord(Record.set(self.cookies, cookie.name, cookie)));\n/**\n * Adds multiple cookies to a Cookies object\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const setAllCookie = /*#__PURE__*/dual(2, (self, cookies) => {\n  const record = {\n    ...self.cookies\n  };\n  for (const cookie of cookies) {\n    InternalRecord.assignProperty(record, cookie.name, cookie);\n  }\n  return fromReadonlyRecord(record);\n});\n/**\n * Combines two Cookies objects, removing duplicates from the first\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const merge = /*#__PURE__*/dual(2, (self, that) => fromReadonlyRecord({\n  ...self.cookies,\n  ...that.cookies\n}));\n/**\n * Removes a cookie by name\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const remove = /*#__PURE__*/dual(2, (self, name) => fromReadonlyRecord(Record.remove(self.cookies, name)));\n/**\n * Gets a cookie from a Cookies object safely.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const get = /*#__PURE__*/dual(args => isCookies(args[0]), (self, name) => Option.fromUndefinedOr(Object.hasOwn(self.cookies, name) ? self.cookies[name] : undefined));\n/**\n * Gets the decoded value of a cookie by name safely.\n *\n * **Details**\n *\n * Returns `Option.none()` when the cookie is not present.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const getValue = /*#__PURE__*/dual(args => isCookies(args[0]), (self, name) => Option.map(get(self, name), cookie => cookie.value));\n/**\n * Creates and adds a cookie safely by name and value.\n *\n * **Details**\n *\n * The cookie fields are validated first; invalid input returns a `CookiesError` in the `Result` failure channel.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const set = /*#__PURE__*/dual(args => isCookies(args[0]), (self, name, value, options) => Result.map(makeCookie(name, value, options), cookie => fromReadonlyRecord(Record.set(self.cookies, name, cookie))));\n/**\n * Creates and adds a cookie by name and value, throwing if the cookie fields are invalid.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const setUnsafe = /*#__PURE__*/dual(args => isCookies(args[0]), (self, name, value, options) => fromReadonlyRecord(Record.set(self.cookies, name, makeCookieUnsafe(name, value, options))));\n/**\n * Adds an expired cookie safely with an empty value, `Max-Age=0`, and an epoch `Expires` value.\n *\n * **Details**\n *\n * Returns a `CookiesError` in the `Result` failure channel when the name or options are invalid.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const expireCookie = /*#__PURE__*/dual(args => isCookies(args[0]), (self, name, options) => set(self, name, \"\", {\n  ...options,\n  maxAge: 0,\n  expires: new Date(0)\n}));\n/**\n * Adds an expired cookie to a Cookies object, throwing an error if invalid\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const expireCookieUnsafe = /*#__PURE__*/dual(args => isCookies(args[0]), (self, name, options) => setUnsafe(self, name, \"\", {\n  ...options,\n  maxAge: 0,\n  expires: new Date(0)\n}));\n/**\n * Creates and adds multiple cookies safely from name/value/options tuples.\n *\n * **Details**\n *\n * If any tuple is invalid, returns the first `CookiesError` and leaves the original collection unchanged.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const setAll = /*#__PURE__*/dual(2, (self, cookies) => {\n  const record = {\n    ...self.cookies\n  };\n  for (const [name, value, options] of cookies) {\n    const result = makeCookie(name, value, options);\n    if (Result.isFailure(result)) {\n      return result;\n    }\n    InternalRecord.assignProperty(record, name, result.success);\n  }\n  return Result.succeed(fromReadonlyRecord(record));\n});\n/**\n * Adds multiple cookies to a Cookies object, throwing an error if invalid\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const setAllUnsafe = /*#__PURE__*/dual(2, (self, cookies) => Result.getOrThrow(setAll(self, cookies)));\n/**\n * Serializes a cookie into a string.\n *\n * **Details**\n *\n * Adapted from https://github.com/fastify/fastify-cookie under MIT License\n *\n * @category encoding\n * @since 4.0.0\n */\nexport function serializeCookie(self) {\n  const error = validateCookie(self.name, self.valueEncoded, self.options);\n  if (error !== undefined) {\n    throw error;\n  }\n  let str = self.name + \"=\" + self.valueEncoded;\n  if (self.options === undefined) {\n    return str;\n  }\n  const options = self.options;\n  if (options.maxAge !== undefined) {\n    const maxAge = Duration.toSeconds(Duration.fromInputUnsafe(options.maxAge));\n    str += \"; Max-Age=\" + Math.trunc(maxAge);\n  }\n  if (options.domain !== undefined) {\n    str += \"; Domain=\" + options.domain;\n  }\n  if (options.path !== undefined) {\n    str += \"; Path=\" + options.path;\n  }\n  if (options.priority !== undefined) {\n    switch (options.priority) {\n      case \"low\":\n        str += \"; Priority=Low\";\n        break;\n      case \"medium\":\n        str += \"; Priority=Medium\";\n        break;\n      case \"high\":\n        str += \"; Priority=High\";\n        break;\n    }\n  }\n  if (options.expires !== undefined) {\n    str += \"; Expires=\" + options.expires.toUTCString();\n  }\n  if (options.httpOnly) {\n    str += \"; HttpOnly\";\n  }\n  if (options.secure) {\n    str += \"; Secure\";\n  }\n  // Draft implementation to support Chrome from 2024-Q1 forward.\n  // See https://datatracker.ietf.org/doc/html/draft-cutler-httpbis-partitioned-cookies#section-2.1\n  if (options.partitioned) {\n    str += \"; Partitioned\";\n  }\n  if (options.sameSite !== undefined) {\n    switch (options.sameSite) {\n      case \"lax\":\n        str += \"; SameSite=Lax\";\n        break;\n      case \"strict\":\n        str += \"; SameSite=Strict\";\n        break;\n      case \"none\":\n        str += \"; SameSite=None\";\n        break;\n    }\n  }\n  return str;\n}\n/**\n * Serializes a `Cookies` object into a Cookie header.\n *\n * @category encoding\n * @since 4.0.0\n */\nexport const toCookieHeader = self => Object.values(self.cookies).map(cookie => `${cookie.name}=${cookie.valueEncoded}`).join(\"; \");\n/**\n * Converts a `Cookies` collection to a record of decoded cookie values keyed by cookie name.\n *\n * @category encoding\n * @since 4.0.0\n */\nexport const toRecord = self => {\n  const record = {};\n  const cookies = Object.values(self.cookies);\n  for (let index = 0; index < cookies.length; index++) {\n    const cookie = cookies[index];\n    InternalRecord.assignProperty(record, cookie.name, cookie.value);\n  }\n  return record;\n};\n/**\n * Serializes a `Cookies` collection into an array of `Set-Cookie` header values.\n *\n * @category encoding\n * @since 4.0.0\n */\nexport const toSetCookieHeaders = self => Object.values(self.cookies).map(serializeCookie);\n/**\n * Parses a cookie header into a record of key-value pairs\n *\n * **Details**\n *\n * Adapted from https://github.com/fastify/fastify-cookie under MIT License\n *\n * @category decoding\n * @since 4.0.0\n */\nexport function parseHeader(header) {\n  const result = {};\n  const strLen = header.length;\n  let pos = 0;\n  let terminatorPos = 0;\n  while (true) {\n    if (terminatorPos === strLen) break;\n    terminatorPos = header.indexOf(\";\", pos);\n    if (terminatorPos === -1) terminatorPos = strLen; // This is the last pair\n    let eqIdx = header.indexOf(\"=\", pos);\n    if (eqIdx === -1) break; // No key-value pairs left\n    if (eqIdx > terminatorPos) {\n      // Malformed key-value pair\n      pos = terminatorPos + 1;\n      continue;\n    }\n    const key = header.substring(pos, eqIdx++).trim();\n    if (!Object.hasOwn(result, key)) {\n      const val = header.charCodeAt(eqIdx) === 0x22 ? header.substring(eqIdx + 1, terminatorPos - 1).trim() : header.substring(eqIdx, terminatorPos).trim();\n      InternalRecord.assignProperty(result, key, !(val.indexOf(\"%\") === -1) ? tryDecodeURIComponent(val) : val);\n    }\n    pos = terminatorPos + 1;\n  }\n  return result;\n}\nconst tryDecodeURIComponent = str => {\n  try {\n    return decodeURIComponent(str);\n    // oxlint-disable-next-line @typescript-eslint/no-unused-vars\n  } catch (_) {\n    return str;\n  }\n};\n//# sourceMappingURL=Cookies.js.map","/**\n * Models URL query parameters as ordered string pairs.\n *\n * `UrlParams` is used for HTTP client query strings, URL-encoded form bodies,\n * and server-side decoding. Values can be built from records, iterables, or\n * native `URLSearchParams`, then updated, serialized, converted to a `URL`, or\n * decoded with schemas.\n *\n * @since 4.0.0\n */\nimport * as Arr from \"../../Array.js\";\nimport * as Equal from \"../../Equal.js\";\nimport * as Equ from \"../../Equivalence.js\";\nimport { dual } from \"../../Function.js\";\nimport * as Hash from \"../../Hash.js\";\nimport { PipeInspectableProto } from \"../../internal/core.js\";\nimport * as InternalRecord from \"../../internal/record.js\";\nimport * as Option from \"../../Option.js\";\nimport { hasProperty } from \"../../Predicate.js\";\nimport * as Tuple from \"../../Tuple.js\";\nconst TypeId = \"~effect/http/UrlParams\";\n/**\n * Returns `true` when a value is a `UrlParams` instance.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isUrlParams = u => hasProperty(u, TypeId);\nconst Proto = {\n  ...PipeInspectableProto,\n  [TypeId]: TypeId,\n  [Symbol.iterator]() {\n    return this.params[Symbol.iterator]();\n  },\n  toJSON() {\n    return {\n      _id: \"UrlParams\",\n      params: Object.fromEntries(this.params)\n    };\n  },\n  [Equal.symbol](that) {\n    return Equivalence(this, that);\n  },\n  [Hash.symbol]() {\n    return Hash.array(this.params.flat());\n  }\n};\n/**\n * Creates `UrlParams` from ordered string key-value pairs.\n *\n * **Details**\n *\n * The input pairs are used as-is and are not coerced or normalized.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = params => {\n  const self = Object.create(Proto);\n  self.params = params;\n  return self;\n};\n/**\n * Creates `UrlParams` from a supported input shape.\n *\n * **Details**\n *\n * Primitive values are converted to strings, arrays produce repeated parameters,\n * nested records use bracket notation, and `undefined` values are omitted.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromInput = input => {\n  if (isUrlParams(input)) {\n    return input;\n  }\n  const parsed = fromInputNested(input);\n  const out = [];\n  for (let i = 0; i < parsed.length; i++) {\n    if (Array.isArray(parsed[i][0])) {\n      const [keys, value] = parsed[i];\n      out.push([`${keys[0]}[${keys.slice(1).join(\"][\")}]`, value]);\n    } else {\n      out.push(parsed[i]);\n    }\n  }\n  return make(out);\n};\nconst fromInputNested = input => {\n  const entries = typeof input[Symbol.iterator] === \"function\" ? Arr.fromIterable(input) : Object.entries(input);\n  const out = [];\n  for (const [key, value] of entries) {\n    if (Array.isArray(value)) {\n      for (let i = 0; i < value.length; i++) {\n        if (value[i] !== undefined) {\n          out.push([key, String(value[i])]);\n        }\n      }\n    } else if (value !== null && typeof value === \"object\") {\n      const nested = fromInputNested(value);\n      for (const [k, v] of nested) {\n        out.push([[key, ...(typeof k === \"string\" ? [k] : k)], v]);\n      }\n    } else if (value !== undefined) {\n      out.push([key, String(value)]);\n    }\n  }\n  return out;\n};\n/**\n * Provides an order-sensitive `Equivalence` instance for `UrlParams`.\n *\n * **Details**\n *\n * Two values are equivalent when they contain the same key-value pairs in the same\n * order.\n *\n * @category instances\n * @since 4.0.0\n */\nexport const Equivalence = /*#__PURE__*/Equ.make((a, b) => arrayEquivalence(a.params, b.params));\nconst arrayEquivalence = /*#__PURE__*/Arr.makeEquivalence(/*#__PURE__*/Tuple.makeEquivalence([/*#__PURE__*/Equ.strictEqual(), /*#__PURE__*/Equ.strictEqual()]));\n/**\n * An empty `UrlParams` value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const empty = /*#__PURE__*/make([]);\n/**\n * Returns all values for a query parameter key in insertion order.\n *\n * **Details**\n *\n * Returns an empty array when the key is absent.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const getAll = /*#__PURE__*/dual(2, (self, key) => Arr.reduce(self.params, [], (acc, [k, value]) => {\n  if (k === key) {\n    acc.push(value);\n  }\n  return acc;\n}));\n/**\n * Returns the first value for a query parameter key safely.\n *\n * **When to use**\n *\n * Use when duplicate query parameters are ordered and the first occurrence has\n * precedence.\n *\n * **Details**\n *\n * Returns `Option.none` when the key is absent.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const getFirst = /*#__PURE__*/dual(2, (self, key) => Arr.findFirst(self.params, ([k]) => k === key).pipe(Option.map(([, value]) => value)));\n/**\n * Returns the last value for a query parameter key safely.\n *\n * **When to use**\n *\n * Use when duplicate query parameters are ordered and the last occurrence has\n * precedence.\n *\n * **Details**\n *\n * Returns `Option.none` when the key is absent.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const getLast = /*#__PURE__*/dual(2, (self, key) => Arr.findLast(self.params, ([k]) => k === key).pipe(Option.map(([, value]) => value)));\n/**\n * Sets a query parameter to a single value.\n *\n * **Details**\n *\n * Existing values for the same key are removed, and the new value is appended to\n * the end.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const set = /*#__PURE__*/dual(3, (self, key, value) => make(Arr.append(Arr.filter(self.params, ([k]) => k !== key), [key, String(value)])));\n/**\n * Transforms the underlying ordered key-value pairs of `UrlParams`.\n *\n * **Details**\n *\n * The result is wrapped in a new `UrlParams` value.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const transform = /*#__PURE__*/dual(2, (self, f) => make(f(self.params)));\n/**\n * Sets multiple query parameters from input.\n *\n * **Details**\n *\n * Keys present in the input replace existing values for those keys, while\n * unmentioned existing parameters are preserved.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const setAll = /*#__PURE__*/dual(2, (self, input) => {\n  const params = fromInput(input).params.slice();\n  const keys = new Set();\n  for (let i = 0; i < params.length; i++) {\n    keys.add(params[i][0]);\n  }\n  for (let i = 0; i < self.params.length; i++) {\n    if (keys.has(self.params[i][0])) continue;\n    params.push(self.params[i]);\n  }\n  return make(params);\n});\n/**\n * Appends a query parameter value without removing existing values for the key.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const append = /*#__PURE__*/dual(3, (self, key, value) => make(Arr.append(self.params, [key, String(value)])));\n/**\n * Appends all query parameters produced from the supplied input.\n *\n * **Details**\n *\n * Existing parameters are preserved.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const appendAll = /*#__PURE__*/dual(2, (self, input) => transform(self, Arr.appendAll(fromInput(input).params)));\n/**\n * Removes all query parameter values for the specified key.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const remove = /*#__PURE__*/dual(2, (self, key) => transform(self, Arr.filter(([k]) => k !== key)));\n/**\n * Serializes `UrlParams` to a URL query string without a leading question mark.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toString = input => new URLSearchParams(fromInput(input).params).toString();\n/**\n * Builds a `Record` containing all the key-value pairs in the given `UrlParams`\n * as `string` (if only one value for a key) or a `NonEmptyArray<string>`\n * (when more than one value for a key)\n *\n * **Example** (Converting parameters to a record)\n *\n * ```ts import.meta.vitest\n * import { UrlParams } from \"effect/unstable/http\"\n *\n * const urlParams = UrlParams.fromInput({\n *   a: 1,\n *   b: true,\n *   c: \"string\",\n *   e: [1, 2, 3]\n * })\n * UrlParams.toRecord(urlParams) // => { a: \"1\", b: \"true\", c: \"string\", e: [\"1\", \"2\", \"3\"] }\n * ```\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toRecord = self => {\n  const out = {};\n  for (const [k, value] of self.params) {\n    if (!Object.hasOwn(out, k)) {\n      InternalRecord.assignProperty(out, k, value);\n    } else {\n      const current = out[k];\n      if (typeof current === \"string\") {\n        InternalRecord.assignProperty(out, k, [current, value]);\n      } else {\n        current.push(value);\n      }\n    }\n  }\n  return out;\n};\n/**\n * Builds a readonly record from `UrlParams`.\n *\n * **Details**\n *\n * Keys with one value map to a string, and keys with multiple values map to a\n * non-empty readonly array of strings.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toReadonlyRecord = toRecord;\n//# sourceMappingURL=UrlParams.js.map","/**\n * Describes data shapes and how unknown input becomes trusted values.\n *\n * A schema can validate input, decode it into an application type, and encode\n * that value back to another representation. This module contains the main\n * schema, codec, decoder, and encoder APIs, together with schemas for common\n * JavaScript values and Effect data types. It also supports refinements,\n * transformations, defaults, classes, JSON Schema generation, test data\n * generation, formatting, equivalence, optics, and differs derived from schema\n * definitions.\n *\n * @since 4.0.0\n */\nimport * as Arr from \"./Array.js\";\nimport * as BigDecimal_ from \"./BigDecimal.js\";\nimport * as ByteSize_ from \"./ByteSize.js\";\nimport * as Cause_ from \"./Cause.js\";\nimport * as Chunk_ from \"./Chunk.js\";\nimport * as Data from \"./Data.js\";\nimport * as DateTime from \"./DateTime.js\";\nimport * as Duration_ from \"./Duration.js\";\nimport * as Effect from \"./Effect.js\";\nimport * as Encoding from \"./Encoding.js\";\nimport * as Equal from \"./Equal.js\";\nimport * as Exit_ from \"./Exit.js\";\nimport { format, formatPropertyKey } from \"./Formatter.js\";\nimport { identity } from \"./Function.js\";\nimport * as HashMap_ from \"./HashMap.js\";\nimport * as HashSet_ from \"./HashSet.js\";\nimport * as core from \"./internal/core.js\";\nimport { effectIsExit } from \"./internal/effect.js\";\nimport * as InternalGraph from \"./internal/graph.js\";\nimport * as InternalRecord from \"./internal/record.js\";\nimport * as InternalAnnotations from \"./internal/schema/annotations.js\";\nimport * as InternalMake from \"./internal/schema/make.js\";\nimport * as InternalStandardSchema from \"./internal/schema/standardSchema.js\";\nimport * as InternalToCodec from \"./internal/schema/toCodec.js\";\nimport * as InternalToDifferJsonPatch from \"./internal/schema/toDifferJsonPatch.js\";\nimport * as InternalToEncoderXml from \"./internal/schema/toEncoderXml.js\";\nimport * as InternalEquivalence from \"./internal/schema/toEquivalence.js\";\nimport * as InternalToFormatter from \"./internal/schema/toFormatter.js\";\nimport * as InternalToIso from \"./internal/schema/toIso.js\";\nimport * as InternalToJsonSchemaDocument from \"./internal/schema/toJsonSchemaDocument.js\";\nimport * as InternalToRepresentation from \"./internal/schema/toRepresentation.js\";\nimport { isSchemaError as isSchemaErrorInternal, SchemaErrorTypeId } from \"./internal/schemaError.js\";\nimport { getStackTraceLimit, setStackTraceLimit } from \"./internal/stackTraceLimit.js\";\nimport { remainder } from \"./Number.js\";\nimport * as Option_ from \"./Option.js\";\nimport * as Order from \"./Order.js\";\nimport * as Pipeable from \"./Pipeable.js\";\nimport * as Predicate from \"./Predicate.js\";\nimport * as Record_ from \"./Record.js\";\nimport * as Redacted_ from \"./Redacted.js\";\nimport * as RegExp_ from \"./RegExp.js\";\nimport * as Result_ from \"./Result.js\";\nimport * as SchemaAST from \"./SchemaAST.js\";\nimport * as SchemaGetter from \"./SchemaGetter.js\";\nimport * as SchemaIssue from \"./SchemaIssue.js\";\nimport * as SchemaParser from \"./SchemaParser.js\";\nimport * as SchemaTransformation from \"./SchemaTransformation.js\";\nimport * as Struct_ from \"./Struct.js\";\nimport * as Cookies_ from \"./unstable/http/Cookies.js\";\nimport * as Headers_ from \"./unstable/http/Headers.js\";\nimport * as UrlParams_ from \"./unstable/http/UrlParams.js\";\nimport * as IpInterface_ from \"./unstable/net/IpInterface.js\";\nimport * as IpNetwork_ from \"./unstable/net/IpNetwork.js\";\nimport * as NetAddress_ from \"./unstable/net/NetAddress.js\";\nconst TypeId = InternalMake.TypeId;\n/**\n * Creates a schema for a **parametric** type (a generic container such as\n * `Array<A>`, `Option<A>`, etc.) by accepting a list of type-parameter schemas\n * and a decoder factory.\n *\n * **When to use**\n *\n * Use when you are defining a schema for a generic container whose validation\n * depends on one or more type-parameter schemas.\n *\n * **Details**\n *\n * The outer call `declareConstructor<T, E, Iso>()` fixes the decoded type `T`,\n * the encoded type `E`, and the optional iso type. The inner call receives:\n * - `typeParameters` — the concrete schemas for each type variable\n * - `run` — a factory that, given resolved codecs for each type parameter,\n *   returns a parsing function `(u, ast, options) => Effect<T, Issue>`\n * - `annotations` — optional metadata\n *\n * @see {@link declare} for creating schemas for non-parametric types.\n *\n * **Example** (Schema for a parametric `Box<A>` type)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schema, SchemaIssue, SchemaParser } from \"effect\"\n *\n * interface Box<A> {\n *   readonly value: A\n * }\n *\n * const isBox = (u: unknown): u is Box<unknown> =>\n *   typeof u === \"object\" && u !== null && \"value\" in u\n *\n * const Box = <A extends Schema.Constraint>(item: A) =>\n *   Schema.declareConstructor<Box<A[\"Type\"]>, Box<A[\"Encoded\"]>>()(\n *     [item],\n *     ([itemCodec]) =>\n *       (u, ast, options) => {\n *         if (!isBox(u)) {\n *           return Effect.fail(new SchemaIssue.InvalidType(ast, u, options))\n *         }\n *         return Effect.map(\n *           SchemaParser.decodeUnknownEffect(itemCodec)(u.value, options),\n *           (value) => ({ value })\n *         )\n *       }\n *   )\n *\n * const schema = Box(Schema.Number)\n * Effect.runSync(Schema.decodeUnknownEffect(schema)({ value: 1 })) // => { value: 1 }\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport function declareConstructor() {\n  return (typeParameters, run, annotations) => {\n    return make(new SchemaAST.Declaration(typeParameters.map(SchemaAST.getAST), typeParameters => run(typeParameters.map(ast => make(ast))), annotations));\n  };\n}\n/**\n * Creates a schema for a **non-parametric** opaque type using a type-guard\n * function. The schema accepts any unknown value and succeeds when `is` returns\n * `true`, failing with an `InvalidType` issue otherwise.\n *\n * **When to use**\n *\n * Use when you are defining a schema for an opaque type with no type parameters\n * and validation can be expressed as a type guard.\n *\n * **Example** (Defining a schema for a custom `UserId` branded type)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * type UserId = string & { readonly _tag: \"UserId\" }\n *\n * const isUserId = (u: unknown): u is UserId =>\n *   typeof u === \"string\" && u.startsWith(\"user_\")\n *\n * const UserId = Schema.declare<UserId>(isUserId, {\n *   title: \"UserId\",\n *   description: \"A user identifier starting with 'user_'\"\n * })\n * Schema.decodeUnknownSync(UserId)(\"user_123\") // => \"user_123\"\n * ```\n *\n * @see {@link declareConstructor} for creating schemas for parametric types.\n *\n * @category constructors\n * @since 3.10.0\n */\nexport function declare(is, annotations) {\n  return declareConstructor()([], () => (input, ast, options) => is(input) ? Effect.succeed(input) : Effect.fail(new SchemaIssue.InvalidType(ast, input, options)), annotations);\n}\n/**\n * Returns a schema widened to the fully-parameterized {@link Bottom} interface,\n * making all 14 type parameters visible to TypeScript.\n *\n * **Details**\n *\n * Normally, concrete schema interfaces (e.g. `Schema<string>`) hide most type\n * parameters. `revealBottom` is useful when writing generic utilities that need\n * to inspect or propagate the complete set of type parameters.\n *\n * **Example** (Inspecting all type parameters of a schema)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const schema = Schema.String\n *\n * // Widen to Bottom to access all 14 type parameters\n * const bottom = Schema.revealBottom(schema)\n *\n * // `bottom` now exposes Type, Encoded, DecodingServices, EncodingServices,\n * // ast, Rebuild, ~type.make.in, Iso, ~type.parameters, etc.\n * type T = typeof bottom[\"Type\"]     // string\n * type E = typeof bottom[\"Encoded\"]  // string\n * ```\n *\n * @category utility types\n * @since 4.0.0\n */\nexport function revealBottom(bottom) {\n  return bottom;\n}\n/**\n * Adds metadata annotations to a schema without changing its runtime behavior.\n * This is the pipeable (curried) counterpart of the `.annotate` method.\n *\n * **Details**\n *\n * Annotations provide extra context used by documentation generators, JSON\n * Schema converters, error formatters, and other tooling. Common keys include\n * `title`, `description`, `examples`, `message`, and `identifier`.\n *\n * **Example** (Adding a title and description)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const Age = Schema.Natural.pipe(\n *   Schema.annotate({\n *     title: \"Age\",\n *     description: \"A non-negative integer representing age in years\"\n *   })\n * )\n * Schema.resolveAnnotations(Age)?.title // => \"Age\"\n * ```\n *\n * @see {@link annotateEncoded} to annotate the encoded side instead.\n *\n * @category annotations\n * @since 4.0.0\n */\nexport function annotate(annotations) {\n  return self => self.annotate(annotations);\n}\n/**\n * Adds metadata annotations to the **encoded** side of a schema without\n * changing its runtime behavior. This is the encoded-side counterpart of\n * `annotate`, which targets the decoded (Type) side.\n *\n * **Details**\n *\n * Internally the schema is flipped so that `Encoded` becomes `Type`,\n * annotated, and then flipped back.\n *\n * **Example** (Adding a title to the encoded representation)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const schema = Schema.NumberFromString.pipe(\n *   Schema.annotateEncoded({\n *     title: \"my title\"\n *   })\n * )\n *\n * Schema.toEncoded(schema).ast.annotations?.title // => \"my title\"\n * ```\n *\n * @see {@link annotate} to annotate the type side instead.\n *\n * @category annotations\n * @since 4.0.0\n */\nexport function annotateEncoded(annotations) {\n  return self => flip(flip(self).annotate(annotations));\n}\n/**\n * Adds key-level annotations to a schema field. This is the pipeable\n * (curried) counterpart of the `.annotateKey` method.\n *\n * **Details**\n *\n * Key annotations apply to a field's position inside a `Struct` or `Tuple`\n * rather than to the field's value type. They can carry a\n * `messageMissingKey` to customise the error shown when the field is absent,\n * as well as standard documentation fields such as `title`, `description`,\n * and `examples`.\n *\n * **Example** (Customizing the missing-key message for a required field)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const schema = Schema.Struct({\n *   username: Schema.String.pipe(\n *     Schema.annotateKey({\n *       description: \"The username used to log in\",\n *       messageMissingKey: \"Username is required\"\n *     })\n *   )\n * })\n * schema.fields.username.ast.context?.annotations?.messageMissingKey // => \"Username is required\"\n * ```\n *\n * @category annotations\n * @since 4.0.0\n */\nexport function annotateKey(annotations) {\n  return self => {\n    return self.rebuild(SchemaAST.annotateKey(self.ast, annotations));\n  };\n}\n/**\n * Returns a codec widened to the full {@link Codec} interface, prompting\n * TypeScript to infer all four type parameters (`T`, `E`, `RD`, `RE`).\n *\n * **Details**\n *\n * When a schema is stored in a variable typed as `Schema<T>` or `Top`, the\n * encoded type and service requirements are erased. Passing the value through\n * `revealCodec` recovers those parameters without any runtime cost.\n *\n * **Example** (Recovering encoded type from a schema variable)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const schema: Schema.Schema<number> = Schema.NumberFromString\n *\n * // Without revealCodec, Encoded is unknown\n * const codec = Schema.revealCodec(schema)\n * type Enc = typeof codec[\"Encoded\"] // string\n * ```\n *\n * @category utility types\n * @since 4.0.0\n */\nexport function revealCodec(codec) {\n  return codec;\n}\n/**\n * Error thrown or returned when schema decoding or encoding fails.\n *\n * **Details**\n *\n * The `issue` field contains a structured {@link SchemaIssue.Issue} tree describing\n * every validation failure, including the path to the problematic value and\n * the expected type or constraint. The `message` field renders the issue tree\n * with the default formatter.\n *\n * **Gotchas**\n *\n * Parsing with `reportInput: true` adds an enumerable `input` field to\n * value-bearing issues. Built-in messages may include reported input, and\n * custom annotations or messages are not sanitized.\n *\n * **Example** (Inspecting a SchemaError)\n *\n * ```ts import.meta.vitest\n * import { Result, Schema } from \"effect\"\n *\n * const result = Schema.decodeUnknownResult(Schema.Number)(\"not a number\")\n * const message = Result.isFailure(result) ? result.failure.message : \"\"\n * message // => \"Expected number\"\n * ```\n *\n * @see {@link isSchemaError} for narrowing unknown values\n * @category errors\n * @since 4.0.0\n */\nexport class SchemaError extends /*#__PURE__*/Data.TaggedError(\"SchemaError\") {\n  [SchemaErrorTypeId] = SchemaErrorTypeId;\n  constructor(issue) {\n    const stackTraceLimit = getStackTraceLimit();\n    setStackTraceLimit(0);\n    try {\n      super({\n        issue\n      });\n    } finally {\n      setStackTraceLimit(stackTraceLimit);\n    }\n  }\n  get message() {\n    return SchemaIssue.defaultFormatter(this.issue);\n  }\n  toString() {\n    return `SchemaError(${this.message})`;\n  }\n}\n/**\n * Returns `true` if `u` is a {@link SchemaError}.\n *\n * **When to use**\n *\n * Use when you need to narrow an unknown value to `SchemaError`.\n *\n * **Example** (Narrowing Schema errors)\n *\n * ```ts import.meta.vitest\n * import { Result, Schema } from \"effect\"\n *\n * const result = Result.try(() => Schema.decodeUnknownSync(Schema.Number)(\"oops\"))\n * const error: unknown = Result.isFailure(result) ? result.failure : undefined\n * Schema.isSchemaError(error) // => true\n * ```\n *\n * @category guards\n * @since 4.0.0\n */\nexport function isSchemaError(u) {\n  return isSchemaErrorInternal(u);\n}\nfunction fromIssueEffect(self) {\n  if (effectIsExit(self)) {\n    return fromIssueExit(self);\n  }\n  return Effect.catchCause(self, cause => Effect.failCauseSync(() => Cause_.map(cause, issue => new SchemaError(issue))));\n}\nfunction fromIssueExit(exit) {\n  return Exit_.isSuccess(exit) ? exit : Exit_.failCause(Cause_.map(exit.cause, issue => new SchemaError(issue)));\n}\nfunction getSchemaErrorOrThrow(cause, message) {\n  let schemaError;\n  for (const reason of cause.reasons) {\n    if (!Cause_.isFailReason(reason) || !isSchemaError(reason.error)) {\n      throw new globalThis.Error(message, {\n        cause\n      });\n    }\n    schemaError ??= reason.error;\n  }\n  if (schemaError === undefined) {\n    throw new globalThis.Error(message, {\n      cause\n    });\n  }\n  return schemaError;\n}\nfunction runSchemaErrorPromise(self) {\n  return Effect.runPromiseExit(self).then(exit => {\n    if (Exit_.isSuccess(exit)) {\n      return exit.value;\n    }\n    throw getSchemaErrorOrThrow(exit.cause, \"Promise adapter can only reject schema errors\");\n  });\n}\nfunction runSchemaErrorSync(self) {\n  const exit = Effect.runSyncExit(self);\n  if (Exit_.isSuccess(exit)) {\n    return exit.value;\n  }\n  throw getSchemaErrorOrThrow(exit.cause, \"Sync adapter can only throw schema errors\");\n}\n/**\n * Returns a \"Standard Schema\" object conforming to the [Standard Schema\n * v1](https://standardschema.dev/) specification.\n *\n * **Details**\n *\n * This function creates a schema whose `validate` method attempts to decode and\n * validate the provided input synchronously. If the underlying `Schema`\n * includes any asynchronous components (e.g., asynchronous message resolutions\n * or checks), then validation will necessarily return a `Promise` instead.\n *\n * **Example** (Creating a standard schema from a regular schema)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * // Define custom hook functions for error formatting\n * const leafHook = (issue: any) => {\n *   switch (issue._tag) {\n *     case \"InvalidType\":\n *       return \"Expected different type\"\n *     case \"InvalidValue\":\n *       return \"Invalid value provided\"\n *     case \"MissingKey\":\n *       return \"Required property missing\"\n *     case \"UnexpectedKey\":\n *       return \"Unexpected property found\"\n *     case \"Forbidden\":\n *       return \"Operation not allowed\"\n *     case \"OneOf\":\n *       return \"Multiple valid options available\"\n *     default:\n *       return \"Validation error\"\n *   }\n * }\n *\n * // Create a standard schema from a regular schema\n * const PersonSchema = Schema.Struct({\n *   name: Schema.NonEmptyString,\n *   age: Schema.Finite.check(Schema.isBetween({ minimum: 0, maximum: 150 }))\n * })\n *\n * const standardSchema = Schema.toStandardSchemaV1(PersonSchema, {\n *   leafHook\n * })\n *\n * // The standard schema can be used with any Standard Schema v1 compatible library\n * const validResult = standardSchema[\"~standard\"].validate({\n *   name: \"Alice\",\n *   age: 30\n * })\n * const invalidResult = standardSchema[\"~standard\"].validate({\n *   name: \"\",\n *   age: 200\n * })\n *\n * if (validResult instanceof Promise || invalidResult instanceof Promise) {\n *   throw new Error(\"Expected synchronous validation\")\n * }\n * if (\"value\" in validResult) {\n *   validResult.value // => { name: \"Alice\", age: 30 }\n * }\n * invalidResult.issues?.map((issue) => issue.path) // => [[\"name\"], [\"age\"]]\n * ```\n *\n * @category converting\n * @since 4.0.0\n */\nexport function toStandardSchemaV1(self, options) {\n  return InternalStandardSchema.toStandardSchemaV1(self, options);\n}\n/**\n * Converts a schema to an experimental Standard JSON Schema V1 representation.\n *\n * **Details**\n *\n * https://github.com/standard-schema/standard-schema/pull/134\n *\n * @category converting\n * @since 4.0.0\n */\nexport function toStandardJSONSchemaV1(self) {\n  return InternalStandardSchema.toStandardJSONSchemaV1(self);\n}\n/**\n * Creates a type guard function that checks if a value conforms to a given\n * schema.\n *\n * **Details**\n *\n * This function returns a predicate that performs a type-safe check, narrowing\n * the type of the input value if the check passes. The predicate returns `false`\n * for schema mismatches.\n *\n * **Gotchas**\n *\n * Only causes made entirely of schema issues are converted to `false`. Causes\n * that contain defects, interruptions, or other non-schema reasons throw\n * instead.\n *\n * **Example** (Defining a basic type guard)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const isString = Schema.is(Schema.String)\n *\n * isString(\"hello\") // => true\n * isString(42) // => false\n *\n * // Type narrowing in action\n * const value: unknown = \"hello\"\n * if (isString(value)) {\n *   // value is now typed as string\n *   value.toUpperCase() // => \"HELLO\"\n * }\n * ```\n *\n * @category guards\n * @since 3.10.0\n */\nexport const is = SchemaParser.is;\n/**\n * Creates an assertion function that throws an error if the input does not match\n * the schema.\n *\n * **When to use**\n *\n * Use to validate unknown input at runtime while narrowing the value with a\n * TypeScript assertion signature.\n *\n * **Details**\n *\n * The input is narrowed if the assertion succeeds. If schema validation fails,\n * the assertion throws an `Error` whose cause is `SchemaIssue.Issue`.\n * Schema validation failures use the generic message `\"Schema validation failed\"`.\n * Format the `cause` explicitly with `SchemaIssue.makeFormatterDefault()` when\n * human-readable details are needed.\n *\n * **Gotchas**\n *\n * Causes that contain defects, interruptions, or other non-schema reasons throw\n * with the underlying `Cause` attached instead of being converted to schema\n * validation errors.\n *\n * **Example** (Asserting and narrowing an input)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaIssue } from \"effect\"\n *\n * const input: unknown = \"hello\"\n *\n * // This will pass silently (no return value) and narrow input to string\n * Schema.asserts(Schema.String, input)\n * input.toUpperCase() // => \"HELLO\"\n *\n * // This will throw an error\n * try {\n *   const invalid: unknown = 123\n *   Schema.asserts(Schema.String, invalid)\n * } catch (error) {\n *   if (error instanceof Error) {\n *     SchemaIssue.isIssue(error.cause) // => true\n *   }\n * }\n * ```\n *\n * @category guards\n * @since 4.0.0\n */\nexport const asserts = SchemaParser.asserts;\n/**\n * Decodes an `unknown` input against a schema, returning an `Effect` that\n * succeeds with the decoded value or fails with a {@link SchemaError}.\n *\n * **When to use**\n *\n * Use when you need to decode unknown input in an `Effect` whose failure\n * channel is `SchemaError`.\n *\n * **Details**\n *\n * Prefer {@link decodeEffect} when the input is already typed as the schema's\n * `Encoded` type.\n * Options may be provided either when creating the decoder or when applying it;\n * application options override creation options.\n *\n * @see {@link SchemaParser.decodeUnknownEffect} for the adapter that fails with `SchemaIssue.Issue` directly\n *\n * @category decoding\n * @since 4.0.0\n */\nexport function decodeUnknownEffect(schema, options) {\n  const parser = SchemaParser.decodeUnknownEffect(schema, options);\n  return (input, options) => {\n    return fromIssueEffect(parser(input, options));\n  };\n}\n/**\n * Decodes a typed input (the schema's `Encoded` type) against a schema,\n * returning an `Effect` that succeeds with the decoded value or fails with a\n * {@link SchemaError}.\n *\n * **When to use**\n *\n * Use when you need to decode input already typed as the schema's `Encoded`\n * type in an `Effect` whose failure channel is `SchemaError`.\n *\n * **Details**\n *\n * For `unknown` input use {@link decodeUnknownEffect}.\n * Options may be provided either when creating the decoder or when applying it;\n * application options override creation options.\n *\n * @see {@link SchemaParser.decodeEffect} for the adapter that fails with `SchemaIssue.Issue` directly\n *\n * @category decoding\n * @since 4.0.0\n */\nexport const decodeEffect = decodeUnknownEffect;\n/**\n * Decodes an `unknown` input against a schema synchronously, returning an\n * `Exit` that is either a `Success` with the decoded value or a `Failure`.\n *\n * **When to use**\n *\n * Use when you need to decode unknown input into an `Exit` and capture schema\n * mismatches as `SchemaError`.\n *\n * **Details**\n *\n * Only usable with schemas that have no `DecodingServices` requirement. Prefer\n * {@link decodeExit} when the input is already typed as the schema's `Encoded`\n * type.\n * Options may be provided either when creating the decoder or when applying it;\n * application options override creation options.\n * Schema mismatches are represented by a `Failure` cause containing\n * `SchemaError`.\n *\n * **Gotchas**\n *\n * Schema issue fail reasons are wrapped as `SchemaError`. Defects,\n * interruptions, and other non-schema reasons remain in the returned `Cause`,\n * including when they are mixed with schema issues.\n *\n * @see {@link SchemaParser.decodeUnknownExit} for the adapter whose failure contains `SchemaIssue.Issue` directly\n *\n * @category decoding\n * @since 4.0.0\n */\nexport function decodeUnknownExit(schema, options) {\n  const parser = SchemaParser.decodeUnknownExit(schema, options);\n  return (input, options) => {\n    return fromIssueExit(parser(input, options));\n  };\n}\n/**\n * Decodes a typed input (the schema's `Encoded` type) against a schema\n * synchronously, returning an `Exit` that is either a `Success` with the decoded\n * value or a `Failure`.\n *\n * **When to use**\n *\n * Use when you need to decode already typed `Encoded` input into an `Exit` and\n * capture schema mismatches as `SchemaError`.\n *\n * **Details**\n *\n * Only usable with schemas that have no `DecodingServices` requirement. For\n * `unknown` input use {@link decodeUnknownExit}.\n * Options may be provided either when creating the decoder or when applying it;\n * application options override creation options.\n * Schema mismatches are represented by a `Failure` cause containing\n * `SchemaError`.\n *\n * **Gotchas**\n *\n * Schema issue fail reasons are wrapped as `SchemaError`. Defects,\n * interruptions, and other non-schema reasons remain in the returned `Cause`,\n * including when they are mixed with schema issues.\n *\n * @see {@link SchemaParser.decodeExit} for the adapter whose failure contains `SchemaIssue.Issue` directly\n *\n * @category decoding\n * @since 4.0.0\n */\nexport const decodeExit = decodeUnknownExit;\n/**\n * Decodes an `unknown` input against a schema, returning an `Option` that is\n * `Some` with the decoded value on success or `None` for schema mismatches.\n *\n * **When to use**\n *\n * Use when you do not know the input type statically and only need to know\n * whether decoding succeeded.\n *\n * **Details**\n *\n * Prefer this over {@link decodeUnknownExit} or {@link decodeUnknownEffect}\n * when you don't need error details. For input already typed as the schema's\n * `Encoded` type use {@link decodeOption}.\n * Options may be provided either when creating the decoder or when applying it;\n * application options override creation options.\n *\n * **Gotchas**\n *\n * Only causes made entirely of schema issues are converted to `None`. Causes\n * that contain defects, interruptions, or other non-schema reasons throw\n * instead.\n *\n * @category decoding\n * @since 3.10.0\n */\nexport const decodeUnknownOption = SchemaParser.decodeUnknownOption;\n/**\n * Decodes a typed input (the schema's `Encoded` type) against a schema,\n * returning an `Option` that is `Some` with the decoded value on success or\n * `None` for schema mismatches.\n *\n * **When to use**\n *\n * Use when you already have input typed as the schema's `Encoded` type and\n * only need to know whether decoding succeeded.\n *\n * **Details**\n *\n * For `unknown` input use {@link decodeUnknownOption}.\n * Options may be provided either when creating the decoder or when applying it;\n * application options override creation options.\n *\n * **Gotchas**\n *\n * Only causes made entirely of schema issues are converted to `None`. Causes\n * that contain defects, interruptions, or other non-schema reasons throw\n * instead.\n *\n * @category decoding\n * @since 3.10.0\n */\nexport const decodeOption = SchemaParser.decodeOption;\n/**\n * Decodes an `unknown` input against a schema, returning a `Result` that\n * succeeds with the decoded value or fails with a {@link SchemaError} for schema\n * mismatches.\n *\n * **When to use**\n *\n * Use when you do not know the input type statically and want schema mismatches\n * returned as `Result.fail` with `SchemaError`.\n *\n * **Details**\n *\n * For input already typed as the schema's `Encoded` type use\n * {@link decodeResult}.\n * Options may be provided either when creating the decoder or when applying it;\n * application options override creation options.\n * Schema mismatches are returned as `Result.fail` with `SchemaError`.\n *\n * **Gotchas**\n *\n * Only causes made entirely of schema issues are returned as `Result.fail`.\n * Causes that contain defects, interruptions, or other non-schema reasons throw\n * instead.\n *\n * @see {@link SchemaParser.decodeUnknownResult} for the adapter that fails with `SchemaIssue.Issue` directly\n *\n * @category decoding\n * @since 4.0.0\n */\nexport function decodeUnknownResult(schema, options) {\n  const parser = SchemaParser.decodeUnknownResult(schema, options);\n  return (input, options) => {\n    return Result_.mapError(parser(input, options), issue => new SchemaError(issue));\n  };\n}\n/**\n * Decodes a typed input (the schema's `Encoded` type) against a schema,\n * returning a `Result` that succeeds with the decoded value or fails with a\n * {@link SchemaError} for schema mismatches.\n *\n * **When to use**\n *\n * Use when you already have input typed as the schema's `Encoded` type and want\n * schema mismatches returned as `Result.fail` with `SchemaError`.\n *\n * **Details**\n *\n * For `unknown` input use {@link decodeUnknownResult}.\n * Options may be provided either when creating the decoder or when applying it;\n * application options override creation options.\n * Schema mismatches are returned as `Result.fail` with `SchemaError`.\n *\n * **Gotchas**\n *\n * Only causes made entirely of schema issues are returned as `Result.fail`.\n * Causes that contain defects, interruptions, or other non-schema reasons throw\n * instead.\n *\n * @see {@link SchemaParser.decodeResult} for the adapter that fails with `SchemaIssue.Issue` directly\n *\n * @category decoding\n * @since 4.0.0\n */\nexport const decodeResult = decodeUnknownResult;\n/**\n * Decodes an `unknown` input against a schema, returning a `Promise` that\n * resolves with the decoded value or rejects with a {@link SchemaError} for\n * schema mismatches.\n *\n * **When to use**\n *\n * Use when you need decoding of unknown input to return a JavaScript `Promise`\n * that rejects with `SchemaError` for schema mismatches.\n *\n * **Details**\n *\n * For input already typed as the schema's `Encoded` type use\n * {@link decodePromise}.\n * Options may be provided either when creating the decoder or when applying it;\n * application options override creation options.\n *\n * **Gotchas**\n *\n * Non-schema failures may reject with a runtime failure instead of\n * `SchemaError`.\n *\n * @see {@link SchemaParser.decodeUnknownPromise} for the adapter that rejects with an `Error` whose cause is `SchemaIssue.Issue`\n *\n * @category decoding\n * @since 3.10.0\n */\nexport function decodeUnknownPromise(schema, options) {\n  const parser = decodeUnknownEffect(schema, options);\n  return (input, options) => {\n    return runSchemaErrorPromise(parser(input, options));\n  };\n}\n/**\n * Decodes a typed input (the schema's `Encoded` type) against a schema,\n * returning a `Promise` that resolves with the decoded value or rejects with a\n * {@link SchemaError} for schema mismatches.\n *\n * **When to use**\n *\n * Use when you already have input typed as the schema's `Encoded` type and\n * need decoding to return a JavaScript `Promise` that rejects with\n * `SchemaError` for schema mismatches.\n *\n * **Details**\n *\n * For `unknown` input use `decodeUnknownPromise`.\n * Options may be provided either when creating the decoder or when applying it;\n * application options override creation options.\n *\n * **Gotchas**\n *\n * Non-schema failures may reject with a runtime failure instead of\n * `SchemaError`.\n *\n * @see {@link SchemaParser.decodePromise} for the adapter that rejects with an `Error` whose cause is `SchemaIssue.Issue`\n *\n * @category decoding\n * @since 3.10.0\n */\nexport const decodePromise = decodeUnknownPromise;\n/**\n * Decodes an `unknown` input against a schema synchronously, returning the\n * decoded value or throwing a {@link SchemaError} for schema mismatches.\n *\n * **When to use**\n *\n * Use when you need to validate unknown data at a synchronous boundary and want\n * schema mismatches to throw `SchemaError`.\n *\n * **Details**\n *\n * For input already typed as the schema's `Encoded` type use `decodeSync`.\n * Only service-free schemas can be decoded synchronously. For alternatives that\n * do not throw on schema mismatches, see `decodeUnknownOption`,\n * `decodeUnknownExit`, or `decodeUnknownEffect`. Options may be provided either\n * when creating the decoder or when applying it; application options override\n * creation options.\n *\n * **Gotchas**\n *\n * Non-schema failures may throw a runtime failure instead of `SchemaError`.\n *\n * **Example** (Decoding with a transformation schema)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const NumberFromString = Schema.NumberFromString\n *\n * Schema.decodeUnknownSync(NumberFromString)(\"42\") // => 42\n * ```\n *\n * @see {@link SchemaParser.decodeUnknownSync} for the adapter that throws an `Error` whose cause is `SchemaIssue.Issue`\n *\n * @category decoding\n * @since 4.0.0\n */\nexport function decodeUnknownSync(schema, options) {\n  const parser = decodeUnknownEffect(schema, options);\n  return (input, options) => {\n    return runSchemaErrorSync(parser(input, options));\n  };\n}\n/**\n * Decodes a typed input (the schema's `Encoded` type) against a schema\n * synchronously, returning the decoded value or throwing a {@link SchemaError}\n * for schema mismatches.\n *\n * **When to use**\n *\n * Use when you already have input typed as the schema's `Encoded` type and\n * want schema mismatches to throw `SchemaError` synchronously.\n *\n * **Details**\n *\n * For `unknown` input use `decodeUnknownSync`.\n * Only service-free schemas can be decoded synchronously. Options may be\n * provided either when creating the decoder or when applying it; application\n * options override creation options.\n *\n * **Gotchas**\n *\n * Non-schema failures may throw a runtime failure instead of `SchemaError`.\n *\n * @see {@link SchemaParser.decodeSync} for the adapter that throws an `Error` whose cause is `SchemaIssue.Issue`\n *\n * @category decoding\n * @since 4.0.0\n */\nexport const decodeSync = decodeUnknownSync;\n/**\n * Encodes an `unknown` input against a schema, returning an `Effect` that\n * succeeds with the encoded value or fails with a {@link SchemaError}.\n *\n * **When to use**\n *\n * Use when you need to encode unknown input in an `Effect` whose failure\n * channel is `SchemaError`.\n *\n * **Details**\n *\n * Prefer {@link encodeEffect} when the value is already typed as the schema's\n * `Type`.\n * Options may be provided either when creating the encoder or when applying it;\n * application options override creation options.\n *\n * **Example** (Encoding a value to a string)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schema } from \"effect\"\n *\n * const NumberFromString = Schema.NumberFromString\n *\n * await Effect.runPromise(Schema.encodeUnknownEffect(NumberFromString)(42)) // => \"42\"\n * ```\n *\n * @see {@link SchemaParser.encodeUnknownEffect} for the adapter that fails with `SchemaIssue.Issue` directly\n *\n * @category encoding\n * @since 4.0.0\n */\nexport function encodeUnknownEffect(schema, options) {\n  const parser = SchemaParser.encodeUnknownEffect(schema, options);\n  return (input, options) => {\n    return fromIssueEffect(parser(input, options));\n  };\n}\n/**\n * Encodes a typed input (the schema's `Type`) against a schema, returning an\n * `Effect` that succeeds with the encoded value or fails with a\n * {@link SchemaError}.\n *\n * **When to use**\n *\n * Use when you need to encode input already typed as the schema's `Type` in\n * an `Effect` whose failure channel is `SchemaError`.\n *\n * **Details**\n *\n * For `unknown` input use {@link encodeUnknownEffect}.\n * Options may be provided either when creating the encoder or when applying it;\n * application options override creation options.\n *\n * @see {@link SchemaParser.encodeEffect} for the adapter that fails with `SchemaIssue.Issue` directly\n *\n * @category encoding\n * @since 4.0.0\n */\nexport const encodeEffect = encodeUnknownEffect;\n/**\n * Encodes an `unknown` input against a schema synchronously, returning an\n * `Exit` that is either a `Success` with the encoded value or a `Failure`.\n *\n * **When to use**\n *\n * Use when you need to encode unknown input into an `Exit` and capture schema\n * mismatches as `SchemaError`.\n *\n * **Details**\n *\n * Only usable with schemas that have no `EncodingServices` requirement. Prefer\n * {@link encodeExit} when the value is already typed as the schema's `Type`.\n * Options may be provided either when creating the encoder or when applying it;\n * application options override creation options.\n * Schema mismatches are represented by a `Failure` cause containing\n * `SchemaError`.\n *\n * **Gotchas**\n *\n * Schema issue fail reasons are wrapped as `SchemaError`. Defects,\n * interruptions, and other non-schema reasons remain in the returned `Cause`,\n * including when they are mixed with schema issues.\n *\n * @see {@link SchemaParser.encodeUnknownExit} for the adapter whose failure contains `SchemaIssue.Issue` directly\n *\n * @category encoding\n * @since 4.0.0\n */\nexport function encodeUnknownExit(schema, options) {\n  const parser = SchemaParser.encodeUnknownExit(schema, options);\n  return (input, options) => {\n    return fromIssueExit(parser(input, options));\n  };\n}\n/**\n * Encodes a typed input (the schema's `Type`) against a schema synchronously,\n * returning an `Exit` that is either a `Success` with the encoded value or a\n * `Failure`.\n *\n * **When to use**\n *\n * Use when you need to encode already typed schema values into an `Exit` and\n * capture schema mismatches as `SchemaError`.\n *\n * **Details**\n *\n * Only usable with schemas that have no `EncodingServices` requirement. For\n * `unknown` input use {@link encodeUnknownExit}.\n * Options may be provided either when creating the encoder or when applying it;\n * application options override creation options.\n * Schema mismatches are represented by a `Failure` cause containing\n * `SchemaError`.\n *\n * **Gotchas**\n *\n * Schema issue fail reasons are wrapped as `SchemaError`. Defects,\n * interruptions, and other non-schema reasons remain in the returned `Cause`,\n * including when they are mixed with schema issues.\n *\n * @see {@link SchemaParser.encodeExit} for the adapter whose failure contains `SchemaIssue.Issue` directly\n *\n * @category encoding\n * @since 4.0.0\n */\nexport const encodeExit = encodeUnknownExit;\n/**\n * Encodes an `unknown` input against a schema, returning an `Option` that is\n * `Some` with the encoded value on success or `None` for schema mismatches.\n *\n * **When to use**\n *\n * Use when you do not know the input type statically and only need to know\n * whether encoding succeeded.\n *\n * **Details**\n *\n * Prefer this over {@link encodeUnknownExit} or {@link encodeUnknownEffect}\n * when you don't need error details. For values already typed as the schema's\n * `Type` use {@link encodeOption}.\n * Options may be provided either when creating the encoder or when applying it;\n * application options override creation options.\n *\n * **Gotchas**\n *\n * Only causes made entirely of schema issues are converted to `None`. Causes\n * that contain defects, interruptions, or other non-schema reasons throw\n * instead.\n *\n * @category encoding\n * @since 3.10.0\n */\nexport const encodeUnknownOption = SchemaParser.encodeUnknownOption;\n/**\n * Encodes a typed input (the schema's `Type`) against a schema, returning an\n * `Option` that is `Some` with the encoded value on success or `None` for schema\n * mismatches.\n *\n * **When to use**\n *\n * Use when you already have a value typed as the schema's `Type` and only need\n * to know whether encoding succeeded.\n *\n * **Details**\n *\n * For `unknown` input use {@link encodeUnknownOption}.\n * Options may be provided either when creating the encoder or when applying it;\n * application options override creation options.\n *\n * **Gotchas**\n *\n * Only causes made entirely of schema issues are converted to `None`. Causes\n * that contain defects, interruptions, or other non-schema reasons throw\n * instead.\n *\n * @category encoding\n * @since 3.10.0\n */\nexport const encodeOption = SchemaParser.encodeOption;\n/**\n * Encodes an `unknown` input against a schema, returning a `Result` that\n * succeeds with the encoded value or fails with a {@link SchemaError} for schema\n * mismatches.\n *\n * **When to use**\n *\n * Use when you do not know the input type statically and want schema mismatches\n * returned as `Result.fail` with `SchemaError`.\n *\n * **Details**\n *\n * For values already typed as the schema's `Type` use {@link encodeResult}.\n * Options may be provided either when creating the encoder or when applying it;\n * application options override creation options.\n * Schema mismatches are returned as `Result.fail` with `SchemaError`.\n *\n * **Gotchas**\n *\n * Only causes made entirely of schema issues are returned as `Result.fail`.\n * Causes that contain defects, interruptions, or other non-schema reasons throw\n * instead.\n *\n * @see {@link SchemaParser.encodeUnknownResult} for the adapter that fails with `SchemaIssue.Issue` directly\n *\n * @category encoding\n * @since 4.0.0\n */\nexport function encodeUnknownResult(schema, options) {\n  const parser = SchemaParser.encodeUnknownResult(schema, options);\n  return (input, options) => {\n    return Result_.mapError(parser(input, options), issue => new SchemaError(issue));\n  };\n}\n/**\n * Encodes a typed input (the schema's `Type`) against a schema, returning a\n * `Result` that succeeds with the encoded value or fails with a\n * {@link SchemaError} for schema mismatches.\n *\n * **When to use**\n *\n * Use when you already have a value typed as the schema's `Type` and want schema\n * mismatches returned as `Result.fail` with `SchemaError`.\n *\n * **Details**\n *\n * For `unknown` input use {@link encodeUnknownResult}.\n * Options may be provided either when creating the encoder or when applying it;\n * application options override creation options.\n * Schema mismatches are returned as `Result.fail` with `SchemaError`.\n *\n * **Gotchas**\n *\n * Only causes made entirely of schema issues are returned as `Result.fail`.\n * Causes that contain defects, interruptions, or other non-schema reasons throw\n * instead.\n *\n * @see {@link SchemaParser.encodeResult} for the adapter that fails with `SchemaIssue.Issue` directly\n *\n * @category encoding\n * @since 4.0.0\n */\nexport const encodeResult = encodeUnknownResult;\n/**\n * Encodes an `unknown` input against a schema, returning a `Promise` that\n * resolves with the encoded value or rejects with a {@link SchemaError} for\n * schema mismatches.\n *\n * **When to use**\n *\n * Use when you need encoding of unknown input to return a JavaScript `Promise`\n * that rejects with `SchemaError` for schema mismatches.\n *\n * **Details**\n *\n * For values already typed as the schema's `Type` use {@link encodePromise}.\n * Options may be provided either when creating the encoder or when applying it;\n * application options override creation options.\n *\n * **Gotchas**\n *\n * Non-schema failures may reject with a runtime failure instead of\n * `SchemaError`.\n *\n * @see {@link SchemaParser.encodeUnknownPromise} for the adapter that rejects with an `Error` whose cause is `SchemaIssue.Issue`\n *\n * @category encoding\n * @since 3.10.0\n */\nexport function encodeUnknownPromise(schema, options) {\n  const parser = encodeUnknownEffect(schema, options);\n  return (input, options) => {\n    return runSchemaErrorPromise(parser(input, options));\n  };\n}\n/**\n * Encodes a typed input (the schema's `Type`) against a schema, returning a\n * `Promise` that resolves with the encoded value or rejects with a\n * {@link SchemaError} for schema mismatches.\n *\n * **When to use**\n *\n * Use when you already have a value typed as the schema's `Type` and need\n * encoding to return a JavaScript `Promise` that rejects with `SchemaError` for\n * schema mismatches.\n *\n * **Details**\n *\n * For `unknown` input use {@link encodeUnknownPromise}.\n * Options may be provided either when creating the encoder or when applying it;\n * application options override creation options.\n *\n * **Gotchas**\n *\n * Non-schema failures may reject with a runtime failure instead of\n * `SchemaError`.\n *\n * @see {@link SchemaParser.encodePromise} for the adapter that rejects with an `Error` whose cause is `SchemaIssue.Issue`\n *\n * @category encoding\n * @since 3.10.0\n */\nexport const encodePromise = encodeUnknownPromise;\n/**\n * Encodes an `unknown` input against a schema synchronously, throwing a\n * {@link SchemaError} for schema mismatches.\n *\n * **When to use**\n *\n * Use when you need to serialize unknown data at a synchronous boundary and\n * want schema mismatches to throw `SchemaError`.\n *\n * **Details**\n *\n * For alternatives that do not throw on schema mismatches, see\n * {@link encodeUnknownOption}, {@link encodeUnknownExit}, or\n * {@link encodeUnknownEffect}. For values already typed as the schema's `Type`\n * use {@link encodeSync}. Options may be provided either when creating the\n * encoder or when applying it; application options override creation options.\n *\n * **Gotchas**\n *\n * Non-schema failures may throw a runtime failure instead of `SchemaError`.\n *\n * @see {@link SchemaParser.encodeUnknownSync} for the adapter that throws an `Error` whose cause is `SchemaIssue.Issue`\n *\n * @category encoding\n * @since 4.0.0\n */\nexport function encodeUnknownSync(schema, options) {\n  const parser = encodeUnknownEffect(schema, options);\n  return (input, options) => {\n    return runSchemaErrorSync(parser(input, options));\n  };\n}\n/**\n * Encodes a typed input (the schema's `Type`) against a schema synchronously,\n * throwing a {@link SchemaError} for schema mismatches.\n *\n * **When to use**\n *\n * Use when you already have a value typed as the schema's `Type` and want\n * schema mismatches to throw `SchemaError` synchronously.\n *\n * **Details**\n *\n * For `unknown` input use {@link encodeUnknownSync}.\n * Options may be provided either when creating the encoder or when applying it;\n * application options override creation options.\n *\n * **Gotchas**\n *\n * Non-schema failures may throw a runtime failure instead of `SchemaError`.\n *\n * @see {@link SchemaParser.encodeSync} for the adapter that throws an `Error` whose cause is `SchemaIssue.Issue`\n *\n * @category encoding\n * @since 4.0.0\n */\nexport const encodeSync = encodeUnknownSync;\n/**\n * Creates a schema from an AST (Abstract Syntax Tree) node.\n *\n * **Details**\n *\n * This is the fundamental constructor for all schemas in the Effect Schema\n * library. It takes an AST node and wraps it in a fully-typed schema that\n * preserves all type information and provides the complete schema API.\n *\n * The `make` function is used internally to create all primitive schemas like\n * `String`, `Number`, `Boolean`, etc., as well as more complex schemas. It's\n * the bridge between the untyped AST representation and the strongly-typed\n * schema.\n *\n * @category constructors\n * @since 3.10.0\n */\nexport const make = InternalMake.make;\n/**\n * Checks whether a value is a `Schema`.\n *\n * @category guards\n * @since 3.10.0\n */\nexport function isSchema(u) {\n  return Predicate.hasProperty(u, TypeId) && u[TypeId] === TypeId;\n}\n/**\n * Creates an exact optional key schema for struct fields. Unlike `optional`,\n * this creates exact optional properties (not `| undefined`) that can be\n * completely omitted from the object.\n *\n * **Example** (Creating a struct with optional key)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const schema = Schema.Struct({\n *   name: Schema.String,\n *   age: Schema.optionalKey(Schema.Number)\n * })\n *\n * // Type: { readonly name: string; readonly age?: number }\n * type Person = typeof schema[\"Type\"]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const optionalKey = /*#__PURE__*/Struct_.lambda(schema => make(SchemaAST.optionalKey(schema.ast), {\n  schema\n}));\n/**\n * Reverses `optionalKey` and returns the inner required schema.\n *\n * **When to use**\n *\n * Use to remove optional-key wrapping from a schema field that was previously\n * wrapped with {@link optionalKey}.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const requiredKey = /*#__PURE__*/Struct_.lambda(self => self.schema);\n/**\n * Marks a struct field as optional, allowing the key to be absent or\n * `undefined`.\n *\n * **Details**\n *\n * The resulting property may be absent or explicitly set to `undefined`.\n * Equivalent to `optionalKey(UndefinedOr(S))`.\n *\n * Use {@link optionalKey} instead if you want exact optional semantics (absent\n * only, not `undefined`).\n *\n * **Example** (Defining an optional field accepting undefined)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const schema = Schema.Struct({\n *   name: Schema.String,\n *   age: Schema.optional(Schema.Number)\n * })\n *\n * // { readonly name: string; readonly age?: number | undefined }\n * type Person = typeof schema.Type\n * ```\n *\n * @category combinators\n * @since 3.10.0\n */\nexport const optional = /*#__PURE__*/Struct_.lambda(self => {\n  const schema = UndefinedOr(self);\n  return make(SchemaAST.optional(self.ast), {\n    schema\n  });\n});\n/**\n * Reverses `optional` and returns the inner schema.\n *\n * **When to use**\n *\n * Use to remove optional wrapping from a schema field that was previously\n * wrapped with {@link optional}.\n *\n * **Details**\n *\n * This also unwraps the `UndefinedOr` member added by `optional`.\n *\n * @category combinators\n * @since 3.10.0\n */\nexport const required = /*#__PURE__*/Struct_.lambda(self => self.schema.members[0]);\n/**\n * Makes a struct field mutable (removes the `readonly` modifier on the property).\n * Use {@link readonlyKey} to reverse.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const mutableKey = /*#__PURE__*/Struct_.lambda(schema => make(SchemaAST.mutableKey(schema.ast), {\n  schema\n}));\n/**\n * Reverses `mutableKey` and returns the inner readonly schema.\n *\n * **When to use**\n *\n * Use to remove mutable-key wrapping from a schema field that was previously\n * wrapped with {@link mutableKey}.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const readonlyKey = /*#__PURE__*/Struct_.lambda(self => self.schema);\n/**\n * Extracts the type-side schema: sets `Encoded` to equal the decoded `Type`,\n * discarding the encoding transformation path.\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const toType = /*#__PURE__*/Struct_.lambda(schema => make(SchemaAST.toType(schema.ast), {\n  schema\n}));\n/**\n * Extracts the encoded-side schema: sets `Type` to equal the `Encoded`,\n * discarding the decoding transformation path.\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const toEncoded = /*#__PURE__*/Struct_.lambda(schema => make(SchemaAST.toEncoded(schema.ast), {\n  schema\n}));\nconst FlipTypeId = \"~effect/Schema/flip\";\nfunction isFlip$(schema) {\n  return Predicate.hasProperty(schema, FlipTypeId) && schema[FlipTypeId] === FlipTypeId;\n}\nexport function flip(schema) {\n  if (isFlip$(schema)) {\n    return schema.schema.rebuild(SchemaAST.flip(schema.ast));\n  }\n  return make(SchemaAST.flip(schema.ast), {\n    [FlipTypeId]: FlipTypeId,\n    schema\n  });\n}\n/**\n * Creates a schema for a single literal value (string, number, bigint, boolean, or null).\n *\n * **Example** (Defining a string literal)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const schema = Schema.Literal(\"hello\")\n * // Type: Schema.Literal<\"hello\">\n * Schema.decodeSync(schema)(\"hello\") // => \"hello\"\n * ```\n *\n * @see {@link Literals} for a schema that represents a union of literals.\n * @see {@link tag} for a schema that represents a literal value that can be\n * used as a discriminator field in tagged unions and has a constructor default.\n * @category constructors\n * @since 3.10.0\n */\nexport function Literal(literal) {\n  const out = make(new SchemaAST.Literal(literal), {\n    literal,\n    transform(to) {\n      return out.pipe(decodeTo(Literal(to), {\n        decode: SchemaGetter.transform(() => to),\n        encode: SchemaGetter.transform(() => literal)\n      }));\n    }\n  });\n  return out;\n}\nfunction templateLiteralParts(parts) {\n  return parts.map(part => isSchema(part) ? part.ast : new SchemaAST.Literal(part));\n}\n/**\n * Creates a schema that validates strings by matching ordered template literal\n * parts.\n *\n * **When to use**\n *\n * Use when the decoded value should remain the matched string and you do not\n * need the individual template parts parsed into a tuple.\n *\n * **Details**\n *\n * Each part can be a literal `string`, `number`, or `bigint`, or a schema whose\n * encoded type is `string`, `number`, or `bigint`. Checks on string, number,\n * and bigint schema parts are applied while matching each segment.\n *\n * **Gotchas**\n *\n * Parts must not contain encodings, including inside unions or nested templates.\n * Construction throws for transformed parts even when their decoded and encoded\n * types are the same. Use {@link TemplateLiteralParser} to decode transformed parts.\n * Brands and supported checks without encodings remain valid.\n *\n * **Example** (Defining a URL path pattern)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const schema = Schema.TemplateLiteral([\"/user/\", Schema.Number])\n * Schema.is(schema)(\"/user/123\") // => true\n * ```\n *\n * @see {@link TemplateLiteralParser} for a schema that also parses matched parts into a tuple.\n * @category constructors\n * @since 3.10.0\n */\nexport function TemplateLiteral(parts) {\n  return make(new SchemaAST.TemplateLiteral(templateLiteralParts(parts)), {\n    parts\n  });\n}\n/**\n * Schema for parsing matched template literal strings into typed tuple parts.\n *\n * **When to use**\n *\n * Use to validate a template literal string and decode the matched parts into\n * typed values.\n *\n * **Details**\n *\n * Unlike {@link TemplateLiteral}, this schema decodes the matched string into a\n * readonly tuple with one element per schema part. Checks on string, number,\n * and bigint schema parts are applied while matching each segment.\n * The source template uses the encoded sides of the parts; the tuple retains\n * their transformations, checks, and decoding and encoding service requirements.\n *\n * **Gotchas**\n *\n * Ambiguous templates use greedy segmentation with backtracking. Encoding a\n * tuple and decoding the resulting string can therefore produce a different\n * tuple when a segment contains a separator used by the template.\n *\n * **Example** (Parsing path parameters)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const schema = Schema.TemplateLiteralParser([\"/user/\", Schema.NumberFromString])\n * Schema.decodeSync(schema)(\"/user/42\") // => [\"/user/\", 42]\n * ```\n *\n * @see {@link TemplateLiteral} for a validation-only version that keeps the string encoded.\n * @category constructors\n * @since 3.10.0\n */\nexport function TemplateLiteralParser(parts) {\n  return make(SchemaAST.templateLiteralParser(templateLiteralParts(parts)), {\n    parts\n  });\n}\n/**\n * Creates a schema from a TypeScript enum object. Validates that the input is one of the enum's values.\n * Numeric enum values must be finite.\n *\n * **Gotchas**\n *\n * Throws when a numeric member is `NaN`, `Infinity`, or `-Infinity`.\n *\n * **Example** (Defining a direction enum)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * enum Direction {\n *   Up = \"Up\",\n *   Down = \"Down\"\n * }\n *\n * const schema = Schema.Enum(Direction)\n * Schema.decodeSync(schema)(Direction.Up) // => \"Up\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport function Enum(enums) {\n  return make(new SchemaAST.Enum(Object.keys(enums).filter(key => typeof enums[enums[key]] !== \"number\").map(key => [key, enums[key]])), {\n    enums\n  });\n}\n/**\n * Schema for the `never` type. Always fails validation — no value satisfies it.\n *\n * @category schemas\n * @since 3.10.0\n */\nexport const Never = /*#__PURE__*/make(SchemaAST.never);\n/**\n * Schema for the `any` type. Accepts any value without validation.\n *\n * @see {@link Unknown} for a safer alternative that uses `unknown`.\n * @category schemas\n * @since 3.10.0\n */\nexport const Any = /*#__PURE__*/make(SchemaAST.any);\n/**\n * Schema for the `unknown` type. Accepts any value without validation.\n *\n * **When to use**\n *\n * Use as a top schema when you need to accept any input while preserving\n * TypeScript's `unknown` safety at use sites.\n *\n * @see {@link Any} for the `any` variant.\n * @category schemas\n * @since 3.10.0\n */\nexport const Unknown = /*#__PURE__*/make(SchemaAST.unknown);\n/**\n * Schema for the `null` literal. Validates that the input is strictly `null`.\n *\n * @see {@link NullOr} for a union with another schema.\n * @category schemas\n * @since 3.10.0\n */\nexport const Null = /*#__PURE__*/make(SchemaAST.null);\n/**\n * Schema for the `undefined` literal. Validates that the input is strictly `undefined`.\n *\n * @see {@link UndefinedOr} for a union with another schema.\n * @category schemas\n * @since 3.10.0\n */\nexport const Undefined = /*#__PURE__*/make(SchemaAST.undefined);\n/**\n * Schema for `string` values. Validates that the input is `typeof` `\"string\"`.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const String = /*#__PURE__*/make(SchemaAST.string);\n/**\n * Schema for `number` values, including `NaN`, `Infinity`, and `-Infinity`.\n *\n * **Details**\n *\n * Default JSON serializer:\n *\n * - Finite numbers are serialized as numbers.\n * - Non-finite values are serialized as strings (`\"NaN\"`, `\"Infinity\"`, `\"-Infinity\"`).\n *\n * @see {@link Finite} for a schema that excludes non-finite values.\n * @category schemas\n * @since 4.0.0\n */\nexport const Number = /*#__PURE__*/make(SchemaAST.number);\n/**\n * Schema for `boolean` values. Validates that the input is `typeof` `\"boolean\"`.\n *\n * **When to use**\n *\n * Use to validate values that are already JavaScript booleans.\n *\n * @see {@link BooleanFromBit} for a schema that decodes bit literals `0` or `1` into a boolean\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const Boolean = /*#__PURE__*/make(SchemaAST.boolean);\n/**\n * Schema for `symbol` values. Validates that the input is `typeof` `\"symbol\"`.\n *\n * @see {@link UniqueSymbol} for a schema that matches a specific symbol.\n * @category schemas\n * @since 4.0.0\n */\nexport const Symbol = /*#__PURE__*/make(SchemaAST.symbol);\n/**\n * Schema for `bigint` values. Validates that the input is `typeof` `\"bigint\"`.\n *\n * **When to use**\n *\n * Use when the input is already a bigint and the schema should validate and\n * preserve bigint values without parsing from another representation.\n *\n * @see {@link BigIntFromString} for parsing string input into a bigint\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const BigInt = /*#__PURE__*/make(SchemaAST.bigInt);\n/**\n * Schema for a TypeScript `void` return value.\n *\n * **When to use**\n *\n * Use when you need to model the return value of a function, RPC, or endpoint\n * whose result is intentionally ignored.\n *\n * **Details**\n *\n * Runtime parsing accepts any present value and discards it, producing\n * `undefined`. The public decoded and encoded TypeScript representation remains\n * `void`, so typed construction, decoding, and encoding APIs are still modeled\n * as `void`.\n *\n * @see {@link Undefined} for a schema that matches only the exact `undefined` value.\n * @category schemas\n * @since 3.10.0\n */\nexport const Void = /*#__PURE__*/make(SchemaAST.void);\n/**\n * Schema for the `object` type. Validates that the input is a non-null object or function\n * (i.e. `typeof value === \"object\" && value !== null || typeof value === \"function\"`).\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const ObjectKeyword = /*#__PURE__*/make(SchemaAST.objectKeyword);\n/**\n * Creates a schema for a specific symbol. Only that exact symbol satisfies the schema.\n *\n * **Gotchas**\n *\n * Only globally registered symbols have a JSON encoding. Their canonical JSON\n * form is the exact string returned by `String(symbol)`. A local symbol cannot\n * be encoded as JSON.\n *\n * **Example** (Defining a specific symbol)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const mySymbol = Symbol.for(\"mySymbol\")\n * const schema = Schema.UniqueSymbol(mySymbol)\n * Schema.decodeSync(schema)(mySymbol) === mySymbol // => true\n * ```\n *\n * @see {@link Symbol} for a schema that accepts any symbol.\n * @category constructors\n * @since 4.0.0\n */\nexport function UniqueSymbol(symbol) {\n  return make(new SchemaAST.UniqueSymbol(symbol));\n}\nfunction makeStruct(ast, fields) {\n  return make(ast, {\n    fields,\n    mapFields(f, options) {\n      const fields = f(this.fields);\n      return makeStruct(SchemaAST.struct(fields, options?.unsafePreserveChecks ? this.ast.checks : undefined), fields);\n    }\n  });\n}\n/**\n * Defines a struct schema from a map of field schemas.\n *\n * **Details**\n *\n * Each field value is a schema. Use {@link optionalKey} or {@link optional} to\n * mark fields as optional, and {@link mutableKey} to mark them as mutable.\n *\n * The resulting schema's `Type` is a readonly object type with the fields'\n * decoded types. The `Encoded` form mirrors the field schemas' encoded types.\n * Declared fields may be inherited and are copied to own properties in the\n * output. The `__proto__` field is accepted only when it is an own property.\n * Parsing does not guarantee that output keys retain their input order.\n *\n * **Example** (Defining a basic struct)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const Person = Schema.Struct({\n *   name: Schema.String,\n *   age: Schema.Number,\n *   email: Schema.optionalKey(Schema.String)\n * })\n *\n * // { readonly name: string; readonly age: number; readonly email?: string }\n * type Person = typeof Person.Type\n *\n * Schema.decodeUnknownSync(Person)({ name: \"Alice\", age: 30 }) // => { name: \"Alice\", age: 30 }\n * ```\n *\n * @category constructors\n * @since 3.10.0\n */\nexport function Struct(fields) {\n  return makeStruct(SchemaAST.struct(fields, undefined), fields);\n}\n/**\n * Adds fields to a struct schema through a struct-mapping lambda.\n *\n * **When to use**\n *\n * Use to add the same fields to an existing struct or every struct member of a\n * union.\n *\n * **Details**\n *\n * This is a shortcut for `MyStruct.mapFields(Struct.assign(fields))`.\n *\n * **Example** (Adding fields to a union of structs)\n *\n * ```ts import.meta.vitest\n * import { Schema, Tuple } from \"effect\"\n *\n * // Add a new field to all members of a union of structs\n * const schema = Schema.Union([\n *   Schema.Struct({ a: Schema.String }),\n *   Schema.Struct({ b: Schema.Number })\n * ]).mapMembers(Tuple.map(Schema.fieldsAssign({ c: Schema.Number })))\n * Schema.decodeSync(schema)({ a: \"a\", c: 1 }) // => { a: \"a\", c: 1 }\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport function fieldsAssign(fields) {\n  return Struct_.lambda(struct => struct.mapFields(Struct_.assign(fields)));\n}\nconst canonicalPropertyKey = key => typeof key === \"symbol\" ? key : globalThis.String(key);\n/**\n * Renames struct keys in the encoded form without changing the decoded type.\n *\n * **Details**\n *\n * Takes a partial mapping `{ decodedKey: encodedKey }` and produces a\n * transformation schema that decodes from the renamed keys and encodes back to\n * the renamed keys. Keys not present in the mapping are left unchanged.\n * If two existing fields would produce the same encoded key, construction\n * fails.\n *\n * **Example** (Renaming `name` to `full_name` in the encoded form)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const Person = Schema.Struct({ name: Schema.String, age: Schema.Number })\n * const Encoded = Person.pipe(Schema.encodeKeys({ name: \"full_name\" }))\n *\n * // Decodes { full_name: \"Alice\", age: 30 } → { name: \"Alice\", age: 30 }\n * Schema.decodeUnknownSync(Encoded)({ full_name: \"Alice\", age: 30 }) // => { name: \"Alice\", age: 30 }\n * ```\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function encodeKeys(mapping) {\n  return function (self) {\n    const fields = {};\n    const appliedMapping = Object.create(null);\n    const reverseMapping = Object.create(null);\n    const seenEncodedKeys = new Set();\n    for (const k of Reflect.ownKeys(self.fields)) {\n      const encoded = toEncoded(self.fields[k]);\n      const hasMapping = Object.hasOwn(mapping, k);\n      const encodedKey = hasMapping ? mapping[k] : k;\n      const canonical = canonicalPropertyKey(encodedKey);\n      if (seenEncodedKeys.has(canonical)) {\n        throw new globalThis.Error(`Duplicate encoded keys: ${formatPropertyKey(encodedKey)}`);\n      }\n      seenEncodedKeys.add(canonical);\n      InternalRecord.assignProperty(fields, encodedKey, encoded);\n      if (hasMapping) {\n        appliedMapping[k] = encodedKey;\n        reverseMapping[encodedKey] = k;\n      }\n    }\n    return Struct(fields).pipe(decodeTo(self, SchemaTransformation.transform({\n      decode: Struct_.renameKeys(reverseMapping),\n      encode: Struct_.renameKeys(appliedMapping)\n    })));\n  };\n}\n/**\n * Adds derived fields to a struct schema during decoding.\n *\n * **Details**\n *\n * Each new field is derived from the decoded struct value via a function that\n * returns `Option`. On encoding the derived fields are stripped. This allows\n * computed or enriched fields to live in the decoded type without appearing in\n * the encoded form.\n *\n * **Example** (Adding a computed `fullName` field)\n *\n * ```ts import.meta.vitest\n * import { Option, Schema } from \"effect\"\n *\n * const Person = Schema.Struct({ first: Schema.String, last: Schema.String })\n * const Extended = Person.pipe(\n *   Schema.extendTo(\n *     { fullName: Schema.String },\n *     { fullName: (p) => Option.some(`${p.first} ${p.last}`) }\n *   )\n * )\n *\n * const alice = Schema.decodeUnknownSync(Extended)({ first: \"Alice\", last: \"Smith\" })\n * alice.fullName // => \"Alice Smith\"\n * ```\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function extendTo(fields, derive) {\n  return self => {\n    const f = Record_.map(self.fields, toType);\n    const to = Struct({\n      ...f,\n      ...fields\n    });\n    return self.pipe(decodeTo(to, SchemaTransformation.transform({\n      decode: input => {\n        const out = {\n          ...input\n        };\n        for (const k in fields) {\n          const f = derive[k];\n          const o = f(input);\n          if (Option_.isSome(o)) {\n            InternalRecord.assignProperty(out, k, o.value);\n          }\n        }\n        return out;\n      },\n      encode: input => {\n        const out = {\n          ...input\n        };\n        for (const k in fields) {\n          delete out[k];\n        }\n        return out;\n      }\n    })));\n  };\n}\n/**\n * Defines a record schema whose dynamic properties are selected by a key schema\n * and decoded with a value schema.\n *\n * **Details**\n *\n * For dynamic keys, the key schema selects matching own properties and the\n * value schema decodes or encodes only those selected properties. Checks on\n * string, number, symbol, and template literal key schemas narrow which\n * properties are selected.\n *\n * For transformed key schemas, property selection is based on encoded property\n * names before the selected key is decoded.\n *\n * **Gotchas**\n *\n * When decoded or encoded key transformations produce the same property key,\n * sequential parsing applies selected own properties in selection order, so\n * the later selected property overwrites the earlier value. Dynamic key\n * selection always examines own properties. Finite literal keys are declared\n * fields and may therefore be inherited. Output key order is not guaranteed.\n *\n * **Example** (Defining a string-keyed record of numbers)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const schema = Schema.Record(Schema.String, Schema.Number)\n *\n * // { readonly [x: string]: number }\n * type R = typeof schema.Type\n *\n * Schema.decodeUnknownSync(schema)({ a: 1, b: 2 }) // => { a: 1, b: 2 }\n * ```\n *\n * @category constructors\n * @since 3.10.0\n */\nexport function Record(key, value) {\n  return make(SchemaAST.record(key.ast, value.ast), {\n    key,\n    value\n  });\n}\n/**\n * Extends a struct schema with one or more record (index-signature) schemas,\n * producing a schema whose decoded type intersects the struct and all records.\n *\n * **Gotchas**\n *\n * TypeScript index signatures also apply to fixed keys. `StructWithRest` does\n * not reject incompatible fixed fields at the call site; use\n * `StructWithRest.ValidateRecords` when you want an explicit type-level\n * compatibility check.\n *\n * **Example** (Defining structs with string-indexed extra keys)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const schema = Schema.StructWithRest(\n *   Schema.Struct({ id: Schema.Number }),\n *   [Schema.Record(Schema.String, Schema.Number)]\n * )\n *\n * // { readonly id: number, readonly [x: string]: number }\n * type T = typeof schema.Type\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport function StructWithRest(schema, records) {\n  return make(SchemaAST.structWithRest(schema.ast, records.map(SchemaAST.getAST)), {\n    schema,\n    records\n  });\n}\nfunction makeTuple(ast, elements) {\n  return make(ast, {\n    elements,\n    mapElements(f, options) {\n      const elements = f(this.elements);\n      return makeTuple(SchemaAST.tuple(elements, options?.unsafePreserveChecks ? this.ast.checks : undefined), elements);\n    }\n  });\n}\n/**\n * Defines a fixed-length tuple schema from an array of element schemas.\n *\n * **Example** (Defining a pair of string and number)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const schema = Schema.Tuple([Schema.String, Schema.Number])\n *\n * Schema.decodeUnknownSync(schema)([\"hello\", 42]) // => [\"hello\", 42]\n * ```\n *\n * @category constructors\n * @since 3.10.0\n */\nexport function Tuple(elements) {\n  return makeTuple(SchemaAST.tuple(elements), elements);\n}\n/**\n * Extends a fixed-length tuple schema with a variadic rest segment.\n *\n * **Details**\n *\n * The resulting tuple starts with the fixed elements from `schema`. The first\n * schema in `rest` is the repeatable element schema, and any additional schemas\n * in `rest` are required trailing tuple elements after the variadic segment. For\n * example, `[Schema.Boolean, Schema.String]` represents zero or more booleans\n * followed by a final string.\n *\n * **Example** (Defining tuples with rest elements)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * // [string, number, ...boolean[]]\n * const schema = Schema.TupleWithRest(\n *   Schema.Tuple([Schema.String, Schema.Number]),\n *   [Schema.Boolean]\n * )\n *\n * Schema.decodeUnknownSync(schema)([\"hello\", 1, true, false]) // => [\"hello\", 1, true, false]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport function TupleWithRest(schema, rest) {\n  return make(SchemaAST.tupleWithRest(schema.ast, rest.map(SchemaAST.getAST)), {\n    schema,\n    rest\n  });\n}\n/**\n * @category constructors\n * @since 4.0.0\n */\nconst ArraySchema = /*#__PURE__*/Struct_.lambda(schema => make(new SchemaAST.Arrays(false, [], [schema.ast]), {\n  value: schema\n}));\nexport {\n/**\n * Defines a `ReadonlyArray` schema for a given element schema.\n *\n * **Example** (Defining an array of strings)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const schema = Schema.Array(Schema.String)\n *\n * Schema.decodeUnknownSync(schema)([\"a\", \"b\", \"c\"]) // => [\"a\", \"b\", \"c\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nArraySchema as Array };\n/** @internal */\nexport function withArrayLengthConstraints(self, minimum, maximum) {\n  if (minimum !== undefined && maximum !== undefined) {\n    return self.check(isLengthBetween(minimum, maximum));\n  }\n  if (minimum !== undefined) return self.check(isMinLength(minimum));\n  if (maximum !== undefined) return self.check(isMaxLength(maximum));\n  return self;\n}\n/**\n * Defines a non-empty `ReadonlyArray` schema — at least one element required.\n * Type is `readonly [T, ...T[]]`.\n *\n * **Example** (Defining a non-empty array of numbers)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const schema = Schema.NonEmptyArray(Schema.Number)\n *\n * Schema.decodeUnknownSync(schema)([1, 2, 3]) // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 3.10.0\n */\nexport const NonEmptyArray = /*#__PURE__*/Struct_.lambda(schema => make(new SchemaAST.Arrays(false, [schema.ast], [schema.ast]), {\n  value: schema\n}));\n/**\n * Creates a schema that accepts either a value decoded by `schema` or an array\n * decoded by `Schema.Array(schema)`, then returns an array.\n *\n * **When to use**\n *\n * Use to accept input that may be provided either as one item or as an array,\n * while normalizing decoded values to a readonly array.\n *\n * **Details**\n *\n * During encoding, one-element arrays are encoded as the single element. Empty\n * arrays and arrays with two or more elements are encoded as arrays.\n *\n * **Gotchas**\n *\n * The single-value branch is tried before the array branch. If `schema` itself\n * accepts arrays, an array input can be treated as one value and wrapped in a\n * one-element array.\n *\n * @see {@link Array} for accepting only array input\n * @see {@link NonEmptyArray} for requiring at least one decoded element\n *\n * @category constructors\n * @since 3.10.0\n */\nexport function ArrayEnsure(schema) {\n  const many = ArraySchema(schema);\n  const to = ArraySchema(toType(schema));\n  const one = decodeTo(Tuple([Unknown]), SchemaTransformation.transform({\n    decode: value => [value],\n    encode: ([value]) => value\n  }))(schema);\n  return make(Union([one, many]).pipe(decodeTo(to)).ast, {\n    from: Union([schema, many]),\n    to\n  });\n}\n/**\n * Returns a new array schema that ensures all elements are unique.\n *\n * **Details**\n *\n * The equivalence used to determine uniqueness is the one provided by\n * `Schema.toEquivalence(item)`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport function UniqueArray(item) {\n  return ArraySchema(item).check(isUnique());\n}\n/**\n * Makes an array or tuple schema mutable, removing the `readonly` modifier.\n *\n * **Gotchas**\n *\n * This combinator does not support an encoding attached to the array or tuple\n * node and throws if one is present. Encodings on element schemas are\n * supported.\n *\n * **Example** (Defining mutable arrays)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const schema = Schema.mutable(Schema.Array(Schema.Number))\n *\n * // number[]   (mutable)\n * type T = typeof schema.Type\n * const value: T = [1, 2]\n * value.push(3)\n * value // => [1, 2, 3]\n * ```\n *\n * @category transforming\n * @since 3.10.0\n */\nexport const mutable = /*#__PURE__*/Struct_.lambda(schema => make(SchemaAST.mutable(schema.ast), {\n  schema\n}));\nfunction makeUnion(ast, members) {\n  return make(ast, {\n    members,\n    mapMembers(f, options) {\n      const members = f(this.members);\n      return makeUnion(SchemaAST.union(members, this.ast.options, options?.unsafePreserveChecks ? this.ast.checks : undefined), members);\n    }\n  });\n}\n/**\n * Creates a union schema from an array of member schemas. Members are tested in\n * order; the first match is returned.\n *\n * **Details**\n *\n * Optionally, specify `mode`:\n * - `\"anyOf\"` (default) — matches if any member matches.\n * - `\"oneOf\"` — matches if exactly one member matches.\n *\n * **Example** (Defining a string or number union)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const schema = Schema.Union([Schema.String, Schema.Number])\n *\n * Schema.decodeUnknownSync(schema)(\"hello\") // => \"hello\"\n * Schema.decodeUnknownSync(schema)(42) // => 42\n * ```\n *\n * @category constructors\n * @since 3.10.0\n */\nexport function Union(members, options) {\n  return makeUnion(SchemaAST.union(members, options, undefined), members);\n}\n/**\n * Creates a union schema from an array of literal values.\n *\n * **Example** (Defining status codes)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const schema = Schema.Literals([\"active\", \"inactive\", \"pending\"])\n * Schema.decodeSync(schema)(\"active\") // => \"active\"\n * ```\n *\n * @see {@link Literal} for a schema that represents a single literal.\n * @category constructors\n * @since 4.0.0\n */\nexport function Literals(literals) {\n  const members = literals.map(Literal);\n  return make(SchemaAST.union(members, undefined, undefined), {\n    literals,\n    members,\n    mapMembers(f) {\n      return Union(f(this.members));\n    },\n    pick(literals) {\n      return Literals(literals);\n    },\n    transform(to) {\n      return Union(members.map((member, index) => member.transform(to[index])));\n    }\n  });\n}\n/**\n * Creates a union schema of `S | null`.\n *\n * @category constructors\n * @since 3.10.0\n */\nexport const NullOr = /*#__PURE__*/Struct_.lambda(self => Union([self, Null]));\n/**\n * Creates a union schema of `S | undefined`.\n *\n * @category constructors\n * @since 3.10.0\n */\nexport const UndefinedOr = /*#__PURE__*/Struct_.lambda(self => Union([self, Undefined]));\n/**\n * Creates a union schema of `S | null | undefined`.\n *\n * @category constructors\n * @since 3.10.0\n */\nexport const NullishOr = /*#__PURE__*/Struct_.lambda(self => Union([self, Null, Undefined]));\n/**\n * Creates a suspended schema that defers evaluation until needed. This is\n * essential for creating recursive schemas where a schema references itself,\n * preventing infinite recursion during schema definition.\n *\n * **Example** (Defining recursive tree schemas)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * interface Tree {\n *   readonly value: number\n *   readonly children: ReadonlyArray<Tree>\n * }\n *\n * const Tree = Schema.Struct({\n *   value: Schema.Number,\n *   children: Schema.Array(Schema.suspend((): Schema.Codec<Tree> => Tree))\n * })\n * Schema.decodeSync(Tree)({ value: 1, children: [] }) // => { value: 1, children: [] }\n * ```\n *\n * @category constructors\n * @since 3.10.0\n */\nexport function suspend(f) {\n  return make(new SchemaAST.Suspend(() => f().ast));\n}\n/**\n * Attaches one or more filter checks to a schema without changing the\n * TypeScript type.\n *\n * **Example** (Adding checks to a schema)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const AgeSchema = Schema.Finite.pipe(\n *   Schema.check(Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(120))\n * )\n * Schema.is(AgeSchema)(42) // => true\n * Schema.is(AgeSchema)(121) // => false\n * ```\n *\n * @category filtering\n * @since 4.0.0\n */\nexport function check(...checks) {\n  return self => self.check(...checks);\n}\n/**\n * Narrows the TypeScript type of a schema's output via a type guard predicate,\n * attaching the guard as a runtime filter check.\n *\n * **Details**\n *\n * The `annotations` parameter annotates the filter created by the refinement.\n * With the default formatter, failed refinements use `message` first,\n * `expected` second, and `<filter>` when neither is provided. `identifier`\n * names type-level failures before the refinement runs; it does not name the\n * failed refinement itself.\n *\n * @category filtering\n * @since 3.10.0\n */\nexport function refine(refinement, annotations) {\n  return schema => make(SchemaAST.appendChecks(schema.ast, [SchemaAST.makeFilterByGuard(refinement, annotations)]), {\n    schema\n  });\n}\n/**\n * Adds a nominal brand to a schema, intersecting the output type with\n * `Brand.Brand<B>` to prevent accidental mixing of structurally identical types.\n *\n * **When to use**\n *\n * Use to make values decoded by an existing schema nominally distinct when the\n * schema already carries the runtime validation you need.\n *\n * **Gotchas**\n *\n * `brand` adds brand metadata and narrows the TypeScript output type, but it\n * does not add runtime checks.\n *\n * @see {@link fromBrand} for applying a Brand constructor's checks along with the brand tag\n *\n * @category branding\n * @since 3.10.0\n */\nexport function brand(identifier) {\n  return schema => make(SchemaAST.brand(schema.ast, identifier), {\n    schema,\n    identifier\n  });\n}\n/**\n * Creates a branded schema from a {@link Brand.Constructor}, applying the\n * constructor's checks and brand tag to the underlying schema.\n *\n * @category branding\n * @since 3.10.0\n */\nexport function fromBrand(identifier, ctor) {\n  return self => {\n    return (ctor.checks ? self.check(...ctor.checks) : self).pipe(brand(identifier));\n  };\n}\n/**\n * Intercepts the decoding pipeline of a schema.\n *\n * **Details**\n *\n * The provided function receives the current decoding `Effect` and `ParseOptions`,\n * and returns a new `Effect` — potentially adding service requirements (`RD`),\n * recovering from errors, or augmenting the result.\n *\n * **Example** (Logging decode failures)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schema } from \"effect\"\n *\n * const events: Array<string> = []\n * const Logged = Schema.String.pipe(\n *   Schema.middlewareDecoding((effect) =>\n *     Effect.tapError(effect, () => Effect.sync(() => events.push(\"decode failed\")))\n *   )\n * )\n * Effect.runSync(Effect.result(Schema.decodeUnknownEffect(Logged)(42)))\n * events // => [\"decode failed\"]\n * ```\n *\n * @see {@link catchDecoding} for a simpler error-recovery variant\n * @category decoding\n * @since 4.0.0\n */\nexport function middlewareDecoding(decode) {\n  return schema => make(SchemaAST.middlewareDecoding(schema.ast, new SchemaTransformation.Middleware(decode, identity)), {\n    schema\n  });\n}\n/**\n * Intercepts the encoding pipeline of a schema.\n *\n * **Details**\n *\n * The provided function receives the current encoding `Effect` and `ParseOptions`,\n * and returns a new `Effect` — potentially adding service requirements (`RE`),\n * recovering from errors, or augmenting the result.\n *\n * **Example** (Logging encode failures)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schema } from \"effect\"\n *\n * const events: Array<string> = []\n * const Logged = Schema.String.pipe(\n *   Schema.middlewareEncoding((effect) =>\n *     Effect.tapError(effect, () => Effect.sync(() => events.push(\"encode failed\")))\n *   )\n * )\n * Effect.runSync(Effect.result(Schema.encodeUnknownEffect(Logged)(42)))\n * events // => [\"encode failed\"]\n * ```\n *\n * @see {@link catchEncoding} for a simpler error-recovery variant\n * @category encoding\n * @since 4.0.0\n */\nexport function middlewareEncoding(encode) {\n  return schema => make(SchemaAST.middlewareEncoding(schema.ast, new SchemaTransformation.Middleware(identity, encode)), {\n    schema\n  });\n}\n/**\n * Recovers from a decoding error by providing a fallback value.\n *\n * **Details**\n *\n * The handler receives the `Issue` and returns an `Effect` that either\n * succeeds with a fallback value or re-fails with a (possibly different) issue.\n *\n * **Example** (Returning a default on decode failure)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, Schema } from \"effect\"\n *\n * const schema = Schema.Number.pipe(\n *   Schema.catchDecoding((_issue) => Effect.succeed(Option.some(0)))\n * )\n * Effect.runSync(Schema.decodeUnknownEffect(schema)(\"invalid\")) // => 0\n * ```\n *\n * @see {@link catchDecodingWithContext} to add service requirements to the handler\n * @category error handling\n * @since 4.0.0\n */\nexport function catchDecoding(f) {\n  return catchDecodingWithContext(f);\n}\n/**\n * Recovers from a decoding error with a handler that may require Effect services.\n *\n * **When to use**\n *\n * Use when you need decoding fallback logic to require services from the Effect\n * context.\n *\n * **Details**\n *\n * The handler receives the `Issue` and returns an `Effect` that either succeeds\n * with a fallback value or re-fails with a (possibly different) issue. The\n * handler's services are added to the schema's decoding services.\n *\n * @see {@link catchDecoding} for recovery handlers that do not require services\n * @see {@link middlewareDecoding} for intercepting or replacing the full decoding pipeline\n *\n * @category error handling\n * @since 4.0.0\n */\nexport function catchDecodingWithContext(f) {\n  return self => middlewareDecoding(Effect.catchEager(f))(self);\n}\n/**\n * Recovers from an encoding error by providing a fallback value.\n *\n * **Details**\n *\n * The handler receives the `Issue` and returns an `Effect` that either\n * succeeds with a fallback value or re-fails with a (possibly different) issue.\n *\n * @see {@link catchEncodingWithContext} to add service requirements to the handler\n * @category error handling\n * @since 4.0.0\n */\nexport function catchEncoding(f) {\n  return catchEncodingWithContext(f);\n}\n/**\n * Recovers from an encoding error with a handler that may require Effect services.\n *\n * **When to use**\n *\n * Use when you need encoding fallback logic to require services from the Effect\n * context.\n *\n * **Details**\n *\n * The handler receives the `Issue` and returns an `Effect` that either succeeds\n * with a fallback encoded value or re-fails with a (possibly different) issue.\n * The handler's services are added to the schema's encoding services.\n *\n * @see {@link catchEncoding} for recovery handlers that do not require services\n * @see {@link middlewareEncoding} for intercepting or replacing the full encoding pipeline\n *\n * @category error handling\n * @since 4.0.0\n */\nexport function catchEncodingWithContext(f) {\n  return self => middlewareEncoding(Effect.catchEager(f))(self);\n}\nexport function decodeTo(to, transformation) {\n  return from => {\n    return make(SchemaAST.decodeTo(from.ast, to.ast, transformation ? SchemaTransformation.make(transformation) : SchemaTransformation.passthrough()), {\n      from,\n      to\n    });\n  };\n}\n/**\n * Constructs a decode-only `SchemaAST.Link`.\n *\n * @internal\n */\nexport function linkDecoding() {\n  return (to, decode) => link()(to, {\n    decode,\n    encode: SchemaGetter.forbiddenEncoding\n  });\n}\n/** @internal */\nexport const TrueLiterals = /*#__PURE__*/Literals([\"true\", \"yes\", \"on\", \"1\", \"y\"]);\n/** @internal */\nexport const FalseLiterals = /*#__PURE__*/Literals([\"false\", \"no\", \"off\", \"0\", \"n\"]);\n/** @internal */\nexport const BooleanLiterals = /*#__PURE__*/Literals([...TrueLiterals.literals, ...FalseLiterals.literals]).pipe(/*#__PURE__*/decodeTo(Boolean, /*#__PURE__*/SchemaTransformation.transform({\n  decode: value => value === \"true\" || value === \"yes\" || value === \"on\" || value === \"1\" || value === \"y\",\n  encode: value => value ? \"true\" : \"false\"\n})));\n/**\n * Applies a transformation to a schema, creating a new schema with the same type but transformed encoding/decoding.\n *\n * **When to use**\n *\n * Use when the decoded type stays the same and the transformation only\n * normalizes values during encoding and decoding.\n *\n * **Details**\n *\n * Call it with a transformation object and then pipe a schema into the returned\n * function. The resulting schema keeps the same `Type` and `Encoded` types as\n * the source schema, while applying the transformation during both decoding and\n * encoding.\n *\n * Internally this uses `toType(self)` as the target schema and combines service\n * requirements from the source schema and the transformation.\n *\n * **Gotchas**\n *\n * Use {@link decodeTo} instead when the transformation should change the\n * decoded type. For this helper, both transformation getters operate on\n * `S[\"Type\"]` values.\n *\n * **Example** (Trimming string values during encoding/decoding)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaGetter } from \"effect\"\n *\n * const Trimmed = Schema.String.pipe(\n *   Schema.decode({\n *     decode: SchemaGetter.transform((s) => s.trim()),\n *     encode: SchemaGetter.transform((s) => s.trim())\n *   })\n * )\n *\n * Schema.decodeUnknownSync(Trimmed)(\"  hello  \") // => \"hello\"\n * ```\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function decode(transformation) {\n  return self => {\n    return decodeTo(toType(self), transformation)(self);\n  };\n}\nexport function encodeTo(to, transformation) {\n  return from => {\n    return transformation ? decodeTo(from, transformation)(to) : decodeTo(from)(to);\n  };\n}\n/**\n * Applies a transformation to a schema's encoded type, creating a new schema where encoding/decoding\n * operate on `S[\"Encoded\"]` rather than `S[\"Type\"]`.\n *\n * **Details**\n *\n * The `decode` getter maps `S[\"Encoded\"]` → `S[\"Encoded\"]` (applied during decoding),\n * and the `encode` getter maps `S[\"Encoded\"]` → `S[\"Encoded\"]` (applied during encoding).\n *\n * **Example** (Upper-casing encoded strings)\n *\n * ```ts import.meta.vitest\n * import { Schema, SchemaGetter } from \"effect\"\n *\n * const UpperFromLower = Schema.String.pipe(\n *   Schema.encode({\n *     decode: SchemaGetter.transform((s: string) => s.toLowerCase()),\n *     encode: SchemaGetter.transform((s: string) => s.toUpperCase())\n *   })\n * )\n * Schema.encodeSync(UpperFromLower)(\"hello\") // => \"HELLO\"\n * ```\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function encode(transformation) {\n  return self => {\n    return decodeTo(self, transformation)(toEncoded(self));\n  };\n}\n/**\n * Attaches a constructor default value to a schema field.\n *\n * **Details**\n *\n * Constructor defaults are applied only during `make*`, not during decoding or\n * encoding. Failures are represented directly as `SchemaIssue.Issue` values.\n *\n * **Example** (Defining an optional field with a static default)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schema } from \"effect\"\n *\n * const MySchema = Schema.Struct({\n *   name: Schema.String.pipe(\n *     Schema.optionalKey,\n *     Schema.withConstructorDefault(Effect.succeed(\"anonymous\"))\n *   )\n * })\n *\n * MySchema.make({}).name // => \"anonymous\"\n * ```\n *\n * @category constructors\n * @since 3.10.0\n */\nexport function withConstructorDefault(\n// `S[\"~type.make.in\"]` instead of `S[\"Type\"]` is intentional here because\n// it makes easier to define the default value if there are nested defaults\ndefaultValue) {\n  return schema => make(SchemaAST.withConstructorDefault(schema.ast, defaultValue), {\n    schema\n  });\n}\nfunction toIssueEffect(self) {\n  return Effect.catchCause(self, cause => Effect.failCauseSync(() => Cause_.map(cause, error => error.issue)));\n}\n/**\n * Makes a struct key optional on the `Encoded` side and provides a default\n * `Encoded` value when the key is missing during decoding.\n *\n * **Details**\n *\n * The key uses `optionalKey` on the encoded side, so it may be absent from the\n * input object but **not** `undefined`. The default value is specified in terms\n * of the `Encoded` type (before any decoding transformations).\n *\n * Options:\n *\n * - `encodingStrategy`:\n *   - `\"passthrough\"` (default): include the value in the encoded output.\n *   - `\"omit\"`: omit the key from the encoded output.\n *\n * **Example** (Providing a default for a missing struct key)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schema } from \"effect\"\n *\n * const MySchema = Schema.Struct({\n *   name: Schema.String.pipe(Schema.withDecodingDefaultKey(Effect.succeed(\"anonymous\")))\n * })\n *\n * Schema.decodeUnknownSync(MySchema)({}).name // => \"anonymous\"\n * ```\n *\n * @see {@link withDecodingDefault} for the value-level variant (key absent **or** `undefined`)\n * @see {@link withDecodingDefaultTypeKey} for the variant where the default is a `Type` value\n * @category decoding\n * @since 4.0.0\n */\nexport function withDecodingDefaultKey(defaultValue, options) {\n  const encode = options?.encodingStrategy === \"omit\" ? SchemaGetter.omit() : SchemaGetter.passthrough();\n  return self => {\n    return optionalKey(toEncoded(self)).pipe(decodeTo(self, {\n      decode: SchemaGetter.withDefault(toIssueEffect(defaultValue)),\n      encode\n    }));\n  };\n}\n/**\n * Makes a struct key optional on the `Encoded` side (`optionalKey`, so the\n * key may be absent but **not** `undefined`) and provides a default `Type`\n * value when the key is missing during decoding.\n *\n * **Details**\n *\n * Unlike {@link withDecodingDefaultKey}, the default value is specified in\n * terms of the `Type` (decoded) representation, so it does not need to go\n * through the decoding transformation.\n *\n * Options:\n *\n * - `encodingStrategy`:\n *   - `\"passthrough\"` (default): include the value in the encoded output.\n *   - `\"omit\"`: omit the key from the encoded output.\n *\n * @see {@link withDecodingDefaultKey} for the variant where the default is an `Encoded` value\n * @see {@link withDecodingDefaultType} for the value-level variant\n * @category decoding\n * @since 4.0.0\n */\nexport function withDecodingDefaultTypeKey(defaultValue, options) {\n  return self => {\n    return toType(self).pipe(withDecodingDefaultKey(defaultValue, options), encodeTo(optionalKey(self)));\n  };\n}\n/**\n * Wraps the `Encoded` side with `optional` (key absent **or** `undefined`)\n * and provides a default `Encoded` value when the field is missing or\n * `undefined` during decoding.\n *\n * **When to use**\n *\n * Use when the default is expressed in the encoded representation, before the\n * field's decoding transformation runs.\n *\n * **Details**\n *\n * The default value is specified in terms of the `Encoded` type (before any\n * decoding transformations).\n *\n * Options:\n *\n * - `encodingStrategy`:\n *   - `\"passthrough\"` (default): include the value in the encoded output.\n *   - `\"omit\"`: omit the key from the encoded output.\n *\n * **Example** (Providing a default for an optional field value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schema } from \"effect\"\n *\n * const MySchema = Schema.Struct({\n *   name: Schema.String.pipe(Schema.optional, Schema.withDecodingDefault(Effect.succeed(\"anonymous\")))\n * })\n *\n * Schema.decodeUnknownSync(MySchema)({ name: undefined }).name // => \"anonymous\"\n * ```\n *\n * @see {@link withDecodingDefaultKey} for the key-level variant (key absent only, not `undefined`)\n * @see {@link withDecodingDefaultType} for the variant where the default is a `Type` value\n * @category decoding\n * @since 3.10.0\n */\nexport function withDecodingDefault(defaultValue, options) {\n  const encode = options?.encodingStrategy === \"omit\" ? SchemaGetter.omit() : SchemaGetter.passthrough();\n  return self => {\n    return optional(toEncoded(self)).pipe(decodeTo(self, {\n      decode: SchemaGetter.withDefault(toIssueEffect(defaultValue)),\n      encode\n    }));\n  };\n}\n/**\n * Wraps the `Encoded` side with `optional` (key absent **or** `undefined`)\n * and provides a default `Type` value when the field is missing or\n * `undefined` during decoding.\n *\n * **When to use**\n *\n * Use when the default is already in the decoded representation and should not\n * pass through the field's decoding transformation.\n *\n * **Details**\n *\n * Unlike {@link withDecodingDefault}, the default value is specified in terms\n * of the `Type` (decoded) representation, so it does not need to go through\n * the decoding transformation.\n *\n * Options:\n *\n * - `encodingStrategy`:\n *   - `\"passthrough\"` (default): include the value in the encoded output.\n *   - `\"omit\"`: omit the key from the encoded output.\n *\n * @see {@link withDecodingDefault} for the variant where the default is an `Encoded` value\n * @see {@link withDecodingDefaultTypeKey} for the key-level variant\n * @category decoding\n * @since 4.0.0\n */\nexport function withDecodingDefaultType(defaultValue, options) {\n  return self => {\n    return toType(self).pipe(withDecodingDefault(defaultValue, options), encodeTo(optional(self)));\n  };\n}\n/**\n * Combines a {@link Literal} schema with {@link withConstructorDefault}, making it ideal\n * for discriminator fields in tagged unions. When constructing via `make`, the\n * `_tag` field can be omitted and will be filled automatically.\n *\n * **Example** (Defining a discriminated union tag)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const A = Schema.Struct({ _tag: Schema.tag(\"A\"), value: Schema.Number })\n *\n * // _tag is optional in make, auto-filled to \"A\"\n * const a = A.make({ value: 42 })\n * a // => { _tag: \"A\", value: 42 }\n * ```\n *\n * @see {@link tagDefaultOmit} to also omit the tag during encoding\n * @see {@link TaggedStruct} for a shorthand that adds `_tag` automatically\n * @category constructors\n * @since 3.10.0\n */\nexport function tag(literal) {\n  return Literal(literal).pipe(withConstructorDefault(Effect.succeed(literal)));\n}\n/**\n * Creates a literal `_tag` schema that is omitted from encoded output.\n *\n * **When to use**\n *\n * Use to decode data that omits the discriminator field while still constructing\n * values with a `_tag` for tagged union matching.\n *\n * **Details**\n *\n * The tag is filled during decoding and construction, like {@link tag}, but is\n * omitted when encoding.\n *\n * **Example** (Omitting tags during encoding)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const A = Schema.Struct({\n *   _tag: Schema.tagDefaultOmit(\"A\"),\n *   value: Schema.Number\n * })\n *\n * // Encode strips the _tag field\n * Schema.encodeUnknownSync(A)({ _tag: \"A\", value: 1 }) // => { value: 1 }\n * ```\n *\n * @see {@link tag} for the variant that keeps the tag during encoding\n * @category constructors\n * @since 4.0.0\n */\nexport function tagDefaultOmit(literal) {\n  return tag(literal).pipe(withDecodingDefaultKey(Effect.succeed(literal), {\n    encodingStrategy: \"omit\"\n  }));\n}\n/**\n * Creates a struct schema with an automatically populated `_tag` field.\n *\n * **When to use**\n *\n * Use to define a tagged union case from a literal tag and a set of fields.\n *\n * **Details**\n *\n * When using the `make` method, the `_tag` field is optional and will be\n * added automatically. However, when decoding or encoding, the `_tag` field\n * must be present in the input.\n *\n * **Example** (Defining a tagged struct shorthand)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * // Defines a struct with a fixed `_tag` field\n * const tagged = Schema.TaggedStruct(\"A\", {\n *   a: Schema.String\n * })\n *\n * // This is the same as writing:\n * const equivalent = Schema.Struct({\n *   _tag: Schema.tag(\"A\"),\n *   a: Schema.String\n * })\n * void tagged\n * void equivalent\n * ```\n *\n * **Example** (Accessing the literal value of the tag)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const tagged = Schema.TaggedStruct(\"A\", {\n *   a: Schema.String\n * })\n *\n * tagged.fields._tag.schema.literal // => \"A\"\n * ```\n *\n * @category constructors\n * @since 3.10.0\n */\nexport function TaggedStruct(value, fields) {\n  return Struct({\n    _tag: tag(value),\n    ...fields\n  });\n}\n/**\n * Augments an existing {@link Union} of tagged structs with utility methods and an ordered tuple of discriminant\n * values.\n *\n * **Gotchas**\n *\n * Throws if multiple members use the same discriminant property key.\n *\n * **Example** (Adding tagged-union utilities to an existing union)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const A = Schema.TaggedStruct(\"A\", { value: Schema.Number })\n * const B = Schema.TaggedStruct(\"B\", { name: Schema.String })\n *\n * const MyUnion = Schema.Union([A, B]).pipe(Schema.toTaggedUnion(\"_tag\"))\n *\n * // Pattern-match on the union\n * const result = MyUnion.match({ _tag: \"A\", value: 1 }, {\n *   A: (a) => `number: ${a.value}`,\n *   B: (b) => `name: ${b.name}`\n * })\n * result // => \"number: 1\"\n * ```\n *\n * @see {@link TaggedUnion} for a shorthand that builds the union from scratch\n * @category combinators\n * @since 4.0.0\n */\nexport function toTaggedUnion(tag) {\n  return self => {\n    const cases = {};\n    const discriminants = [];\n    const discriminantKeys = new Set();\n    const guards = {};\n    const isAnyOf = keys => value => keys.includes(value[tag]);\n    walk(self);\n    return Object.assign(self, {\n      cases,\n      discriminants,\n      isAnyOf,\n      guards,\n      match,\n      matchOrElse\n    });\n    function walk(schema) {\n      const ast = schema.ast;\n      if (SchemaAST.isUnion(ast) && \"members\" in schema && globalThis.Array.isArray(schema.members) && schema.members.every(isSchema)) {\n        return schema.members.forEach(walk);\n      }\n      const sentinels = SchemaAST.collectSentinels(ast);\n      if (sentinels.length > 0) {\n        const literal = sentinels.find(s => s.key === tag)?.literal;\n        if (Predicate.isPropertyKey(literal)) {\n          const key = typeof literal === \"number\" ? globalThis.String(literal) : literal;\n          if (discriminantKeys.has(key)) {\n            throw new globalThis.Error(`Duplicate discriminant: ${globalThis.String(literal)}`);\n          }\n          discriminantKeys.add(key);\n          discriminants.push(literal);\n          InternalRecord.assignProperty(cases, literal, schema);\n          InternalRecord.assignProperty(guards, literal, SchemaParser.is(toType(schema)));\n          return;\n        }\n      }\n      throw new globalThis.Error(\"No literal or unique symbol found\");\n    }\n    function match() {\n      if (arguments.length === 1) {\n        const cases = arguments[0];\n        return function (value) {\n          const key = value[tag];\n          const handler = Object.hasOwn(cases, key) ? cases[key] : undefined;\n          return handler(value);\n        };\n      }\n      const value = arguments[0];\n      const cases = arguments[1];\n      const key = value[tag];\n      const handler = Object.hasOwn(cases, key) ? cases[key] : undefined;\n      return handler(value);\n    }\n    function matchOrElse() {\n      if (arguments.length === 2) {\n        const cases = arguments[0];\n        const orElse = arguments[1];\n        return function (value) {\n          const key = value[tag];\n          const handler = Object.hasOwn(cases, key) ? cases[key] ?? orElse : orElse;\n          return handler(value);\n        };\n      }\n      const value = arguments[0];\n      const cases = arguments[1];\n      const orElse = arguments[2];\n      const key = value[tag];\n      const handler = Object.hasOwn(cases, key) ? cases[key] ?? orElse : orElse;\n      return handler(value);\n    }\n  };\n}\n/**\n * Builds a discriminated union from a record of field sets, one per variant.\n * Each key becomes the `_tag` literal and the value is passed to {@link TaggedStruct}.\n * The result includes `cases`, `guards`, `isAnyOf`, `match`, and `matchOrElse` utilities.\n *\n * **Example** (Pattern matching a discriminated union)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const Shape = Schema.TaggedUnion({\n *   Circle: { radius: Schema.Number },\n *   Rectangle: { width: Schema.Number, height: Schema.Number }\n * })\n *\n * // Pattern-match on a decoded value\n * const area = Shape.match({ _tag: \"Circle\", radius: 5 }, {\n *   Circle: (c) => Math.PI * c.radius ** 2,\n *   Rectangle: (r) => r.width * r.height\n * })\n * Math.round(area * 100) / 100 // => 78.54\n * ```\n *\n * @see {@link toTaggedUnion} to augment an existing union instead\n * @category constructors\n * @since 4.0.0\n */\nexport function TaggedUnion(casesByTag) {\n  const cases = {};\n  const members = [];\n  for (const key of Object.keys(casesByTag)) {\n    const member = TaggedStruct(key, casesByTag[key]);\n    InternalRecord.assignProperty(cases, key, member);\n    members.push(member);\n  }\n  const union = Union(members);\n  const {\n    guards,\n    isAnyOf,\n    match,\n    matchOrElse\n  } = toTaggedUnion(\"_tag\")(union);\n  return make(union.ast, {\n    cases,\n    isAnyOf,\n    guards,\n    match,\n    matchOrElse\n  });\n}\n/**\n * Wraps a struct schema so that its decoded `Type` becomes a nominally distinct type `Self`.\n * Useful for creating opaque types that are structurally identical to a base struct\n * but type-incompatible with it.\n *\n * **Example** (Defining opaque structs)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * class Person extends Schema.Opaque<Person>()(\n *   Schema.Struct({\n *     name: Schema.String\n *   })\n * ) {}\n *\n * // Decoded value is Person, not { name: string }\n * const person = Schema.decodeUnknownSync(Person)({ name: \"Alice\" })\n * person.name // => \"Alice\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport function Opaque() {\n  return schema => schema;\n}\n/**\n * Creates a schema that validates values using `instanceof`.\n * Decoding and encoding pass the value through unchanged.\n *\n * **Example** (Defining a schema for a built-in class)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const DateSchema = Schema.instanceOf(Date)\n *\n * const decoded = Schema.decodeUnknownSync(DateSchema)(new Date(\"2024-01-01\"))\n * decoded.toISOString() // => \"2024-01-01T00:00:00.000Z\"\n * ```\n *\n * @category constructors\n * @since 3.10.0\n */\nexport function instanceOf(constructor, annotations) {\n  return declare(u => u instanceof constructor, annotations);\n}\n/**\n * Constructs an `SchemaAST.Link` that describes how a value of type `T` encodes to and decodes from a `To` schema.\n * Used when building low-level AST transformations that bridge two schema types.\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function link() {\n  return (encodeTo, transformation) => {\n    return new SchemaAST.Link(encodeTo.ast, SchemaTransformation.make(transformation));\n  };\n}\n/**\n * Creates a custom validation filter from a predicate function.\n *\n * **Details**\n *\n * The predicate receives the decoded input value, the schema AST, and parse\n * options, and returns a `FilterOutput`. Non-success outputs are normalized into\n * schema issues. The `annotations` parameter annotates the filter itself; with\n * the default formatter, failures use `message` first, `expected` second, and\n * `<filter>` when neither is provided.\n *\n * When `abort` is `true`, parsing stops after this filter fails instead of\n * collecting later check failures.\n *\n * **Example** (Reporting failure at a nested path)\n *\n * ```ts import.meta.vitest\n * import { Result, Schema } from \"effect\"\n *\n * const schema = Schema.Struct({ password: Schema.String, confirmPassword: Schema.String }).check(\n *   Schema.makeFilter((o) =>\n *     o.password === o.confirmPassword\n *       ? undefined\n *       : { path: [\"password\"], issue: \"password and confirmPassword must match\" }\n *   )\n * )\n *\n * const result = Schema.decodeUnknownResult(schema)({ password: \"123456\", confirmPassword: \"1234567\" })\n * if (Result.isFailure(result) && result.failure.issue._tag === \"Filter\" && result.failure.issue.issue._tag === \"Pointer\") {\n *   result.failure.issue.issue.path // => [\"password\"]\n * }\n * ```\n *\n * **Example** (Reporting multiple failures at once)\n *\n * ```ts import.meta.vitest\n * import { Result, Schema } from \"effect\"\n *\n * const schema = Schema.Struct({ a: Schema.Finite, b: Schema.Finite, c: Schema.Finite }).check(\n *   Schema.makeFilter((o) => {\n *     const issues: Array<Schema.FilterIssue> = []\n *     if (o.a > 0) {\n *       if (o.b <= 0) issues.push({ path: [\"b\"], issue: \"b must be greater than 0\" })\n *       if (o.c <= 0) issues.push({ path: [\"c\"], issue: \"c must be greater than 0\" })\n *     }\n *     return issues\n *   })\n * )\n *\n * const result = Schema.decodeUnknownResult(schema)({ a: 1, b: 0, c: 0 })\n * if (Result.isFailure(result) && result.failure.issue._tag === \"Filter\" && result.failure.issue.issue._tag === \"Composite\") {\n *   result.failure.issue.issue.issues.map((issue) => issue._tag === \"Pointer\" ? issue.path : []) // => [[\"b\"], [\"c\"]]\n * }\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeFilter = SchemaAST.makeFilter;\n/**\n * Groups multiple checks into a single {@link SchemaAST.FilterGroup}, applying\n * optional shared annotations to the group as a whole.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport function makeFilterGroup(checks, annotations = undefined) {\n  return new SchemaAST.FilterGroup(checks, annotations);\n}\nconst TRIMMED_PATTERN = \"^\\\\S[\\\\s\\\\S]*\\\\S$|^\\\\S$|^$\";\n/**\n * Validates that a string has no leading or trailing whitespace.\n *\n * **Details**\n *\n * JSON Schema:\n *\n * This check corresponds to a `pattern` constraint in JSON Schema that\n * matches strings without leading or trailing whitespace.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies a `patterns`\n * constraint to ensure generated strings match the trimmed pattern.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isTrimmed(annotations) {\n  const regExp = new globalThis.RegExp(TRIMMED_PATTERN);\n  return makeFilter(s => s.trim() === s, {\n    expected: \"a string with no leading or trailing whitespace\",\n    representation: {\n      id: \"effect/schema/isTrimmed\",\n      payload: null\n    },\n    toJsonSchema: () => ({\n      pattern: regExp.source\n    }),\n    toCode: () => ({\n      runtime: \"Schema.isTrimmed()\"\n    }),\n    arbitraryConstraint: {\n      patterns: [{\n        source: TRIMMED_PATTERN,\n        flags: \"\"\n      }]\n    },\n    ...annotations\n  });\n}\n/**\n * Validates that a string matches the specified regular expression pattern.\n *\n * **Details**\n *\n * JSON Schema:\n *\n * JSON Schema receives the RegExp source as a `pattern`. JavaScript flags are\n * not represented, so validation can differ when the RegExp uses flags or\n * relies on JavaScript's non-Unicode behavior.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies a `patterns`\n * constraint to ensure generated strings match the specified RegExp pattern.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isPattern(regExp, annotations) {\n  const source = regExp.source;\n  const flags = regExp.flags;\n  const runtimeRegExp = flags === \"\" ? `new RegExp(${format(source)})` : `new RegExp(${format(source)}, ${format(flags)})`;\n  return SchemaAST.isPattern(regExp, {\n    toCode: () => ({\n      runtime: `Schema.isPattern(${runtimeRegExp})`\n    }),\n    ...annotations\n  });\n}\n/**\n * Validates that a string represents a finite number.\n *\n * **Details**\n *\n * JSON Schema:\n *\n * This check corresponds to a `pattern` constraint in JSON Schema that matches\n * strings representing finite numbers.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies a `patterns`\n * constraint to ensure generated strings match the number string pattern.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isStringFinite(annotations) {\n  return SchemaAST.isStringFinite({\n    toCode: () => ({\n      runtime: \"Schema.isStringFinite()\"\n    }),\n    ...annotations\n  });\n}\n/**\n * Validates that a string is a signed base-10 integer literal for Effect's\n * BigInt string encoding.\n *\n * **Details**\n *\n * The check uses the pattern `^-?\\d+$`. It does not accept leading `+`, decimal\n * points, exponent notation, separators, or non-decimal inputs such as\n * hexadecimal strings.\n *\n * JSON Schema:\n * This check corresponds to a `pattern` constraint with the same signed\n * base-10 integer pattern.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isStringBigInt(annotations) {\n  return SchemaAST.isStringBigInt({\n    toCode: () => ({\n      runtime: \"Schema.isStringBigInt()\"\n    }),\n    ...annotations\n  });\n}\n/**\n * Validates that a string has the `Symbol(description)` format used by Effect's\n * symbol string encoding.\n *\n * **Details**\n *\n * The check uses the pattern `^Symbol\\((.*)\\)$`. It is not a general test for\n * whether a string can be passed to JavaScript's `Symbol()` function.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isStringSymbol(annotations) {\n  return SchemaAST.isStringSymbol({\n    toCode: () => ({\n      runtime: \"Schema.isStringSymbol()\"\n    }),\n    ...annotations\n  });\n}\nconst getUUIDRegExp = version => {\n  if (version) {\n    return new globalThis.RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);\n  }\n  return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|[fF]{8}-[fF]{4}-[fF]{4}-[fF]{4}-[fF]{12})$/;\n};\n/**\n * Validates that a string is a strict Universally Unique Identifier (UUID).\n *\n * **When to use**\n *\n * Use when you need UUID semantics, including version and RFC variant bits,\n * rather than only the dashed hexadecimal shape.\n *\n * **Details**\n *\n * Without a version argument, this accepts UUID versions 1 through 8, the nil\n * UUID (`00000000-0000-0000-0000-000000000000`), and the max UUID\n * (`ffffffff-ffff-ffff-ffff-ffffffffffff`). With a version argument, this\n * accepts only UUIDs with that version and RFC variant bits; nil and max UUIDs\n * are not versioned UUIDs and do not match version-specific checks.\n *\n * JSON Schema:\n *\n * This check corresponds to a `pattern` constraint in JSON Schema that matches\n * UUID format, and includes a `format: \"uuid\"` annotation.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies a `patterns`\n * constraint to ensure generated strings match the UUID pattern.\n *\n * @see {@link isGUID} for shape-only GUID validation.\n * @category validation\n * @since 4.0.0\n */\nexport function isUUID(version, annotations) {\n  const regExp = getUUIDRegExp(version);\n  return isPattern(regExp, {\n    expected: version ? `a UUID v${version}` : \"a UUID\",\n    representation: {\n      id: \"effect/schema/isUUID\",\n      payload: {\n        version: version ?? null\n      }\n    },\n    toJsonSchema: () => ({\n      pattern: regExp.source,\n      format: \"uuid\"\n    }),\n    toCode: () => ({\n      runtime: version === undefined ? \"Schema.isUUID()\" : `Schema.isUUID(${version})`\n    }),\n    ...annotations\n  });\n}\nconst GUID_REGEXP = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;\n/**\n * Validates that a string has the GUID / UUID textual shape.\n *\n * **When to use**\n *\n * Use when you need to accept dashed hexadecimal identifiers without enforcing\n * UUID version or variant bits.\n *\n * **Details**\n *\n * This check accepts strings in the `8-4-4-4-12` hexadecimal form. JSON Schema\n * output includes the corresponding `pattern` constraint and intentionally does\n * not include `format: \"uuid\"` because GUID validation is looser than UUID\n * validation.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies a `patterns`\n * constraint to ensure generated strings match the GUID pattern.\n *\n * @see {@link isUUID} for strict UUID validation.\n * @category validation\n * @since 4.0.0\n */\nexport function isGUID(annotations) {\n  return isPattern(GUID_REGEXP, {\n    expected: \"a GUID\",\n    representation: {\n      id: \"effect/schema/isGUID\",\n      payload: null\n    },\n    toJsonSchema: () => ({\n      pattern: GUID_REGEXP.source\n    }),\n    toCode: () => ({\n      runtime: \"Schema.isGUID()\"\n    }),\n    ...annotations\n  });\n}\n/**\n * Validates that a string is a valid ULID (Universally Unique Lexicographically\n * Sortable Identifier).\n *\n * **Details**\n *\n * JSON Schema:\n *\n * This check corresponds to a `pattern` constraint in JSON Schema that matches\n * the ULID format.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies a `patterns`\n * constraint to ensure generated strings match the ULID pattern.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isULID(annotations) {\n  const regExp = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;\n  return isPattern(regExp, {\n    representation: {\n      id: \"effect/schema/isULID\",\n      payload: null\n    },\n    toJsonSchema: () => ({\n      pattern: regExp.source\n    }),\n    toCode: () => ({\n      runtime: \"Schema.isULID()\"\n    }),\n    ...annotations\n  });\n}\n/**\n * Validates that a string is valid Base64 encoded data.\n *\n * **Details**\n *\n * JSON Schema:\n *\n * This check corresponds to a `pattern` constraint in JSON Schema that matches\n * Base64 format.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies a `patterns`\n * constraint to ensure generated strings match the Base64 pattern.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isBase64(annotations) {\n  const regExp = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n  return isPattern(regExp, {\n    expected: \"a base64 encoded string\",\n    representation: {\n      id: \"effect/schema/isBase64\",\n      payload: null\n    },\n    toJsonSchema: () => ({\n      pattern: regExp.source\n    }),\n    toCode: () => ({\n      runtime: \"Schema.isBase64()\"\n    }),\n    ...annotations\n  });\n}\n/**\n * Validates that a string is valid Base64URL encoded data (Base64 with URL-safe\n * characters).\n *\n * **Details**\n *\n * JSON Schema:\n *\n * This check corresponds to a `pattern` constraint in JSON Schema that matches\n * Base64URL format.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies a `patterns`\n * constraint to ensure generated strings match the Base64URL pattern.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isBase64Url(annotations) {\n  const regExp = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;\n  return isPattern(regExp, {\n    expected: \"a base64url encoded string\",\n    representation: {\n      id: \"effect/schema/isBase64Url\",\n      payload: null\n    },\n    toJsonSchema: () => ({\n      pattern: regExp.source\n    }),\n    toCode: () => ({\n      runtime: \"Schema.isBase64Url()\"\n    }),\n    ...annotations\n  });\n}\n/**\n * Validates at runtime that a string starts with the specified literal prefix.\n *\n * **Details**\n *\n * RegExp metacharacters in the prefix are escaped in JSON Schema and arbitrary\n * metadata so that the generated patterns retain literal `startsWith` semantics.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isStartsWith(startsWith, annotations) {\n  const formatted = JSON.stringify(startsWith);\n  const regExp = new globalThis.RegExp(`^${RegExp_.escape(startsWith)}`);\n  return makeFilter(s => s.startsWith(startsWith), {\n    expected: `a string starting with ${formatted}`,\n    representation: {\n      id: \"effect/schema/isStartsWith\",\n      payload: {\n        startsWith\n      }\n    },\n    toJsonSchema: () => ({\n      pattern: regExp.source\n    }),\n    toCode: () => ({\n      runtime: `Schema.isStartsWith(${format(startsWith)})`\n    }),\n    arbitraryConstraint: {\n      patterns: [{\n        source: regExp.source,\n        flags: regExp.flags\n      }]\n    },\n    ...annotations\n  });\n}\n/**\n * Validates at runtime that a string ends with the specified literal suffix.\n *\n * **Details**\n *\n * RegExp metacharacters in the suffix are escaped in JSON Schema and arbitrary\n * metadata so that the generated patterns retain literal `endsWith` semantics.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isEndsWith(endsWith, annotations) {\n  const formatted = JSON.stringify(endsWith);\n  const regExp = new globalThis.RegExp(`${RegExp_.escape(endsWith)}$`);\n  return makeFilter(s => s.endsWith(endsWith), {\n    expected: `a string ending with ${formatted}`,\n    representation: {\n      id: \"effect/schema/isEndsWith\",\n      payload: {\n        endsWith\n      }\n    },\n    toJsonSchema: () => ({\n      pattern: regExp.source\n    }),\n    toCode: () => ({\n      runtime: `Schema.isEndsWith(${format(endsWith)})`\n    }),\n    arbitraryConstraint: {\n      patterns: [{\n        source: regExp.source,\n        flags: regExp.flags\n      }]\n    },\n    ...annotations\n  });\n}\n/**\n * Validates at runtime that a string contains the specified literal substring.\n *\n * **Details**\n *\n * RegExp metacharacters in the substring are escaped in JSON Schema and\n * arbitrary metadata so that the generated patterns retain literal `includes`\n * semantics.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isIncludes(includes, annotations) {\n  const formatted = JSON.stringify(includes);\n  const regExp = new globalThis.RegExp(RegExp_.escape(includes));\n  return makeFilter(s => s.includes(includes), {\n    expected: `a string including ${formatted}`,\n    representation: {\n      id: \"effect/schema/isIncludes\",\n      payload: {\n        includes\n      }\n    },\n    toJsonSchema: () => ({\n      pattern: regExp.source\n    }),\n    toCode: () => ({\n      runtime: `Schema.isIncludes(${format(includes)})`\n    }),\n    arbitraryConstraint: {\n      patterns: [{\n        source: regExp.source,\n        flags: regExp.flags\n      }]\n    },\n    ...annotations\n  });\n}\nconst UPPERCASED_PATTERN = \"^[^a-z]*$\";\n/**\n * Validates that a string is unchanged by JavaScript's `toUpperCase()`.\n *\n * **Details**\n *\n * This accepts empty strings and characters that do not have lowercase forms,\n * such as digits, punctuation, and whitespace. It rejects strings that would\n * change when uppercased.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isUppercased(annotations) {\n  const regExp = new globalThis.RegExp(UPPERCASED_PATTERN);\n  return makeFilter(s => s.toUpperCase() === s, {\n    expected: \"a string with all characters in uppercase\",\n    representation: {\n      id: \"effect/schema/isUppercased\",\n      payload: null\n    },\n    toJsonSchema: () => ({\n      pattern: regExp.source\n    }),\n    toCode: () => ({\n      runtime: \"Schema.isUppercased()\"\n    }),\n    arbitraryConstraint: {\n      patterns: [{\n        source: UPPERCASED_PATTERN,\n        flags: \"\"\n      }]\n    },\n    ...annotations\n  });\n}\nconst LOWERCASED_PATTERN = \"^[^A-Z]*$\";\n/**\n * Validates that a string is unchanged by JavaScript's `toLowerCase()`.\n *\n * **Details**\n *\n * This accepts empty strings and characters that do not have uppercase forms,\n * such as digits, punctuation, and whitespace. It rejects strings that would\n * change when lowercased.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isLowercased(annotations) {\n  const regExp = new globalThis.RegExp(LOWERCASED_PATTERN);\n  return makeFilter(s => s.toLowerCase() === s, {\n    expected: \"a string with all characters in lowercase\",\n    representation: {\n      id: \"effect/schema/isLowercased\",\n      payload: null\n    },\n    toJsonSchema: () => ({\n      pattern: regExp.source\n    }),\n    toCode: () => ({\n      runtime: \"Schema.isLowercased()\"\n    }),\n    arbitraryConstraint: {\n      patterns: [{\n        source: LOWERCASED_PATTERN,\n        flags: \"\"\n      }]\n    },\n    ...annotations\n  });\n}\nconst CAPITALIZED_PATTERN = \"^(?:[^a-z][\\\\s\\\\S]*)?$\";\n/**\n * Validates that the first character of a string is unchanged by\n * `toUpperCase()`.\n *\n * **Details**\n *\n * Empty strings pass. Strings whose first character has no lowercase form, such\n * as a digit, punctuation mark, or whitespace, also pass.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isCapitalized(annotations) {\n  const regExp = new globalThis.RegExp(CAPITALIZED_PATTERN);\n  return makeFilter(s => s.charAt(0).toUpperCase() === s.charAt(0), {\n    expected: \"a string with the first character in uppercase\",\n    representation: {\n      id: \"effect/schema/isCapitalized\",\n      payload: null\n    },\n    toJsonSchema: () => ({\n      pattern: regExp.source\n    }),\n    toCode: () => ({\n      runtime: \"Schema.isCapitalized()\"\n    }),\n    arbitraryConstraint: {\n      patterns: [{\n        source: CAPITALIZED_PATTERN,\n        flags: \"\"\n      }]\n    },\n    ...annotations\n  });\n}\nconst UNCAPITALIZED_PATTERN = \"^(?:[^A-Z][\\\\s\\\\S]*)?$\";\n/**\n * Validates that the first character of a string is unchanged by\n * `toLowerCase()`.\n *\n * **Details**\n *\n * Empty strings pass. Strings whose first character has no uppercase form, such\n * as a digit, punctuation mark, or whitespace, also pass.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isUncapitalized(annotations) {\n  const regExp = new globalThis.RegExp(UNCAPITALIZED_PATTERN);\n  return makeFilter(s => s.charAt(0).toLowerCase() === s.charAt(0), {\n    expected: \"a string with the first character in lowercase\",\n    representation: {\n      id: \"effect/schema/isUncapitalized\",\n      payload: null\n    },\n    toJsonSchema: () => ({\n      pattern: regExp.source\n    }),\n    toCode: () => ({\n      runtime: \"Schema.isUncapitalized()\"\n    }),\n    arbitraryConstraint: {\n      patterns: [{\n        source: UNCAPITALIZED_PATTERN,\n        flags: \"\"\n      }]\n    },\n    ...annotations\n  });\n}\n/**\n * Schema for finite numbers, rejecting `NaN`, `Infinity`, and `-Infinity`.\n *\n * @category schemas\n * @since 3.10.0\n */\nexport const Finite = /*#__PURE__*/make(SchemaAST.finite);\n/**\n * Validates that a number is finite (not `Infinity`, `-Infinity`, or `NaN`).\n *\n * **Details**\n *\n * JSON Schema:\n *\n * This check does not have a direct JSON Schema equivalent, but ensures the\n * number is valid and finite.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies a finite-number constraint.\n *\n * @category validation\n * @since 4.0.0\n */\nexport const isFinite = SchemaAST.isFinite;\n/**\n * Creates a greater-than (`>`) check for any ordered type from an\n * `Order.Order` instance.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function makeIsGreaterThan(options) {\n  const gt = Order.isGreaterThan(options.order);\n  const formatter = options.formatter ?? format;\n  return (exclusiveMinimum, annotations) => {\n    return makeFilter(input => gt(input, exclusiveMinimum), {\n      expected: `a value greater than ${formatter(exclusiveMinimum)}`,\n      arbitraryConstraint: {\n        order: options.order,\n        minimum: exclusiveMinimum,\n        exclusiveMinimum: true\n      },\n      ...options.annotate?.(exclusiveMinimum),\n      ...annotations\n    });\n  };\n}\n/**\n * Creates a greater-than-or-equal-to (`>=`) check for any ordered type from an\n * `Order.Order` instance.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function makeIsGreaterThanOrEqualTo(options) {\n  const gte = Order.isGreaterThanOrEqualTo(options.order);\n  const formatter = options.formatter ?? format;\n  return (minimum, annotations) => {\n    return makeFilter(input => gte(input, minimum), {\n      expected: `a value greater than or equal to ${formatter(minimum)}`,\n      arbitraryConstraint: {\n        order: options.order,\n        minimum\n      },\n      ...options.annotate?.(minimum),\n      ...annotations\n    });\n  };\n}\n/**\n * Creates a less-than (`<`) check for any ordered type from an `Order.Order`\n * instance.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function makeIsLessThan(options) {\n  const lt = Order.isLessThan(options.order);\n  const formatter = options.formatter ?? format;\n  return (exclusiveMaximum, annotations) => {\n    return makeFilter(input => lt(input, exclusiveMaximum), {\n      expected: `a value less than ${formatter(exclusiveMaximum)}`,\n      arbitraryConstraint: {\n        order: options.order,\n        maximum: exclusiveMaximum,\n        exclusiveMaximum: true\n      },\n      ...options.annotate?.(exclusiveMaximum),\n      ...annotations\n    });\n  };\n}\n/**\n * Creates a less-than-or-equal-to (`<=`) check for any ordered type from an\n * `Order.Order` instance.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function makeIsLessThanOrEqualTo(options) {\n  const lte = Order.isLessThanOrEqualTo(options.order);\n  const formatter = options.formatter ?? format;\n  return (maximum, annotations) => {\n    return makeFilter(input => lte(input, maximum), {\n      expected: `a value less than or equal to ${formatter(maximum)}`,\n      arbitraryConstraint: {\n        order: options.order,\n        maximum\n      },\n      ...options.annotate?.(maximum),\n      ...annotations\n    });\n  };\n}\n/**\n * Creates an inclusive or exclusive range check for any ordered type from an\n * `Order.Order` instance.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function makeIsBetween(deriveOptions) {\n  const greaterThanOrEqualTo = Order.isGreaterThanOrEqualTo(deriveOptions.order);\n  const greaterThan = Order.isGreaterThan(deriveOptions.order);\n  const lessThanOrEqualTo = Order.isLessThanOrEqualTo(deriveOptions.order);\n  const lessThan = Order.isLessThan(deriveOptions.order);\n  const formatter = deriveOptions.formatter ?? format;\n  return (options, annotations) => {\n    const gte = options.exclusiveMinimum ? greaterThan : greaterThanOrEqualTo;\n    const lte = options.exclusiveMaximum ? lessThan : lessThanOrEqualTo;\n    return makeFilter(input => gte(input, options.minimum) && lte(input, options.maximum), {\n      expected: `a value between ${formatter(options.minimum)}${options.exclusiveMinimum ? \" (excluded)\" : \"\"} and ${formatter(options.maximum)}${options.exclusiveMaximum ? \" (excluded)\" : \"\"}`,\n      arbitraryConstraint: {\n        order: deriveOptions.order,\n        minimum: options.minimum,\n        maximum: options.maximum,\n        ...(options.exclusiveMinimum && {\n          exclusiveMinimum: true\n        }),\n        ...(options.exclusiveMaximum && {\n          exclusiveMaximum: true\n        })\n      },\n      ...deriveOptions.annotate?.(options),\n      ...annotations\n    });\n  };\n}\n/**\n * Creates a divisibility check for any numeric type from a remainder function\n * and a zero value.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function makeIsMultipleOf(options) {\n  return (divisor, annotations) => {\n    const formatter = options.formatter ?? format;\n    return makeFilter(input => options.remainder(input, divisor) === options.zero, {\n      expected: `a value that is a multiple of ${formatter(divisor)}`,\n      ...options.annotate?.(divisor),\n      ...annotations\n    });\n  };\n}\nfunction encodeNumberPayload(number) {\n  if (!globalThis.Number.isFinite(number)) {\n    throw new globalThis.RangeError(`Expected a finite number, got ${format(number)}`);\n  }\n  return number;\n}\n/**\n * Validates that a number is greater than the specified value (exclusive).\n *\n * **Details**\n *\n * JSON Schema:\n *\n * This check corresponds to the `exclusiveMinimum` constraint in JSON Schema.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies an\n * `exclusiveMinimum` constraint to ensure generated numbers are greater than\n * the specified value.\n *\n * @category validation\n * @since 4.0.0\n */\nexport const isGreaterThan = /*#__PURE__*/makeIsGreaterThan({\n  order: Order.Number,\n  annotate: exclusiveMinimum => ({\n    representation: {\n      id: \"effect/schema/isGreaterThan\",\n      payload: {\n        exclusiveMinimum: encodeNumberPayload(exclusiveMinimum)\n      }\n    },\n    toJsonSchema: () => ({\n      exclusiveMinimum\n    }),\n    toCode: () => ({\n      runtime: `Schema.isGreaterThan(${format(exclusiveMinimum)})`\n    })\n  })\n});\n/**\n * Validates that a number is greater than or equal to the specified value\n * (inclusive).\n *\n * **Details**\n *\n * JSON Schema:\n *\n * This check corresponds to the `minimum` constraint in JSON Schema.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies a `minimum` constraint\n * to ensure generated numbers are greater than or equal to the specified value.\n *\n * @category validation\n * @since 4.0.0\n */\nexport const isGreaterThanOrEqualTo = /*#__PURE__*/makeIsGreaterThanOrEqualTo({\n  order: Order.Number,\n  annotate: minimum => ({\n    representation: {\n      id: \"effect/schema/isGreaterThanOrEqualTo\",\n      payload: {\n        minimum: encodeNumberPayload(minimum)\n      }\n    },\n    toJsonSchema: () => ({\n      minimum\n    }),\n    toCode: () => ({\n      runtime: `Schema.isGreaterThanOrEqualTo(${format(minimum)})`\n    })\n  })\n});\n/**\n * Validates that a number is less than the specified value (exclusive).\n *\n * **Details**\n *\n * JSON Schema:\n *\n * This check corresponds to the `exclusiveMaximum` constraint in JSON Schema.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies an\n * `exclusiveMaximum` constraint to ensure generated numbers are less than the\n * specified value.\n *\n * @category validation\n * @since 4.0.0\n */\nexport const isLessThan = /*#__PURE__*/makeIsLessThan({\n  order: Order.Number,\n  annotate: exclusiveMaximum => ({\n    representation: {\n      id: \"effect/schema/isLessThan\",\n      payload: {\n        exclusiveMaximum: encodeNumberPayload(exclusiveMaximum)\n      }\n    },\n    toJsonSchema: () => ({\n      exclusiveMaximum\n    }),\n    toCode: () => ({\n      runtime: `Schema.isLessThan(${format(exclusiveMaximum)})`\n    })\n  })\n});\n/**\n * Validates that a number is less than or equal to the specified value\n * (inclusive).\n *\n * **Details**\n *\n * JSON Schema:\n *\n * This check corresponds to the `maximum` constraint in JSON Schema.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies a `maximum` constraint\n * to ensure generated numbers are less than or equal to the specified value.\n *\n * @category validation\n * @since 4.0.0\n */\nexport const isLessThanOrEqualTo = /*#__PURE__*/makeIsLessThanOrEqualTo({\n  order: Order.Number,\n  annotate: maximum => ({\n    representation: {\n      id: \"effect/schema/isLessThanOrEqualTo\",\n      payload: {\n        maximum: encodeNumberPayload(maximum)\n      }\n    },\n    toJsonSchema: () => ({\n      maximum\n    }),\n    toCode: () => ({\n      runtime: `Schema.isLessThanOrEqualTo(${format(maximum)})`\n    })\n  })\n});\n/**\n * Validates that a number is within a specified range. The range boundaries can\n * be inclusive or exclusive based on the provided options.\n *\n * **Details**\n *\n * JSON Schema:\n *\n * This check corresponds to `minimum`/`maximum` or `exclusiveMinimum`/`exclusiveMaximum`\n * constraints in JSON Schema, depending on the options provided.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies `minimum` and\n * `maximum` constraints with optional `exclusiveMinimum` and\n * `exclusiveMaximum` flags to ensure generated numbers fall within the\n * specified range.\n *\n * @category validation\n * @since 4.0.0\n */\nexport const isBetween = /*#__PURE__*/makeIsBetween({\n  order: Order.Number,\n  annotate: options => {\n    const exclusiveMinimum = options.exclusiveMinimum ? true : undefined;\n    const exclusiveMaximum = options.exclusiveMaximum ? true : undefined;\n    const payload = {\n      minimum: encodeNumberPayload(options.minimum),\n      maximum: encodeNumberPayload(options.maximum),\n      ...(exclusiveMinimum && {\n        exclusiveMinimum\n      }),\n      ...(exclusiveMaximum && {\n        exclusiveMaximum\n      })\n    };\n    return {\n      representation: {\n        id: \"effect/schema/isBetween\",\n        payload\n      },\n      toJsonSchema: () => ({\n        [exclusiveMinimum ? \"exclusiveMinimum\" : \"minimum\"]: options.minimum,\n        [exclusiveMaximum ? \"exclusiveMaximum\" : \"maximum\"]: options.maximum\n      }),\n      toCode: () => ({\n        runtime: `Schema.isBetween({ minimum: ${format(options.minimum)}, maximum: ${format(options.maximum)}, exclusiveMinimum: ${format(exclusiveMinimum)}, exclusiveMaximum: ${format(exclusiveMaximum)} })`\n      })\n    };\n  }\n});\n/**\n * Validates that a number is a multiple of the specified divisor.\n *\n * **Details**\n *\n * JSON Schema:\n *\n * This check corresponds to the `multipleOf` constraint in JSON Schema.\n * Negative divisors are normalized to their absolute value because JSON\n * Schema requires `multipleOf` to be positive.\n *\n * **Gotchas**\n *\n * Throws a `RangeError` when `divisor` is zero or is not finite.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isMultipleOf(divisor, annotations) {\n  if (!globalThis.Number.isFinite(divisor) || divisor === 0) {\n    throw new globalThis.RangeError(`Expected a finite non-zero number, got ${globalThis.String(divisor)}`);\n  }\n  divisor = globalThis.Math.abs(divisor);\n  return makeFilter(input => remainder(input, divisor) === 0, {\n    expected: `a value that is a multiple of ${divisor}`,\n    representation: {\n      id: \"effect/schema/isMultipleOf\",\n      payload: {\n        divisor\n      }\n    },\n    toJsonSchema: () => ({\n      multipleOf: divisor\n    }),\n    toCode: () => ({\n      runtime: `Schema.isMultipleOf(${format(divisor)})`\n    }),\n    ...annotations\n  });\n}\n/**\n * Validates that a number is a safe integer (within the safe integer range\n * that can be exactly represented in JavaScript).\n *\n * **Details**\n *\n * JSON Schema:\n *\n * This check corresponds to the `type: \"integer\"` constraint in JSON Schema.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies an integer constraint.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isInt(annotations) {\n  return makeFilter(n => globalThis.Number.isSafeInteger(n), {\n    expected: \"an integer\",\n    representation: {\n      id: \"effect/schema/isInt\",\n      payload: null\n    },\n    toJsonSchema: () => ({\n      type: \"integer\"\n    }),\n    toCode: () => ({\n      runtime: \"Schema.isInt()\"\n    }),\n    arbitraryConstraint: {\n      number: \"integer\"\n    },\n    ...annotations\n  });\n}\n/**\n * Schema for integers, rejecting `NaN`, `Infinity`, and `-Infinity`.\n *\n * @category schemas\n * @since 3.10.0\n */\nexport const Int = /*#__PURE__*/Number.check(/*#__PURE__*/isInt());\n/**\n * Schema for non-negative safe integers, including zero.\n *\n * **When to use**\n *\n * Use when you need a count, index, or size that cannot be negative.\n *\n * @see {@link Int} for safe integers that may be negative\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const Natural = /*#__PURE__*/Int.check(/*#__PURE__*/isGreaterThanOrEqualTo(0));\n/**\n * Validates that a number is a 32-bit signed integer (range: -2,147,483,648 to\n * 2,147,483,647).\n *\n * **Details**\n *\n * JSON Schema:\n *\n * This check corresponds to the `format: \"int32\"` constraint in OpenAPI 3.1,\n * or `minimum`/`maximum` constraints in other JSON Schema targets.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies integer and range\n * constraints to ensure generated numbers are 32-bit signed integers.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isInt32(annotations) {\n  return new SchemaAST.FilterGroup([isInt(), isBetween({\n    minimum: -2147483648,\n    maximum: 2147483647\n  })], {\n    expected: \"a 32-bit integer\",\n    ...annotations\n  });\n}\n/**\n * Validates that a number is a 32-bit unsigned integer (range: 0 to\n * 4,294,967,295).\n *\n * **Details**\n *\n * JSON Schema:\n *\n * This check corresponds to the `format: \"uint32\"` constraint in OpenAPI 3.1,\n * or `minimum`/`maximum` constraints in other JSON Schema targets.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies integer and range\n * constraints to ensure generated numbers are 32-bit unsigned integers.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isUint32(annotations) {\n  return new SchemaAST.FilterGroup([isInt(), isBetween({\n    minimum: 0,\n    maximum: 4294967295\n  })], {\n    expected: \"a 32-bit unsigned integer\",\n    ...annotations\n  });\n}\nfunction encodeDatePayload(date) {\n  if (globalThis.Number.isNaN(date.getTime())) {\n    throw new globalThis.RangeError(`Expected a valid Date, got ${format(date)}`);\n  }\n  return date.toISOString();\n}\nfunction formatDateRuntime(date) {\n  return `new Date(${format(date.getTime())})`;\n}\n/**\n * Validates that a Date is greater than the specified value (exclusive).\n *\n * **Details**\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies an exclusive lower bound.\n *\n * @category validation\n * @since 4.0.0\n */\nexport const isGreaterThanDate = /*#__PURE__*/makeIsGreaterThan({\n  order: Order.Date,\n  annotate: exclusiveMinimum => {\n    const encoded = encodeDatePayload(exclusiveMinimum);\n    return {\n      representation: {\n        id: \"effect/schema/isGreaterThanDate\",\n        payload: {\n          exclusiveMinimum: encoded\n        }\n      },\n      toJsonSchema: () => ({}),\n      toCode: () => ({\n        runtime: `Schema.isGreaterThanDate(${formatDateRuntime(exclusiveMinimum)})`\n      })\n    };\n  }\n});\n/**\n * Validates that a Date is greater than or equal to the specified date\n * (inclusive).\n *\n * **Details**\n *\n * JSON Schema:\n *\n * This check does not have a direct JSON Schema equivalent, as JSON Schema\n * validates date strings, not Date objects.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies an inclusive lower bound.\n *\n * @category validation\n * @since 4.0.0\n */\nexport const isGreaterThanOrEqualToDate = /*#__PURE__*/makeIsGreaterThanOrEqualTo({\n  order: Order.Date,\n  annotate: minimum => {\n    const encoded = encodeDatePayload(minimum);\n    return {\n      representation: {\n        id: \"effect/schema/isGreaterThanOrEqualToDate\",\n        payload: {\n          minimum: encoded\n        }\n      },\n      toJsonSchema: () => ({}),\n      toCode: () => ({\n        runtime: `Schema.isGreaterThanOrEqualToDate(${formatDateRuntime(minimum)})`\n      })\n    };\n  }\n});\n/**\n * Validates that a Date is less than the specified value (exclusive).\n *\n * **Details**\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies an exclusive upper bound.\n *\n * @category validation\n * @since 4.0.0\n */\nexport const isLessThanDate = /*#__PURE__*/makeIsLessThan({\n  order: Order.Date,\n  annotate: exclusiveMaximum => {\n    const encoded = encodeDatePayload(exclusiveMaximum);\n    return {\n      representation: {\n        id: \"effect/schema/isLessThanDate\",\n        payload: {\n          exclusiveMaximum: encoded\n        }\n      },\n      toJsonSchema: () => ({}),\n      toCode: () => ({\n        runtime: `Schema.isLessThanDate(${formatDateRuntime(exclusiveMaximum)})`\n      })\n    };\n  }\n});\n/**\n * Validates that a Date is less than or equal to the specified date\n * (inclusive).\n *\n * **Details**\n *\n * JSON Schema:\n *\n * This check does not have a direct JSON Schema equivalent, as JSON Schema\n * validates date strings, not Date objects.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies an inclusive upper bound.\n *\n * @category validation\n * @since 4.0.0\n */\nexport const isLessThanOrEqualToDate = /*#__PURE__*/makeIsLessThanOrEqualTo({\n  order: Order.Date,\n  annotate: maximum => {\n    const encoded = encodeDatePayload(maximum);\n    return {\n      representation: {\n        id: \"effect/schema/isLessThanOrEqualToDate\",\n        payload: {\n          maximum: encoded\n        }\n      },\n      toJsonSchema: () => ({}),\n      toCode: () => ({\n        runtime: `Schema.isLessThanOrEqualToDate(${formatDateRuntime(maximum)})`\n      })\n    };\n  }\n});\n/**\n * Validates that a Date is within a specified range. The range boundaries can\n * be inclusive or exclusive based on the provided options.\n *\n * **Details**\n *\n * JSON Schema:\n *\n * This check does not have a direct JSON Schema equivalent, as JSON Schema\n * validates date strings, not Date objects.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies the specified lower and upper bounds.\n *\n * @category validation\n * @since 4.0.0\n */\nexport const isBetweenDate = /*#__PURE__*/makeIsBetween({\n  order: Order.Date,\n  annotate: options => {\n    const exclusiveMinimum = options.exclusiveMinimum ? true : undefined;\n    const exclusiveMaximum = options.exclusiveMaximum ? true : undefined;\n    const payload = {\n      minimum: encodeDatePayload(options.minimum),\n      maximum: encodeDatePayload(options.maximum),\n      ...(exclusiveMinimum && {\n        exclusiveMinimum\n      }),\n      ...(exclusiveMaximum && {\n        exclusiveMaximum\n      })\n    };\n    return {\n      representation: {\n        id: \"effect/schema/isBetweenDate\",\n        payload\n      },\n      toJsonSchema: () => ({}),\n      toCode: () => ({\n        runtime: `Schema.isBetweenDate({ minimum: ${formatDateRuntime(options.minimum)}, maximum: ${formatDateRuntime(options.maximum)}, exclusiveMinimum: ${format(exclusiveMinimum)}, exclusiveMaximum: ${format(exclusiveMaximum)} })`\n      })\n    };\n  }\n});\n/**\n * Validates that a BigInt is greater than the specified value (exclusive).\n *\n * **Details**\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies an exclusive lower bound.\n *\n * @category validation\n * @since 4.0.0\n */\nexport const isGreaterThanBigInt = /*#__PURE__*/makeIsGreaterThan({\n  order: Order.BigInt,\n  annotate: exclusiveMinimum => {\n    const encoded = exclusiveMinimum.toString(10);\n    return {\n      representation: {\n        id: \"effect/schema/isGreaterThanBigInt\",\n        payload: {\n          exclusiveMinimum: encoded\n        }\n      },\n      toJsonSchema: () => ({}),\n      toCode: () => ({\n        runtime: `Schema.isGreaterThanBigInt(${format(exclusiveMinimum)})`\n      })\n    };\n  }\n});\n/**\n * Validates that a BigInt is greater than or equal to the specified value\n * (inclusive).\n *\n * **Details**\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies an inclusive lower bound.\n *\n * @category validation\n * @since 4.0.0\n */\nexport const isGreaterThanOrEqualToBigInt = /*#__PURE__*/makeIsGreaterThanOrEqualTo({\n  order: Order.BigInt,\n  annotate: minimum => {\n    const encoded = minimum.toString(10);\n    return {\n      representation: {\n        id: \"effect/schema/isGreaterThanOrEqualToBigInt\",\n        payload: {\n          minimum: encoded\n        }\n      },\n      toJsonSchema: () => ({}),\n      toCode: () => ({\n        runtime: `Schema.isGreaterThanOrEqualToBigInt(${format(minimum)})`\n      })\n    };\n  }\n});\n/**\n * Validates that a BigInt is less than the specified value (exclusive).\n *\n * **Details**\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies an exclusive upper bound.\n *\n * @category validation\n * @since 4.0.0\n */\nexport const isLessThanBigInt = /*#__PURE__*/makeIsLessThan({\n  order: Order.BigInt,\n  annotate: exclusiveMaximum => {\n    const encoded = exclusiveMaximum.toString(10);\n    return {\n      representation: {\n        id: \"effect/schema/isLessThanBigInt\",\n        payload: {\n          exclusiveMaximum: encoded\n        }\n      },\n      toJsonSchema: () => ({}),\n      toCode: () => ({\n        runtime: `Schema.isLessThanBigInt(${format(exclusiveMaximum)})`\n      })\n    };\n  }\n});\n/**\n * Validates that a BigInt is less than or equal to the specified value\n * (inclusive).\n *\n * **Details**\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies an inclusive upper bound.\n *\n * @category validation\n * @since 4.0.0\n */\nexport const isLessThanOrEqualToBigInt = /*#__PURE__*/makeIsLessThanOrEqualTo({\n  order: Order.BigInt,\n  annotate: maximum => {\n    const encoded = maximum.toString(10);\n    return {\n      representation: {\n        id: \"effect/schema/isLessThanOrEqualToBigInt\",\n        payload: {\n          maximum: encoded\n        }\n      },\n      toJsonSchema: () => ({}),\n      toCode: () => ({\n        runtime: `Schema.isLessThanOrEqualToBigInt(${format(maximum)})`\n      })\n    };\n  }\n});\n/**\n * Validates that a BigInt is within a specified range. The range boundaries can\n * be inclusive or exclusive based on the provided options.\n *\n * **Details**\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies the specified lower and upper bounds.\n *\n * @category validation\n * @since 4.0.0\n */\nexport const isBetweenBigInt = /*#__PURE__*/makeIsBetween({\n  order: Order.BigInt,\n  annotate: options => {\n    const exclusiveMinimum = options.exclusiveMinimum ? true : undefined;\n    const exclusiveMaximum = options.exclusiveMaximum ? true : undefined;\n    const payload = {\n      minimum: options.minimum.toString(10),\n      maximum: options.maximum.toString(10),\n      ...(exclusiveMinimum && {\n        exclusiveMinimum\n      }),\n      ...(exclusiveMaximum && {\n        exclusiveMaximum\n      })\n    };\n    return {\n      representation: {\n        id: \"effect/schema/isBetweenBigInt\",\n        payload\n      },\n      toJsonSchema: () => ({}),\n      toCode: () => ({\n        runtime: `Schema.isBetweenBigInt({ minimum: ${format(options.minimum)}, maximum: ${format(options.maximum)}, exclusiveMinimum: ${format(exclusiveMinimum)}, exclusiveMaximum: ${format(exclusiveMaximum)} })`\n      })\n    };\n  }\n});\n/**\n * Validates that a value has at least the specified length. Works with strings\n * and arrays.\n *\n * **Details**\n *\n * JSON Schema:\n *\n * For arrays, this check corresponds to `minItems`. For strings, it corresponds\n * to `minLength`. JavaScript counts UTF-16 code units while JSON Schema counts\n * Unicode code points, so the two validations can differ for some strings.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies a `minLength`\n * constraint to ensure generated strings or arrays have at least the required\n * length.\n *\n * **Example** (Checking minimum length)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const NonEmptyStringSchema = Schema.String.check(Schema.isMinLength(1))\n * const NonEmptyArraySchema = Schema.Array(Schema.Number).check(Schema.isMinLength(1))\n * Schema.is(NonEmptyStringSchema)(\"a\") // => true\n * Schema.is(NonEmptyArraySchema)([1]) // => true\n * ```\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isMinLength(minLength, annotations) {\n  minLength = Math.max(0, Math.floor(minLength));\n  return makeFilter(input => input.length >= minLength, {\n    expected: `a value with a length of at least ${minLength}`,\n    representation: {\n      id: \"effect/schema/isMinLength\",\n      payload: {\n        minLength\n      }\n    },\n    toJsonSchema: ({\n      type\n    }) => type === \"array\" ? {\n      minItems: minLength\n    } : {\n      minLength\n    },\n    toCode: () => ({\n      runtime: `Schema.isMinLength(${minLength})`\n    }),\n    [InternalAnnotations.STRUCTURAL_ANNOTATION_KEY]: true,\n    arbitraryConstraint: {\n      minLength\n    },\n    ...annotations\n  });\n}\n/**\n * Validates that a value has at least one element. Works with strings and arrays.\n * This is equivalent to `isMinLength(1)`.\n *\n * **Details**\n *\n * JSON Schema:\n *\n * This check corresponds to the `minLength: 1` constraint for strings or the\n * `minItems: 1` constraint for arrays in JSON Schema.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies a `minLength: 1`\n * constraint to ensure generated strings or arrays are non-empty.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isNonEmpty(annotations) {\n  return isMinLength(1, annotations);\n}\n/**\n * Validates that a value has at most the specified length. Works with strings\n * and arrays.\n *\n * **Details**\n *\n * JSON Schema:\n *\n * This check corresponds to the `maxLength` constraint for strings or the\n * `maxItems` constraint for arrays in JSON Schema.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies a `maxLength`\n * constraint to ensure generated strings or arrays have at most the required\n * length.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isMaxLength(maxLength, annotations) {\n  maxLength = Math.max(0, Math.floor(maxLength));\n  return makeFilter(input => input.length <= maxLength, {\n    expected: `a value with a length of at most ${maxLength}`,\n    representation: {\n      id: \"effect/schema/isMaxLength\",\n      payload: {\n        maxLength\n      }\n    },\n    toJsonSchema: ({\n      type\n    }) => type === \"array\" ? {\n      maxItems: maxLength\n    } : {\n      maxLength\n    },\n    toCode: () => ({\n      runtime: `Schema.isMaxLength(${maxLength})`\n    }),\n    [InternalAnnotations.STRUCTURAL_ANNOTATION_KEY]: true,\n    arbitraryConstraint: {\n      maxLength\n    },\n    ...annotations\n  });\n}\n/**\n * Validates that a value's length is within the specified range. Works with\n * strings and arrays.\n *\n * **Details**\n *\n * JSON Schema:\n *\n * For arrays, this check corresponds to `minItems` and `maxItems`. For strings,\n * it corresponds to `minLength` and `maxLength`. JavaScript counts UTF-16 code\n * units while JSON Schema counts Unicode code points, so the two validations\n * can differ for some strings.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies `minLength` and\n * `maxLength` constraints to ensure generated strings or arrays have a length\n * within the specified range.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isLengthBetween(minimum, maximum, annotations) {\n  minimum = Math.max(0, Math.floor(minimum));\n  maximum = Math.max(0, Math.floor(maximum));\n  return makeFilter(input => input.length >= minimum && input.length <= maximum, {\n    expected: minimum === maximum ? `a value with a length of ${minimum}` : `a value with a length between ${minimum} and ${maximum}`,\n    representation: {\n      id: \"effect/schema/isLengthBetween\",\n      payload: {\n        minimum,\n        maximum\n      }\n    },\n    toJsonSchema: ({\n      type\n    }) => type === \"array\" ? {\n      allOf: [{\n        minItems: minimum\n      }, {\n        maxItems: maximum\n      }]\n    } : {\n      allOf: [{\n        minLength: minimum\n      }, {\n        maxLength: maximum\n      }]\n    },\n    toCode: () => ({\n      runtime: `Schema.isLengthBetween(${minimum}, ${maximum})`\n    }),\n    [InternalAnnotations.STRUCTURAL_ANNOTATION_KEY]: true,\n    arbitraryConstraint: {\n      minLength: minimum,\n      maxLength: maximum\n    },\n    ...annotations\n  });\n}\n/**\n * Validates that a value has at least the specified size. Works with values\n * that have a `size` property, such as `Set` or `Map`.\n *\n * **Details**\n *\n * JSON Schema:\n *\n * This check does not have a direct JSON Schema equivalent, as it applies to\n * values with a `size` property rather than standard JSON Schema types.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies a node-local `minSize` constraint.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isMinSize(minSize, annotations) {\n  minSize = Math.max(0, Math.floor(minSize));\n  return makeFilter(input => input.size >= minSize, {\n    expected: `a value with a size of at least ${minSize}`,\n    representation: {\n      id: \"effect/schema/isMinSize\",\n      payload: {\n        minSize\n      }\n    },\n    toJsonSchema: () => ({}),\n    toCode: () => ({\n      runtime: `Schema.isMinSize(${minSize})`\n    }),\n    [InternalAnnotations.STRUCTURAL_ANNOTATION_KEY]: true,\n    arbitraryConstraint: {\n      minSize\n    },\n    ...annotations\n  });\n}\n/**\n * Validates that a value has at most the specified size. Works with values\n * that have a `size` property, such as `Set` or `Map`.\n *\n * **Details**\n *\n * JSON Schema:\n *\n * This check does not have a direct JSON Schema equivalent, as it applies to\n * values with a `size` property rather than standard JSON Schema types.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies a node-local `maxSize` constraint.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isMaxSize(maxSize, annotations) {\n  maxSize = Math.max(0, Math.floor(maxSize));\n  return makeFilter(input => input.size <= maxSize, {\n    expected: `a value with a size of at most ${maxSize}`,\n    representation: {\n      id: \"effect/schema/isMaxSize\",\n      payload: {\n        maxSize\n      }\n    },\n    toJsonSchema: () => ({}),\n    toCode: () => ({\n      runtime: `Schema.isMaxSize(${maxSize})`\n    }),\n    [InternalAnnotations.STRUCTURAL_ANNOTATION_KEY]: true,\n    arbitraryConstraint: {\n      maxSize\n    },\n    ...annotations\n  });\n}\n/**\n * Validates that a value's size is within the specified range. Works with\n * values that have a `size` property, such as `Set` or `Map`.\n *\n * **Details**\n *\n * JSON Schema:\n *\n * This check does not have a direct JSON Schema equivalent, as it applies to\n * values with a `size` property rather than standard JSON Schema types.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies node-local `minSize` and `maxSize` constraints.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isSizeBetween(minimum, maximum, annotations) {\n  minimum = Math.max(0, Math.floor(minimum));\n  maximum = Math.max(0, Math.floor(maximum));\n  return makeFilter(input => input.size >= minimum && input.size <= maximum, {\n    expected: minimum === maximum ? `a value with a size of ${minimum}` : `a value with a size between ${minimum} and ${maximum}`,\n    representation: {\n      id: \"effect/schema/isSizeBetween\",\n      payload: {\n        minimum,\n        maximum\n      }\n    },\n    toJsonSchema: () => ({}),\n    toCode: () => ({\n      runtime: `Schema.isSizeBetween(${minimum}, ${maximum})`\n    }),\n    [InternalAnnotations.STRUCTURAL_ANNOTATION_KEY]: true,\n    arbitraryConstraint: {\n      minSize: minimum,\n      maxSize: maximum\n    },\n    ...annotations\n  });\n}\n/**\n * Validates that an object contains at least the specified number of\n * properties. This includes both string and symbol keys when counting\n * properties.\n *\n * **Details**\n *\n * JSON Schema:\n *\n * This check corresponds to `minProperties` in JSON Schema. Effect applies the\n * check to the decoded object, while JSON Schema applies it to the original\n * input. Defaults and property transformations can therefore produce different\n * results.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies a node-local `minProperties` constraint.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isMinProperties(minProperties, annotations) {\n  minProperties = Math.max(0, Math.floor(minProperties));\n  return makeFilter(input => Reflect.ownKeys(input).length >= minProperties, {\n    expected: `a value with at least ${minProperties === 1 ? \"1 entry\" : `${minProperties} entries`}`,\n    representation: {\n      id: \"effect/schema/isMinProperties\",\n      payload: {\n        minProperties\n      }\n    },\n    toJsonSchema: () => ({\n      minProperties\n    }),\n    toCode: () => ({\n      runtime: `Schema.isMinProperties(${minProperties})`\n    }),\n    [InternalAnnotations.STRUCTURAL_ANNOTATION_KEY]: true,\n    arbitraryConstraint: {\n      minProperties\n    },\n    ...annotations\n  });\n}\n/**\n * Validates that an object contains at most the specified number of properties.\n * This includes both string and symbol keys when counting properties.\n *\n * **Details**\n *\n * JSON Schema:\n *\n * This check corresponds to `maxProperties` in JSON Schema. Effect applies the\n * check to the decoded object, while JSON Schema applies it to the original\n * input. Excess-property handling and property transformations can therefore\n * produce different results.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies a node-local `maxProperties` constraint.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isMaxProperties(maxProperties, annotations) {\n  maxProperties = Math.max(0, Math.floor(maxProperties));\n  return makeFilter(input => Reflect.ownKeys(input).length <= maxProperties, {\n    expected: `a value with at most ${maxProperties === 1 ? \"1 entry\" : `${maxProperties} entries`}`,\n    representation: {\n      id: \"effect/schema/isMaxProperties\",\n      payload: {\n        maxProperties\n      }\n    },\n    toJsonSchema: () => ({\n      maxProperties\n    }),\n    toCode: () => ({\n      runtime: `Schema.isMaxProperties(${maxProperties})`\n    }),\n    [InternalAnnotations.STRUCTURAL_ANNOTATION_KEY]: true,\n    arbitraryConstraint: {\n      maxProperties\n    },\n    ...annotations\n  });\n}\n/**\n * Validates that an object contains between `minimum` and `maximum` properties (inclusive).\n * This includes both string and symbol keys when counting properties.\n *\n * **Details**\n *\n * JSON Schema:\n *\n * This check corresponds to `minProperties` and `maxProperties` in JSON\n * Schema. Effect applies the check to the decoded object, while JSON Schema\n * applies it to the original input. Defaults, excess-property handling, and\n * property transformations can therefore produce different results.\n *\n * Arbitrary:\n *\n * During arbitrary generation, this applies node-local `minProperties` and `maxProperties` constraints.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isPropertiesLengthBetween(minimum, maximum, annotations) {\n  minimum = Math.max(0, Math.floor(minimum));\n  maximum = Math.max(0, Math.floor(maximum));\n  return makeFilter(input => Reflect.ownKeys(input).length >= minimum && Reflect.ownKeys(input).length <= maximum, {\n    expected: minimum === maximum ? `a value with exactly ${minimum === 1 ? \"1 entry\" : `${minimum} entries`}` : `a value with between ${minimum} and ${maximum} entries`,\n    representation: {\n      id: \"effect/schema/isPropertiesLengthBetween\",\n      payload: {\n        minimum,\n        maximum\n      }\n    },\n    toJsonSchema: () => ({\n      minProperties: minimum,\n      maxProperties: maximum\n    }),\n    toCode: () => ({\n      runtime: `Schema.isPropertiesLengthBetween(${minimum}, ${maximum})`\n    }),\n    [InternalAnnotations.STRUCTURAL_ANNOTATION_KEY]: true,\n    arbitraryConstraint: {\n      minProperties: minimum,\n      maxProperties: maximum\n    },\n    ...annotations\n  });\n}\n/**\n * Validates that every own property key of an object satisfies the encoded side\n * of the provided key schema.\n *\n * **Details**\n *\n * This check uses `Reflect.ownKeys`, so symbol keys are validated in addition to\n * string property names.\n *\n * JSON Schema:\n * This check corresponds to `propertyNames` in JSON Schema. Effect checks the\n * decoded object's keys, including symbols, while JSON Schema checks the string\n * names in the original input. Property transformations and excess-property\n * handling can therefore produce different results.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isPropertyNames(keySchema, annotations) {\n  const propertyNames = toEncoded(keySchema);\n  const parser = SchemaParser._issue(propertyNames.ast);\n  return makeFilter((input, ast, options) => {\n    const keys = Reflect.ownKeys(input);\n    const issues = [];\n    for (const key of keys) {\n      const issue = parser(key, options);\n      if (issue !== undefined) {\n        issues.push(new SchemaIssue.Pointer([key], issue));\n        if (options.errors === \"first\") break;\n      }\n    }\n    if (Arr.isArrayNonEmpty(issues)) {\n      return new SchemaIssue.Composite(ast, issues, input, options);\n    }\n    return true;\n  }, {\n    expected: \"an object with property names matching the schema\",\n    representation: {\n      id: \"effect/schema/isPropertyNames\",\n      payload: null,\n      schemas: [propertyNames.ast]\n    },\n    toJsonSchema: ({\n      schemas\n    }) => ({\n      propertyNames: schemas[0]\n    }),\n    toCode: ({\n      schemas\n    }) => ({\n      runtime: `Schema.isPropertyNames(${schemas[0].runtime})`\n    }),\n    [InternalAnnotations.STRUCTURAL_ANNOTATION_KEY]: true,\n    ...annotations\n  });\n}\n/**\n * Validates that all items in an array are unique according to Effect equality.\n *\n * **Details**\n *\n * JSON Schema:\n * This check corresponds to the `uniqueItems: true` constraint in JSON Schema.\n *\n * Arbitrary:\n * During arbitrary generation, this applies a node-local identity selector\n * for constructive uniqueness using Effect equality.\n *\n * @category validation\n * @since 4.0.0\n */\nexport function isUnique(annotations) {\n  return makeFilter(input => Arr.dedupe(input).length === input.length, {\n    expected: \"an array with unique items\",\n    representation: {\n      id: \"effect/schema/isUnique\",\n      payload: null\n    },\n    toJsonSchema: () => ({\n      uniqueItems: true\n    }),\n    toCode: () => ({\n      runtime: \"Schema.isUnique()\"\n    }),\n    arbitraryConstraint: {\n      uniqueBy: identity\n    },\n    ...annotations\n  });\n}\n/**\n * Validates that all first elements in an array of key-value tuples are unique according to Effect equality.\n *\n * **Details**\n *\n * Arbitrary:\n * During arbitrary generation, this projects each entry to its key for constructive uniqueness.\n *\n * JSON Schema:\n * JSON Schema has no equivalent constraint, so this check is omitted from generated documents.\n *\n * @see {@link isUnique} for validating uniqueness of complete array elements\n * @category validation\n * @since 4.0.0\n */\nexport function isUniqueKey(annotations) {\n  return makeFilter(input => Arr.dedupe(input.map(([key]) => key)).length === input.length, {\n    expected: \"an array with unique keys\",\n    representation: {\n      id: \"effect/schema/isUniqueKey\",\n      payload: null\n    },\n    toCode: () => ({\n      runtime: \"Schema.isUniqueKey()\"\n    }),\n    arbitraryConstraint: {\n      uniqueBy: entry => entry[0]\n    },\n    ...annotations\n  });\n}\n/**\n * Schema for non-empty strings. Validates that a string has at least one\n * character.\n *\n * @category schemas\n * @since 3.10.0\n */\nexport const NonEmptyString = /*#__PURE__*/String.check(/*#__PURE__*/isNonEmpty());\n/**\n * Schema for strings whose JavaScript `length` is exactly `1`.\n *\n * **When to use**\n *\n * Use to validate string values that must have `length === 1`.\n *\n * **Gotchas**\n *\n * This schema uses JavaScript `String.length`, so visible characters made from\n * multiple UTF-16 code units do not satisfy `length === 1`.\n *\n * @see {@link String} for unconstrained string values\n * @see {@link NonEmptyString} for strings with length greater than zero\n * @see {@link isLengthBetween} for the underlying length check\n *\n * @category schemas\n * @since 3.10.0\n */\nexport const Char = /*#__PURE__*/String.check(/*#__PURE__*/isLengthBetween(1, 1));\nconst getErrorOptionsKey = options => (options?.includeStack === true ? 1 : 0) | (options?.excludeCause === true ? 2 : 0);\nconst getErrorOptions = key => {\n  switch (key) {\n    case 0:\n      return undefined;\n    case 1:\n      return {\n        includeStack: true\n      };\n    case 2:\n      return {\n        excludeCause: true\n      };\n    case 3:\n      return {\n        includeStack: true,\n        excludeCause: true\n      };\n  }\n};\nconst errorSchemaCache = [];\n/**\n * Schema for JavaScript `Error` objects.\n *\n * **Details**\n *\n * Default JSON serializer:\n *\n * Encodes an `Error` as an object with `message`, optional `name`, and optional\n * `cause` properties, and decodes that object back into an `Error`. Stack\n * traces are omitted by default for security. Pass `{ includeStack: true }` to\n * include stack traces, or `{ excludeCause: true }` to omit causes.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport function ErrorInstance(options) {\n  const key = getErrorOptionsKey(options);\n  const cached = errorSchemaCache[key];\n  if (cached !== undefined) {\n    return cached;\n  }\n  const normalizedOptions = getErrorOptions(key);\n  const schema = instanceOf(globalThis.Error, {\n    representation: {\n      id: \"effect/schema/Error\",\n      payload: normalizedOptions ?? null\n    },\n    toCode: () => ({\n      runtime: normalizedOptions !== undefined ? `Schema.ErrorInstance(${format(normalizedOptions)})` : `Schema.ErrorInstance()`,\n      Type: `globalThis.Error`\n    }),\n    expected: \"Error\",\n    toCodecJson: () => link()(JsonError, SchemaTransformation.errorFromJsonError(normalizedOptions))\n  });\n  errorSchemaCache[key] = schema;\n  return schema;\n}\nconst defectSchemaCache = [];\n/**\n * Schema for unexpected defect values represented as `unknown` with a JSON\n * encoded form.\n *\n * **When to use**\n *\n * Use when you need a schema for `Cause` defects or other unexpected failures\n * whose runtime value may be any value.\n *\n * **Details**\n *\n * The encoded side is {@link Json}. During decoding, JSON objects with a string\n * `message` property are decoded into JavaScript `Error` values, preserving a\n * non-default `name` and any string `stack`. Other JSON values decode\n * unchanged.\n *\n * During encoding, JavaScript `Error` values encode to JSON objects with\n * `name`, `message`, and optional `cause` properties. Pass\n * `{ includeStack: true }` to include string stack traces in encoded `Error`\n * defects, or `{ excludeCause: true }` to omit causes. Other values are\n * serialized through Effect's JSON formatter and then parsed back into JSON\n * when possible.\n *\n * **Gotchas**\n *\n * This schema is for carrying defects across JSON boundaries, not for\n * preserving every JavaScript value exactly. Some values cannot round-trip\n * unchanged:\n *\n * - A non-`Error` object such as `{ message: \"boom\" }` encodes as an\n *   error-shaped JSON object and decodes back as an `Error`.\n * - JSON serialization normalizes unsupported values. For example,\n *   `undefined` array elements encode as `null`, unsupported object properties\n *   are omitted, and circular references are dropped.\n * - Values that cannot be represented as JSON fall back to Effect's formatted\n *   string representation.\n *\n * @see {@link ErrorInstance} for a schema that only accepts JavaScript `Error` values.\n * @category schemas\n * @since 4.0.0\n */\nexport function Defect(options) {\n  const key = getErrorOptionsKey(options);\n  const cached = defectSchemaCache[key];\n  if (cached !== undefined) {\n    return cached;\n  }\n  const schema = Json.pipe(decodeTo(Unknown, SchemaTransformation.defectFromJson(getErrorOptions(key))));\n  defectSchemaCache[key] = schema;\n  return schema;\n}\n/**\n * Schema for readonly maps whose keys and values conform to the provided\n * schemas.\n *\n * @category schemas\n * @since 3.10.0\n */\nexport function ReadonlyMap(key, value) {\n  const schema = declareConstructor()([key, value], ([key, value]) => {\n    const array = ArraySchema(Tuple([key, value]));\n    return (input, ast, options) => {\n      if (input instanceof globalThis.Map) {\n        return Effect.mapBothEager(SchemaParser.decodeUnknownEffect(array)([...input], options), {\n          onSuccess: array => new globalThis.Map(array),\n          onFailure: issue => SchemaIssue.makeCompositeAtKey(ast, \"entries\", issue, input, options)\n        });\n      }\n      return Effect.fail(new SchemaIssue.InvalidType(ast, input, options));\n    };\n  }, {\n    representation: {\n      id: \"effect/schema/ReadonlyMap\",\n      payload: null\n    },\n    toCode: ({\n      typeParameters\n    }) => ({\n      runtime: `Schema.ReadonlyMap(${typeParameters[0].runtime}, ${typeParameters[1].runtime})`,\n      Type: `globalThis.ReadonlyMap<${typeParameters[0].Type}, ${typeParameters[1].Type}>`\n    }),\n    expected: \"ReadonlyMap\",\n    toCodec: ([key, value]) => link()(ArraySchema(Tuple([key, value])), SchemaTransformation.transform({\n      decode: entries => new globalThis.Map(entries),\n      encode: map => [...map.entries()]\n    }))\n  });\n  return make(schema.ast, {\n    key,\n    value\n  });\n}\n/**\n * Schema for readonly sets whose values conform to the provided element schema.\n *\n * @category schemas\n * @since 3.10.0\n */\nexport function ReadonlySet(value) {\n  const schema = declareConstructor()([value], ([value]) => {\n    const array = ArraySchema(value);\n    return (input, ast, options) => {\n      if (input instanceof globalThis.Set) {\n        return Effect.mapBothEager(SchemaParser.decodeUnknownEffect(array)([...input], options), {\n          onSuccess: array => new globalThis.Set(array),\n          onFailure: issue => SchemaIssue.makeCompositeAtKey(ast, \"values\", issue, input, options)\n        });\n      }\n      return Effect.fail(new SchemaIssue.InvalidType(ast, input, options));\n    };\n  }, {\n    representation: {\n      id: \"effect/schema/ReadonlySet\",\n      payload: null\n    },\n    toCode: ({\n      typeParameters\n    }) => ({\n      runtime: `Schema.ReadonlySet(${typeParameters[0].runtime})`,\n      Type: `globalThis.ReadonlySet<${typeParameters[0].Type}>`\n    }),\n    expected: \"ReadonlySet\",\n    toCodec: ([value]) => link()(ArraySchema(value), SchemaTransformation.transform({\n      decode: values => new globalThis.Set(values),\n      encode: set => [...set.values()]\n    }))\n  });\n  return make(schema.ast, {\n    value\n  });\n}\n/**\n * Schema for JavaScript `RegExp` objects.\n *\n * **Details**\n *\n * The default JSON serializer encodes a `RegExp` as `{ source, flags }`.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const RegExp = /*#__PURE__*/instanceOf(globalThis.RegExp, {\n  representation: {\n    id: \"effect/schema/RegExp\",\n    payload: null\n  },\n  toCode: () => ({\n    runtime: `Schema.RegExp`,\n    Type: `globalThis.RegExp`\n  }),\n  expected: \"RegExp\",\n  toCodecJson: () => link()(Struct({\n    source: String,\n    flags: String\n  }), SchemaTransformation.transformEffect({\n    decode: (e, options) => Effect.try({\n      try: () => new globalThis.RegExp(e.source, e.flags),\n      catch: () => new SchemaIssue.InvalidValue({\n        expected: \"valid RegExp source and flags\"\n      }, e, options)\n    }),\n    encode: regExp => Effect.succeed({\n      source: regExp.source,\n      flags: regExp.flags\n    })\n  }))\n});\nconst URLString = /*#__PURE__*/String.annotate({\n  expected: \"a string that will be decoded as a URL\"\n});\n/**\n * Schema for JavaScript `URL` objects.\n *\n * **Details**\n *\n * Default JSON serializer:\n *\n * - encodes `URL` as a `string`\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const URL = /*#__PURE__*/instanceOf(globalThis.URL, {\n  representation: {\n    id: \"effect/schema/URL\",\n    payload: null\n  },\n  toCode: () => ({\n    runtime: `Schema.URL`,\n    Type: `globalThis.URL`\n  }),\n  expected: \"URL\",\n  toCodecJson: () => link()(URLString, SchemaTransformation.urlFromString)\n});\n/**\n * Schema that decodes a `string` into a `URL`.\n *\n * **Details**\n *\n * Decoding:\n * - A **valid** URL `string` is decoded as a `URL`\n *\n * Encoding:\n * - A `URL` is encoded as a `string`\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const URLFromString = /*#__PURE__*/URLString.pipe(/*#__PURE__*/decodeTo(URL, SchemaTransformation.urlFromString));\nconst DateString = /*#__PURE__*/String.annotate({\n  expected: \"a string that will be decoded as a Date\"\n});\n/**\n * Schema for valid JavaScript `Date` objects.\n *\n * **When to use**\n *\n * Use to validate in-memory values that must already be valid JavaScript date\n * objects.\n *\n * **Details**\n *\n * This schema accepts `Date` instances whose timestamp is not `NaN`. The\n * default JSON serializer encodes dates as ISO 8601 strings.\n *\n * **Example** (Defining a Date schema)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const date = Schema.decodeUnknownSync(Schema.Date)(new Date(\"2024-01-01\"))\n * date.toISOString() // => \"2024-01-01T00:00:00.000Z\"\n * ```\n *\n * @see {@link DateFromString} for decoding strings into Date instances\n * @see {@link DateFromMillis} for decoding epoch milliseconds into Date instances\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const Date = /*#__PURE__*/declare(input => input instanceof globalThis.Date && !globalThis.Number.isNaN(input.getTime()), {\n  representation: {\n    id: \"effect/schema/Date\",\n    payload: null\n  },\n  toCode: () => ({\n    runtime: `Schema.Date`,\n    Type: `globalThis.Date`\n  }),\n  expected: \"a valid Date\",\n  toCodecJson: () => link()(DateString, SchemaTransformation.dateFromString)\n});\n/**\n * Schema that decodes a string into a JavaScript `Date`.\n *\n * **When to use**\n *\n * Use to model string-encoded dates that decode to JavaScript `Date` objects\n * and encode back to strings.\n *\n * **Details**\n *\n * Decoding:\n * The string is passed to JavaScript `Date` construction.\n *\n * Encoding:\n * A `Date` is encoded as an ISO string.\n *\n * Invalid date strings fail decoding.\n *\n * @see {@link DateFromMillis} for decoding epoch milliseconds into Date instances\n * @see {@link DateTimeUtcFromString} for decoding date-time strings into UTC values\n * @see {@link Date} for accepting Date instances directly\n *\n * @category schemas\n * @since 3.10.0\n */\nexport const DateFromString = /*#__PURE__*/DateString.pipe(/*#__PURE__*/decodeTo(Date, SchemaTransformation.dateFromString));\n/**\n * Schema that decodes epoch milliseconds into a JavaScript `Date`.\n *\n * **When to use**\n *\n * Use to model numeric millisecond timestamps that decode to JavaScript `Date`\n * objects and encode back to numbers.\n *\n * **Details**\n *\n * Decoding:\n * A safe integer number of milliseconds since the Unix epoch is decoded as a\n * `Date`.\n *\n * Encoding:\n * A `Date` is encoded as its millisecond timestamp.\n *\n * **Gotchas**\n *\n * JavaScript `Date` supports a narrower range than safe integers, so integers\n * outside the supported `Date` range fail decoding.\n *\n * @see {@link DateFromString} for decoding string-encoded dates\n * @see {@link DateTimeUtcFromMillis} for decoding epoch milliseconds into UTC values\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const DateFromMillis = /*#__PURE__*/Int.pipe(/*#__PURE__*/decodeTo(Date, SchemaTransformation.dateFromMillis));\nconst JsonString = /*#__PURE__*/String.annotate({\n  expected: \"a string that will be decoded as JSON\",\n  contentMediaType: \"application/json\"\n});\n/**\n * Returns a schema that decodes a JSON string and then decodes the parsed value\n * using the given schema.\n *\n * **Details**\n *\n * This is useful when working with JSON-encoded strings where the actual\n * structure of the value is known and described by an existing schema.\n *\n * During decoding, the resulting schema first parses the input string as JSON,\n * using `reviver` when provided, and then runs the provided schema on the\n * parsed result. During encoding, it first encodes with the provided schema and\n * then passes the result to `JSON.stringify` with the optional `replacer` and\n * `space`.\n *\n * **Example** (Formatting encoded JSON)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const schema = Schema.Struct({ a: Schema.Number })\n * const schemaFromJsonString = Schema.fromJsonString(schema, { space: 2 })\n *\n * Schema.encodeSync(schemaFromJsonString)({ a: 1 }) // => \"{\\n  \\\"a\\\": 1\\n}\"\n * ```\n *\n * @category schemas\n * @since 4.0.0\n */\nexport function fromJsonString(schema, options) {\n  return JsonString.pipe(decodeTo(schema, SchemaTransformation.fromJsonString(options)));\n}\n/** @internal */\nexport const UnknownFromJsonString = /*#__PURE__*/fromJsonString(Unknown);\n/**\n * Schema for JavaScript `File` objects.\n *\n * **Details**\n *\n * The default JSON serializer encodes a `File` as `{ data, type, name, lastModified }`\n * where `data` is base64-encoded.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const File = /*#__PURE__*/instanceOf(globalThis.File, {\n  representation: {\n    id: \"effect/schema/File\",\n    payload: null\n  },\n  toCode: () => ({\n    runtime: `Schema.File`,\n    Type: `globalThis.File`\n  }),\n  expected: \"File\",\n  toCodecJson: () => link()(Struct({\n    data: String.check(isBase64()),\n    type: String,\n    name: String,\n    lastModified: Int\n  }), SchemaTransformation.transformEffect({\n    decode: (e, options) => Result_.match(Encoding.decodeBase64(e.data), {\n      onFailure: () => Effect.fail(new SchemaIssue.InvalidValue({\n        expected: \"a valid Base64 string\"\n      }, e.data, options)),\n      onSuccess: bytes => {\n        const buffer = new globalThis.Uint8Array(bytes);\n        return Effect.succeed(new globalThis.File([buffer], e.name, {\n          type: e.type,\n          lastModified: e.lastModified\n        }));\n      }\n    }),\n    encode: (file, options) => Effect.tryPromise({\n      try: async () => {\n        const bytes = new globalThis.Uint8Array(await file.arrayBuffer());\n        return {\n          data: Encoding.encodeBase64(bytes),\n          type: file.type,\n          name: file.name,\n          lastModified: file.lastModified\n        };\n      },\n      catch: () => new SchemaIssue.InvalidValue({\n        expected: \"a readable File\"\n      }, file, options)\n    })\n  }))\n});\n/**\n * Schema for JavaScript `FormData` objects.\n *\n * **Details**\n *\n * The default JSON serializer encodes a `FormData` as an array of `[key, entry]`\n * pairs where each entry is tagged as `\"String\"` or `\"File\"`.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const FormData = /*#__PURE__*/instanceOf(globalThis.FormData, {\n  representation: {\n    id: \"effect/schema/FormData\",\n    payload: null\n  },\n  toCode: () => ({\n    runtime: `Schema.FormData`,\n    Type: `globalThis.FormData`\n  }),\n  expected: \"FormData\",\n  toCodecJson: () => link()(ArraySchema(Tuple([String, Union([Struct({\n    _tag: tag(\"String\"),\n    value: String\n  }), Struct({\n    _tag: tag(\"File\"),\n    value: File\n  })])])), SchemaTransformation.transformEffect({\n    decode: e => {\n      const out = new globalThis.FormData();\n      for (const [key, entry] of e) {\n        out.append(key, entry.value);\n      }\n      return Effect.succeed(out);\n    },\n    encode: formData => {\n      return Effect.succeed(globalThis.Array.from(formData.entries()).map(([key, value]) => {\n        if (typeof value === \"string\") {\n          return [key, {\n            _tag: \"String\",\n            value\n          }];\n        } else {\n          return [key, {\n            _tag: \"File\",\n            value\n          }];\n        }\n      }));\n    }\n  }))\n});\n/**\n * Schema for decoding `FormData` through a bracket-notation tree.\n *\n * **When to use**\n *\n * Use to decode browser or multipart form data into a structured schema value.\n *\n * **Details**\n *\n * The decoding process has two steps:\n *\n * 1. Parse `FormData` into a nested tree record.\n * 2. Decode the parsed value with the given schema.\n *\n * You can express nested values using bracket notation.\n *\n * If you want to decode string fields into non-string primitive values, use\n * `Schema.toCodecStringTree`.\n *\n * **Example** (Decoding a flat structure)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const schema = Schema.fromFormData(\n *   Schema.Struct({\n *     a: Schema.String\n *   })\n * )\n *\n * const formData = new FormData()\n * formData.append(\"a\", \"1\")\n * formData.append(\"b\", \"2\")\n *\n * Schema.decodeUnknownSync(schema)(formData) // => { a: \"1\" }\n * ```\n *\n * **Example** (Decoding nested fields)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const schema = Schema.fromFormData(\n *   Schema.Struct({\n *     a: Schema.String,\n *     b: Schema.Struct({\n *       c: Schema.String,\n *       d: Schema.String\n *     })\n *   })\n * )\n *\n * const formData = new FormData()\n * formData.append(\"a\", \"1\")\n * formData.append(\"b[c]\", \"2\")\n * formData.append(\"b[d]\", \"3\")\n *\n * Schema.decodeUnknownSync(schema)(formData) // => { a: \"1\", b: { c: \"2\", d: \"3\" } }\n * ```\n *\n * **Example** (Parsing non-string values)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const schema = Schema.fromFormData(\n *   Schema.toCodecStringTree(\n *     Schema.Struct({\n *       a: Schema.Int\n *     })\n *   )\n * )\n *\n * const formData = new FormData()\n * formData.append(\"a\", \"1\")\n *\n * Schema.decodeUnknownSync(schema)(formData) // => { a: 1 }\n * ```\n *\n * @category decoding\n * @since 4.0.0\n */\nexport function fromFormData(schema) {\n  return FormData.pipe(decodeTo(schema, SchemaTransformation.fromFormData));\n}\n/**\n * Schema for JavaScript `URLSearchParams` objects.\n *\n * **Details**\n *\n * The default JSON serializer encodes a `URLSearchParams` as a query string.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const URLSearchParams = /*#__PURE__*/instanceOf(globalThis.URLSearchParams, {\n  representation: {\n    id: \"effect/schema/URLSearchParams\",\n    payload: null\n  },\n  toCode: () => ({\n    runtime: `Schema.URLSearchParams`,\n    Type: `globalThis.URLSearchParams`\n  }),\n  expected: \"URLSearchParams\",\n  toCodecJson: () => link()(String.annotate({\n    expected: \"a query string that will be decoded as URLSearchParams\"\n  }), SchemaTransformation.transform({\n    decode: e => new globalThis.URLSearchParams(e),\n    encode: params => params.toString()\n  }))\n});\n/**\n * Schema for decoding `URLSearchParams` through a bracket-notation tree.\n *\n * **When to use**\n *\n * Use to decode query parameters into a structured schema value.\n *\n * **Details**\n *\n * The decoding process has two steps:\n *\n * 1. Parse `URLSearchParams` into a nested tree record.\n * 2. Decode the parsed value with the given schema.\n *\n * You can express nested values using bracket notation.\n *\n * If you want to decode values that are not strings, use\n * `Schema.toCodecStringTree`. This serializer preserves values such as\n * numbers when compatible with the schema.\n *\n * **Example** (Decoding a flat structure)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const schema = Schema.fromURLSearchParams(\n *   Schema.Struct({\n *     a: Schema.String\n *   })\n * )\n *\n * const urlSearchParams = new URLSearchParams(\"a=1&b=2\")\n *\n * Schema.decodeUnknownSync(schema)(urlSearchParams) // => { a: \"1\" }\n * ```\n *\n * **Example** (Decoding nested fields)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const schema = Schema.fromURLSearchParams(\n *   Schema.Struct({\n *     a: Schema.String,\n *     b: Schema.Struct({\n *       c: Schema.String,\n *       d: Schema.String\n *     })\n *   })\n * )\n *\n * const urlSearchParams = new URLSearchParams(\"a=1&b[c]=2&b[d]=3\")\n *\n * Schema.decodeUnknownSync(schema)(urlSearchParams) // => { a: \"1\", b: { c: \"2\", d: \"3\" } }\n * ```\n *\n * **Example** (Parsing non-string values)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const schema = Schema.fromURLSearchParams(\n *   Schema.toCodecStringTree(\n *     Schema.Struct({\n *       a: Schema.Int\n *     })\n *   )\n * )\n *\n * const urlSearchParams = new URLSearchParams(\"a=1&b=2\")\n *\n * Schema.decodeUnknownSync(schema)(urlSearchParams) // => { a: 1 }\n * ```\n *\n * @category decoding\n * @since 4.0.0\n */\nexport function fromURLSearchParams(schema) {\n  return URLSearchParams.pipe(decodeTo(schema, SchemaTransformation.fromURLSearchParams));\n}\n/**\n * Schema that parses a string into a `number` using JavaScript\n * number coercion.\n *\n * **Details**\n *\n * Decoding:\n * A `string` is decoded as a number, including possible non-finite values such as\n * `NaN`, `Infinity`, and `-Infinity`. Use `FiniteFromString` to reject non-finite\n * numbers.\n *\n * Encoding:\n * A number is encoded as a `string`.\n *\n * @category schemas\n * @since 3.10.0\n */\nexport const NumberFromString = /*#__PURE__*/String.annotate({\n  expected: \"a string that will be decoded as a number\"\n}).pipe(/*#__PURE__*/decodeTo(Number, SchemaTransformation.numberFromString));\n/**\n * Schema that parses a string into a finite number.\n *\n * **Details**\n *\n * Decoding:\n * - A `string` is decoded as a finite number, rejecting `NaN`, `Infinity`, and\n *   `-Infinity` values.\n *\n * Encoding:\n * - A finite number is encoded as a `string`.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const FiniteFromString = /*#__PURE__*/String.annotate({\n  expected: \"a string that will be decoded as a finite number\"\n}).pipe(/*#__PURE__*/decodeTo(Finite, SchemaTransformation.numberFromString));\n/**\n * Schema that parses a string into a `bigint`.\n *\n * **When to use**\n *\n * Use to parse signed base-10 integer strings into bigint values while encoding\n * bigint values back to decimal strings.\n *\n * **Details**\n *\n * Decoding:\n * - A `string` is decoded as a `bigint`.\n *\n * Encoding:\n * - A `bigint` is encoded as a `string`.\n *\n * **Gotchas**\n *\n * Decoding accepts only strings matching `^-?\\d+$`.\n *\n * @see {@link isStringBigInt} for the string predicate used by this schema\n * @see {@link BigInt} for validating values that are already bigint values\n * @see {@link NumberFromString} for parsing JavaScript number strings, including non-finite values\n * @see {@link BigDecimalFromString} for parsing decimal number strings\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const BigIntFromString = /*#__PURE__*/make(SchemaAST.bigIntString).pipe(/*#__PURE__*/decodeTo(BigInt, SchemaTransformation.bigintFromString));\n/**\n * Schema for strings that contains no leading or trailing whitespaces.\n *\n * @category schemas\n * @since 3.10.0\n */\nexport const Trimmed = /*#__PURE__*/String.check(/*#__PURE__*/isTrimmed());\n/**\n * Schema that trims whitespace from a string.\n *\n * **Details**\n *\n * Decoding:\n * - A `string` is decoded as a string with no leading or trailing whitespaces.\n *\n * Encoding:\n * - The trimmed string is encoded as is.\n *\n * @category schemas\n * @since 3.10.0\n */\nexport const Trim = /*#__PURE__*/String.annotate({\n  expected: \"a string that will be decoded as a trimmed string\"\n}).pipe(/*#__PURE__*/decodeTo(Trimmed, /*#__PURE__*/SchemaTransformation.trim()));\n/**\n * Decodes a base64 (RFC4648) encoded string into a UTF-8 string.\n *\n * **Details**\n *\n * Decoding:\n * - A **valid** base64 encoded string is decoded as a UTF-8 `string`.\n *\n * Encoding:\n * - A `string` is encoded as a base64-encoded string.\n *\n * @category schemas\n * @since 3.10.0\n */\nexport const StringFromBase64 = /*#__PURE__*/String.annotate({\n  expected: \"a base64 encoded string that will be decoded as a UTF-8 string\"\n}).pipe(/*#__PURE__*/decodeTo(String, SchemaTransformation.stringFromBase64String));\n/**\n * Decodes a base64 (URL) encoded string into a UTF-8 string.\n *\n * **Details**\n *\n * Decoding:\n * - A **valid** base64 (URL) encoded string is decoded as a UTF-8 `string`.\n *\n * Encoding:\n * - A `string` is encoded as a base64 (URL) encoded string.\n *\n * @category schemas\n * @since 3.10.0\n */\nexport const StringFromBase64Url = /*#__PURE__*/String.annotate({\n  expected: \"a base64 (URL) encoded string that will be decoded as a UTF-8 string\"\n}).pipe(/*#__PURE__*/decodeTo(String, SchemaTransformation.stringFromBase64UrlString));\n/**\n * Decodes a hex encoded string into a UTF-8 string.\n *\n * **Details**\n *\n * Decoding:\n * - A **valid** hex encoded string is decoded as a UTF-8 `string`.\n *\n * Encoding:\n * - A `string` is encoded as a hex string.\n *\n * @category schemas\n * @since 3.10.0\n */\nexport const StringFromHex = /*#__PURE__*/String.annotate({\n  expected: \"a hex encoded string that will be decoded as a UTF-8 string\"\n}).pipe(/*#__PURE__*/decodeTo(String, SchemaTransformation.stringFromHexString));\n/**\n * Decodes a URI component encoded string into a UTF-8 string.\n * Can be used to store data in a URL.\n *\n * **Details**\n *\n * Decoding:\n * - A **valid** URI component encoded string is decoded as a UTF-8 `string`.\n *\n * Encoding:\n * - A `string` is encoded as a URI component encoded string.\n *\n * **Example** (Decoding URI component strings)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const PaginationSchema = Schema.Struct({\n *   maxItemPerPage: Schema.Number,\n *   page: Schema.Number\n * })\n *\n * const UrlSchema = Schema.StringFromUriComponent.pipe(\n *   Schema.decodeTo(Schema.fromJsonString(PaginationSchema))\n * )\n *\n * Schema.encodeSync(UrlSchema)({ maxItemPerPage: 10, page: 1 }) // => \"%7B%22maxItemPerPage%22%3A10%2C%22page%22%3A1%7D\"\n * ```\n *\n * @category schemas\n * @since 3.12.0\n */\nexport const StringFromUriComponent = /*#__PURE__*/String.annotate({\n  expected: \"a URI component encoded string that will be decoded as a UTF-8 string\"\n}).pipe(/*#__PURE__*/decodeTo(String, SchemaTransformation.stringFromUriComponent));\n/**\n * Schema for property keys accepted by Effect schemas: finite `number`,\n * `symbol`, or `string`.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const PropertyKey = /*#__PURE__*/Union([Finite, Symbol, String]);\n/**\n * Schema for a Standard Schema v1 failure result.\n *\n * **Details**\n *\n * The result contains an `issues` array where each issue has a message and an\n * optional path made of property keys or keyed path segments.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const StandardSchemaV1FailureResult = /*#__PURE__*/Struct({\n  issues: /*#__PURE__*/ArraySchema(/*#__PURE__*/Struct({\n    message: String,\n    path: /*#__PURE__*/optional(/*#__PURE__*/ArraySchema(/*#__PURE__*/Union([PropertyKey, /*#__PURE__*/Struct({\n      key: PropertyKey\n    })])))\n  }))\n});\n/**\n * Schema for a boolean parsed from 0 or 1.\n *\n * **When to use**\n *\n * Use when decoding data sources that represent booleans as `0 | 1` while\n * keeping boolean values in the decoded model.\n *\n * **Details**\n *\n * Decoding accepts only `0 | 1`, maps `1` to `true`, and maps `0` to `false`.\n * Encoding maps `true` to `1` and `false` to `0`.\n *\n * @see {@link Boolean} for validating values that are already booleans\n * @see {@link Literals} for keeping bit literals instead of decoding them\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const BooleanFromBit = /*#__PURE__*/Literals([0, 1]).pipe(/*#__PURE__*/decodeTo(Boolean, /*#__PURE__*/SchemaTransformation.transform({\n  decode: bit => bit === 1,\n  encode: bool => bool ? 1 : 0\n})));\nconst Base64String = /*#__PURE__*/String.annotate({\n  expected: \"a base64 encoded string that will be decoded as Uint8Array\",\n  format: \"byte\",\n  contentEncoding: \"base64\"\n});\n/**\n * Schema for JavaScript `Uint8Array` objects.\n *\n * **Details**\n *\n * Default JSON serializer:\n *\n * The default JSON serializer encodes Uint8Array as a Base64 encoded string.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const Uint8Array = /*#__PURE__*/instanceOf(globalThis.Uint8Array, {\n  representation: {\n    id: \"effect/schema/Uint8Array\",\n    payload: null\n  },\n  toCode: () => ({\n    runtime: `Schema.Uint8Array`,\n    Type: `globalThis.Uint8Array`\n  }),\n  expected: \"Uint8Array\",\n  toCodecJson: () => link()(Base64String, SchemaTransformation.uint8ArrayFromBase64String)\n});\n/**\n * Schema that decodes a base64 encoded string into a\n * `Uint8Array`.\n *\n * **Details**\n *\n * Decoding:\n * - A **valid** base64 encoded string is decoded as a `Uint8Array`.\n *\n * Encoding:\n * - A `Uint8Array` is encoded as a base64-encoded string.\n *\n * @category schemas\n * @since 3.10.0\n */\nexport const Uint8ArrayFromBase64 = /*#__PURE__*/Base64String.pipe(/*#__PURE__*/decodeTo(Uint8Array, SchemaTransformation.uint8ArrayFromBase64String));\n/**\n * Schema that decodes a base64 (URL) encoded string into a\n * `Uint8Array`.\n *\n * **Details**\n *\n * Decoding:\n * - A **valid** base64 (URL) encoded string is decoded as a `Uint8Array`.\n *\n * Encoding:\n * - A `Uint8Array` is encoded as a base64 (URL) encoded string.\n *\n * @category schemas\n * @since 3.10.0\n */\nexport const Uint8ArrayFromBase64Url = /*#__PURE__*/String.annotate({\n  expected: \"a base64 (URL) encoded string that will be decoded as a Uint8Array\"\n}).pipe(/*#__PURE__*/decodeTo(Uint8Array, {\n  decode: /*#__PURE__*/SchemaGetter.decodeBase64Url(),\n  encode: /*#__PURE__*/SchemaGetter.encodeBase64Url()\n}));\n/**\n * Schema that decodes a hex encoded string into a\n * `Uint8Array`.\n *\n * **Details**\n *\n * Decoding:\n * - A **valid** hex encoded string is decoded as a `Uint8Array`.\n *\n * Encoding:\n * - A `Uint8Array` is encoded as a hex encoded string.\n *\n * @category schemas\n * @since 3.10.0\n */\nexport const Uint8ArrayFromHex = /*#__PURE__*/String.annotate({\n  expected: \"a hex encoded string that will be decoded as a Uint8Array\"\n}).pipe(/*#__PURE__*/decodeTo(Uint8Array, {\n  decode: /*#__PURE__*/SchemaGetter.decodeHex(),\n  encode: /*#__PURE__*/SchemaGetter.encodeHex()\n}));\n// -----------------------------------------------------------------------------\n// BigDecimal schemas\n// -----------------------------------------------------------------------------\nconst bigDecimalFromString = /*#__PURE__*/SchemaTransformation.transformEffect({\n  decode: (s, options) => {\n    const result = BigDecimal_.fromString(s);\n    return Option_.isNone(result) ? Effect.fail(new SchemaIssue.InvalidValue({\n      expected: \"a valid BigDecimal string\"\n    }, s, options)) : Effect.succeed(result.value);\n  },\n  encode: bd => Effect.succeed(BigDecimal_.format(bd))\n});\n/**\n * Validates that a BigDecimal is greater than the specified value (exclusive).\n *\n * @category validation\n * @since 4.0.0\n */\nexport const isGreaterThanBigDecimal = /*#__PURE__*/makeIsGreaterThan({\n  order: BigDecimal_.Order,\n  formatter: bd => BigDecimal_.format(bd)\n});\n/**\n * Validates that a BigDecimal is greater than or equal to the specified value\n * (inclusive).\n *\n * @category validation\n * @since 4.0.0\n */\nexport const isGreaterThanOrEqualToBigDecimal = /*#__PURE__*/makeIsGreaterThanOrEqualTo({\n  order: BigDecimal_.Order,\n  formatter: bd => BigDecimal_.format(bd)\n});\n/**\n * Validates that a BigDecimal is less than the specified value (exclusive).\n *\n * @category validation\n * @since 4.0.0\n */\nexport const isLessThanBigDecimal = /*#__PURE__*/makeIsLessThan({\n  order: BigDecimal_.Order,\n  formatter: bd => BigDecimal_.format(bd)\n});\n/**\n * Validates that a BigDecimal is less than or equal to the specified value\n * (inclusive).\n *\n * @category validation\n * @since 4.0.0\n */\nexport const isLessThanOrEqualToBigDecimal = /*#__PURE__*/makeIsLessThanOrEqualTo({\n  order: BigDecimal_.Order,\n  formatter: bd => BigDecimal_.format(bd)\n});\n/**\n * Validates that a `BigDecimal` is within a specified range.\n *\n * **Details**\n *\n * The minimum and maximum boundaries are inclusive by default. Pass\n * `exclusiveMinimum` or `exclusiveMaximum` to exclude either boundary.\n *\n * @category validation\n * @since 4.0.0\n */\nexport const isBetweenBigDecimal = /*#__PURE__*/makeIsBetween({\n  order: BigDecimal_.Order,\n  formatter: bd => BigDecimal_.format(bd)\n});\nconst BigDecimalString = /*#__PURE__*/String.annotate({\n  expected: \"a string that will be decoded as a BigDecimal\"\n});\nconst arbitraryBigDecimalMaxScale = 20;\nfunction bigIntArbitrarySchema(minimum, maximum) {\n  if (minimum !== undefined && maximum !== undefined) {\n    return BigInt.check(isBetweenBigInt({\n      minimum,\n      maximum\n    }));\n  }\n  if (minimum !== undefined) return BigInt.check(isGreaterThanOrEqualToBigInt(minimum));\n  if (maximum !== undefined) return BigInt.check(isLessThanOrEqualToBigInt(maximum));\n  return BigInt;\n}\nfunction bigDecimalValueAtScale(value, scale) {\n  return value.value * globalThis.BigInt(10) ** globalThis.BigInt(scale - value.scale);\n}\nfunction bigDecimalArbitrarySchema(constraint) {\n  if (constraint?.minimum === undefined && constraint?.maximum === undefined) {\n    return Struct({\n      value: BigInt,\n      scale: Int.check(isBetween({\n        minimum: 0,\n        maximum: arbitraryBigDecimalMaxScale\n      }))\n    });\n  }\n  const scale = Math.max(arbitraryBigDecimalMaxScale, constraint.minimum?.scale ?? 0, constraint.maximum?.scale ?? 0, constraint.exclusiveMinimum === true && constraint.minimum !== undefined ? constraint.minimum.scale + 1 : 0, constraint.exclusiveMaximum === true && constraint.maximum !== undefined ? constraint.maximum.scale + 1 : 0);\n  const minimum = constraint.minimum === undefined ? undefined : bigDecimalValueAtScale(constraint.minimum, scale) + (constraint.exclusiveMinimum === true ? globalThis.BigInt(1) : globalThis.BigInt(0));\n  const maximum = constraint.maximum === undefined ? undefined : bigDecimalValueAtScale(constraint.maximum, scale) - (constraint.exclusiveMaximum === true ? globalThis.BigInt(1) : globalThis.BigInt(0));\n  if (minimum !== undefined && maximum !== undefined && minimum > maximum) {\n    return Struct({\n      value: BigInt,\n      scale: Int.check(isBetween({\n        minimum: 0,\n        maximum: arbitraryBigDecimalMaxScale\n      }))\n    });\n  }\n  return Struct({\n    value: bigIntArbitrarySchema(minimum, maximum),\n    scale: Literal(scale)\n  });\n}\n/**\n * Schema for `BigDecimal` values.\n *\n * **When to use**\n *\n * Use when you already have Effect decimal instances and need schema\n * validation, formatting, equivalence, and JSON string serialization.\n *\n * **Details**\n *\n * Default JSON serializer:\n *\n * - encodes `BigDecimal` as a `string`\n *\n * @see {@link BigDecimalFromString} for parsing string input into a BigDecimal\n *\n * @category schemas\n * @since 3.10.0\n */\nexport const BigDecimal = /*#__PURE__*/declare(BigDecimal_.isBigDecimal, {\n  representation: {\n    id: \"effect/schema/BigDecimal\",\n    payload: null\n  },\n  toCode: () => ({\n    runtime: `Schema.BigDecimal`,\n    Type: `BigDecimal.BigDecimal`,\n    importDeclarations: [`import * as BigDecimal from \"effect/BigDecimal\"`]\n  }),\n  expected: \"BigDecimal\",\n  toCodecArbitrary: ({\n    constraint\n  }) => linkDecoding()(bigDecimalArbitrarySchema(constraint), SchemaGetter.transform(({\n    scale,\n    value\n  }) => BigDecimal_.make(value, scale))),\n  toCodecJson: () => link()(BigDecimalString, bigDecimalFromString),\n  toFormatter: () => bd => BigDecimal_.format(bd)\n});\n/**\n * Schema that parses a string into a `BigDecimal`.\n *\n * **When to use**\n *\n * Use to parse decimal or exponent-notation strings into arbitrary-precision\n * BigDecimal values while encoding them back to strings.\n *\n * **Details**\n *\n * Decoding:\n * - A `string` is decoded with `BigDecimal.fromString`.\n *\n * Encoding:\n * - A `BigDecimal` is encoded with `BigDecimal.format`.\n *\n * **Gotchas**\n *\n * An empty string decodes as zero.\n *\n * @see {@link BigDecimal} for validating values that are already BigDecimal values\n * @see {@link BigIntFromString} for parsing base-10 integer strings into bigint values\n * @see {@link NumberFromString} for parsing JavaScript number strings\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const BigDecimalFromString = /*#__PURE__*/BigDecimalString.pipe(/*#__PURE__*/decodeTo(BigDecimal, bigDecimalFromString));\n/**\n * Schema for exact, non-negative `ByteSize` values.\n *\n * **Details**\n *\n * The JSON codec encodes the byte count as a bigint string, preserving values\n * beyond JavaScript's safe-integer range. The StringTree codec uses the\n * human-readable byte-size syntax exposed by {@link ByteSizeFromString}.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const ByteSize = /*#__PURE__*/declare(ByteSize_.isByteSize, {\n  representation: {\n    id: \"effect/schema/ByteSize\",\n    payload: null\n  },\n  toCode: () => ({\n    runtime: `Schema.ByteSize`,\n    Type: `ByteSize.ByteSize`,\n    importDeclarations: [`import * as ByteSize from \"effect/ByteSize\"`]\n  }),\n  expected: \"ByteSize\",\n  toCodecJson: () => link()(BigInt.check(isGreaterThanOrEqualToBigInt(globalThis.BigInt(0))), SchemaTransformation.transform({\n    decode: ByteSize_.bytes,\n    encode: ByteSize_.toBigInt\n  })),\n  toCodecStringTree: () => link()(ByteSizeString, SchemaTransformation.byteSizeFromString)\n});\nconst ByteSizeString = /*#__PURE__*/String.annotate({\n  expected: \"a string that will be decoded as a ByteSize\"\n});\n/**\n * Schema that decodes byte-size strings into exact, non-negative `ByteSize`\n * values.\n *\n * **Details**\n *\n * Decoding accepts an unsigned base-10 integer or decimal followed by optional\n * whitespace and one of these case-sensitive units:\n *\n * - bytes: `B`, `byte`, or `bytes`\n * - decimal SI units (powers of 1,000): `kB`, `MB`, `GB`, `TB`, `PB`, `EB`,\n *   `ZB`, `YB`, `RB`, or `QB`, plus their lowercase singular and plural names\n * - binary IEC units (powers of 1,024): `KiB`, `MiB`, `GiB`, `TiB`, `PiB`,\n *   `EiB`, `ZiB`, or `YiB`, plus their lowercase singular and plural names\n *\n * Leading and trailing whitespace is ignored. A decimal quantity must resolve\n * to an integral number of bytes, so `1.5 kB` is accepted while `0.1 KiB` is\n * rejected.\n *\n * Encoding returns the exact byte count as `<count> byte` or `<count> bytes`.\n *\n * **Gotchas**\n *\n * A unit is required. Signs, exponent notation, digit separators, and ambiguous\n * unit spellings such as `KB`, `mb`, `Mb`, or `b` are rejected.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const ByteSizeFromString = /*#__PURE__*/ByteSizeString.pipe(/*#__PURE__*/decodeTo(ByteSize, SchemaTransformation.byteSizeFromString));\n/**\n * Schema that decodes non-negative bigint byte counts.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const ByteSizeFromBigInt = /*#__PURE__*/BigInt.pipe(/*#__PURE__*/decodeTo(ByteSize, SchemaTransformation.byteSizeFromBigInt));\n/**\n * Schema that decodes non-negative safe-integer byte counts.\n *\n * **Details**\n *\n * Encoding fails when the byte count exceeds `Number.MAX_SAFE_INTEGER`.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const ByteSizeFromNumber = /*#__PURE__*/Number.pipe(/*#__PURE__*/decodeTo(ByteSize, SchemaTransformation.byteSizeFromNumber));\n/**\n * Creates a schema for `Cause.Reason` values using separate schemas for typed\n * failures and unexpected defects.\n *\n * **When to use**\n *\n * Use when serializing or decoding individual cause reasons separately from a\n * full failure cause, with distinct schemas for typed errors and defects.\n *\n * **Details**\n *\n * `Fail` reasons use the `error` schema, `Die` reasons use the `defect` schema,\n * and `Interrupt` reasons carry only an optional fiber id.\n *\n * @see {@link Cause} for constructing schemas for full Cause values\n * @see {@link CauseReasonIso} for the ISO shape of each cause reason\n *\n * @category schemas\n * @since 4.0.0\n */\nexport function CauseReason(error, defect) {\n  const schema = declareConstructor()([error, defect], ([error, defect]) => (input, ast, options) => {\n    if (!Cause_.isReason(input)) {\n      return Effect.fail(new SchemaIssue.InvalidType(ast, input, options));\n    }\n    switch (input._tag) {\n      case \"Fail\":\n        return Effect.mapBothEager(SchemaParser.decodeUnknownEffect(error)(input.error, options), {\n          onSuccess: Cause_.makeFailReason,\n          onFailure: issue => SchemaIssue.makeCompositeAtKey(ast, \"error\", issue, input, options)\n        });\n      case \"Die\":\n        return Effect.mapBothEager(SchemaParser.decodeUnknownEffect(defect)(input.defect, options), {\n          onSuccess: Cause_.makeDieReason,\n          onFailure: issue => SchemaIssue.makeCompositeAtKey(ast, \"defect\", issue, input, options)\n        });\n      case \"Interrupt\":\n        return Effect.succeed(input);\n    }\n  }, {\n    representation: {\n      id: \"effect/schema/CauseReason\",\n      payload: null\n    },\n    toCode: ({\n      typeParameters\n    }) => ({\n      runtime: `Schema.CauseReason(${typeParameters[0].runtime}, ${typeParameters[1].runtime})`,\n      Type: `Cause.Failure<${typeParameters[0].Type}, ${typeParameters[1].Type}>`,\n      importDeclarations: [`import * as Cause from \"effect/Cause\"`]\n    }),\n    expected: \"Cause.Failure\",\n    toCodec: ([error, defect]) => link()(Union([Struct({\n      _tag: Literal(\"Fail\"),\n      error\n    }), Struct({\n      _tag: Literal(\"Die\"),\n      defect\n    }), Struct({\n      _tag: Literal(\"Interrupt\"),\n      fiberId: UndefinedOr(Finite)\n    })]), SchemaTransformation.transform({\n      decode: e => {\n        switch (e._tag) {\n          case \"Fail\":\n            return Cause_.makeFailReason(e.error);\n          case \"Die\":\n            return Cause_.makeDieReason(e.defect);\n          case \"Interrupt\":\n            return Cause_.makeInterruptReason(e.fiberId);\n        }\n      },\n      encode: identity\n    }))\n  });\n  return make(schema.ast, {\n    error,\n    defect\n  });\n}\n/**\n * Creates a schema for `Cause` values using separate schemas for typed failures\n * and unexpected defects.\n *\n * **When to use**\n *\n * Use to validate, transform, or serialize Effect failure causes when typed\n * failures and unexpected defects need separate schemas.\n *\n * **Details**\n *\n * The `error` schema is applied to `Fail` reasons and the `defect` schema is\n * applied to `Die` reasons. Interrupt reasons do not use either schema and\n * carry only an optional fiber id.\n *\n * @see {@link CauseReason} for the schema used by each individual cause reason\n * @see {@link CauseIso} for the ordered array representation used by the schema ISO\n *\n * @category schemas\n * @since 3.10.0\n */\nexport function Cause(error, defect) {\n  const schema = declareConstructor()([error, defect], ([error, defect]) => {\n    const failures = ArraySchema(CauseReason(error, defect));\n    return (input, ast, options) => {\n      if (!Cause_.isCause(input)) {\n        return Effect.fail(new SchemaIssue.InvalidType(ast, input, options));\n      }\n      return Effect.mapBothEager(SchemaParser.decodeUnknownEffect(failures)(input.reasons, options), {\n        onSuccess: Cause_.fromReasons,\n        onFailure: issue => SchemaIssue.makeCompositeAtKey(ast, \"failures\", issue, input, options)\n      });\n    };\n  }, {\n    representation: {\n      id: \"effect/schema/Cause\",\n      payload: null\n    },\n    toCode: ({\n      typeParameters\n    }) => ({\n      runtime: `Schema.Cause(${typeParameters[0].runtime}, ${typeParameters[1].runtime})`,\n      Type: `Cause.Cause<${typeParameters[0].Type}, ${typeParameters[1].Type}>`,\n      importDeclarations: [`import * as Cause from \"effect/Cause\"`]\n    }),\n    expected: \"Cause\",\n    toCodec: ([error, defect]) => link()(ArraySchema(CauseReason(error, defect)), SchemaTransformation.transform({\n      decode: Cause_.fromReasons,\n      encode: ({\n        reasons: failures\n      }) => failures\n    }))\n  });\n  return make(schema.ast, {\n    error,\n    defect\n  });\n}\n// -----------------------------------------------------------------------------\n// Chunk schemas\n// -----------------------------------------------------------------------------\nfunction chunkLink(values) {\n  return link()(values, SchemaTransformation.transform({\n    decode: Chunk_.fromIterable,\n    encode: Arr.fromIterable\n  }));\n}\n/**\n * Schema for chunks whose values conform to the provided element schema.\n *\n * @category schemas\n * @since 3.10.0\n */\nexport function Chunk(value) {\n  const schema = declareConstructor()([value], ([value]) => {\n    const values = ArraySchema(value);\n    return (input, ast, options) => {\n      if (Chunk_.isChunk(input)) {\n        return Effect.mapBothEager(SchemaParser.decodeUnknownEffect(values)(Arr.fromIterable(input), options), {\n          onSuccess: Chunk_.fromIterable,\n          onFailure: issue => SchemaIssue.makeCompositeAtKey(ast, \"values\", issue, input, options)\n        });\n      }\n      return Effect.fail(new SchemaIssue.InvalidType(ast, input, options));\n    };\n  }, {\n    representation: {\n      id: \"effect/schema/Chunk\",\n      payload: null\n    },\n    toCode: ({\n      typeParameters\n    }) => ({\n      runtime: `Schema.Chunk(${typeParameters[0].runtime})`,\n      Type: `Chunk.Chunk<${typeParameters[0].Type}>`\n    }),\n    expected: \"Chunk\",\n    toCodec: ([value]) => chunkLink(ArraySchema(value)),\n    toCodecArbitrary: ({\n      constraint,\n      typeParameters: [value]\n    }) => chunkLink(withArrayLengthConstraints(ArraySchema(value), constraint?.minLength, constraint?.maxLength)),\n    toEquivalence: ([value]) => Chunk_.makeEquivalence(value)\n  });\n  return make(schema.ast, {\n    value\n  });\n}\n// -----------------------------------------------------------------------------\n// DateTime schemas\n// -----------------------------------------------------------------------------\nfunction dateTimeUtcFromInput() {\n  return SchemaGetter.transformEffect((input, options) => {\n    return Option_.match(DateTime.make(input), {\n      onNone: () => Effect.fail(new SchemaIssue.InvalidValue({\n        message: \"Invalid DateTime input\"\n      }, input, options)),\n      onSome: dt => Effect.succeed(DateTime.toUtc(dt))\n    });\n  });\n}\nconst timeZoneOffsetFromNumber = /*#__PURE__*/SchemaTransformation.transform({\n  decode: n => DateTime.zoneMakeOffset(n),\n  encode: tz => tz.offset\n});\nconst timeZoneNamedFromString = /*#__PURE__*/SchemaTransformation.transformEffect({\n  decode: (s, options) => {\n    return Option_.match(DateTime.zoneMakeNamed(s), {\n      onNone: () => Effect.fail(new SchemaIssue.InvalidValue({\n        expected: \"a valid IANA time zone\"\n      }, s, options)),\n      onSome: Effect.succeed\n    });\n  },\n  encode: tz => Effect.succeed(tz.id)\n});\nconst timeZoneFromString = /*#__PURE__*/SchemaTransformation.transformEffect({\n  decode: (s, options) => {\n    return Option_.match(DateTime.zoneFromString(s), {\n      onNone: () => Effect.fail(new SchemaIssue.InvalidValue({\n        expected: \"a valid time zone\"\n      }, s, options)),\n      onSome: Effect.succeed\n    });\n  },\n  encode: tz => Effect.succeed(DateTime.zoneToString(tz))\n});\nconst dateTimeUtcFromString = /*#__PURE__*/SchemaTransformation.transformEffect({\n  decode: (s, options) => {\n    return Option_.match(DateTime.make(s), {\n      onNone: () => Effect.fail(new SchemaIssue.InvalidValue({\n        expected: \"a valid UTC DateTime string\"\n      }, s, options)),\n      onSome: result => Effect.succeed(DateTime.toUtc(result))\n    });\n  },\n  encode: utc => Effect.succeed(DateTime.formatIso(utc))\n});\nconst dateTimeZonedFromString = /*#__PURE__*/SchemaTransformation.transformEffect({\n  decode: (s, options) => {\n    return Option_.match(DateTime.makeZonedFromString(s), {\n      onNone: () => Effect.fail(new SchemaIssue.InvalidValue({\n        expected: \"a valid Zoned DateTime string\"\n      }, s, options)),\n      onSome: Effect.succeed\n    });\n  },\n  encode: zoned => Effect.succeed(DateTime.formatIsoZoned(zoned))\n});\nconst arbitraryMinimumDateTimestamp = -8_640_000_000_000_000;\nconst arbitraryMaximumDateTimestamp = 8_640_000_000_000_000;\nconst arbitraryMinimumZonedDateTimeTimestamp = arbitraryMinimumDateTimestamp + 14 * 60 * 60 * 1000;\nconst arbitraryMaximumZonedDateTimeTimestamp = arbitraryMaximumDateTimestamp - 14 * 60 * 60 * 1000;\nconst arbitraryMinimumTimeZoneOffset = -12 * 60 * 60 * 1000;\nconst arbitraryMaximumTimeZoneOffset = 14 * 60 * 60 * 1000;\nconst arbitraryNamedTimeZones = [\"UTC\", \"Europe/London\", \"America/New_York\", \"Asia/Tokyo\", \"Australia/Sydney\"];\nfunction dateTimeArbitraryBounds(constraint, domainMinimum, domainMaximum) {\n  const minimum = Math.max(domainMinimum, constraint?.minimum === undefined ? domainMinimum : constraint.minimum.epochMilliseconds + (constraint.exclusiveMinimum === true ? 1 : 0));\n  const maximum = Math.min(domainMaximum, constraint?.maximum === undefined ? domainMaximum : constraint.maximum.epochMilliseconds - (constraint.exclusiveMaximum === true ? 1 : 0));\n  return minimum <= maximum ? [minimum, maximum] : [domainMinimum, domainMaximum];\n}\nfunction dateTimeArbitraryInteger(minimum, maximum) {\n  return Int.check(isBetween({\n    minimum,\n    maximum\n  }));\n}\nfunction timeZoneArbitrarySchema() {\n  return Union([dateTimeArbitraryInteger(arbitraryMinimumTimeZoneOffset, arbitraryMaximumTimeZoneOffset), Literals(arbitraryNamedTimeZones)]);\n}\n/**\n * Schema for `DateTime.Utc` values.\n *\n * **When to use**\n *\n * Use to validate existing `DateTime.Utc` schema values and use the default JSON\n * codec that represents them as UTC ISO strings.\n *\n * **Details**\n *\n * The default JSON codec decodes UTC ISO strings into `DateTime.Utc` values and\n * encodes `DateTime.Utc` values as UTC ISO strings.\n *\n * @see {@link DateTimeUtcFromString} for decoding date-time strings into UTC values\n * @see {@link DateTimeUtcFromDate} for decoding JavaScript Date values into UTC values\n * @see {@link DateTimeUtcFromMillis} for decoding epoch milliseconds into UTC values\n * @see {@link DateTimeZoned} for preserving zoned DateTime values\n *\n * @category schemas\n * @since 3.10.0\n */\nexport const DateTimeUtc = /*#__PURE__*/declare(u => DateTime.isDateTime(u) && DateTime.isUtc(u), {\n  representation: {\n    id: \"effect/schema/DateTimeUtc\",\n    payload: null\n  },\n  toCode: () => ({\n    runtime: `Schema.DateTimeUtc`,\n    Type: `DateTime.Utc`,\n    importDeclarations: [`import * as DateTime from \"effect/DateTime\"`]\n  }),\n  expected: \"DateTime.Utc\",\n  toCodecArbitrary: ({\n    constraint\n  }) => {\n    const [minimum, maximum] = dateTimeArbitraryBounds(constraint, arbitraryMinimumDateTimestamp, arbitraryMaximumDateTimestamp);\n    return linkDecoding()(dateTimeArbitraryInteger(minimum, maximum), SchemaGetter.transform(DateTime.makeUnsafe));\n  },\n  toCodecJson: () => link()(String, dateTimeUtcFromString),\n  toFormatter: () => utc => utc.toString()\n});\n/**\n * Schema that decodes a `Date` into a `DateTime.Utc`.\n *\n * **When to use**\n *\n * Use when you need to decode valid JavaScript `Date` objects into\n * `DateTime.Utc` values.\n *\n * **Details**\n *\n * Decoding:\n * - A **valid** `Date` is decoded as a `DateTime.Utc`\n *\n * Encoding:\n * - A `DateTime.Utc` is encoded as a `Date`\n *\n * @see {@link DateTimeUtc} for validating values that are already `DateTime.Utc`\n * @see {@link DateTimeUtcFromString} for decoding date-time strings into UTC values\n * @see {@link DateTimeUtcFromMillis} for decoding epoch milliseconds into UTC values\n * @see {@link Date} for validating Date instances without converting them\n *\n * @category schemas\n * @since 3.12.0\n */\nexport const DateTimeUtcFromDate = /*#__PURE__*/Date.pipe(/*#__PURE__*/decodeTo(DateTimeUtc, {\n  decode: /*#__PURE__*/dateTimeUtcFromInput(),\n  encode: /*#__PURE__*/SchemaGetter.transform(DateTime.toDateUtc)\n}));\n/**\n * Schema that decodes a date-time string into a `DateTime.Utc`.\n *\n * **Details**\n *\n * Decoding:\n *\n * - A string accepted by `DateTime.make` is parsed and normalized to UTC. Strings\n *   without an explicit zone are interpreted as UTC.\n *\n * Encoding:\n *\n * - A `DateTime.Utc` is encoded as a UTC ISO 8601 string.\n *\n * @see {@link DateTimeUtcFromDate} for decoding JavaScript Date values into UTC values\n * @see {@link DateTimeUtcFromMillis} for decoding epoch milliseconds into UTC values\n * @see {@link DateFromString} for decoding strings into JavaScript Date instances\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const DateTimeUtcFromString = /*#__PURE__*/String.annotate({\n  expected: \"a string that will be decoded as a DateTime.Utc\"\n}).pipe(/*#__PURE__*/decodeTo(DateTimeUtc, dateTimeUtcFromString));\n/**\n * Schema that decodes a number into a `DateTime.Utc`.\n *\n * **Details**\n *\n * Decoding:\n * - A number of milliseconds since the Unix epoch is decoded as a `DateTime.Utc`\n *\n * Encoding:\n * - A `DateTime.Utc` is encoded as a number of milliseconds since the Unix epoch.\n *\n * @see {@link DateTimeUtcFromDate} for decoding JavaScript Date values into UTC values\n * @see {@link DateTimeUtcFromString} for decoding date-time strings into UTC values\n * @see {@link DateFromMillis} for decoding epoch milliseconds into JavaScript Date instances\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const DateTimeUtcFromMillis = /*#__PURE__*/Int.pipe(/*#__PURE__*/decodeTo(DateTimeUtc, {\n  decode: /*#__PURE__*/dateTimeUtcFromInput(),\n  encode: /*#__PURE__*/SchemaGetter.transform(DateTime.toEpochMillis)\n}));\n/**\n * Schema for `DateTime.TimeZone.Offset` values.\n *\n * **Details**\n *\n * Default JSON serializer:\n *\n * - encodes `DateTime.TimeZone.Offset` as a number (offset in milliseconds)\n *\n * @category schemas\n * @since 3.10.0\n */\nexport const TimeZoneOffset = /*#__PURE__*/declare(DateTime.isTimeZoneOffset, {\n  representation: {\n    id: \"effect/schema/TimeZoneOffset\",\n    payload: null\n  },\n  toCode: () => ({\n    runtime: `Schema.TimeZoneOffset`,\n    Type: `DateTime.TimeZone.Offset`,\n    importDeclarations: [`import * as DateTime from \"effect/DateTime\"`]\n  }),\n  expected: \"DateTime.TimeZone.Offset\",\n  toCodecJson: () => link()(Int, timeZoneOffsetFromNumber),\n  toFormatter: () => tz => DateTime.zoneToString(tz)\n});\nconst TimeZoneNamedString = /*#__PURE__*/String.annotate({\n  expected: \"an IANA time zone identifier\"\n});\n/**\n * Schema for `DateTime.TimeZone.Named` values.\n *\n * **Details**\n *\n * Default JSON serializer:\n *\n * - encodes `DateTime.TimeZone.Named` as a string (IANA time zone identifier)\n *\n * @category schemas\n * @since 3.10.0\n */\nexport const TimeZoneNamed = /*#__PURE__*/declare(DateTime.isTimeZoneNamed, {\n  representation: {\n    id: \"effect/schema/TimeZoneNamed\",\n    payload: null\n  },\n  toCode: () => ({\n    runtime: `Schema.TimeZoneNamed`,\n    Type: `DateTime.TimeZone.Named`,\n    importDeclarations: [`import * as DateTime from \"effect/DateTime\"`]\n  }),\n  expected: \"DateTime.TimeZone.Named\",\n  toCodecArbitrary: () => linkDecoding()(Literals(arbitraryNamedTimeZones), SchemaGetter.transform(DateTime.zoneMakeNamedUnsafe)),\n  toCodecJson: () => link()(TimeZoneNamedString, timeZoneNamedFromString),\n  toFormatter: () => tz => DateTime.zoneToString(tz)\n});\n/**\n * Schema that parses an IANA time zone identifier string into a `DateTime.TimeZone.Named`.\n *\n * **Details**\n *\n * Decoding:\n * - A `string` is decoded as a `DateTime.TimeZone.Named`.\n *\n * Encoding:\n * - A `DateTime.TimeZone.Named` is encoded as a `string`.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const TimeZoneNamedFromString = /*#__PURE__*/TimeZoneNamedString.pipe(/*#__PURE__*/decodeTo(TimeZoneNamed, timeZoneNamedFromString));\nconst TimeZoneString = /*#__PURE__*/String.annotate({\n  expected: \"a time zone string (IANA identifier or offset like +03:00)\"\n});\n/**\n * Schema for `DateTime.TimeZone` values.\n *\n * **Details**\n *\n * Default JSON serializer:\n *\n * - encodes `DateTime.TimeZone` as a string (IANA identifier or offset like\n *   `+03:00`)\n *\n * @category schemas\n * @since 3.10.0\n */\nexport const TimeZone = /*#__PURE__*/declare(DateTime.isTimeZone, {\n  representation: {\n    id: \"effect/schema/TimeZone\",\n    payload: null\n  },\n  toCode: () => ({\n    runtime: `Schema.TimeZone`,\n    Type: `DateTime.TimeZone`,\n    importDeclarations: [`import * as DateTime from \"effect/DateTime\"`]\n  }),\n  expected: \"DateTime.TimeZone\",\n  toCodecArbitrary: () => linkDecoding()(timeZoneArbitrarySchema(), SchemaGetter.transform(value => typeof value === \"number\" ? DateTime.zoneMakeOffset(value) : DateTime.zoneMakeNamedUnsafe(value))),\n  toCodecJson: () => link()(TimeZoneString, timeZoneFromString),\n  toFormatter: () => tz => DateTime.zoneToString(tz)\n});\n/**\n * Schema that parses a time zone string into a `DateTime.TimeZone`.\n *\n * **Details**\n *\n * Decoding:\n * - A `string` (IANA identifier or offset like `+03:00`) is decoded as a `DateTime.TimeZone`.\n *\n * Encoding:\n * - A `DateTime.TimeZone` is encoded as a `string`.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const TimeZoneFromString = /*#__PURE__*/TimeZoneString.pipe(/*#__PURE__*/decodeTo(TimeZone, timeZoneFromString));\nconst DateTimeZonedString = /*#__PURE__*/String.annotate({\n  expected: \"a zoned DateTime string (e.g. 2024-01-01T00:00:00.000+00:00[Europe/London])\"\n});\n/**\n * Schema for `DateTime.Zoned` values.\n *\n * **Details**\n *\n * Default JSON serializer:\n *\n * - encodes offset zones as an ISO date-time with a numeric offset, such as\n *   `YYYY-MM-DDTHH:mm:ss.sss+HH:MM`\n * - encodes named zones by appending the IANA identifier in brackets, such as\n *   `YYYY-MM-DDTHH:mm:ss.sss+HH:MM[Time/Zone]`\n *\n * @category schemas\n * @since 3.10.0\n */\nexport const DateTimeZoned = /*#__PURE__*/declare(u => DateTime.isDateTime(u) && DateTime.isZoned(u), {\n  representation: {\n    id: \"effect/schema/DateTimeZoned\",\n    payload: null\n  },\n  toCode: () => ({\n    runtime: `Schema.DateTimeZoned`,\n    Type: `DateTime.Zoned`,\n    importDeclarations: [`import * as DateTime from \"effect/DateTime\"`]\n  }),\n  expected: \"DateTime.Zoned\",\n  toCodecArbitrary: ({\n    constraint\n  }) => {\n    const [minimum, maximum] = dateTimeArbitraryBounds(constraint, arbitraryMinimumZonedDateTimeTimestamp, arbitraryMaximumZonedDateTimeTimestamp);\n    return linkDecoding()(Struct({\n      epochMilliseconds: dateTimeArbitraryInteger(minimum, maximum),\n      timeZone: timeZoneArbitrarySchema()\n    }), SchemaGetter.transform(({\n      epochMilliseconds,\n      timeZone\n    }) => DateTime.makeZonedUnsafe(epochMilliseconds, {\n      timeZone\n    })));\n  },\n  toCodecJson: () => link()(DateTimeZonedString, dateTimeZonedFromString),\n  toFormatter: () => zoned => DateTime.formatIsoZoned(zoned),\n  toEquivalence: () => DateTime.Equivalence\n});\n/**\n * Schema that parses a zoned DateTime string into a `DateTime.Zoned`.\n *\n * **Details**\n *\n * Decoding:\n * - A `string` (e.g. `2024-01-01T00:00:00.000+00:00[Europe/London]`) is decoded as a `DateTime.Zoned`.\n *\n * Encoding:\n * - A `DateTime.Zoned` is encoded as a `string`.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const DateTimeZonedFromString = /*#__PURE__*/DateTimeZonedString.pipe(/*#__PURE__*/decodeTo(DateTimeZoned, dateTimeZonedFromString));\nconst netAddressFromString = (declaration, parse, encode, identifier) => String.pipe(decodeTo(declaration, SchemaTransformation.transformEffect({\n  decode: (input, options) => {\n    const result = parse(input);\n    return Result_.isSuccess(result) ? Effect.succeed(result.success) : Effect.fail(new SchemaIssue.InvalidValue({\n      message: result.failure.message\n    }, input, options));\n  },\n  encode: value => Effect.succeed(encode(value))\n}))).annotate({\n  identifier\n});\n/**\n * Schema for already-constructed MAC address values.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const MacAddress = /*#__PURE__*/declare(NetAddress_.isMacAddress, {\n  identifier: \"MacAddress\"\n});\n/**\n * Schema for MAC addresses encoded as canonical colon-separated hexadecimal strings.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const MacAddressFromString = /*#__PURE__*/netAddressFromString(MacAddress, NetAddress_.macAddressFromString, NetAddress_.formatMacAddress, \"MacAddressFromString\");\n/**\n * Schema for already-constructed IPv4 address values.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const Ipv4Address = /*#__PURE__*/declare(NetAddress_.isIpv4Address, {\n  identifier: \"Ipv4Address\"\n});\n/**\n * Schema for IPv4 addresses encoded as canonical dotted-decimal strings.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const Ipv4AddressFromString = /*#__PURE__*/netAddressFromString(Ipv4Address, NetAddress_.ipv4FromString, NetAddress_.formatIp, \"Ipv4AddressFromString\");\n/**\n * Schema for already-constructed IPv6 address values.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const Ipv6Address = /*#__PURE__*/declare(NetAddress_.isIpv6Address, {\n  identifier: \"Ipv6Address\"\n});\n/**\n * Schema for IPv6 addresses encoded as canonical strings.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const Ipv6AddressFromString = /*#__PURE__*/netAddressFromString(Ipv6Address, NetAddress_.ipv6FromString, NetAddress_.formatIp, \"Ipv6AddressFromString\");\n/**\n * Schema for already-constructed IPv4 or IPv6 address values.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const IpAddress = /*#__PURE__*/declare(NetAddress_.isIpAddress, {\n  identifier: \"IpAddress\"\n});\n/**\n * Schema for IP addresses encoded as canonical numeric strings.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const IpAddressFromString = /*#__PURE__*/netAddressFromString(IpAddress, NetAddress_.ipFromString, NetAddress_.formatIp, \"IpAddressFromString\");\n/**\n * Schema for already-constructed IPv4 interface address values.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const Ipv4Interface = /*#__PURE__*/declare(IpInterface_.isIpv4Interface, {\n  identifier: \"Ipv4Interface\"\n});\n/**\n * Schema for IPv4 interface addresses encoded as an address and prefix length.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const Ipv4InterfaceFromString = /*#__PURE__*/netAddressFromString(Ipv4Interface, IpInterface_.ipv4FromString, IpInterface_.format, \"Ipv4InterfaceFromString\");\n/**\n * Schema for already-constructed IPv6 interface address values.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const Ipv6Interface = /*#__PURE__*/declare(IpInterface_.isIpv6Interface, {\n  identifier: \"Ipv6Interface\"\n});\n/**\n * Schema for IPv6 interface addresses encoded as an address and prefix length.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const Ipv6InterfaceFromString = /*#__PURE__*/netAddressFromString(Ipv6Interface, IpInterface_.ipv6FromString, IpInterface_.format, \"Ipv6InterfaceFromString\");\n/**\n * Schema for already-constructed IPv4 or IPv6 interface address values.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const IpInterface = /*#__PURE__*/declare(IpInterface_.isIpInterface, {\n  identifier: \"IpInterface\"\n});\n/**\n * Schema for IPv4 or IPv6 interface addresses encoded as an address and prefix length.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const IpInterfaceFromString = /*#__PURE__*/netAddressFromString(IpInterface, IpInterface_.fromString, IpInterface_.format, \"IpInterfaceFromString\");\n/**\n * Schema for already-constructed canonical IPv4 network prefixes.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const Ipv4Network = /*#__PURE__*/declare(IpNetwork_.isIpv4Network, {\n  identifier: \"Ipv4Network\"\n});\n/**\n * Schema for canonical IPv4 network prefixes encoded in CIDR notation.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const Ipv4NetworkFromString = /*#__PURE__*/netAddressFromString(Ipv4Network, IpNetwork_.ipv4FromString, IpNetwork_.format, \"Ipv4NetworkFromString\");\n/**\n * Schema for already-constructed canonical IPv6 network prefixes.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const Ipv6Network = /*#__PURE__*/declare(IpNetwork_.isIpv6Network, {\n  identifier: \"Ipv6Network\"\n});\n/**\n * Schema for canonical IPv6 network prefixes encoded in CIDR notation.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const Ipv6NetworkFromString = /*#__PURE__*/netAddressFromString(Ipv6Network, IpNetwork_.ipv6FromString, IpNetwork_.format, \"Ipv6NetworkFromString\");\n/**\n * Schema for already-constructed canonical IPv4 or IPv6 network prefixes.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const IpNetwork = /*#__PURE__*/declare(IpNetwork_.isIpNetwork, {\n  identifier: \"IpNetwork\"\n});\n/**\n * Schema for canonical IPv4 or IPv6 network prefixes encoded in CIDR notation.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const IpNetworkFromString = /*#__PURE__*/netAddressFromString(IpNetwork, IpNetwork_.fromString, IpNetwork_.format, \"IpNetworkFromString\");\n/**\n * Schema for already-constructed resolved IPv4 internet addresses.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const InetAddressV4 = /*#__PURE__*/declare(NetAddress_.isInetAddressV4, {\n  identifier: \"InetAddressV4\"\n});\n/**\n * Schema for already-constructed resolved IPv6 internet addresses.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const InetAddressV6 = /*#__PURE__*/declare(NetAddress_.isInetAddressV6, {\n  identifier: \"InetAddressV6\"\n});\n/**\n * Schema for already-constructed resolved internet addresses.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const InetAddress = /*#__PURE__*/declare(NetAddress_.isInetAddress, {\n  identifier: \"InetAddress\"\n});\n/**\n * Schema for resolved internet addresses encoded as numeric socket strings.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const InetAddressFromString = /*#__PURE__*/netAddressFromString(InetAddress, NetAddress_.inetAddressFromString, NetAddress_.formatInet, \"InetAddressFromString\");\n/**\n * Schema for already-constructed Unix-domain filesystem addresses.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const UnixPathAddress = /*#__PURE__*/declare(NetAddress_.isUnixPathAddress, {\n  identifier: \"UnixPathAddress\"\n});\n/**\n * Schema for Unix-domain filesystem addresses encoded as opaque path strings.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const UnixPathAddressFromString = /*#__PURE__*/String.pipe(decodeTo(UnixPathAddress, SchemaTransformation.transform({\n  decode: NetAddress_.unixPathAddress,\n  encode: address => address.path\n}))).annotate({\n  identifier: \"UnixPathAddressFromString\"\n});\n/**\n * Schema for already-constructed portable concrete socket addresses.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const SocketAddress = /*#__PURE__*/declare(NetAddress_.isSocketAddress, {\n  identifier: \"SocketAddress\"\n});\n// -----------------------------------------------------------------------------\n// Duration schemas\n// -----------------------------------------------------------------------------\nconst durationFromString = /*#__PURE__*/SchemaTransformation.transformEffect({\n  decode: (s, options) => Option_.match(Duration_.fromInput(s), {\n    onNone: () => Effect.fail(new SchemaIssue.InvalidValue({\n      expected: \"a valid Duration string\"\n    }, s, options)),\n    onSome: Effect.succeed\n  }),\n  encode: duration => Effect.succeed(globalThis.String(duration))\n});\nconst durationFromNanos = /*#__PURE__*/SchemaTransformation.transformEffect({\n  decode: i => Effect.succeed(Duration_.nanos(i)),\n  encode: (a, options) => Option_.match(Duration_.toNanos(a), {\n    onNone: () => Effect.fail(new SchemaIssue.InvalidValue({\n      expected: \"a Duration representable as a bigint\"\n    }, a, options)),\n    onSome: nanos => Effect.succeed(nanos)\n  })\n});\nconst durationFromMillis = /*#__PURE__*/SchemaTransformation.transform({\n  decode: i => Duration_.millis(i),\n  encode: a => Duration_.toMillis(a)\n});\n/**\n * Schema for `Duration` values.\n *\n * **Details**\n *\n * The default JSON serializer encodes `Duration` as a tagged object with the\n * duration type and value.\n *\n * **Example** (Defining a Duration schema)\n *\n * ```ts import.meta.vitest\n * import { Duration, Schema } from \"effect\"\n *\n * Schema.decodeUnknownSync(Schema.Duration)(Duration.seconds(5)) // => Duration.seconds(5)\n * ```\n *\n * @category schemas\n *\n * @since 3.10.0\n */\nexport const Duration = /*#__PURE__*/declare(Duration_.isDuration, {\n  representation: {\n    id: \"effect/schema/Duration\",\n    payload: null\n  },\n  toCode: () => ({\n    runtime: `Schema.Duration`,\n    Type: `Duration.Duration`,\n    importDeclarations: [`import * as Duration from \"effect/Duration\"`]\n  }),\n  expected: \"Duration\",\n  toCodecJson: () => link()(Union([Struct({\n    _tag: Literal(\"Infinity\")\n  }), Struct({\n    _tag: Literal(\"NegativeInfinity\")\n  }), Struct({\n    _tag: Literal(\"Nanos\"),\n    value: BigInt\n  }), Struct({\n    _tag: Literal(\"Millis\"),\n    value: Int\n  })]), SchemaTransformation.transform({\n    decode: e => {\n      switch (e._tag) {\n        case \"Infinity\":\n          return Duration_.infinity;\n        case \"NegativeInfinity\":\n          return Duration_.negativeInfinity;\n        case \"Nanos\":\n          return Duration_.nanos(e.value);\n        case \"Millis\":\n          return Duration_.millis(e.value);\n      }\n    },\n    encode: duration => {\n      switch (duration.value._tag) {\n        case \"Infinity\":\n          return {\n            _tag: \"Infinity\"\n          };\n        case \"NegativeInfinity\":\n          return {\n            _tag: \"NegativeInfinity\"\n          };\n        case \"Nanos\":\n          return {\n            _tag: \"Nanos\",\n            value: duration.value.nanos\n          };\n        case \"Millis\":\n          return {\n            _tag: \"Millis\",\n            value: duration.value.millis\n          };\n      }\n    }\n  }))\n});\nconst DurationString = /*#__PURE__*/String.annotate({\n  expected: \"a string that will be decoded as a Duration\"\n});\n/**\n * Schema that parses a string into a `Duration`.\n *\n * **Details**\n *\n * Decoding:\n * - A `string` is decoded as a `Duration`, accepting any format that\n *   `Duration.fromInput` can parse.\n *\n * Encoding:\n * - A `Duration` is encoded as a parseable `string`.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const DurationFromString = /*#__PURE__*/DurationString.pipe(/*#__PURE__*/decodeTo(Duration, durationFromString));\n/**\n * Schema that decodes a `bigint` into a `Duration`, treating the bigint as\n * nanoseconds.\n *\n * **Details**\n *\n * Decoding:\n * A `bigint` representing nanoseconds is decoded as a `Duration`.\n *\n * Encoding:\n * Finite durations are encoded as a `bigint` number of nanoseconds. Encoding\n * fails when the duration cannot be represented as nanoseconds, such as\n * `Duration.infinity` or `Duration.negativeInfinity`.\n *\n * @category schemas\n * @since 3.10.0\n */\nexport const DurationFromNanos = /*#__PURE__*/BigInt.pipe(/*#__PURE__*/decodeTo(Duration, durationFromNanos));\n/**\n * Schema that decodes a number into a `Duration`, treating the number as\n * milliseconds.\n *\n * **Details**\n *\n * Decoding:\n * - A finite or infinite number is decoded as a `Duration`\n *\n * Encoding:\n * - A `Duration` is encoded to a finite or infinite number of milliseconds\n *\n * **Gotchas**\n *\n * `NaN` is decoded as `Duration.zero`, matching `Duration.millis`.\n *\n * @category schemas\n * @since 3.10.0\n */\nexport const DurationFromMillis = /*#__PURE__*/Number.pipe(/*#__PURE__*/decodeTo(Duration, durationFromMillis));\n/**\n * Creates a schema for `Exit` values using schemas for the success value, typed\n * failure, and unexpected defect channels.\n *\n * **When to use**\n *\n * Use when serializing or validating an effect outcome where success, typed\n * failure, and defects each need their own schema.\n *\n * @category schemas\n * @since 3.10.0\n */\nexport function Exit(value, error, defect) {\n  const schema = declareConstructor()([value, error, defect], ([value, error, defect]) => {\n    const cause = Cause(error, defect);\n    return (input, ast, options) => {\n      if (!Exit_.isExit(input)) {\n        return Effect.fail(new SchemaIssue.InvalidType(ast, input, options));\n      }\n      switch (input._tag) {\n        case \"Success\":\n          return Effect.mapBothEager(SchemaParser.decodeUnknownEffect(value)(input.value, options), {\n            onSuccess: Exit_.succeed,\n            onFailure: issue => SchemaIssue.makeCompositeAtKey(ast, \"value\", issue, input, options)\n          });\n        case \"Failure\":\n          return Effect.mapBothEager(SchemaParser.decodeUnknownEffect(cause)(input.cause, options), {\n            onSuccess: Exit_.failCause,\n            onFailure: issue => SchemaIssue.makeCompositeAtKey(ast, \"cause\", issue, input, options)\n          });\n      }\n    };\n  }, {\n    representation: {\n      id: \"effect/schema/Exit\",\n      payload: null\n    },\n    toCode: ({\n      typeParameters\n    }) => ({\n      runtime: `Schema.Exit(${typeParameters[0].runtime}, ${typeParameters[1].runtime}, ${typeParameters[2].runtime})`,\n      Type: `Exit.Exit<${typeParameters[0].Type}, ${typeParameters[1].Type}, ${typeParameters[2].Type}>`,\n      importDeclarations: [`import * as Exit from \"effect/Exit\"`]\n    }),\n    expected: \"Exit\",\n    toCodec: ([value, error, defect]) => link()(Union([Struct({\n      _tag: Literal(\"Success\"),\n      value\n    }), Struct({\n      _tag: Literal(\"Failure\"),\n      cause: Cause(error, defect)\n    })]), SchemaTransformation.transform({\n      decode: e => e._tag === \"Success\" ? Exit_.succeed(e.value) : Exit_.failCause(e.cause),\n      encode: exit => Exit_.isSuccess(exit) ? {\n        _tag: \"Success\",\n        value: exit.value\n      } : {\n        _tag: \"Failure\",\n        cause: exit.cause\n      }\n    }))\n  });\n  return make(schema.ast, {\n    value,\n    error,\n    defect\n  });\n}\nfunction graphEncodedSchema(type, node, edge) {\n  return Struct({\n    type: Literal(type),\n    nodes: ArraySchema(Struct({\n      index: Natural,\n      data: node\n    })),\n    edges: ArraySchema(Struct({\n      index: Natural,\n      source: Natural,\n      target: Natural,\n      data: edge\n    }))\n  });\n}\nfunction graphDecode(input, options) {\n  let previous = -1;\n  const indexes = new Set();\n  for (let i = 0; i < input.nodes.length; i++) {\n    const index = input.nodes[i].index;\n    if (index <= previous) {\n      return Effect.fail(new SchemaIssue.Pointer([\"nodes\", i, \"index\"], new SchemaIssue.InvalidValue({\n        expected: \"a strictly increasing node index\"\n      }, index, options)));\n    }\n    previous = index;\n    indexes.add(index);\n  }\n  previous = -1;\n  for (let i = 0; i < input.edges.length; i++) {\n    const edge = input.edges[i];\n    if (edge.index <= previous) {\n      return Effect.fail(new SchemaIssue.Pointer([\"edges\", i, \"index\"], new SchemaIssue.InvalidValue({\n        expected: \"a strictly increasing edge index\"\n      }, edge.index, options)));\n    }\n    previous = edge.index;\n    if (!indexes.has(edge.source)) {\n      return Effect.fail(new SchemaIssue.Pointer([\"edges\", i, \"source\"], new SchemaIssue.InvalidValue({\n        expected: \"an encoded node index\"\n      }, edge.source, options)));\n    }\n    if (!indexes.has(edge.target)) {\n      return Effect.fail(new SchemaIssue.Pointer([\"edges\", i, \"target\"], new SchemaIssue.InvalidValue({\n        expected: \"an encoded node index\"\n      }, edge.target, options)));\n    }\n  }\n  return Effect.succeed(InternalGraph.hydrate(input));\n}\nfunction graphEncode(input, type, options) {\n  if (!InternalGraph.isGraph(input) || input.mutable || input.type !== type) {\n    return Effect.fail(new SchemaIssue.InvalidValue({\n      expected: `an immutable ${type} Graph`\n    }, input, options));\n  }\n  return Effect.succeed(InternalGraph.snapshot(input));\n}\nfunction graphToEquivalence(node, edge) {\n  return (self, that) => {\n    const a = InternalGraph.snapshot(self);\n    const b = InternalGraph.snapshot(that);\n    if (a.type !== b.type || a.nodes.length !== b.nodes.length || a.edges.length !== b.edges.length) return false;\n    for (let i = 0; i < a.nodes.length; i++) {\n      if (a.nodes[i].index !== b.nodes[i].index || !node(a.nodes[i].data, b.nodes[i].data)) return false;\n    }\n    for (let i = 0; i < a.edges.length; i++) {\n      const ae = a.edges[i];\n      const be = b.edges[i];\n      const sameEndpoints = a.type === \"directed\" ? ae.source === be.source && ae.target === be.target : ae.source === be.source && ae.target === be.target || ae.source === be.target && ae.target === be.source;\n      if (ae.index !== be.index || !sameEndpoints || !edge(ae.data, be.data)) return false;\n    }\n    return true;\n  };\n}\nfunction graphToArbitrary(type, node, edge) {\n  return linkDecoding()(Union([Null, Struct({\n    nodes: NonEmptyArray(node),\n    edges: ArraySchema(Tuple([Natural, Natural, edge]))\n  })]), SchemaGetter.transform(input => {\n    if (input === null) return InternalGraph.hydrate({\n      type,\n      nodes: [],\n      edges: []\n    });\n    const nodes = input.nodes.map((data, index) => ({\n      index,\n      data\n    }));\n    return InternalGraph.hydrate({\n      type,\n      nodes,\n      edges: input.edges.map(([source, target, data], index) => ({\n        index,\n        source: source % nodes.length,\n        target: target % nodes.length,\n        data\n      }))\n    });\n  }));\n}\nexport function Graph(type, node, edge) {\n  const schema = declareConstructor()([node, edge], ([node, edge]) => {\n    const encoded = graphEncodedSchema(type, node, edge);\n    return (input, ast, options) => {\n      if (!InternalGraph.isGraph(input) || input.mutable || input.type !== type) {\n        return Effect.fail(new SchemaIssue.InvalidType(ast, input, options));\n      }\n      return Effect.flatMap(SchemaParser.decodeUnknownEffect(encoded)(InternalGraph.snapshot(input), options), snapshot => graphDecode(snapshot, options));\n    };\n  }, {\n    representation: {\n      id: \"effect/schema/Graph\",\n      payload: type\n    },\n    toCode: ({\n      typeParameters\n    }) => ({\n      runtime: `Schema.Graph(${format(type)}, ${typeParameters[0].runtime}, ${typeParameters[1].runtime})`,\n      Type: `Graph.Graph<${typeParameters[0].Type}, ${typeParameters[1].Type}, ${format(type)}>`,\n      importDeclarations: [`import * as Graph from \"effect/Graph\"`]\n    }),\n    expected: `an immutable ${type} Graph`,\n    toCodec: ([node, edge]) => link()(graphEncodedSchema(type, node, edge), SchemaTransformation.transformEffect({\n      decode: graphDecode,\n      encode: (graph, options) => graphEncode(graph, type, options)\n    })),\n    toCodecArbitrary: ({\n      typeParameters: [node, edge]\n    }) => graphToArbitrary(type, node, edge),\n    toEquivalence: ([node, edge]) => graphToEquivalence(node, edge)\n  });\n  return make(schema.ast, {\n    type,\n    node,\n    edge\n  });\n}\n// -----------------------------------------------------------------------------\n// HashMap schemas\n// -----------------------------------------------------------------------------\nfunction hashMapLink(entries) {\n  return link()(entries, SchemaTransformation.transform({\n    decode: HashMap_.fromIterable,\n    encode: HashMap_.toEntries\n  }));\n}\n/**\n * Schema for hash maps whose keys and values conform to the provided schemas.\n *\n * @category schemas\n * @since 3.10.0\n */\nexport function HashMap(key, value) {\n  const schema = declareConstructor()([key, value], ([key, value]) => {\n    const entries = ArraySchema(Tuple([key, value]));\n    return (input, ast, options) => {\n      if (HashMap_.isHashMap(input)) {\n        return Effect.mapBothEager(SchemaParser.decodeUnknownEffect(entries)(HashMap_.toEntries(input), options), {\n          onSuccess: HashMap_.fromIterable,\n          onFailure: issue => SchemaIssue.makeCompositeAtKey(ast, \"entries\", issue, input, options)\n        });\n      }\n      return Effect.fail(new SchemaIssue.InvalidType(ast, input, options));\n    };\n  }, {\n    representation: {\n      id: \"effect/schema/HashMap\",\n      payload: null\n    },\n    toCode: ({\n      typeParameters\n    }) => ({\n      runtime: `Schema.HashMap(${typeParameters[0].runtime}, ${typeParameters[1].runtime})`,\n      Type: `HashMap.HashMap<${typeParameters[0].Type}, ${typeParameters[1].Type}>`,\n      importDeclarations: [`import * as HashMap from \"effect/HashMap\"`]\n    }),\n    expected: \"HashMap\",\n    toCodec: ([key, value]) => hashMapLink(ArraySchema(Tuple([key, value]))),\n    toCodecArbitrary: ({\n      constraint,\n      typeParameters: [key, value]\n    }) => hashMapLink(withArrayLengthConstraints(ArraySchema(Tuple([key, value])).check(isUniqueKey()), constraint?.minSize, constraint?.maxSize)),\n    toEquivalence: ([key, value]) => Equal.makeCompareMap(key, value)\n  });\n  return make(schema.ast, {\n    key,\n    value\n  });\n}\n// -----------------------------------------------------------------------------\n// HashSet schemas\n// -----------------------------------------------------------------------------\nfunction hashSetLink(values) {\n  return link()(values, SchemaTransformation.transform({\n    decode: HashSet_.fromIterable,\n    encode: Arr.fromIterable\n  }));\n}\n/**\n * Schema for hash sets whose values conform to the provided element schema.\n *\n * @category schemas\n * @since 3.10.0\n */\nexport function HashSet(value) {\n  const schema = declareConstructor()([value], ([value]) => {\n    const values = ArraySchema(value);\n    return (input, ast, options) => {\n      if (HashSet_.isHashSet(input)) {\n        return Effect.mapBothEager(SchemaParser.decodeUnknownEffect(values)(Arr.fromIterable(input), options), {\n          onSuccess: HashSet_.fromIterable,\n          onFailure: issue => SchemaIssue.makeCompositeAtKey(ast, \"values\", issue, input, options)\n        });\n      }\n      return Effect.fail(new SchemaIssue.InvalidType(ast, input, options));\n    };\n  }, {\n    representation: {\n      id: \"effect/schema/HashSet\",\n      payload: null\n    },\n    toCode: ({\n      typeParameters\n    }) => ({\n      runtime: `Schema.HashSet(${typeParameters[0].runtime})`,\n      Type: `HashSet.HashSet<${typeParameters[0].Type}>`\n    }),\n    expected: \"HashSet\",\n    toCodec: ([value]) => hashSetLink(ArraySchema(value)),\n    toCodecArbitrary: ({\n      constraint,\n      typeParameters: [value]\n    }) => hashSetLink(withArrayLengthConstraints(ArraySchema(value).check(isUnique()), constraint?.minSize, constraint?.maxSize)),\n    toEquivalence: ([value]) => Equal.makeCompareSet(value)\n  });\n  return make(schema.ast, {\n    value\n  });\n}\n/**\n * Schema for `Option<A>` values.\n *\n * @category schemas\n * @since 3.10.0\n */\nexport function Option(value) {\n  const schema = declareConstructor()([value], ([value]) => (input, ast, options) => {\n    if (Option_.isOption(input)) {\n      if (Option_.isNone(input)) {\n        return Effect.succeedNone;\n      }\n      return Effect.mapBothEager(SchemaParser.decodeUnknownEffect(value)(input.value, options), {\n        onSuccess: Option_.some,\n        onFailure: issue => SchemaIssue.makeCompositeAtKey(ast, \"value\", issue, input, options)\n      });\n    }\n    return Effect.fail(new SchemaIssue.InvalidType(ast, input, options));\n  }, {\n    representation: {\n      id: \"effect/schema/Option\",\n      payload: null\n    },\n    toCode: ({\n      typeParameters\n    }) => ({\n      runtime: `Schema.Option(${typeParameters[0].runtime})`,\n      Type: `Option.Option<${typeParameters[0].Type}>`,\n      importDeclarations: [`import * as Option from \"effect/Option\"`]\n    }),\n    expected: \"Option\",\n    toCodec: ([value]) => link()(Union([Struct({\n      _tag: Literal(\"Some\"),\n      value\n    }), Struct({\n      _tag: Literal(\"None\")\n    })]), SchemaTransformation.transform({\n      decode: e => e._tag === \"None\" ? Option_.none() : Option_.some(e.value),\n      encode: o => Option_.isSome(o) ? {\n        _tag: \"Some\",\n        value: o.value\n      } : {\n        _tag: \"None\"\n      }\n    }))\n  });\n  return make(schema.ast, {\n    value\n  });\n}\n/**\n * Decodes a nullable, required value `T` to a required `Option<T>` value.\n *\n * **Details**\n *\n * Decoding maps `null` to `None` and all other values to `Some`. Encoding maps\n * `None` to `null` and maps `Some` to its value.\n *\n * @category schemas\n * @since 3.10.0\n */\nexport function OptionFromNullOr(schema) {\n  return NullOr(schema).pipe(decodeTo(Option(toType(schema)), SchemaTransformation.optionFromNullOr()));\n}\n/**\n * Decodes a required value that may be `undefined` to a required `Option<T>`\n * value.\n *\n * **Details**\n *\n * Decoding maps `undefined` to `None` and all other values to `Some`. Encoding\n * maps `None` to `undefined` and maps `Some` to its value.\n *\n * @category schemas\n * @since 3.10.0\n */\nexport function OptionFromUndefinedOr(schema) {\n  return UndefinedOr(schema).pipe(decodeTo(Option(toType(schema)), SchemaTransformation.optionFromUndefinedOr()));\n}\n/**\n * Decodes a nullish value `T` to a required `Option<T>` value.\n *\n * **Details**\n *\n * Decoding maps `null` and `undefined` to `None` and all other values to\n * `Some`. Encoding maps `None` to `null` or `undefined` depending on\n * `options.onNoneEncoding`, which defaults to `undefined`, and maps `Some` to\n * its value.\n *\n * @category schemas\n * @since 3.10.0\n */\nexport function OptionFromNullishOr(schema, options) {\n  return NullishOr(schema).pipe(decodeTo(Option(toType(schema)), SchemaTransformation.optionFromNullishOr(options)));\n}\n/**\n * Schema for HTTP cookie values.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const Cookie = /*#__PURE__*/declare(Cookies_.isCookie, {\n  representation: {\n    id: \"effect/http/Cookie\",\n    payload: null\n  },\n  toCode: () => ({\n    runtime: \"Schema.Cookie\",\n    Type: \"Cookies.Cookie\",\n    importDeclarations: [`import * as Cookies from \"effect/unstable/http/Cookies\"`]\n  }),\n  expected: \"Cookie\"\n});\n/**\n * Schema for HTTP cookie collections.\n *\n * **Details**\n *\n * JSON encoding uses `Set-Cookie` header strings, while isomorphic encoding uses\n * a readonly record of cookie values.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const Cookies = /*#__PURE__*/declare(Cookies_.isCookies, {\n  representation: {\n    id: \"effect/http/Cookies\",\n    payload: null\n  },\n  toCode: () => ({\n    runtime: \"Schema.Cookies\",\n    Type: \"Cookies.Cookies\",\n    importDeclarations: [`import * as Cookies from \"effect/unstable/http/Cookies\"`]\n  }),\n  expected: \"Cookies\",\n  toCodecJson: () => link()(ArraySchema(String), SchemaTransformation.transform({\n    decode: Cookies_.fromSetCookie,\n    encode: Cookies_.toSetCookieHeaders\n  })),\n  toCodecIso: () => link()(Record(String, Cookie), SchemaTransformation.transform({\n    decode: Cookies_.fromReadonlyRecord,\n    encode: cookies => cookies.cookies\n  }))\n});\n/**\n * Schema that decodes HTTP cookies into a record of decoded string values keyed\n * by cookie name.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const RecordFromCookies = /*#__PURE__*/Cookies.pipe(/*#__PURE__*/decodeTo(/*#__PURE__*/Record(String, String), /*#__PURE__*/SchemaTransformation.transform({\n  decode: Cookies_.toRecord,\n  encode: self => Cookies_.fromIterable(globalThis.Object.entries(self).map(([name, value]) => Cookies_.makeCookieUnsafe(name, value)))\n})));\n/**\n * Schema for HTTP headers encoded as records of string values.\n *\n * **Details**\n *\n * Decoding normalizes header names; encoding returns a plain record.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const Headers = /*#__PURE__*/declare(Headers_.isHeaders, {\n  representation: {\n    id: \"effect/http/Headers\",\n    payload: null\n  },\n  toCode: () => ({\n    runtime: \"Schema.Headers\",\n    Type: \"Headers.Headers\",\n    importDeclarations: [`import * as Headers from \"effect/unstable/http/Headers\"`]\n  }),\n  expected: \"Headers\",\n  toEquivalence: () => Headers_.Equivalence,\n  toCodec: () => link()(Record(String, String), SchemaTransformation.transform({\n    decode: Headers_.fromInput,\n    encode: headers => ({\n      ...headers\n    })\n  }))\n});\n/**\n * Schema for HTTP URL parameters.\n *\n * **Details**\n *\n * The encoded representation is an array of string key-value tuples.\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const UrlParams = /*#__PURE__*/declare(UrlParams_.isUrlParams, {\n  representation: {\n    id: \"effect/http/UrlParams\",\n    payload: null\n  },\n  toCode: () => ({\n    runtime: \"Schema.UrlParams\",\n    Type: \"UrlParams.UrlParams\",\n    importDeclarations: [`import * as UrlParams from \"effect/unstable/http/UrlParams\"`]\n  }),\n  expected: \"UrlParams\",\n  toEquivalence: () => UrlParams_.Equivalence,\n  toCodec: () => link()(ArraySchema(Tuple([String, String])), SchemaTransformation.transform({\n    decode: UrlParams_.make,\n    encode: self => self.params\n  }))\n});\n/**\n * Extracts a JSON value from the first occurrence of the given `field` in URL\n * parameters.\n *\n * **Example** (Decoding a JSON parameter field)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n * import { UrlParams } from \"effect/unstable/http\"\n *\n * const extractFoo = Schema.JsonFromUrlParamsField(\"foo\").pipe(\n *   Schema.decodeTo(Schema.Struct({\n *     some: Schema.String,\n *     number: Schema.Number\n *   }))\n * )\n *\n * const decoded = Schema.decodeSync(extractFoo)(UrlParams.fromInput({\n *   foo: `{\"some\":\"bar\",\"number\":42}`,\n *   baz: \"qux\"\n * }))\n * const result = [decoded.some, decoded.number] // => [\"bar\", 42]\n * ```\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const JsonFromUrlParamsField = (field, options) => UrlParams.pipe(decodeTo(fromJsonString(Unknown, options), SchemaTransformation.transformEffect({\n  decode: params => Option_.match(UrlParams_.getFirst(params, field), {\n    onNone: () => Effect.fail(new SchemaIssue.Pointer([field], new SchemaIssue.MissingKey(undefined))),\n    onSome: Effect.succeed\n  }),\n  encode: value => Effect.succeed(UrlParams_.make([[field, value]]))\n})));\n/**\n * Schema that decodes URL parameters into a record of string values.\n *\n * **Details**\n *\n * Keys with one value decode to a string, and keys with multiple values decode to\n * a non-empty readonly array of strings.\n *\n * **Example** (Decoding URL parameters to a record)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n * import { UrlParams } from \"effect/unstable/http\"\n *\n * const toStruct = Schema.RecordFromUrlParams.pipe(\n *   Schema.decodeTo(Schema.Struct({\n *     some: Schema.String,\n *     number: Schema.FiniteFromString\n *   }))\n * )\n *\n * const decoded = Schema.decodeSync(toStruct)(UrlParams.fromInput({\n *   some: \"value\",\n *   number: 42\n * }))\n * const result = [decoded.some, decoded.number] // => [\"value\", 42]\n * ```\n *\n * @unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const RecordFromUrlParams = /*#__PURE__*/UrlParams.pipe(/*#__PURE__*/decodeTo(/*#__PURE__*/Record(String, /*#__PURE__*/Union([String, /*#__PURE__*/NonEmptyArray(String)])), /*#__PURE__*/SchemaTransformation.transform({\n  decode: UrlParams_.toReadonlyRecord,\n  encode: UrlParams_.fromInput\n})));\n/**\n * Decodes an optional value `A` to a required `Option<A>` value.\n *\n * **Details**\n *\n * Decoding maps a missing key to `None` and a present value to `Some`.\n * Encoding maps `None` to a missing key and maps `Some` to its value.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport function OptionFromOptionalKey(schema) {\n  return optionalKey(schema).pipe(decodeTo(Option(toType(schema)), SchemaTransformation.optionFromOptionalKey()));\n}\n/**\n * Decodes an optional or `undefined` value `A` to a required `Option<A>`\n * value.\n *\n * **Details**\n *\n * Decoding maps a missing key or a present `undefined` value to `None`, and\n * maps all other values to `Some`. Encoding maps `None` to a missing key and\n * maps `Some` to its value.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport function OptionFromOptional(schema) {\n  return optional(schema).pipe(decodeTo(Option(toType(schema)), SchemaTransformation.optionFromOptional()));\n}\n/**\n * Decodes an optional or `null` or `undefined` value `A` to a required `Option<A>`\n * value.\n *\n * **Details**\n *\n * Decoding maps a missing key, `undefined`, or `null` to `None`, and maps all\n * other values to `Some`. Encoding maps `Some` to its value. `None` is encoded\n * according to `options.onNoneEncoding`: `\"omit\"` encodes a missing key,\n * `null` encodes `null`, and `undefined` encodes `undefined`.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport function OptionFromOptionalNullOr(schema, options) {\n  const onNoneEncoding = options === undefined ? \"omit\" : options.onNoneEncoding;\n  const noneValue = onNoneEncoding === null ? null : undefined;\n  return optional(NullOr(schema)).pipe(decodeTo(Option(toType(schema)), SchemaTransformation.transformOptional({\n    decode: oe => oe.pipe(Option_.filter(Predicate.isNotNullish), Option_.some),\n    encode: onNoneEncoding === \"omit\" ? Option_.flatten : ot => Option_.some(Option_.getOrElse(Option_.flatten(ot), () => noneValue))\n  })));\n}\n/**\n * Schema for `Redacted` values, which hide their contents from inspection.\n *\n * **Details**\n *\n * Options:\n *\n * - `label`: When provided, the schema will behave as follows:\n *   - Values will be validated against the label in addition to the wrapped schema\n *   - The default JSON serializer will deserialize into a `Redacted` instance with the label\n *   - The arbitrary generator will produce a `Redacted` instance with the label\n *   - The formatter will return the label\n * - `disallowJsonEncode`: When set to `true`, when attempting to encode a `Redacted` instance\n *   into JSON, it will fail with an error. This is useful when the wrapped schema is\n *   sensitive and should not be exposed in JSON.\n *\n * @see {@link RedactedFromValue} for decoding raw values and wrapping them in `Redacted`.\n * @category schemas\n * @since 3.10.0\n */\nexport function Redacted(value, options) {\n  const label = typeof options?.label === \"string\" ? options.label : undefined;\n  const disallowJsonEncode = options?.disallowJsonEncode === true;\n  const normalizedOptions = label !== undefined ? disallowJsonEncode ? {\n    label,\n    disallowJsonEncode: true\n  } : {\n    label\n  } : disallowJsonEncode ? {\n    disallowJsonEncode: true\n  } : undefined;\n  const decodeLabel = label !== undefined ? SchemaParser.decodeUnknownEffect(Literal(label)) : undefined;\n  const schema = declareConstructor()([value], ([value]) => (input, ast, poptions) => {\n    if (Redacted_.isRedacted(input)) {\n      const label = decodeLabel !== undefined ? Effect.mapErrorEager(decodeLabel(input.label, poptions), issue => new SchemaIssue.Pointer([\"label\"], issue)) : Effect.void;\n      return Effect.flatMapEager(label, () => Effect.mapBothEager(SchemaParser.decodeUnknownEffect(value)(Redacted_.value(input), poptions), {\n        onSuccess: () => input,\n        onFailure: () => {\n          return new SchemaIssue.Composite(ast, [new SchemaIssue.Pointer([\"value\"], new SchemaIssue.InvalidValue(undefined, input, poptions))], input, poptions);\n        }\n      }));\n    }\n    return Effect.fail(new SchemaIssue.InvalidType(ast, input, poptions));\n  }, {\n    representation: {\n      id: \"effect/schema/Redacted\",\n      payload: normalizedOptions ?? null\n    },\n    toCode: ({\n      typeParameters\n    }) => ({\n      runtime: normalizedOptions !== undefined ? `Schema.Redacted(${typeParameters[0].runtime}, ${format(normalizedOptions)})` : `Schema.Redacted(${typeParameters[0].runtime})`,\n      Type: `Redacted.Redacted<${typeParameters[0].Type}>`,\n      importDeclarations: [`import * as Redacted from \"effect/Redacted\"`]\n    }),\n    expected: \"Redacted\",\n    toCodecJson: ([value]) => link()(value, {\n      decode: SchemaGetter.transform(e => Redacted_.make(e, {\n        label\n      })),\n      encode: disallowJsonEncode ? SchemaGetter.forbidden(oe => \"Cannot serialize Redacted\" + (Option_.isSome(oe) && typeof oe.value.label === \"string\" ? ` with label: \"${oe.value.label}\"` : \"\")) : SchemaGetter.transform(Redacted_.value)\n    }),\n    toEquivalence: ([value]) => Redacted_.makeEquivalence(value)\n  });\n  return make(schema.ast, {\n    value\n  });\n}\n/**\n * Decodes a value and wraps it in `Redacted<A>`. Unlike {@link Redacted} which\n * expects the input to already be a `Redacted` instance, this schema decodes\n * the raw value and wraps it.\n *\n * @see {@link Redacted} for schemas whose input is already a `Redacted` value.\n * @category schemas\n * @since 4.0.0\n */\nexport function RedactedFromValue(value, options) {\n  return decodeTo(Redacted(toType(value), {\n    label: options?.label,\n    disallowJsonEncode: options?.disallowEncode\n  }), {\n    decode: SchemaGetter.transform(t => Redacted_.make(t, {\n      label: options?.label\n    })),\n    encode: options?.disallowEncode ? SchemaGetter.forbidden(oe => \"Cannot encode Redacted\" + (Option_.isSome(oe) && typeof oe.value.label === \"string\" ? ` with label: \"${oe.value.label}\"` : \"\")) : SchemaGetter.transform(Redacted_.value)\n  })(value);\n}\n/**\n * Schema for `Result<A, E>` values.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport function Result(success, failure) {\n  const schema = declareConstructor()([success, failure], ([success, failure]) => (input, ast, options) => {\n    if (!Result_.isResult(input)) {\n      return Effect.fail(new SchemaIssue.InvalidType(ast, input, options));\n    }\n    switch (input._tag) {\n      case \"Success\":\n        return Effect.mapBothEager(SchemaParser.decodeEffect(success)(input.success, options), {\n          onSuccess: Result_.succeed,\n          onFailure: issue => SchemaIssue.makeCompositeAtKey(ast, \"success\", issue, input, options)\n        });\n      case \"Failure\":\n        return Effect.mapBothEager(SchemaParser.decodeEffect(failure)(input.failure, options), {\n          onSuccess: Result_.fail,\n          onFailure: issue => SchemaIssue.makeCompositeAtKey(ast, \"failure\", issue, input, options)\n        });\n    }\n  }, {\n    representation: {\n      id: \"effect/schema/Result\",\n      payload: null\n    },\n    toCode: ({\n      typeParameters\n    }) => ({\n      runtime: `Schema.Result(${typeParameters[0].runtime}, ${typeParameters[1].runtime})`,\n      Type: `Result.Result<${typeParameters[0].Type}, ${typeParameters[1].Type}>`,\n      importDeclarations: [`import * as Result from \"effect/Result\"`]\n    }),\n    expected: \"Result\",\n    toCodec: ([success, failure]) => link()(Union([Struct({\n      _tag: Literal(\"Success\"),\n      success\n    }), Struct({\n      _tag: Literal(\"Failure\"),\n      failure\n    })]), SchemaTransformation.transform({\n      decode: e => e._tag === \"Success\" ? Result_.succeed(e.success) : Result_.fail(e.failure),\n      encode: r => Result_.isSuccess(r) ? {\n        _tag: \"Success\",\n        success: r.success\n      } : {\n        _tag: \"Failure\",\n        failure: r.failure\n      }\n    }))\n  });\n  return make(schema.ast, {\n    success,\n    failure\n  });\n}\nconst immerable = /*#__PURE__*/globalThis.Symbol.for(\"immer-draftable\");\nconst payloadToken = {};\nfunction makeClass(Inherited, identifier, struct, annotations, proto) {\n  const getClassSchema = getClassSchemaFactory(struct, identifier, annotations);\n  const ClassTypeId = getClassTypeId(identifier); // HMR support\n  const out = class extends Inherited {\n    constructor(...[input, options]) {\n      const internalOptions = options;\n      const payload = internalOptions?.[\"~payload\"];\n      const value = payload?.token === payloadToken ? payload.value : struct.make(input ?? {}, options);\n      super(value, {\n        ...options,\n        disableChecks: true,\n        \"~payload\": {\n          token: payloadToken,\n          value\n        }\n      });\n    }\n    static [TypeId] = TypeId;\n    get [ClassTypeId]() {\n      return ClassTypeId;\n    }\n    static [immerable] = true;\n    static identifier = identifier;\n    static fields = struct.fields;\n    static get ast() {\n      return getClassSchema(this).ast;\n    }\n    static pipe() {\n      return Pipeable.pipeArguments(this, arguments);\n    }\n    static rebuild(ast) {\n      return getClassSchema(this).rebuild(ast);\n    }\n    static make(input, options) {\n      return SchemaParser.make(getClassSchema(this))(input ?? {}, options);\n    }\n    static makeOption(input, options) {\n      return SchemaParser.makeOption(getClassSchema(this))(input ?? {}, options);\n    }\n    static makeEffect(input, options) {\n      return getClassSchema(this).makeEffect(input ?? {}, options);\n    }\n    static annotate(annotations) {\n      return this.rebuild(SchemaAST.annotate(this.ast, annotations));\n    }\n    static annotateKey(annotations) {\n      return this.rebuild(SchemaAST.annotateKey(this.ast, annotations));\n    }\n    static check(...checks) {\n      return this.rebuild(SchemaAST.appendChecks(this.ast, checks));\n    }\n    static extend(identifier) {\n      return (schema, annotations) => {\n        const extension = isStruct(schema) ? schema : Struct(schema);\n        const fields = {\n          ...struct.fields,\n          ...extension.fields\n        };\n        const ast = SchemaAST.struct(fields, struct.ast.checks, {\n          identifier\n        });\n        return makeClass(this, identifier, makeStruct(SchemaAST.appendChecks(ast, extension.ast.checks), fields), annotations, proto);\n      };\n    }\n    static mapFields(f, options) {\n      return struct.mapFields(f, options);\n    }\n  };\n  if (proto !== undefined) {\n    Object.assign(out.prototype, proto(identifier));\n  }\n  return out;\n}\nfunction getClassTransformation(self) {\n  return new SchemaTransformation.Transformation(SchemaGetter.transform(input => new self(input, {\n    \"~payload\": {\n      token: payloadToken,\n      value: input\n    }\n  })), SchemaGetter.passthrough());\n}\nfunction getClassTypeId(identifier) {\n  return `~effect/Schema/Class/${identifier}`;\n}\nfunction getClassSchemaFactory(from, identifier, annotations) {\n  let memo;\n  return self => {\n    if (memo !== undefined) {\n      return memo;\n    }\n    const ClassTypeId = getClassTypeId(identifier);\n    const isClassValue = input => input instanceof self || Predicate.hasProperty(input, ClassTypeId);\n    const transformation = getClassTransformation(self);\n    const to = make(new SchemaAST.Declaration([from.ast], () => (input, ast, options) => {\n      return isClassValue(input) ? Effect.succeed(input) : Effect.fail(new SchemaIssue.InvalidType(ast, input, options));\n    }, {\n      identifier,\n      [InternalAnnotations.CONSTRUCTOR_ANNOTATION_KEY]: ([from]) => ({\n        isConstructed: isClassValue,\n        link: new SchemaAST.Link(from, transformation)\n      }),\n      toCodec: ([from]) => new SchemaAST.Link(from.ast, transformation),\n      toEquivalence: ([from]) => from,\n      toFormatter: ([from]) => t => `${self.identifier}(${from(t)})`,\n      [InternalAnnotations.SENTINELS_ANNOTATION_KEY]: SchemaAST.collectSentinels(from.ast),\n      ...annotations\n    }));\n    return memo = decodeTo(to, transformation)(from);\n  };\n}\nfunction isStruct(schema) {\n  return isSchema(schema);\n}\n/**\n * Creates a schema-backed class whose constructor validates input against a\n * {@link Struct} schema. Construction throws an `Error` with a\n * `SchemaIssue.Issue` in its `cause` on invalid input.\n *\n * **When to use**\n *\n * Use when you need a schema-backed data class with validated construction,\n * schema-derived decoding/encoding, and class-style methods or inheritance.\n *\n * **Details**\n *\n * Pass the desired class type as the first type parameter. The second optional\n * type parameter can be used to add nominal brands.\n *\n * The `identifier` is the schema's stable runtime name. It is exposed on the\n * class, stored in the schema AST, and used to label diagnostics and generated\n * references as well as to format class instances.\n *\n * It also derives a runtime marker that recognizes instances across hot module\n * reloads, where `instanceof` can fail because the constructor has been\n * replaced. The identifier is explicit because the outer JavaScript class name\n * is not available while the `extends` expression is evaluated and may change\n * through renaming or minification.\n *\n * **Gotchas**\n *\n * Passing `disableChecks` in the options skips constructor validation.\n *\n * **Example** (Defining a basic class)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * class Person extends Schema.Class<Person>(\"Person\")({\n *   name: Schema.String,\n *   age: Schema.Number\n * }) {}\n *\n * const alice = new Person({ name: \"Alice\", age: 30 })\n * alice.name // => \"Alice\"\n * String(alice) // => \"Person({\\\"name\\\":\\\"Alice\\\",\\\"age\\\":30})\"\n * ```\n *\n * **Example** (Extending a class)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * class Animal extends Schema.Class<Animal>(\"Animal\")({\n *   name: Schema.String\n * }) {}\n *\n * class Dog extends Animal.extend<Dog>(\"Dog\")({\n *   breed: Schema.String\n * }) {}\n *\n * const dog = new Dog({ name: \"Rex\", breed: \"Labrador\" })\n * dog.name // => \"Rex\"\n * dog.breed // => \"Labrador\"\n * ```\n *\n * @see {@link TaggedClass} for adding a `_tag` literal field to the class schema\n * @see {@link Error} for defining schema-backed error classes\n * @see {@link TaggedError} for defining tagged schema-backed error classes\n *\n * @category constructors\n * @since 3.10.0\n */\nexport const Class = identifier => (schema, annotations) => {\n  const struct = isStruct(schema) ? schema : Struct(schema);\n  return makeClass(Data.Class, identifier, struct, annotations, identifier => ({\n    toString() {\n      return `${identifier}(${format({\n        ...this\n      })})`;\n    }\n  }));\n};\n/**\n * Defines a schema-backed class with an automatically populated `_tag` field.\n *\n * **When to use**\n *\n * Use to define class instances that are validated by a schema and participate\n * in tagged union matching.\n *\n * **Details**\n *\n * The optional `identifier` parameter overrides the schema identifier;\n * it defaults to the `tag` value.\n *\n * **Example** (Defining a tagged class)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * class Circle extends Schema.TaggedClass<Circle>()(\"Circle\", {\n *   radius: Schema.Number\n * }) {}\n *\n * const c = new Circle({ radius: 5 })\n * c._tag // => \"Circle\"\n * c.radius // => 5\n * ```\n *\n * @category constructors\n * @since 3.10.0\n */\nexport const TaggedClass = identifier => {\n  return (tagValue, schema, annotations) => {\n    const struct = isStruct(schema) ? schema.mapFields(fields => ({\n      _tag: tag(tagValue),\n      ...fields\n    }), {\n      unsafePreserveChecks: true\n    }) : TaggedStruct(tagValue, schema);\n    return Class(identifier ?? tagValue)(struct, annotations);\n  };\n};\n/**\n * Creates a schema-backed error class that can be used as a typed,\n * yieldable error in Effect programs. Combines {@link Class} validation with\n * the `YieldableError` interface so instances can be yielded directly inside\n * `Effect.gen`.\n *\n * **Example** (Schema-backed error)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schema } from \"effect\"\n *\n * class NotFound extends Schema.Error<NotFound>(\"NotFound\")({\n *   id: Schema.Number\n * }) {}\n *\n * const program = Effect.gen(function*() {\n *   yield* new NotFound({ id: 1 })\n * })\n * const error = await Effect.runPromise(Effect.flip(program))\n * error.id // => 1\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Error = identifier => (schema, annotations) => {\n  const struct = isStruct(schema) ? schema : Struct(schema);\n  const self = makeClass(core.Error, identifier, struct, annotations, identifier => ({\n    name: identifier\n  }));\n  return self;\n};\n/**\n * Defines a schema-backed yieldable error class with an automatically populated\n * `_tag` field.\n *\n * **When to use**\n *\n * Use to define typed errors that are schema validated, yielded in `Effect.gen`,\n * and matched as tagged union members.\n *\n * **Example** (Defining a tagged error class)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schema } from \"effect\"\n *\n * class NotFound extends Schema.TaggedError<NotFound>()(\"NotFound\", {\n *   id: Schema.Number\n * }) {}\n *\n * const program = Effect.gen(function*() {\n *   yield* new NotFound({ id: 42 })\n * })\n * const error = await Effect.runPromise(Effect.flip(program))\n * error._tag // => \"NotFound\"\n * error.id // => 42\n * ```\n *\n * @category constructors\n * @since 3.10.0\n */\nexport const TaggedError = identifier => {\n  return (tagValue, schema, annotations) => {\n    const struct = isStruct(schema) ? schema.mapFields(fields => ({\n      _tag: tag(tagValue),\n      ...fields\n    }), {\n      unsafePreserveChecks: true\n    }) : TaggedStruct(tagValue, schema);\n    return Error(identifier ?? tagValue)(struct, annotations);\n  };\n};\n/**\n * Attaches a custom formatter used by `toFormatter`.\n *\n * **Details**\n *\n * Use this when the formatter derived from the schema structure is not suitable.\n * The annotation is applied through this helper because adding it directly to\n * `Annotations.Bottom` would make schemas invariant.\n *\n * @category formatting\n * @since 4.0.0\n */\nexport function overrideToFormatter(toFormatter) {\n  return self => self.annotate({\n    toFormatter\n  });\n}\n/**\n * Derives a string formatter function from a schema. The formatter converts\n * a value to its human-readable string representation, recursing into structs,\n * arrays, and unions.\n *\n * **Details**\n *\n * The optional `onBefore` hook lets you intercept specific AST nodes before\n * the default formatting logic runs.\n *\n * @category formatting\n * @since 4.0.0\n */\nexport function toFormatter(schema, options) {\n  return InternalToFormatter.toFormatter(schema.ast, options);\n}\n/**\n * Overrides the equivalence derivation for a schema by supplying a custom\n * `Equivalence`.\n *\n * **When to use**\n *\n * Use when you need a custom equivalence instead of the default structural\n * equivalence derived by {@link toEquivalence}.\n *\n * @category instances\n * @since 4.0.0\n */\nexport function overrideToEquivalence(toEquivalence) {\n  return self => self.annotate({\n    toEquivalence\n  });\n}\n/**\n * Derives an `Equivalence` from a schema. Two values are considered equal when\n * every field (and nested field) compares equal according to the schema\n * structure.\n *\n * **Example** (Comparing structs)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n *\n * const eq = Schema.toEquivalence(Schema.Struct({ id: Schema.Number, name: Schema.String }))\n *\n * eq({ id: 1, name: \"Alice\" }, { id: 1, name: \"Alice\" }) // => true\n * eq({ id: 1, name: \"Alice\" }, { id: 2, name: \"Alice\" }) // => false\n * ```\n *\n * @category instances\n * @since 4.0.0\n */\nexport function toEquivalence(schema) {\n  return InternalEquivalence.toEquivalence(schema.ast);\n}\n/**\n * Derives an intermediate `SchemaRepresentation.Document` from the encoded\n * side of a schema.\n *\n * **When to use**\n *\n * Use when you have a `Schema` and need its live structural representation for inspection, persistence, or compilation.\n *\n * **Details**\n *\n * Use {@link toType} before this function to represent the type side instead.\n * The optional reference policy controls which candidates are extracted into the document's reference table. By\n * default, only candidates with a resolved identifier become references; recursive candidates always require one.\n *\n * @see {@link SchemaRepresentation.toRepresentation} for converting a `SchemaAST.AST` directly\n *\n * @category converting\n * @since 4.0.0\n */\nexport function toRepresentation(schema, options) {\n  return InternalToRepresentation.toRepresentation(schema.ast, options);\n}\n/**\n * Returns a JSON Schema document using draft 2020-12.\n *\n * **When to use**\n *\n * Use when you need a draft-2020-12 description of the canonical JSON form of a runtime schema.\n *\n * **Details**\n *\n * The `options` parameter controls reference extraction and generation details\n * such as excess properties and synthesized check descriptions; it does not\n * change the draft target. The reference policy receives canonical JSON\n * encoded ASTs. By default, anonymous non-recursive candidates remain inline,\n * while candidates with resolved identifiers become definitions. Declarations\n * are lowered through their `toCodecJson` or `toCodec` annotation when\n * available before the representation document is compiled.\n *\n * The generated document is intended for preliminary validation. JSON Schema\n * and Effect checks do not always have identical semantics, so the Effect\n * decoder remains the final authority. Passing JSON Schema validation does not\n * guarantee that Effect decoding will succeed.\n *\n * **Gotchas**\n *\n * JSON Schema generation is best-effort. String length uses Unicode code points\n * in JSON Schema and UTF-16 code units in Effect. A generated `pattern` cannot\n * retain JavaScript RegExp flags. Object property checks apply to the original\n * input in JSON Schema but to the decoded object in Effect. `oneOf` can also\n * reject values accepted by overlapping Effect union members. Custom\n * `toJsonSchema` annotations are the annotation author's responsibility. When\n * canonical JSON derivation adds an artificial transformation, checks and\n * annotations on its source node are not copied to the JSON target, so they do\n * not appear in the emitted document. Opaque declarations without a structural\n * codec are represented by an unconstrained JSON Schema. The default\n * `onExcessProperty: \"ignore\"` matches the decoder default and leaves\n * unrepresentable index-signature keys open. In `\"error\"` mode, the compiler\n * constrains those keys with `propertyNames` and applies a permissive choice of\n * candidate index value schemas. The Effect decoder enforces the exact\n * key-value association.\n *\n * @see {@link SchemaRepresentation.toJsonSchemaDocument} for compiling an existing live representation document\n *\n * @category converting\n * @since 4.0.0\n */\nexport function toJsonSchemaDocument(schema, options) {\n  const document = InternalToRepresentation.toRepresentation(InternalToCodec.toCodecJsonAST(schema.ast), options);\n  return InternalToJsonSchemaDocument.toJsonSchemaDocument(document, options);\n}\n/**\n * Derives a canonical JSON codec from a schema. The encoded form is `Json`, and\n * decoding produces the schema's `Type`.\n *\n * **Details**\n *\n * Derivation does not run transformations. Annotation links may be asynchronous,\n * may fail, and may use optional services; the consuming parser chooses the\n * execution and failure handling. Because hooks do not widen the returned\n * service types, links cannot require services not declared by the input schema.\n *\n * **Gotchas**\n *\n * Declarations without a `toCodecJson` or `toCodec` annotation use `Json` as\n * their encoded schema. This keeps codec construction total, but encoding or\n * decoding can still fail when declaration values are not JSON values. A\n * `toCodecJson` callback can return `undefined` when the declaration is already\n * in canonical JSON form. When derivation adds an artificial transformation,\n * checks and annotations remain on its source node rather than being copied to\n * the JSON target. Source checks still run after the transformation.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toCodecJson = InternalToCodec.toCodecJson;\n/**\n * Derives an isomorphism codec from a schema. The encoded form is the schema's\n * `Iso` type — the intermediate representation used for round-tripping.\n *\n * **Details**\n *\n * Annotation links may be asynchronous, may fail, and may use optional services;\n * the consuming parser chooses the execution and failure handling.\n *\n * **Gotchas**\n *\n * Links cannot require services because the returned `Codec` does not expose\n * service requirements.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toCodecIso = InternalToCodec.toCodecIso;\n/**\n * Converts a schema to the StringTree canonical codec, where every leaf value\n * becomes a string while preserving the original structure.\n *\n * **Details**\n *\n * Derivation does not run transformations. Annotation links may be asynchronous,\n * may fail, and may use optional services; the consuming parser chooses the\n * execution and failure handling. Links cannot require services not declared by\n * the input schema because hooks do not widen the returned service types.\n *\n * **Gotchas**\n *\n * Declarations must provide a structural `toCodecStringTree`, `toCodecJson`, or\n * `toCodec` encoding. A callback can return `undefined` when the declaration is\n * already in canonical StringTree form.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toCodecStringTree = InternalToCodec.toCodecStringTree;\n/**\n * Allows array schemas to decode from either an array input or a single value\n * input.\n *\n * **When to use**\n *\n * Use when you need to accept transport formats that may represent a\n * single-item array as a bare value, such as query-string or form-data adapters.\n *\n * **Gotchas**\n *\n * This combinator is intentionally not part of `toCodecStringTree`; it adds a\n * decoding convenience rather than a canonical StringTree representation. It\n * does not parse comma-separated strings.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toCodecArrayFromSingle = InternalToCodec.toCodecArrayFromSingle;\n/**\n * Derives an XML encoder from a codec.\n *\n * **Details**\n *\n * The returned function encodes a value through `toCodecStringTree` and returns\n * an `Effect` that succeeds with the XML string or fails with a\n * {@link SchemaIssue.Issue} if codec encoding fails.\n *\n * @category encoding\n * @since 4.0.0\n */\nexport function toEncoderXml(codec, options) {\n  return InternalToEncoderXml.toEncoderXml(codec, options);\n}\n/**\n * Derives an `Iso` optic from a schema that isomorphically converts between\n * the schema's `Type` and its `Iso` (intermediate / serialized form).\n *\n * **Details**\n *\n * Reading through the `Iso` encodes the schema value, while replacing through\n * it decodes the new focus.\n *\n * **Gotchas**\n *\n * This API runs synchronously, so failing, asynchronous, or service-dependent\n * transformations can throw. Schema failures use `\"Schema validation failed\"`\n * with a `SchemaIssue.Issue` in `cause`; format it with\n * `SchemaIssue.makeFormatterDefault()`. Consume {@link toCodecIso} with an\n * effectful parser for asynchronous execution or explicit failure handling.\n *\n * @category converting\n * @since 4.0.0\n */\nexport function toIso(schema) {\n  return InternalToIso.toIso(schema);\n}\n/**\n * Returns an identity `Iso` over the schema's source (`Type`) side.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport function toIsoSource(schema) {\n  return InternalToIso.toIsoSource(schema);\n}\n/**\n * Returns an identity `Iso` over the schema's focus (`Iso`) side.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport function toIsoFocus(schema) {\n  return InternalToIso.toIsoFocus(schema);\n}\n/**\n * Overrides a schema's derived ISO codec with an explicit target codec.\n *\n * **When to use**\n *\n * Use to provide a custom ISO transformation when the default derivation is not\n * appropriate.\n *\n * **Details**\n *\n * The resulting schema carries a custom `Iso` type parameter and uses the\n * provided `decode` and `encode` getters to transform between the schema type\n * and the target codec.\n *\n * @category transforming\n * @since 4.0.0\n */\nexport function overrideToCodecIso(to, transformation) {\n  return schema => {\n    return make(SchemaAST.annotate(schema.ast, {\n      toCodecIso: () => new SchemaAST.Link(to.ast, SchemaTransformation.make(transformation))\n    }), {\n      schema\n    });\n  };\n}\n/**\n * Derives a JSON Patch differ from a codec. Serializes values to JSON (via\n * {@link toCodecJson}), computes RFC 6902 JSON Patch operations between old\n * and new values, and can apply patches back to the typed value.\n *\n * **Details**\n *\n * `diff` encodes both values before computing the patch. `patch` encodes the old\n * value, applies the patch to its JSON representation, and decodes the result.\n *\n * **Gotchas**\n *\n * This API runs synchronously, so failing, asynchronous, or service-dependent\n * transformations can throw. Schema failures use `\"Schema validation failed\"`\n * with a `SchemaIssue.Issue` in `cause`; format it with\n * `SchemaIssue.makeFormatterDefault()`. Invalid patch operations instead produce\n * {@link JsonPatch.apply} errors.\n *\n * @category converting\n * @since 4.0.0\n */\nexport function toDifferJsonPatch(schema) {\n  return InternalToDifferJsonPatch.toDifferJsonPatch(schema);\n}\n/**\n * Creates a recursive schema for a {@link Tree} of values described by `node`.\n * The resulting schema accepts a single node value, an array of trees, or an\n * object whose values are trees.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport function Tree(node) {\n  const Tree$ref = suspend(() => Tree);\n  const Tree = Union([node, ArraySchema(Tree$ref), Record(String, Tree$ref)]);\n  return Tree;\n}\n/**\n * Schema that accepts and validates any immutable JSON-compatible value.\n *\n * **Example** (Validating a JSON value)\n *\n * ```ts import.meta.vitest\n * import { Option, Schema } from \"effect\"\n *\n * Schema.decodeUnknownOption(Schema.Json)({ key: [1, true, null] }) // => Option.some({ key: [1, true, null] })\n * ```\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const Json = /*#__PURE__*/make(/*#__PURE__*/SchemaAST.annotate(SchemaAST.Json, {\n  toCode: () => ({\n    runtime: \"Schema.Json\",\n    Type: \"Schema.Json\"\n  })\n}));\n/**\n * Schema for readonly string-keyed records whose values are JSON-compatible.\n *\n * **When to use**\n *\n * Use when you need to validate a JSON object rather than any JSON value.\n *\n * **Example** (Validating a JSON object)\n *\n * ```ts import.meta.vitest\n * import { Option, Schema } from \"effect\"\n *\n * Schema.decodeUnknownOption(Schema.JsonObject)({ key: [1, true, null] }) // => Option.some({ key: [1, true, null] })\n * Schema.decodeUnknownOption(Schema.JsonObject)([1, 2, 3]) // => Option.none()\n * ```\n *\n * @see {@link Json} for a schema that also accepts JSON arrays and primitive values\n * @category schemas\n * @since 4.0.0\n */\nexport const JsonObject = /*#__PURE__*/Record(String, Json);\nconst JsonError = /*#__PURE__*/Struct({\n  message: String,\n  name: /*#__PURE__*/optionalKey(String),\n  stack: /*#__PURE__*/optionalKey(String),\n  cause: /*#__PURE__*/optionalKey(Json)\n});\n/**\n * Schema that accepts any mutable JSON-compatible value. See {@link Json} for\n * the immutable variant.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const MutableJson = /*#__PURE__*/make(/*#__PURE__*/SchemaAST.annotate(SchemaAST.MutableJson, {\n  toCode: () => ({\n    runtime: \"Schema.MutableJson\",\n    Type: \"Schema.MutableJson\"\n  })\n}));\n/**\n * Resolves the typed annotations from a schema. The term \"resolve\" (rather\n * than \"get\") reflects the lookup strategy: if the schema has checks, the\n * annotations are taken from the last check; otherwise they are taken from\n * the base schema instance.\n *\n * @category getters\n * @since 4.0.0\n */\nexport function resolveAnnotations(schema) {\n  return InternalAnnotations.resolve(schema.ast);\n}\n/**\n * Resolves the context (key-level) annotations from a schema. Context\n * annotations are those attached via `annotateKey` and live on the AST's\n * `context` rather than on the schema node itself.\n *\n * @category getters\n * @since 4.0.0\n */\nexport function resolveAnnotationsKey(schema) {\n  return schema.ast.context?.annotations;\n}\n//# sourceMappingURL=Schema.js.map","import * as Context from \"./Context.js\";\nimport * as Predicate from \"./Predicate.js\";\nimport * as Schema from \"./Schema.js\";\nconst TypeId = \"~effect/Terminal\";\nconst QuitErrorTypeId = \"~effect/Terminal/QuitError\";\n/**\n * Represents an error that occurs when a user attempts to\n * quit out of a `Terminal` prompt for input (usually by entering `ctrl`+`c`).\n *\n * **When to use**\n *\n * Use when implementing terminal input or prompts that need to signal\n * user-requested cancellation through the typed error channel.\n *\n * @see {@link isQuitError} for checking unknown errors when handling terminal cancellation\n *\n * @category errors\n * @since 4.0.0\n */\nexport class QuitError extends /*#__PURE__*/Schema.Error(\"QuitError\")({\n  _tag: /*#__PURE__*/Schema.tag(\"QuitError\")\n}) {\n  /**\n   * Marks this value as a terminal quit error for runtime guards.\n   *\n   * @since 4.0.0\n   */\n  [QuitErrorTypeId] = QuitErrorTypeId;\n}\n/**\n * Returns `true` if the provided value is a `Terminal.QuitError`.\n *\n * **When to use**\n *\n * Use to narrow unknown failures to `QuitError` when handling terminal input\n * cancellation.\n *\n * **Details**\n *\n * Returns `true` when the value carries the `QuitError` runtime marker and\n * narrows it to `QuitError`.\n *\n * @see {@link QuitError} for the error value produced when terminal input is quit\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isQuitError = u => Predicate.hasProperty(u, QuitErrorTypeId);\n/**\n * Service tag for command-line input and output services.\n *\n * **When to use**\n *\n * Use to access or provide platform terminal capabilities such as reading\n * input, writing output, and inspecting terminal dimensions.\n *\n * @category services\n * @since 4.0.0\n */\nexport const Terminal = /*#__PURE__*/Context.Service(\"effect/Terminal\");\n/**\n * Creates a `Terminal` service implementation.\n *\n * **When to use**\n *\n * Use to construct a custom `Terminal` service implementation from concrete\n * terminal capabilities when writing a platform adapter, test implementation,\n * or custom runtime service.\n *\n * **Details**\n *\n * The implementation object supplies `columns`, `rows`, `readInput`,\n * `readLine`, and `display`; `make` attaches the `Terminal` service marker so\n * the result can be provided through the `Terminal` context service.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = impl => Terminal.of({\n  ...impl,\n  [TypeId]: TypeId\n});\n//# sourceMappingURL=Terminal.js.map","import * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport { badArgument } from \"effect/PlatformError\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Queue from \"effect/Queue\";\nimport * as RcRef from \"effect/RcRef\";\nimport * as Terminal from \"effect/Terminal\";\nimport * as readline from \"node:readline\";\n/**\n * Creates a scoped process-backed `Terminal` using Node `readline`, enabling\n * TTY raw mode while in scope and using the supplied predicate to decide when\n * key input should end.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = /*#__PURE__*/Effect.fnUntraced(function* (shouldQuit = defaultShouldQuit) {\n  const stdin = process.stdin;\n  const stdout = process.stdout;\n  const lines = yield* Queue.make();\n  // stdin \"end\" fires once per process, so remember end-of-input for readers\n  // created after the event (Bun never sets `readableEnded`).\n  let inputEnded = stdin.readableEnded;\n  let readlineActive = false;\n  const onStdinEnd = () => {\n    inputEnded = true;\n    if (!readlineActive) {\n      Queue.endUnsafe(lines);\n    }\n  };\n  stdin.once(\"end\", onStdinEnd);\n  yield* Effect.addFinalizer(() => Effect.sync(() => stdin.off(\"end\", onStdinEnd)));\n  const rlRef = yield* RcRef.make({\n    acquire: Effect.acquireRelease(Effect.sync(() => {\n      const rl = readline.createInterface({\n        input: stdin,\n        escapeCodeTimeout: 50\n      });\n      const onLine = line => Queue.offerUnsafe(lines, line);\n      const onClose = () => {\n        readlineActive = false;\n        Queue.endUnsafe(lines);\n      };\n      readlineActive = true;\n      readline.emitKeypressEvents(stdin, rl);\n      rl.on(\"line\", onLine);\n      rl.once(\"close\", onClose);\n      if (stdin.isTTY) {\n        stdin.setRawMode(true);\n      }\n      return {\n        rl,\n        onClose,\n        onLine\n      };\n    }), ({\n      rl,\n      onClose,\n      onLine\n    }) => Effect.sync(() => {\n      readlineActive = false;\n      rl.off(\"line\", onLine);\n      rl.off(\"close\", onClose);\n      if (stdin.isTTY) {\n        stdin.setRawMode(false);\n      }\n      rl.close();\n      if (inputEnded) {\n        Queue.endUnsafe(lines);\n      }\n    })),\n    idleTimeToLive: \"10 millis\"\n  });\n  const columns = Effect.sync(() => stdout.columns ?? 0);\n  const rows = Effect.sync(() => stdout.rows ?? 0);\n  const readInput = Effect.gen(function* () {\n    const queue = yield* Queue.make();\n    const handleKeypress = (s, k) => {\n      const userInput = {\n        input: Option.fromUndefinedOr(s),\n        key: {\n          name: k.name ?? \"\",\n          ctrl: !!k.ctrl,\n          meta: !!k.meta,\n          shift: !!k.shift\n        }\n      };\n      Queue.offerUnsafe(queue, userInput);\n      if (shouldQuit(userInput)) {\n        Queue.endUnsafe(queue);\n      }\n    };\n    // Deno's `process.stdin` shim does not keep the event loop alive, so a\n    // program blocked on input can exit before `end` is ever delivered. A\n    // timer holds the loop open for as long as this reader is active.\n    const keepAlive = setInterval(() => {}, 2147483647);\n    // Without this, consumers (e.g. `Prompt.run`) hang forever on closed stdin.\n    const handleEnd = () => {\n      clearInterval(keepAlive);\n      Queue.endUnsafe(queue);\n    };\n    yield* Effect.addFinalizer(() => Effect.sync(() => {\n      clearInterval(keepAlive);\n      stdin.off(\"keypress\", handleKeypress);\n      stdin.off(\"end\", handleEnd);\n    }));\n    stdin.on(\"keypress\", handleKeypress);\n    if (inputEnded) {\n      handleEnd();\n    } else {\n      yield* RcRef.get(rlRef);\n      stdin.once(\"end\", handleEnd);\n    }\n    return queue;\n  });\n  const readLine = Effect.suspend(() => Queue.poll(lines).pipe(Effect.flatMap(Option.match({\n    onNone: () => Effect.scoped(Effect.andThen(RcRef.get(rlRef), Queue.take(lines))),\n    onSome: Effect.succeed\n  })), Effect.mapError(() => new Terminal.QuitError({}))));\n  const display = prompt => Effect.uninterruptible(Effect.callback(resume => {\n    stdout.write(prompt, err => Predicate.isNullish(err) ? resume(Effect.void) : resume(Effect.fail(badArgument({\n      module: \"Terminal\",\n      method: \"display\",\n      description: \"Failed to write prompt to stdout\",\n      cause: err\n    }))));\n  }));\n  return Terminal.make({\n    columns,\n    rows,\n    readInput,\n    readLine,\n    display\n  });\n});\n/**\n * Provides the default process-backed `Terminal` service, ending key input on\n * Ctrl+C or Ctrl+D.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.effect(Terminal.Terminal, /*#__PURE__*/make(defaultShouldQuit));\nfunction defaultShouldQuit(input) {\n  return input.key.ctrl && (input.key.name === \"c\" || input.key.name === \"d\");\n}\n//# sourceMappingURL=NodeTerminal.js.map","/**\n * Node.js implementation of the Effect `Terminal` service.\n *\n * This module reuses the shared Node terminal implementation. `make` creates a\n * scoped process-backed `Terminal` service, and `layer` provides the default\n * service with the standard quit behavior for key input.\n *\n * @since 4.0.0\n */\nimport * as NodeTerminal from \"@effect/platform-node-shared/NodeTerminal\";\n/**\n * Creates a scoped `Terminal` service backed by process stdin/stdout, using the\n * optional predicate to decide when key input should end the input stream.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = NodeTerminal.make;\n/**\n * Provides the default process-backed `Terminal` service, ending key input on\n * the default quit keys.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = NodeTerminal.layer;\n//# sourceMappingURL=NodeTerminal.js.map","import * as Layer from \"effect/Layer\";\nimport * as NodeChildProcessSpawner from \"./NodeChildProcessSpawner.js\";\nimport * as NodeCrypto from \"./NodeCrypto.js\";\nimport * as NodeFileSystem from \"./NodeFileSystem.js\";\nimport * as NodePath from \"./NodePath.js\";\nimport * as NodeStdio from \"./NodeStdio.js\";\nimport * as NodeTerminal from \"./NodeTerminal.js\";\n/**\n * Provides the default Node implementations for child process spawning,\n * filesystem, path, stdio, and terminal services.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.provideMerge(NodeChildProcessSpawner.layer, /*#__PURE__*/Layer.mergeAll(NodeFileSystem.layer, NodeCrypto.layer, NodePath.layer, NodeStdio.layer, NodeTerminal.layer));\n//# sourceMappingURL=NodeServices.js.map","import { Cause, Effect, Exit, Inspectable } from 'effect'\n\nexport interface RunOptions {\n  readonly signal?: AbortSignal | undefined\n}\n\nfunction causeMessage(cause: Cause.Cause<unknown>): string {\n  if (Cause.hasInterruptsOnly(cause)) {\n    // What pi's own tools throw for a cancelled run.\n    return 'Operation aborted'\n  }\n  if (Cause.hasDies(cause)) {\n    return Cause.pretty(cause)\n  }\n  return cause.reasons\n    .filter(Cause.isFailReason)\n    .map(({ error }) => {\n      if (error instanceof Error) {\n        return error.message || error.name\n      }\n      return typeof error === 'string' ? error : Inspectable.toStringUnknown(error)\n    })\n    .join('\\n')\n}\n\n/** The rejection message is what the model reads back as the tool result. */\nexport async function runTool<A, E>(\n  effect: Effect.Effect<A, E>,\n  options?: RunOptions,\n): Promise<A> {\n  const exit = await Effect.runPromiseExit(effect, options)\n  if (Exit.isFailure(exit)) {\n    throw new Error(causeMessage(exit.cause))\n  }\n  return exit.value\n}\n\nexport interface RunHandlerOptions<B> {\n  readonly onError?: (message: string) => B\n}\n\nexport async function runHandler<A, E, B = undefined>(\n  effect: Effect.Effect<A, E>,\n  options?: RunHandlerOptions<B>,\n): Promise<A | B> {\n  const exit = await Effect.runPromiseExit(effect)\n  if (Exit.isSuccess(exit)) {\n    return exit.value\n  }\n  if (options?.onError) {\n    return options.onError(causeMessage(exit.cause))\n  }\n  const die = exit.cause.reasons.find(Cause.isDieReason)\n  if (die !== undefined) {\n    throw die.defect\n  }\n  return undefined as B\n}\n","import type {\n  AgentToolResult,\n  Theme,\n  ThemeColor,\n  TruncationResult,\n} from '@earendil-works/pi-coding-agent'\nimport {\n  DEFAULT_MAX_BYTES,\n  DEFAULT_MAX_LINES,\n  formatSize,\n  keyHint,\n} from '@earendil-works/pi-coding-agent'\nimport type { Component } from '@earendil-works/pi-tui'\nimport { Text, truncateToWidth } from '@earendil-works/pi-tui'\n\nexport interface TextPreviewOptions {\n  text: string\n  maxLines: number\n  expanded: boolean\n  theme: Theme\n  color?: ThemeColor\n}\n\nexport class TextPreview implements Component {\n  private readonly body: Text\n  private readonly maxLines: number\n  private readonly expanded: boolean\n  private readonly theme: Theme\n\n  constructor({\n    text,\n    maxLines,\n    expanded,\n    theme,\n    color = 'dim',\n  }: TextPreviewOptions) {\n    // Styled per source line so wrapping re-emits the color on each visual line.\n    const styled = text\n      .split('\\n')\n      .map((line) => theme.fg(color, line))\n      .join('\\n')\n    this.body = new Text(styled, 0, 0)\n    this.maxLines = maxLines\n    this.expanded = expanded\n    this.theme = theme\n  }\n\n  invalidate(): void {\n    this.body.invalidate()\n  }\n\n  render(width: number): string[] {\n    const lines = this.body.render(width)\n    const hidden = lines.length - this.maxLines\n    if (this.expanded || hidden <= 0) {\n      return lines\n    }\n    const hint = `${this.theme.fg('muted', `... (${hidden} more lines,`)} ${keyHint(\n      'app.tools.expand',\n      'to expand',\n    )})`\n    return [...lines.slice(0, this.maxLines), truncateToWidth(hint, width, '...')]\n  }\n}\n\nexport function getTextOutput(\n  result: Pick<AgentToolResult<unknown>, 'content'>,\n): string {\n  return result.content\n    .filter((content) => content.type === 'text')\n    .map((content) => content.text.replace(/\\r/g, ''))\n    .join('\\n')\n}\n\nexport interface ExpandableTextOptions {\n  header: string\n  content: string\n  maxLines: number\n  expanded: boolean\n  theme: Theme\n  truncation?: TruncationResult\n}\n\nexport class ExpandableText implements Component {\n  private readonly parts: Component[]\n\n  constructor({\n    header,\n    content,\n    maxLines,\n    expanded,\n    theme,\n    truncation,\n  }: ExpandableTextOptions) {\n    const body = content.replace(/\\n+$/, '')\n    this.parts = [\n      new Text(header, 0, 0),\n      body\n        ? new TextPreview({\n            text: body,\n            maxLines,\n            expanded,\n            theme,\n            color: 'toolOutput',\n          })\n        : new Text(theme.fg('dim', '(empty response)'), 0, 0),\n    ]\n\n    const notice = truncation ? formatTruncationNotice(truncation) : ''\n    if (notice) {\n      this.parts.push(new Text(theme.fg('warning', notice), 0, 0))\n    }\n  }\n\n  invalidate(): void {\n    for (const part of this.parts) {\n      part.invalidate()\n    }\n  }\n\n  render(width: number): string[] {\n    return this.parts.flatMap((part) => part.render(width))\n  }\n}\n\nexport function formatTruncationNotice(truncation: TruncationResult): string {\n  let result = ''\n\n  if (truncation.truncated) {\n    if (truncation.firstLineExceedsLimit) {\n      result = `[First line exceeds ${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit]`\n    }\n\n    if (truncation.truncatedBy === 'lines') {\n      result = `[Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines (${truncation.maxLines ?? DEFAULT_MAX_LINES} line limit)]`\n    } else if (truncation.truncatedBy === 'bytes') {\n      result = `[Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)]`\n    }\n  }\n\n  return result\n}\n","import * as fs from 'node:fs'\nimport * as path from 'node:path'\nimport { Data, Effect, Fiber, Filter, Schema, Stream } from 'effect'\nimport type { PlatformError } from 'effect/PlatformError'\nimport { ChildProcess, ChildProcessSpawner } from 'effect/unstable/process'\n\nconst STDERR_CAP = 50 * 1024\nconst FORCE_KILL_AFTER = '5 seconds'\n\nexport interface SubagentUsage {\n  turns: number\n  input: number\n  output: number\n  cacheRead: number\n  cacheWrite: number\n  cost: number\n  contextTokens: number\n}\n\nexport interface SubagentResult {\n  output: string\n  toolCalls: number\n  usage: SubagentUsage\n  sessionId?: string | undefined\n  durationMs?: number | undefined\n}\n\nexport const emptyResult: SubagentResult = {\n  output: '',\n  toolCalls: 0,\n  usage: {\n    turns: 0,\n    input: 0,\n    output: 0,\n    cacheRead: 0,\n    cacheWrite: 0,\n    cost: 0,\n    contextTokens: 0,\n  },\n}\n\nexport class SubagentStopError extends Data.TaggedError('SubagentStopError')<{\n  readonly reason: 'error' | 'aborted'\n  readonly errorMessage?: string | undefined\n  readonly stderr: string\n  readonly result: SubagentResult\n}> {\n  override readonly message: string =\n    this.errorMessage ||\n    this.stderr.trim() ||\n    this.result.output ||\n    `run stopped (${this.reason})`\n}\n\nexport class SubagentExitError extends Data.TaggedError('SubagentExitError')<{\n  readonly exitCode: number\n  readonly stderr: string\n  readonly result: SubagentResult\n}> {\n  override readonly message: string =\n    this.stderr.trim() ||\n    this.result.output ||\n    `pi exited with code ${this.exitCode}`\n}\n\nexport class SubagentNoOutputError extends Data.TaggedError(\n  'SubagentNoOutputError',\n)<{\n  readonly stderr: string\n  readonly result: SubagentResult\n}> {\n  override readonly message: string =\n    'Subagent produced no assistant messages (unexpected or empty JSON event stream)' +\n    (this.stderr.trim() ? `\\nstderr: ${this.stderr.trim()}` : '')\n}\n\nconst SessionHeader = Schema.Struct({\n  type: Schema.Literal('session'),\n  id: Schema.String,\n})\n\nconst AssistantMessageEnd = Schema.Struct({\n  type: Schema.Literal('message_end'),\n  message: Schema.Struct({\n    role: Schema.Literal('assistant'),\n    content: Schema.Array(\n      Schema.Struct({\n        type: Schema.String,\n        text: Schema.optional(Schema.String),\n      }),\n    ),\n    usage: Schema.optional(\n      Schema.Struct({\n        input: Schema.optional(Schema.Number),\n        output: Schema.optional(Schema.Number),\n        cacheRead: Schema.optional(Schema.Number),\n        cacheWrite: Schema.optional(Schema.Number),\n        totalTokens: Schema.optional(Schema.Number),\n        cost: Schema.optional(\n          Schema.Struct({ total: Schema.optional(Schema.Number) }),\n        ),\n      }),\n    ),\n    stopReason: Schema.optional(Schema.String),\n    errorMessage: Schema.optional(Schema.String),\n  }),\n})\n\nconst SubagentEvent = Schema.fromJsonString(\n  Schema.Union([SessionHeader, AssistantMessageEnd]),\n)\n\ninterface RunState {\n  result: SubagentResult\n  stopReason?: string | undefined\n  errorMessage?: string | undefined\n}\n\nfunction foldMessage(\n  state: RunState,\n  message: (typeof AssistantMessageEnd)['Type']['message'],\n): RunState {\n  const { result } = state\n  let toolCalls = result.toolCalls\n  const texts: string[] = []\n  for (const part of message.content) {\n    if (part.type === 'text' && part.text !== undefined) {\n      texts.push(part.text)\n    } else if (part.type === 'toolCall') {\n      toolCalls += 1\n    }\n  }\n  const text = texts.join('\\n\\n').trim()\n  const usage = message.usage\n  return {\n    result: {\n      ...result,\n      output: text.length > 0 ? text : result.output,\n      toolCalls,\n      usage: {\n        turns: result.usage.turns + 1,\n        input: result.usage.input + (usage?.input ?? 0),\n        output: result.usage.output + (usage?.output ?? 0),\n        cacheRead: result.usage.cacheRead + (usage?.cacheRead ?? 0),\n        cacheWrite: result.usage.cacheWrite + (usage?.cacheWrite ?? 0),\n        cost: result.usage.cost + (usage?.cost?.total ?? 0),\n        contextTokens: usage?.totalTokens ?? result.usage.contextTokens,\n      },\n    },\n    stopReason: message.stopReason ?? state.stopReason,\n    errorMessage: message.errorMessage ?? state.errorMessage,\n  }\n}\n\nexport function runSubagent(options: {\n  prompt: string\n  sessionDir: string\n  name?: string | undefined\n  model?: string | undefined\n  cwd?: string | undefined\n  tools?: ReadonlyArray<string> | undefined\n  onSession?: ((sessionId: string) => void) | undefined\n}): Effect.Effect<\n  SubagentResult,\n  SubagentStopError | SubagentExitError | SubagentNoOutputError | PlatformError,\n  ChildProcessSpawner.ChildProcessSpawner\n> {\n  return Effect.scoped(\n    Effect.gen(function* () {\n      // `--exclude-tools subagent` keeps children from spawning their own.\n      const args = [\n        '--mode',\n        'json',\n        '-p',\n        '--session-dir',\n        options.sessionDir,\n        '--exclude-tools',\n        'subagent',\n      ]\n      // pi exits on an empty --name.\n      const name = options.name?.trim()\n      if (name) {\n        args.push('--name', name)\n      }\n      if (options.tools !== undefined) {\n        if (options.tools.length > 0) {\n          args.push('--tools', options.tools.join(','))\n        } else {\n          args.push('--no-tools')\n        }\n      }\n      if (options.model !== undefined) {\n        args.push('--model', options.model)\n      }\n\n      // Re-invoke the running harness: the entry script via the current runtime,\n      // the executable itself for compiled binaries, or `pi` on PATH.\n      const currentScript = process.argv[1]\n      const isBunVirtualScript = currentScript?.startsWith('/$bunfs/root/')\n      const execName = path.basename(process.execPath).toLowerCase()\n      const invocation =\n        currentScript && !isBunVirtualScript && fs.existsSync(currentScript)\n          ? { command: process.execPath, args: [currentScript, ...args] }\n          : /^(node|bun)(\\.exe)?$/.test(execName)\n            ? { command: 'pi', args }\n            : { command: process.execPath, args }\n\n      const startedAt = Date.now()\n      const handle = yield* ChildProcess.make(invocation.command, invocation.args, {\n        cwd: options.cwd,\n        // Overrides a process-wide long retention setting. The explicit value\n        // also tells @pi-plugins/claude-oauth not to extend child TTLs.\n        env: { PI_CACHE_RETENTION: 'short' },\n        extendEnv: true,\n        stdin: Stream.make(new TextEncoder().encode(options.prompt)),\n        forceKillAfter: FORCE_KILL_AFTER,\n      })\n\n      const stderrFiber = yield* Effect.forkScoped(\n        handle.stderr.pipe(\n          Stream.decodeText,\n          Stream.runFold(\n            () => '',\n            (acc, chunk) =>\n              acc.length >= STDERR_CAP\n                ? acc\n                : acc + chunk.slice(0, STDERR_CAP - acc.length),\n          ),\n        ),\n      )\n\n      const state = yield* handle.stdout.pipe(\n        Stream.decodeText,\n        Stream.splitLines,\n        Stream.filterMap(\n          Filter.fromPredicateOption(Schema.decodeUnknownOption(SubagentEvent)),\n        ),\n        Stream.runFoldEffect(\n          (): RunState => ({ result: emptyResult }),\n          (previous, event) =>\n            Effect.sync(() => {\n              if (event.type === 'session') {\n                // A second header would cost the caller an extra render.\n                if (previous.result.sessionId !== undefined) {\n                  return previous\n                }\n                options.onSession?.(event.id)\n                return {\n                  ...previous,\n                  result: { ...previous.result, sessionId: event.id },\n                }\n              }\n              return foldMessage(previous, event.message)\n            }),\n        ),\n      )\n\n      const exitCode = Number(yield* handle.exitCode)\n      const stderr = yield* Fiber.join(stderrFiber)\n      const result = { ...state.result, durationMs: Date.now() - startedAt }\n\n      if (state.stopReason === 'error' || state.stopReason === 'aborted') {\n        return yield* new SubagentStopError({\n          reason: state.stopReason,\n          errorMessage: state.errorMessage,\n          stderr,\n          result,\n        })\n      }\n      if (exitCode !== 0) {\n        return yield* new SubagentExitError({ exitCode, stderr, result })\n      }\n      if (result.usage.turns === 0) {\n        return yield* new SubagentNoOutputError({ stderr, result })\n      }\n\n      return result\n    }),\n  )\n}\n","import { truncateHead } from '@earendil-works/pi-coding-agent'\nimport { formatTruncationNotice } from '@pi-plugins/shared/ui'\nimport type { SubagentResult } from './runner'\n\nexport function capToolOutput(text: string): string {\n  const truncation = truncateHead(text)\n  return truncation.truncated\n    ? `${truncation.content}\\n\\n${formatTruncationNotice(truncation)}`\n    : truncation.content\n}\n\nfunction formatTokens(count: number): string {\n  if (count < 1000) {\n    return count.toString()\n  }\n  if (count < 10000) {\n    return `${(count / 1000).toFixed(1)}k`\n  }\n  if (count < 1000000) {\n    return `${Math.round(count / 1000)}k`\n  }\n  return `${(count / 1000000).toFixed(1)}M`\n}\n\nfunction formatDuration(ms: number): string {\n  const totalSeconds = Math.round(ms / 1000)\n  if (totalSeconds < 60) {\n    return `${totalSeconds}s`\n  }\n  const seconds = `${totalSeconds % 60}`.padStart(2, '0')\n  const minutes = Math.floor(totalSeconds / 60) % 60\n  const hours = Math.floor(totalSeconds / 3600)\n  return hours > 0\n    ? `${hours}h${`${minutes}`.padStart(2, '0')}m${seconds}s`\n    : `${minutes}m${seconds}s`\n}\n\nexport function formatStats(result: SubagentResult): string {\n  const { usage, toolCalls } = result\n  const parts: string[] = []\n  if (usage.turns > 0) {\n    parts.push(`${usage.turns} turn${usage.turns > 1 ? 's' : ''}`)\n  }\n  if (toolCalls > 0) {\n    parts.push(`${toolCalls} tool${toolCalls > 1 ? 's' : ''}`)\n  }\n  if (usage.input > 0) {\n    parts.push(`↑${formatTokens(usage.input)}`)\n  }\n  if (usage.output > 0) {\n    parts.push(`↓${formatTokens(usage.output)}`)\n  }\n  if (usage.cacheRead > 0) {\n    parts.push(`R${formatTokens(usage.cacheRead)}`)\n  }\n  if (usage.cacheWrite > 0) {\n    parts.push(`W${formatTokens(usage.cacheWrite)}`)\n  }\n  if (usage.cost > 0) {\n    parts.push(`$${usage.cost.toFixed(4)}`)\n  }\n  if (result.durationMs !== undefined) {\n    parts.push(formatDuration(result.durationMs))\n  }\n  return parts.join(' ')\n}\n","import * as path from 'node:path'\nimport type { ExtensionAPI } from '@earendil-works/pi-coding-agent'\nimport { getAgentDir } from '@earendil-works/pi-coding-agent'\nimport { Text } from '@earendil-works/pi-tui'\nimport * as NodeServices from '@effect/platform-node/NodeServices'\nimport { runTool } from '@pi-plugins/shared/run'\nimport { ExpandableText, TextPreview } from '@pi-plugins/shared/ui'\nimport { Effect } from 'effect'\nimport { Type, type Static } from 'typebox'\nimport {\n  emptyResult,\n  runSubagent,\n  type SubagentResult,\n  type SubagentUsage,\n} from './runner'\nimport { capToolOutput, formatStats } from './utils'\n\n// Wrapped terminal rows, not source lines, so a row's height stays bounded.\nconst PROMPT_PREVIEW_LINES = 3\nconst OUTPUT_PREVIEW_LINES = 5\nconst METADATA_LABEL_WIDTH = 9\n\nconst subagentSchema = Type.Object({\n  description: Type.String({\n    description: 'A short (3-5 word) description of the task',\n  }),\n  prompt: Type.String({\n    description: 'The task for the agent to perform',\n  }),\n  model: Type.Optional(\n    Type.String({\n      description:\n        \"Leave unset: the subagent then runs on this session's model and thinking level. \" +\n        'Set it only when the user explicitly asked for a different model — never pass your own.',\n    }),\n  ),\n  cwd: Type.Optional(\n    Type.String({\n      description: 'Working directory for the agent process',\n    }),\n  ),\n})\n\nexport type SubagentInput = Static<typeof subagentSchema>\n\ninterface SubagentDetails extends SubagentResult {\n  cwd?: string | undefined\n  model?: string | undefined\n  failed?: boolean | undefined\n  errorMessage?: string | undefined\n  stderr?: string | undefined\n}\n\nexport default function subagent(pi: ExtensionAPI) {\n  const pending: SubagentUsage[] = []\n\n  // Folds subagent cost into the parent session so the footer's cumulative cost\n  // includes delegated work. Only `cost.total`: the token fields feed pi's\n  // auto-compaction heuristics and must stay untouched.\n  pi.on('message_end', ({ message }) => {\n    if (\n      message.role !== 'assistant' ||\n      message.usage.totalTokens <= 0 ||\n      pending.length === 0\n    ) {\n      return undefined\n    }\n    const cost = { ...message.usage.cost }\n    for (const run of pending.splice(0)) {\n      cost.total += run.cost\n    }\n    return { message: { ...message, usage: { ...message.usage, cost } } }\n  })\n\n  pi.registerTool<typeof subagentSchema, SubagentDetails>({\n    name: 'subagent',\n    label: 'Subagent',\n    description:\n      'Delegate a substantial, clearly scoped subtask with a concrete deliverable that can be completed independently. ' +\n      'Use direct tools for routine searches, file reads, and small changes. ' +\n      'The subagent runs as a separate headless pi instance without this conversation’s history. ' +\n      'Provide the necessary context, whether edits are allowed, and the expected output. ' +\n      'It shares the filesystem with the parent. ' +\n      'This call blocks until the subagent finishes, then returns its final response.',\n    promptSnippet:\n      'Delegate self-contained tasks to subagents (isolated headless pi instances).',\n    parameters: subagentSchema,\n    async execute(_toolCallId, params, signal, onUpdate, ctx) {\n      const model =\n        params.model ??\n        (ctx.model === undefined\n          ? undefined\n          : `${ctx.model.provider}/${ctx.model.id}:${pi.getThinkingLevel()}`)\n\n      // Relative to the parent session's cwd, not the process cwd: they differ\n      // for resumed and cross-project sessions.\n      const cwd =\n        params.cwd !== undefined ? path.resolve(ctx.cwd, params.cwd) : ctx.cwd\n\n      // Inheriting the parent's tool set keeps a restricted parent (e.g.\n      // `pi --tools read`) from being escaped through a child with default tools.\n      const tools = pi.getActiveTools().filter((name) => name !== 'subagent')\n\n      // Beside pi's per-project `--<cwd>--` directories, so child sessions stay\n      // out of `pi -c` / `pi -r` but resolve by id from anywhere.\n      const configured = process.env['PI_SUBAGENT_SESSION_DIR']\n      const sessionDir = configured\n        ? path.resolve(configured)\n        : path.join(getAgentDir(), 'sessions', 'subagents')\n\n      const program = runSubagent({\n        prompt: params.prompt,\n        sessionDir,\n        name: params.description,\n        model,\n        cwd,\n        tools,\n        // The only live update: each one repaints pi's scrollback once the row\n        // has scrolled out of view.\n        onSession: (sessionId) => {\n          onUpdate?.({\n            content: [{ type: 'text', text: '' }],\n            details: { ...emptyResult, sessionId, model, cwd },\n          })\n        },\n      }).pipe(\n        Effect.map((result) => ({\n          content: [\n            {\n              type: 'text' as const,\n              text: result.output ? capToolOutput(result.output) : '(no output)',\n            },\n          ],\n          details: { ...result, model, cwd },\n        })),\n        Effect.catch((error) => {\n          const result = 'result' in error ? error.result : emptyResult\n          const label = error._tag === 'SubagentStopError' ? error.reason : 'failed'\n          const reason =\n            error._tag === 'PlatformError'\n              ? `Failed to run subagent: ${error.message}`\n              : error.message\n          return Effect.succeed({\n            content: [\n              {\n                type: 'text' as const,\n                text: `Subagent ${label}: ${capToolOutput(reason)}`,\n              },\n            ],\n            details: {\n              ...result,\n              model,\n              cwd,\n              failed: true,\n              errorMessage: reason,\n              stderr: 'stderr' in error ? error.stderr : undefined,\n            },\n            isError: true,\n          })\n        }),\n        Effect.tap(({ details }) => Effect.sync(() => pending.push(details.usage))),\n        Effect.provide(NodeServices.layer),\n      )\n\n      return await runTool(program, { signal })\n    },\n    renderCall(args, theme, { expanded }) {\n      const title = new Text(\n        theme.fg('toolTitle', theme.bold('subagent ')) +\n          theme.fg('accent', args.description ?? '...'),\n        0,\n        0,\n      )\n      if (args.prompt === undefined) {\n        return title\n      }\n\n      const preview = new TextPreview({\n        text: args.prompt,\n        maxLines: PROMPT_PREVIEW_LINES,\n        expanded,\n        theme,\n      })\n      return {\n        render: (width) => [...title.render(width), ...preview.render(width)],\n        invalidate: () => {\n          title.invalidate()\n          preview.invalidate()\n        },\n      }\n    },\n    renderResult({ details }, { expanded, isPartial }, theme, context) {\n      const metadata: Array<[string, string]> = []\n      if (details.cwd !== undefined && details.cwd !== context.cwd) {\n        metadata.push(['cwd', details.cwd])\n      }\n      if (details.model !== undefined) {\n        metadata.push(['model', details.model])\n      }\n      if (details.sessionId !== undefined) {\n        // Never a prefix: uuidv7 ids share their leading digits across a batch.\n        metadata.push(['session', details.sessionId])\n      }\n\n      const metadataBlock = metadata\n        .map(\n          ([label, value]) =>\n            theme.fg('dim', label.padEnd(METADATA_LABEL_WIDTH)) +\n            theme.fg('muted', value),\n        )\n        .join('\\n')\n\n      if (isPartial) {\n        return new Text(metadataBlock ? `\\n${metadataBlock}` : '', 0, 0)\n      }\n\n      const failed = details.failed === true\n      const stats = formatStats(details)\n      let status = failed ? theme.fg('error', '✗') : theme.fg('success', '✓')\n      if (stats) {\n        status += ` ${theme.fg('muted', stats)}`\n      }\n\n      const content =\n        details.output ||\n        (failed ? (details.stderr?.trim() ?? '') : '') ||\n        '(no output)'\n\n      let header = metadataBlock ? `\\n${metadataBlock}\\n\\n${status}` : `\\n${status}`\n      if (failed && details.errorMessage && details.errorMessage !== content) {\n        header += `\\n${theme.fg('error', `Error: ${details.errorMessage}`)}`\n      }\n\n      return new ExpandableText({\n        header,\n        content: expanded ? content : capToolOutput(content),\n        maxLines: OUTPUT_PREVIEW_LINES,\n        expanded,\n        theme,\n      })\n    },\n  })\n}\n"],"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,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,MAAa,iBAAiB,MAAM,SAAS;CAC3C,QAAQ,KAAK,QAAb;EACE,KAAK,GACH,OAAO;EACT,KAAK,GACH,OAAO,KAAK,EAAE,CAAC,IAAI;EACrB,K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